Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adding test for diagnosis viewset #2729

Merged
merged 4 commits into from
Jan 12, 2025
Merged

Conversation

DraKen0009
Copy link
Contributor

@DraKen0009 DraKen0009 commented Jan 11, 2025

Proposed Changes

  • Added test for diagnosis
  • Updated the test case for symptoms
  • Added make command to run specific tests

Merge Checklist

  • Tests added/fixed
  • Update docs in /docs
  • Linting Complete
  • Any other necessary step

Only PR's with test cases included and passing lint and test pipelines will be reviewed

@ohcnetwork/care-backend-maintainers @ohcnetwork/care-backend-admins

Summary by CodeRabbit

Release Notes

  • Documentation

    • Updated CONTRIBUTING.md with new instructions for running tests using Docker
      • Added command to run all tests
      • Added command to run specific test files or methods
  • Tests

    • Enhanced test coverage for diagnosis management with a new test suite
    • Improved clarity and coverage of permission-related tests for symptom creation
    • Added new test scenarios for permission-based access control across different organizations

@DraKen0009 DraKen0009 requested a review from a team as a code owner January 11, 2025 09:57
Copy link

coderabbitai bot commented Jan 11, 2025

📝 Walkthrough

Walkthrough

This pull request introduces enhancements to testing documentation and functionality. The CONTRIBUTING.md file is updated with new instructions for running tests using Docker, including commands for executing all tests and specific tests. The Makefile is modified to allow specifying a test path when running tests. Additionally, the test coverage is expanded for the diagnosis and symptom APIs, with new test methods added to address various permission scenarios. These changes collectively aim to improve the testing process, as if it needed any more help.

Changes

File Change Summary
CONTRIBUTING.md Added Docker test running instructions: make test for all tests and make test path=<path_to_test> for specific tests
Makefile Updated test target to support optional test path parameter
care/emr/tests/test_diagnosis_api.py Added comprehensive TestDiagnosisViewSet test suite for diagnosis management
care/emr/tests/test_symptom_api.py Enhanced TestSymptomViewSet with additional permission-related test methods

Possibly related PRs

Suggested reviewers

  • vigneshhari

Poem

