Skip to content

added test cases for form submission viewset#3622

Open
praffq wants to merge 1 commit intodevelopfrom
prafful/tests/form-submission
Open

added test cases for form submission viewset#3622
praffq wants to merge 1 commit intodevelopfrom
prafful/tests/form-submission

Conversation

@praffq
Copy link
Copy Markdown
Contributor

@praffq praffq commented Apr 12, 2026

Proposed Changes

  • Added test cases for form submission viewset

Associated Issue

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

  • Tests
    • Added comprehensive test coverage for form submission endpoints, validating access controls, filtering capabilities, state transitions, and error handling across list, create, retrieve, and update operations.

@praffq praffq requested a review from a team as a code owner April 12, 2026 20:33
Copy link
Copy Markdown

@greptile-apps greptile-apps Bot left a comment

Choose a reason for hiding this comment

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

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 12, 2026

📝 Walkthrough

Walkthrough

A new test module for the FormSubmission viewset is introduced, providing comprehensive coverage of list, create, retrieve, update, and delete endpoints, including permission validation, filter enforcement, and completed encounter restrictions across HTTP methods.

Changes

Cohort / File(s) Summary
FormSubmission API Tests
care/emr/tests/test_form_submission_api.py
New test suite with TestFormSubmissionViewSet class covering API endpoint behaviors: list endpoint filtering and permission checks (400/403 for missing filters/permissions, 403 for completed encounters), create endpoint validation (patient/encounter permission checks, encounter-derived patient assignment, response_dump persistence), retrieve endpoint access control, update endpoint modifications with status and response_dump changes (403 for completed encounters, 200 for entered_in_error transitions), and delete endpoint returning 405 (unsupported). Includes setup, helper methods, and test cases for valid/invalid UUIDs and various permission scopes.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description includes proposed changes and associated issue, but lacks critical details and incomplete sections per the repository template. Please fill out the merge checklist section and consider adding more context about the scope and coverage of tests added.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: adding comprehensive test cases for the form submission viewset.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch prafful/tests/form-submission

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
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.

🧹 Nitpick comments (3)
care/emr/tests/test_form_submission_api.py (3)

64-72: Consolidate duplicated permission helper setup.

Both helpers repeat the same role-attachment workflow; a single parameterized helper would reduce copy/paste drift (which we all enjoy maintaining until we don’t).

Proposed refactor
+    def _grant_submit_permission(self, permission_name):
+        permissions = [permission_name]
+        role = self.create_role_with_permissions(permissions)
+        self.attach_role_facility_organization_user(self.organization, self.user, role)
+
     def _grant_patient_submit_permission(self):
-        permissions = [PatientPermissions.can_submit_patient_questionnaire.name]
-        role = self.create_role_with_permissions(permissions)
-        self.attach_role_facility_organization_user(self.organization, self.user, role)
+        self._grant_submit_permission(
+            PatientPermissions.can_submit_patient_questionnaire.name
+        )
 
     def _grant_encounter_submit_permission(self):
-        permissions = [EncounterPermissions.can_submit_encounter_questionnaire.name]
-        role = self.create_role_with_permissions(permissions)
-        self.attach_role_facility_organization_user(self.organization, self.user, role)
+        self._grant_submit_permission(
+            EncounterPermissions.can_submit_encounter_questionnaire.name
+        )

