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

Update allergy_intolerance update spec and added tests #2778

Merged
merged 1 commit into from
Jan 24, 2025

Conversation

sainak
Copy link
Member

@sainak sainak commented Jan 24, 2025

Proposed Changes

  • Update allergy_intolerance update spec and added 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

  • New Features

    • Enhanced authorization and data handling for allergy intolerance records
    • Added more robust validation for encounter-related operations
  • Bug Fixes

    • Improved permission checks for creating and updating allergy intolerance records
    • Added validation to prevent unauthorized access to clinical data
  • Tests

    • Comprehensive test suite added for Allergy Intolerance API
    • Implemented tests for various user permission scenarios

@sainak sainak requested a review from a team as a code owner January 24, 2025 12:48
Copy link
Contributor

coderabbitai bot commented Jan 24, 2025

📝 Walkthrough

Walkthrough

The pull request introduces significant refinements to the Allergy Intolerance management system, focusing on enhancing authorization, data validation, and specification models. The changes primarily target the AllergyIntoleranceViewSet and its associated specification classes, implementing more robust permission checks and restructuring data models to support more precise encounter-related operations.

Changes

File Change Summary
care/emr/api/viewsets/allergy_intolerance.py - Updated Pydantic models
- Added authorize_update method
- Modified authorize_create method
- Introduced clean_update_data method
care/emr/resources/allergy_intolerance/spec.py - Renamed specification classes
- Added encounter validation
- Restructured data models
- Updated serialization methods
care/emr/tests/test_allergy_intolerance_api.py - Added comprehensive test suite for AllergyIntoleranceViewSet
- Implemented permission and functionality tests

Sequence Diagram

sequenceDiagram
    participant User
    participant AllergyIntoleranceViewSet
    participant EncounterModel
    participant AuthorizationService

    User->>AllergyIntoleranceViewSet: Request Update
    AllergyIntoleranceViewSet->>EncounterModel: Retrieve Encounter
    EncounterModel-->>AllergyIntoleranceViewSet: Encounter Details
    AllergyIntoleranceViewSet->>AuthorizationService: Check Permissions
    AuthorizationService-->>AllergyIntoleranceViewSet: Permission Result
    alt Permission Granted
        AllergyIntoleranceViewSet->>AllergyIntoleranceViewSet: Update Record
    else Permission Denied
        AllergyIntoleranceViewSet-->>User: 403 Forbidden
    end
Loading

Possibly related PRs

Suggested reviewers

  • vigneshhari

Poem

🩺 Allergy's Dance of Code

In bytes of care, permissions bloom,
Encounters whisper, models resume,
A dance of specs, both old and new,
Where data flows with permission's hue!

🌈✨

✨ 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.

@vigneshhari vigneshhari merged commit 6add747 into develop Jan 24, 2025
5 of 6 checks passed
@vigneshhari vigneshhari deleted the sainak/update-allergy-spec branch January 24, 2025 12:51
Copy link
Contributor

@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: 0

🧹 Nitpick comments (8)
care/emr/api/viewsets/allergy_intolerance.py (2)

69-77: Granular update authorization introduced.
The authorize_update method now properly checks if the user can update the related Encounter. Might be worth verifying that mismatched patient IDs are also disallowed at this level, if that’s not enforced elsewhere.


78-80: Selective field preservation.
Retaining only the encounter field in clean_update_data is sensible, but verify there's no unintentional data loss if you plan to allow partial updates to other fields in the future.

care/emr/resources/allergy_intolerance/spec.py (2)

76-82: Renaming and reorganizing write spec fields.
Renaming AllergyIntoleranceSpec to AllergyIntoleranceWriteSpec is a logical step. The structure is more coherent, though watch out for any missing fields if future expansions are planned.


104-107: Setting encounter and patient on deserialization.
The approach directly pulls the encounter from the DB, reducing guesswork. Just confirm that no additional data validation is needed for partial updates.

care/emr/tests/test_allergy_intolerance_api.py (4)

22-46: Comprehensive setup.
Creating test data and patching validate_valueset helps keep tests isolated. This is well done, though you might eventually consider a fixture-based approach for even cleaner code organization.


102-122: Test: list with valid permissions.
Properly verifying a 200 response for can_view_clinical_data. It's thorough, though verifying the response body might catch data regressions.


156-174: Test: list single encounter with permissions.
Filtering by ?encounter= is validated. Possibly check if only that encounter’s results appear in the response.


446-469: Test: retrieve with permissions.
Checks a successful read scenario. Possibly reaffirm the entire payload is correct in future expansions.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5efcfbb and 53da4cc.

📒 Files selected for processing (3)
  • care/emr/api/viewsets/allergy_intolerance.py (4 hunks)
  • care/emr/resources/allergy_intolerance/spec.py (3 hunks)
  • care/emr/tests/test_allergy_intolerance_api.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test / test
  • GitHub Check: Analyze (python)
🔇 Additional comments (36)
care/emr/api/viewsets/allergy_intolerance.py (4)

18-18: Good import addition.
Importing Encounter is necessary for the new update logic.


23-24: New spec imports look consistent.
Renaming these specs aligns well with the updated naming convention. Nice job maintaining clarity here.


36-36: Accurate schema assignment for create.
Using AllergyIntoleranceWriteSpec ensures the correct data structure is validated upon creation.


48-50: Consistent model references.
Assigning pydantic_update_model to AllergyIntoleranceUpdateSpec clarifies how partial updates differ from writes. Just make sure no references to the old classes remain in other parts of the code.