🧪 Testing, testing, one-two-three
Docker commands now set us free
Paths selected with surgical might
Our code's quality shines so bright
(Just don't break anything, pretty please) 🔍

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (5)
care/emr/tests/test_symptom_api.py (2)

167-170: I see you're keeping us on our toes with that indentation.

The pipeline caught this one. Mind fixing the indentation to match the rest of the file?

🧰 Tools
🪛 GitHub Actions: Lint Code Base

[warning] 167-170: Code formatting issue: Incorrect indentation fixed by ruff-format


248-284: The test is great, but the name could be more... specific.

Consider renaming to better reflect both aspects being tested:
test_create_symptom_with_organisation_user_can_view_but_not_create_across_organizations

care/emr/tests/test_diagnosis_api.py (2)

98-102: Oh, those pesky plural forms!

There's a typo in the test names: "diagnosiss" should be "diagnoses". This appears in multiple test methods.

-    def test_list_diagnosiss_with_permissions(self):
+    def test_list_diagnoses_with_permissions(self):

1-621: Impressive test coverage, though we could make it a bit DRYer.

Consider extracting common test setup patterns into helper methods. For example, the permission setup and encounter creation appear frequently:

def setup_user_with_permissions(self, permissions):
    role = self.create_role_with_permissions(permissions)
    self.attach_role_facility_organization_user(self.organization, self.user, role)
    return role

def create_test_encounter(self, status=None):
    return self.create_encounter(
        patient=self.patient,
        facility=self.facility,
        organization=self.organization,
        status=status,
    )
🧰 Tools
🪛 Ruff (0.8.2)

424-424: print found

(T201)


621-621: No newline at end of file

Add trailing newline

(W292)

🪛 GitHub Actions: Lint Code Base

[error] 424-424: T201: print statement found in test file. Remove print statement.


[error] 618-618: Missing newline at end of file


[warning] 167-170: Code formatting issue: Incorrect indentation fixed by ruff-format

CONTRIBUTING.md (1)

125-128: The new test commands documentation looks good, but...

Consider adding a concrete example to make it even clearer:

 # To run a specific test file, class, or method:
 make test path=<path_to_test>
+# Example:
+# make test path=care/emr/tests/test_diagnosis_api.py:TestDiagnosisViewSet.test_create_diagnosis_with_permissions
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7256345 and 7d5e1ca.

📒 Files selected for processing (4)
  • CONTRIBUTING.md (1 hunks)
  • Makefile (1 hunks)
  • care/emr/tests/test_diagnosis_api.py (1 hunks)
  • care/emr/tests/test_symptom_api.py (7 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
care/emr/tests/test_diagnosis_api.py

424-424: print found

(T201)


621-621: No newline at end of file

Add trailing newline

(W292)

care/emr/tests/test_symptom_api.py

620-620: No newline at end of file

Add trailing newline

(W292)

🪛 GitHub Actions: Lint Code Base
care/emr/tests/test_diagnosis_api.py

[error] 424-424: T201: print statement found in test file. Remove print statement.


[error] 618-618: Missing newline at end of file


[warning] 167-170: Code formatting issue: Incorrect indentation fixed by ruff-format

care/emr/tests/test_symptom_api.py

[error] 617-617: Missing newline at end of file


[warning] 167-170: Code formatting issue: Incorrect indentation fixed by ruff-format

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test / test
  • GitHub Check: Analyze (python)
🔇 Additional comments (2)
care/emr/tests/test_symptom_api.py (1)

223-235: Nice work on the cross-organization permission test!

Good coverage of the security boundary between organizations. The test setup is clear and the assertions verify the expected behavior.

Makefile (1)

56-56: Nice enhancement to the test command!

The addition of the $(path) variable makes the test command more flexible. This will be particularly useful for running specific test cases.

care/emr/tests/test_diagnosis_api.py Outdated Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (4)
care/emr/tests/test_diagnosis_api.py (4)

21-44: Consider adding docstring to the test class.

While the test methods have docstrings, the test class itself could use a docstring explaining its purpose and the overall testing strategy. I mean, it's not like we're mind readers or anything.

 class TestDiagnosisViewSet(CareAPITestBase):
+    """
+    Test suite for DiagnosisViewSet API endpoints.
+    
+    Tests CRUD operations with various permission combinations and encounter statuses.
+    """
     def setUp(self):

58-76: Consider using more descriptive parameter names.

The **kwargs parameter in create_diagnosis is a bit... mysterious. It might be helpful to list the expected kwargs in the docstring, you know, for those of us who appreciate documentation.

     def create_diagnosis(self, encounter, patient, **kwargs):
+        """
+        Create a diagnosis for testing.
+        
+        Args:
+            encounter: The encounter associated with the diagnosis
+            patient: The patient associated with the diagnosis
+            **kwargs: Additional fields for Condition model (e.g., notes, onset_date)
+        """

419-424: Consider using constants for severity values.

Instead of hardcoding the string "mild", consider using the SeverityChoices enum that's already imported. Just a thought, you know, for consistency's sake.

-        diagnosis_data_updated["severity"] = "mild"
+        diagnosis_data_updated["severity"] = SeverityChoices.mild.value

1-620: Consider adding edge case tests.

While the test coverage is good, there are some edge cases that might be worth testing:

  1. Creating/updating a diagnosis with invalid code format
  2. Testing with malformed encounter IDs
  3. Testing concurrent updates to the same diagnosis

Not that I'm saying the current tests aren't good enough, but you know, there's always room for improvement.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7d5e1ca and 2a4b874.

📒 Files selected for processing (2)
  • care/emr/tests/test_diagnosis_api.py (1 hunks)
  • care/emr/tests/test_symptom_api.py (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • care/emr/tests/test_symptom_api.py
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test / test
  • GitHub Check: Analyze (python)
🔇 Additional comments (2)
care/emr/tests/test_diagnosis_api.py (2)

1-18: LGTM! Clean and well-organized imports.

The imports are logically grouped and follow a clear pattern: standard library, Django, third-party, and local imports.


538-620: LGTM! Comprehensive delete test cases.

The delete tests cover all necessary permission combinations and edge cases. Nice work on being thorough with the test coverage!

care/emr/tests/test_diagnosis_api.py Outdated Show resolved Hide resolved
Copy link

codecov bot commented Jan 11, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 46.74%. Comparing base (7256345) to head (ea46858).
Report is 5 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #2729      +/-   ##
===========================================
+ Coverage    46.72%   46.74%   +0.02%     
===========================================
  Files          313      313              
  Lines        17697    17697              
  Branches      1704     1704              
===========================================
+ Hits          8269     8273       +4     
+ Misses        9359     9355       -4     
  Partials        69       69              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (5)
care/emr/tests/test_diagnosis_api.py (5)

1-1: Consider using random.choice instead of secrets.choice

While secrets.choice provides cryptographically secure random selections, it's a bit... excessive for generating test data. random.choice would be more appropriate here, unless you're testing something specifically related to security.

-from secrets import choice
+from random import choice

48-56: Add type hints to improve code clarity

The helper methods would benefit from type hints. It would make the code more maintainable and self-documenting, especially for methods like _get_diagnosis_url and create_diagnosis.

-    def _get_diagnosis_url(self, diagnosis_id):
+    def _get_diagnosis_url(self, diagnosis_id: str) -> str:

-    def create_diagnosis(self, encounter, patient, **kwargs):
+    def create_diagnosis(self, encounter: Encounter, patient: Patient, **kwargs) -> Condition:

-    def generate_data_for_diagnosis(self, encounter, **kwargs):
+    def generate_data_for_diagnosis(self, encounter: Encounter, **kwargs) -> dict:

Also applies to: 58-76, 78-95


97-203: Add pagination test for list endpoint

While the permission tests are quite thorough (almost suspiciously so), there's no test for pagination behavior. Consider adding a test case that verifies the endpoint correctly handles large result sets.

Here's a suggested test case:

def test_list_diagnosis_pagination(self):
    """
    Test that the list endpoint correctly paginates results
    """
    permissions = [PatientPermissions.can_view_clinical_data.name]
    role = self.create_role_with_permissions(permissions)
    self.attach_role_facility_organization_user(self.organization, self.user, role)

    encounter = self.create_encounter(
        patient=self.patient,
        facility=self.facility,
        organization=self.organization,
    )
    
    # Create more diagnoses than the default page size
    for _ in range(11):  # Assuming default page size is 10
        self.create_diagnosis(encounter=encounter, patient=self.patient)
    
    response = self.client.get(self.base_url)
    self.assertEqual(response.status_code, 200)
    self.assertTrue('next' in response.json())
    self.assertEqual(len(response.json()['results']), 10)

420-559: Add test for partial updates using PATCH

The update tests are quite extensive (maybe someone really likes testing permissions?), but they're missing tests for partial updates using PATCH.

Here's a suggested test case:

def test_partial_update_diagnosis(self):
    """
    Test that PATCH requests correctly update only specified fields
    """
    permissions = [
        EncounterPermissions.can_write_encounter.name,
        PatientPermissions.can_view_clinical_data.name,
    ]
    role = self.create_role_with_permissions(permissions)
    self.attach_role_facility_organization_user(self.organization, self.user, role)

    encounter = self.create_encounter(
        patient=self.patient,
        facility=self.facility,
        organization=self.organization,
    )
    diagnosis = self.create_diagnosis(encounter=encounter, patient=self.patient)
    
    url = self._get_diagnosis_url(diagnosis.external_id)
    patch_data = {"severity": "mild"}
    
    response = self.client.patch(url, patch_data, format="json")
    self.assertEqual(response.status_code, 200)
    self.assertEqual(response.json()["severity"], "mild")

560-642: Add test for cascade deletion behavior

The delete tests cover permissions thoroughly (perhaps a bit too thoroughly?), but they're missing a test to verify cascade deletion behavior with related objects.

Here's a suggested test case:

def test_delete_diagnosis_cascade_behavior(self):
    """
    Test that deleting a diagnosis properly handles related objects
    """
    permissions = [
        EncounterPermissions.can_write_encounter.name,
        PatientPermissions.can_view_clinical_data.name,
    ]
    role = self.create_role_with_permissions(permissions)
    self.attach_role_facility_organization_user(self.organization, self.user, role)

    encounter = self.create_encounter(
        patient=self.patient,
        facility=self.facility,
        organization=self.organization,
    )
    diagnosis = self.create_diagnosis(encounter=encounter, patient=self.patient)
    
    # Create related objects here if any
    
    url = self._get_diagnosis_url(diagnosis.external_id)
    response = self.client.delete(url)
    self.assertEqual(response.status_code, 204)
    
    # Verify related objects are handled correctly
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2a4b874 and ea46858.

📒 Files selected for processing (2)
  • care/emr/tests/test_diagnosis_api.py (1 hunks)
  • care/emr/tests/test_symptom_api.py (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • care/emr/tests/test_symptom_api.py
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test / test
  • GitHub Check: Analyze (python)

care/emr/tests/test_diagnosis_api.py Show resolved Hide resolved
care/emr/tests/test_diagnosis_api.py Show resolved Hide resolved
@DraKen0009 DraKen0009 self-assigned this Jan 11, 2025
@vigneshhari vigneshhari merged commit 3411890 into develop Jan 12, 2025
8 checks passed
@vigneshhari vigneshhari deleted the prafful/tests/diagnosis branch January 12, 2025 15:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

2 participants