-
Notifications
You must be signed in to change notification settings - Fork 333
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 tests for questionnaire and few minor changes #2745
base: develop
Are you sure you want to change the base?
Conversation
📝 WalkthroughWalkthroughThe pull request introduces modifications to the questionnaire API's permission handling and validation logic. Changes span across multiple files, focusing on refining permission checks in the Changes
Sequence DiagramsequenceDiagram
participant User
participant QuestionnaireViewSet
participant ValidationUtils
participant Database
User->>QuestionnaireViewSet: Submit Questionnaire
QuestionnaireViewSet->>ValidationUtils: Validate Questionnaire Data
ValidationUtils-->>QuestionnaireViewSet: Validation Result
alt Validation Successful
QuestionnaireViewSet->>Database: Save Questionnaire
Database-->>QuestionnaireViewSet: Save Confirmation
QuestionnaireViewSet-->>User: Success Response
else Validation Failed
QuestionnaireViewSet-->>User: Error Response
end
Possibly related PRs
Suggested reviewers
Poem
Finishing Touches
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 (5)
care/emr/tests/test_questionnaire_api.py (1)
224-249
: Consider testing all question types for comprehensive validationWhile the
test_individual_invalid_submissions
method covers several question types, it omits tests for'string'
,'text'
, and'structured'
. Including these types would ensure that all question variants are properly validated, preventing potential issues with untested types.care/emr/resources/questionnaire/utils.py (4)
30-40
: Would it kill you to add some type hints?The function looks good, but it could benefit from:
- Type hints for parameters and return value
- Validation that answer_option is actually a list
-def get_valid_choices(question): +def get_valid_choices(question: dict) -> list[str]: """ Extracts valid choices from a choice question dictionary. + + Args: + question: The question dictionary containing answer options + Returns: + List of valid choice values + Raises: + ValueError: If no answer options are found """ answer_options = question.get("answer_option", []) - if not answer_options: + if not isinstance(answer_options, list) or not answer_options: error = f"No 'answer_option' found in question with id {question.get('id')}." raise ValueError(error)
66-68
: Perhaps we could make the date formats a bit more... informative?The switch to explicit format strings is good, but consider:
- Moving format strings to constants
- Including the expected format in error messages
+DATE_FORMAT = "%Y-%m-%d" +DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S" +TIME_FORMAT = "%H:%M:%S" - datetime.strptime(value.value, "%Y-%m-%d").date() # noqa DTZ007 + datetime.strptime(value.value, DATE_FORMAT).date() # noqa DTZ007 - datetime.strptime(value.value, "%Y-%m-%dT%H:%M:%S") # noqa DTZ007 + datetime.strptime(value.value, DATETIME_FORMAT) # noqa DTZ007And in the error handling:
- errors.append(f"Invalid {value_type}") + errors.append(f"Invalid {value_type}. Expected format: {DATE_FORMAT if value_type == QuestionType.date.value else DATETIME_FORMAT}")
74-77
: The URL validation is a bit... minimalist, isn't it?While checking scheme and netloc is a good start, consider:
- More descriptive error messages
- Additional validations for common URL issues
elif value_type == QuestionType.url.value: parsed = urlparse(value.value) if not all([parsed.scheme, parsed.netloc]): - errors.append(f"Invalid {value_type}") + missing = [] + if not parsed.scheme: + missing.append("scheme (e.g., http, https)") + if not parsed.netloc: + missing.append("network location (e.g., example.com)") + errors.append(f"Invalid URL: missing {' and '.join(missing)}") + elif parsed.scheme not in ['http', 'https']: + errors.append(f"Invalid URL: scheme must be http or https")
42-42
: That noqa PLR0912 is practically begging for a refactor...The
validate_data
function has grown quite complex. Consider splitting it into smaller, focused validation functions for each type:
- validate_numeric_value
- validate_date_value
- validate_choice_value
- validate_url_value
This would improve maintainability and make it easier to add new validations in the future. Would you like me to provide an example of how this could be structured?
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
care/emr/api/viewsets/questionnaire.py
(2 hunks)care/emr/resources/questionnaire/utils.py
(3 hunks)care/emr/tests/test_questionnaire_api.py
(1 hunks)care/utils/tests/base.py
(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: test / test
🔇 Additional comments (3)
care/emr/tests/test_questionnaire_api.py (1)
620-653
: Verify that submittingNone
values activates the questionnaire as intendedIn
test_active_questionnaire_modification_prevented
, the test submits a response withNone
values to activate the questionnaire. It would be wise to confirm that this approach effectively activates the questionnaire without causing validation errors, ensuring the test accurately reflects the desired behavior.care/utils/tests/base.py (1)
16-19
: Addition ofcreate_super_user
method enhances test capabilitiesThe
create_super_user
method is correctly implemented, allowing for efficient creation of superuser accounts in tests. This addition will facilitate testing scenarios that require elevated privileges.care/emr/api/viewsets/questionnaire.py (1)
Line range hint
83-88
: Confirm intention behind update permission changesThe
permissions_controller
method no longer includes"update"
in the actions requiringcan_write_questionnaire
permission. Instead, updates are now restricted to superusers via theauthorize_update
method. Just to be sure, please verify that this change aligns with the desired permission model and that regular users with write permissions are no longer expected to update questionnaires.
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #2745 +/- ##
===========================================
+ Coverage 60.49% 61.92% +1.42%
===========================================
Files 252 252
Lines 12707 12719 +12
Branches 1111 1116 +5
===========================================
+ Hits 7687 7876 +189
+ Misses 4951 4735 -216
- Partials 69 108 +39 ☔ View full report in Codecov by Sentry. |
Merge Checklist
/docs
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
Bug Fixes
Tests