As per coding guidelines, "Prioritize readability and maintainability; follow Django's coding style guide (PEP 8 compliance)."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@care/emr/tests/test_form_submission_api.py` around lines 64 - 72, The two
helpers _grant_patient_submit_permission and _grant_encounter_submit_permission
duplicate the same role creation and attachment logic; replace them with a
single parameterized helper (e.g., _grant_submit_permission or
_grant_permission) that accepts the permission name or enum value, calls
create_role_with_permissions([permission]) and
attach_role_facility_organization_user(self.organization, self.user, role), then
update callers to use the new helper; remove the two duplicated methods to keep
tests DRY and PEP8-compliant.

227-236: Use the created response ID instead of “latest row” selection.

order_by("-id").first() is a bit looser than needed here; selecting by returned id makes the assertion deterministic and easier to reason about.

Proposed refactor
         response = self.client.post(self.base_url, data, format="json")
         self.assertEqual(response.status_code, 200)
-        submission = FormSubmission.objects.order_by("-id").first()
+        submission = FormSubmission.objects.get(external_id=response.json()["id"])
         self.assertEqual(submission.patient, self.encounter.patient)

As per coding guidelines, "Prioritize readability and maintainability; follow Django's coding style guide (PEP 8 compliance)."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@care/emr/tests/test_form_submission_api.py` around lines 227 - 236, The test
test_create_with_encounter_sets_patient_from_encounter uses a loose lookup
FormSubmission.objects.order_by("-id").first() to assert the created
submission’s patient; instead, extract the created submission id from the POST
response (e.g. response.data or response.json() id field returned by
self.client.post) and query FormSubmission.objects.get(pk=that_id) to make the
assertion deterministic and clear, replacing the order_by("-id").first() lookup
with a get by id.

191-198: Rename “invalid UUID” tests to “nonexistent UUID” for precision.

These cases use valid UUIDs that do not exist in DB. Renaming keeps intent crisp and avoids future confusion when malformed-UUID tests are added.

As per coding guidelines, "Use descriptive variable and function names; adhere to naming conventions (e.g., lowercase with underscores for functions and variables)."

Also applies to: 257-269

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@care/emr/tests/test_form_submission_api.py` around lines 191 - 198, Rename
the misleading "invalid_uuid" test functions to "nonexistent_uuid" to reflect
that they use well-formed UUIDs not present in the DB: change
test_list_with_invalid_patient_uuid -> test_list_with_nonexistent_patient_uuid
and test_list_with_invalid_encounter_uuid ->
test_list_with_nonexistent_encounter_uuid (and apply the same renaming pattern
to the similar tests referenced at lines 257-269). Update any local
references/usages of those function names (e.g., in test discovery or comments)
so the new names are used consistently.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@care/emr/tests/test_form_submission_api.py`:
- Around line 64-72: The two helpers _grant_patient_submit_permission and
_grant_encounter_submit_permission duplicate the same role creation and
attachment logic; replace them with a single parameterized helper (e.g.,
_grant_submit_permission or _grant_permission) that accepts the permission name
or enum value, calls create_role_with_permissions([permission]) and
attach_role_facility_organization_user(self.organization, self.user, role), then
update callers to use the new helper; remove the two duplicated methods to keep
tests DRY and PEP8-compliant.
- Around line 227-236: The test
test_create_with_encounter_sets_patient_from_encounter uses a loose lookup
FormSubmission.objects.order_by("-id").first() to assert the created
submission’s patient; instead, extract the created submission id from the POST
response (e.g. response.data or response.json() id field returned by
self.client.post) and query FormSubmission.objects.get(pk=that_id) to make the
assertion deterministic and clear, replacing the order_by("-id").first() lookup
with a get by id.
- Around line 191-198: Rename the misleading "invalid_uuid" test functions to
"nonexistent_uuid" to reflect that they use well-formed UUIDs not present in the
DB: change test_list_with_invalid_patient_uuid ->
test_list_with_nonexistent_patient_uuid and
test_list_with_invalid_encounter_uuid ->
test_list_with_nonexistent_encounter_uuid (and apply the same renaming pattern
to the similar tests referenced at lines 257-269). Update any local
references/usages of those function names (e.g., in test discovery or comments)
so the new names are used consistently.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: c2a1cf02-4521-411d-b784-86f4be2399ae

📥 Commits

Reviewing files that changed from the base of the PR and between 2645cb0 and 8f42b0c.

📒 Files selected for processing (1)
  • care/emr/tests/test_form_submission_api.py

@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 12, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 77.37%. Comparing base (2645cb0) to head (8f42b0c).

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #3622      +/-   ##
===========================================
+ Coverage    77.20%   77.37%   +0.16%     
===========================================
  Files          474      474              
  Lines        22421    22421              
  Branches      2348     2348              
===========================================
+ Hits         17310    17348      +38     
+ Misses        4531     4492      -39     
- Partials       580      581       +1     

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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.

1 participant