✅ Verification successful

Everything looks perfectly aligned with the new spec classes
I've thoroughly checked, and there are no lingering references to any old spec classes anywhere in the codebase. The transition appears to be complete, not that anyone was worried.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Checking references to old spec classes
rg -A 3 "AllergyIntoleranceSpec" 

Length of output: 1487


Script:

#!/bin/bash
# Broader search for any allergy intolerance related classes
rg -i "allergy.*intolerance.*spec|allergyintolerance.*spec"

Length of output: 1828

care/emr/resources/allergy_intolerance/spec.py (6)

55-55: New AllergyIntoleranceUpdateSpec class recognized.
This separation clarifies the distinction between creating vs updating. Looks good.


60-61: Non-mandatory note field.
Allowing note to be optional nicely accommodates situations with no comments. No issues here.


63-69: Encounter validator helps prevent invalid references.
Raising a ValueError ensures immediate feedback if the provided encounter doesn’t exist—this is a good move.


72-72: Deserialization step for encounter.
This ensures the model object is correctly linked to the encounter. Just double-check concurrency handling if multiple processes might update the same record simultaneously.


87-87: Default onset object is fine.
Providing a default dictionary for onset can help avoid KeyError checks. No concerns here.


134-135: Reading encounter external ID on serialization.
Including encounter in the output fosters clarity. Looks neat.

care/emr/tests/test_allergy_intolerance_api.py (26)

47-49: Graceful teardown.
Stopping the patcher ensures no side effects leak into other tests. Minimal but necessary cleanup.


50-59: Detail URL helper.
A neat utility to clarify test code. Approved for readability.


60-80: Creation helper.
baker.make usage is flexible and keeps test logic DRY. The random status choices are a tiny bit unpredictable but fine for coverage.


81-100: Factory for request data.
Generating valid POST bodies ensures consistency across tests. Good approach.


123-141: Test: list with completed encounter.
Ensuring 403 when the encounter is completed is correct. A prime example of negative testing done right.


142-155: Test: list with no permissions.
Good job confirming unauthorized access fails with 403. Straightforward coverage.


175-194: Test: single encounter with completed status.
Returns 403 for a completed record. Preserves data integrity. Clear test scenario.


195-209: Test: list single encounter without permissions.
Again, neat negative test ensuring no leaks of info. Consistency is good.


211-230: Test: create without permissions.
Enforces 403 as expected. Nicely ensures non-privileged users can’t create data.


231-264: Test: create with different facility organization.
Smartly checks mismatch scenarios. The code does a thorough job rejecting unauthorized facility access.


265-305: Test: creation with organization user.
Verifies a user from a certain org can indeed create data for a patient. The test is quite robust, ensuring correct cross-organization checks.


306-332: Test: create with permissions on open encounter.
200 indicates success. Checking the returned fields for correctness is a nice detail.


333-357: Test: create with permissions on completed encounter.
Proves the user is blocked with 403. This matches real-world workflows where completed encounters shouldn’t be altered.


358-385: Test: create with missing facility association.
This scenario ensures the user can’t create entries in unassociated facilities. Good, strict enforcement.


386-413: Test: create with mismatched patient ID.
Returning 403 is correct. The test ensures no accidental cross-patient data manipulations.


414-444: Test: create with invalid encounter ID.
400 error is the correct response, verifying the new validator checks. Good clarity in the returned error message.


470-495: Test: retrieve single encounter with permissions.
Ensures a parameter-based retrieval also respects the user’s access. Nicely consistent with the rest of the logic.


496-515: Test: retrieve single encounter without permissions.
403 is correct. Continues the pattern of robust permission checks.


516-533: Test: retrieve without relevant permissions.
Even if the user can write, they can’t view. Rightfully returns 403.


535-566: Test: update with all permissions.
can_write_encounter, can_write_patient, and can_view_clinical_data produce a 200. Confirming updated fields is a good practice.


567-602: Test: update single encounter with permissions.
Again, returning 200 confirms success. The additional param ?encounter= helps replicate real usage scenarios.


603-631: Test: update single encounter lacking can_view_clinical_data.
403 properly enforces read-level permission. This consistency helps avoid data leaks.


632-660: Test: update without relevant permissions.
Solely having can_write_patient isn’t enough to read or update data. Good negative scenario coverage.


661-691: Test: update closed encounter.
Completed encounters are immutable. 403 is consistent with the domain policy.


692-737: Test: changing encounter ID with proper permissions.
Confirms the user can reassign an allergy intolerance to another active encounter. This is a strong multi-encounter use case test.


738-778: Test: changing encounter ID without new encounter permission.
Denies the update with 403. Crisp conclusion that roles and ownership are strictly enforced.

Copy link

codecov bot commented Jan 24, 2025

Codecov Report

Attention: Patch coverage is 62.85714% with 13 lines in your changes missing coverage. Please review.

Project coverage is 56.69%. Comparing base (5efcfbb) to head (53da4cc).
Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
care/emr/resources/allergy_intolerance/spec.py 64.00% 9 Missing ⚠️
care/emr/api/viewsets/allergy_intolerance.py 60.00% 4 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #2778      +/-   ##
===========================================
- Coverage    56.69%   56.69%   -0.01%     
===========================================
  Files          208      208              
  Lines         9547     9569      +22     
  Branches       939      942       +3     
===========================================
+ Hits          5413     5425      +12     
- Misses        4118     4128      +10     
  Partials        16       16              

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants