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 tests for questionnaire and few minor changes #2745

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from

Conversation

DraKen0009
Copy link
Contributor

@DraKen0009 DraKen0009 commented Jan 17, 2025

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 questionnaire validation with new checks for choice and URL questions
    • Improved permission handling for questionnaire submissions
  • Bug Fixes

    • Refined permission logic for questionnaire updates and submissions
  • Tests

    • Added comprehensive test suite for questionnaire API
    • Implemented validation tests for different question types and permissions
    • Added utility method for creating superuser in test environment

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

coderabbitai bot commented Jan 17, 2025

📝 Walkthrough

Walkthrough

The 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 QuestionnaireViewSet, enhancing data validation utilities, and expanding the test suite for comprehensive coverage. The modifications aim to streamline permission logic and strengthen input validation for questionnaire submissions.

Changes

File Change Summary
care/emr/api/viewsets/questionnaire.py - Removed "update" action from permissions check
- Simplified submit method's permission logic
care/emr/resources/questionnaire/utils.py - Added get_valid_choices() function
- Enhanced validate_data() with choice and URL validations
- Updated date/datetime parsing
care/emr/tests/test_questionnaire_api.py - Added comprehensive test classes for questionnaire API
- Implemented validation and permission tests
care/utils/tests/base.py - Added create_super_user() method to CareAPITestBase

Sequence Diagram

sequenceDiagram
    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
Loading

Possibly related PRs

Suggested reviewers

  • bodhish
  • vigneshhari

Poem

🧐 Permissions dance, a subtle art
Code refactored, a brand new start
Validators sing their validation song
Testing frameworks, now standing strong
Questionnaires whisper their digital delight 🌟

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

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

224-249: Consider testing all question types for comprehensive validation

While 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:

  1. Moving format strings to constants
  2. 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 DTZ007

And 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:

  1. More descriptive error messages
  2. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9994737 and 9368366.

📒 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 submitting None values activates the questionnaire as intended

In test_active_questionnaire_modification_prevented, the test submits a response with None 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 of create_super_user method enhances test capabilities

The 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 changes

The permissions_controller method no longer includes "update" in the actions requiring can_write_questionnaire permission. Instead, updates are now restricted to superusers via the authorize_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.

Copy link

codecov bot commented Jan 17, 2025

Codecov Report

Attention: Patch coverage is 75.00000% with 5 lines in your changes missing coverage. Please review.

Project coverage is 61.92%. Comparing base (9994737) to head (9368366).

Files with missing lines Patch % Lines
care/emr/resources/questionnaire/utils.py 82.35% 2 Missing and 1 partial ⚠️
care/emr/api/viewsets/questionnaire.py 33.33% 1 Missing and 1 partial ⚠️
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.
📢 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.

1 participant