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

Remove deprecated imports from a few more apps #8696

Merged
merged 1 commit into from
Nov 14, 2024

Conversation

SpecLad
Copy link
Contributor

@SpecLad SpecLad commented Nov 13, 2024

Motivation and context

This is a continuation of #8626.

How has this been tested?

Checklist

  • I submit my changes into the develop branch
  • [ ] I have created a changelog fragment
  • [ ] I have updated the documentation accordingly
  • [ ] I have added tests to cover my changes
  • [ ] I have linked related issues (see GitHub docs)
  • [ ] I have increased versions of npm packages if it is necessary
    (cvat-canvas,
    cvat-core,
    cvat-data and
    cvat-ui)

License

  • I submit my code changes under the same MIT License that covers the project.
    Feel free to contact the maintainers if that's a concern.

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced error handling in the invoke method to raise ValidationError with appropriate messages for missing mandatory arguments during lambda function invocation.
  • New Features

    • Improved clarity in type hinting across various classes and methods, transitioning to built-in types for consistency and modern Python standards.
  • Documentation

    • Updated comments and documentation to reflect changes in type hinting and error handling improvements.
  • Tests

    • Adjusted type hints in test cases for better alignment with modern Python practices, while maintaining the overall structure and functionality of tests.

Copy link
Contributor

coderabbitai bot commented Nov 13, 2024

Walkthrough

The changes in this pull request involve updating type hints across multiple files to utilize built-in types instead of those from the typing module. This includes modifications to method signatures and attributes in classes, primarily focusing on lists, dictionaries, and tuples. Additionally, there are enhancements to error handling in specific methods to improve clarity. Overall, the changes are syntactical and cosmetic, with no alterations to the core logic or functionality.

Changes

File Change Summary
cvat/apps/events/tests/test_events.py Updated _deserialize method parameter type from List[dict] to list[dict].
cvat/apps/iam/permissions.py Changed reasons attribute type from List[str] to list[str] and updated get_iam_context return type from Dict[str, Any] to dict[str, Any].
cvat/apps/iam/rules/tests/generate_tests.py Removed import of Sequence from typing and imported from collections.abc.
cvat/apps/iam/serializers.py Updated get_email_verification_required and get_key method types from Dict to dict. Enhanced error handling in save method.
cvat/apps/iam/utils.py Changed return type of get_opa_bundle from Tuple[bytes, str] to tuple[bytes, str].
cvat/apps/lambda_manager/tests/test_lambda.py Updated _create_org method type from Dict[int, str] to dict[int, str]. Removed Dict import from typing.
cvat/apps/lambda_manager/views.py Updated invoke and _call_detector method types from Dict to dict. Enhanced error handling in invoke method.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant LambdaFunction
    participant LambdaJob

    User->>LambdaFunction: invoke(db_task, data)
    LambdaFunction->>LambdaJob: _call_detector(function, db_task, labels)
    LambdaJob->>LambdaJob: Check label compatibility
    LambdaJob-->>LambdaFunction: Return results
    LambdaFunction-->>User: Return response
Loading

🐇 "In code we trust, with types so bright,
We hop along, through day and night.
From List to list, we make it clear,
Our functions now shine, bring us good cheer!
With errors caught, and clarity gained,
In the world of Python, we’ve joyfully trained!" 🐇


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

sonarcloud bot commented Nov 13, 2024

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

🧹 Outside diff range and nitpick comments (4)
cvat/apps/iam/utils.py (1)

16-16: LGTM! Consider adding docstring.

The type hint change from Tuple[bytes, str] to tuple[bytes, str] is correct and aligns with PEP 585 (Python 3.9+).

Consider adding a docstring to explain:

  • The purpose of the OPA bundle
  • The format of the returned tuple (bundle bytes and ETag)
  • The caching behavior
 @functools.lru_cache(maxsize=None)
 def get_opa_bundle() -> tuple[bytes, str]:
+    """Generate a tarball containing OPA (Open Policy Agent) rules.
+
+    Returns:
+        tuple[bytes, str]: A tuple containing:
+            - bytes: The gzipped tar bundle of Rego policy files
+            - str: The BLAKE2b hash of the bundle (ETag)
+
+    Note:
+        Results are cached indefinitely using @lru_cache.
+        Cache is invalidated when rules are added via add_opa_rules_path().
+    """
     bundle_file = io.BytesIO()
cvat/apps/iam/serializers.py (2)

Line range hint 1-156: Add tests for authentication-related changes

The PR checklist indicates that no tests were added. Given that this file handles critical authentication functionality, please consider adding tests to verify:

  1. Error handling in the registration flow
  2. Type compatibility with both dict and User objects
  3. Validation error formatting

Would you like me to help create a test suite for these changes?


Review error details exposure in validation error handling

Consider limiting the detail provided by as_serializer_error to prevent potential information disclosure in authentication contexts.

  • cvat/apps/iam/serializers.py: Lines 19-25
🔗 Analysis chain

Line range hint 89-94: Review error details exposure in validation error handling

While the error handling improvement is good, consider reviewing the security implications of exposing detailed validation errors through as_serializer_error. In authentication contexts, it's often better to provide generic error messages to prevent information disclosure.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar error handling patterns in authentication-related files
rg -g '!*.{json,md,yml}' -A 3 'DjangoValidationError.*ValidationError' cvat/apps/iam/

Length of output: 87


Script:

#!/bin/bash
# Search for usages of 'as_serializer_error' in the iam app
rg --glob '!*.{json,md,yml}' 'as_serializer_error' cvat/apps/iam/

Length of output: 158

cvat/apps/iam/permissions.py (1)

37-37: LGTM! Consider extending type hint modernization.

The type hint updates to use built-in collection types (list[str], dict[str, Any]) align with PEP 585 and improve code readability.

Consider updating other type hints in the file to use built-in collection types consistently. For example:

  • url: str
  • user_id: int
  • group_name: Optional[str]
  • org_id: Optional[int]
  • org_owner_id: Optional[int]
  • org_role: Optional[str]
  • scope: str
  • obj: Optional[Any]

These attributes in the OpenPolicyAgentPermission class already use the correct format, but maintaining consistency throughout the codebase would be beneficial.

Also applies to: 87-87

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 506b288 and cebc659.

📒 Files selected for processing (7)
  • cvat/apps/events/tests/test_events.py (2 hunks)
  • cvat/apps/iam/permissions.py (3 hunks)
  • cvat/apps/iam/rules/tests/generate_tests.py (1 hunks)
  • cvat/apps/iam/serializers.py (2 hunks)
  • cvat/apps/iam/utils.py (1 hunks)
  • cvat/apps/lambda_manager/tests/test_lambda.py (2 hunks)
  • cvat/apps/lambda_manager/views.py (4 hunks)
🔇 Additional comments (10)
cvat/apps/iam/rules/tests/generate_tests.py (2)

10-13: LGTM! Good modernization of imports.

The change from typing.Sequence to collections.abc.Sequence follows modern Python best practices and aligns with PEP 585.


10-13: Verify Python version compatibility.

Since collections.abc.Sequence as a generic type requires Python 3.9+, let's verify the project's Python version requirements.

✅ Verification successful

Python version compatibility verified.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check Python version requirements in the project

# Check setup.py or pyproject.toml for Python version constraint
fd -e toml -e py setup pyproject | xargs rg -A 5 'python_requires|python_version'

# Check if there are any Python version related configuration files
fd -e python-version

Length of output: 1019

cvat/apps/iam/serializers.py (1)

35-35: LGTM: Type hints are accurate and helpful

The type hints correctly specify that these methods can handle both dict and User objects, with precise return type annotations.

Also applies to: 39-39

cvat/apps/events/tests/test_events.py (2)

45-45: LGTM! Type hint modernization looks good

The change from List[dict] to list[dict] aligns with PEP 585 for built-in generics while maintaining the same type safety.


8-8: Verify Python version compatibility for type hints

While modernizing type hints to use built-in types, Optional is still imported from typing. This suggests Python < 3.10 compatibility is needed (where Optional wasn't available as |None).

cvat/apps/iam/permissions.py (1)

11-11: LGTM! Good practice with imports.

The import changes follow best practices:

  • Using Sequence from collections.abc
  • Retaining Any, Optional, TypeVar from typing as they don't have built-in equivalents

Also applies to: 14-14

cvat/apps/lambda_manager/views.py (3)

15-15: LGTM! Correct usage of typing imports

The imports of Any and Optional from the typing module are necessary as these types don't have built-in equivalents.


234-237: LGTM! Proper usage of built-in type hints

The change from Dict[str, Any] to dict[str, Any] aligns with PEP 585, using built-in types as generic types.


657-657: LGTM! Consistent type hint modernization

The changes correctly update the type hints to use built-in types while maintaining the nested structure:

  • dict[str, dict[str, Any]] for labels
  • dict[str, str] for mapping

Also applies to: 659-659

cvat/apps/lambda_manager/tests/test_lambda.py (1)

1443-1443: LGTM! Good modernization of type hints.

The change from Dict to dict aligns with Python 3.9+ type hinting best practices, where built-in collection types can be used directly for type annotations. This improves code readability while maintaining the same functionality.

@codecov-commenter
Copy link

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 74.25%. Comparing base (506b288) to head (cebc659).
Report is 1 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #8696      +/-   ##
===========================================
+ Coverage    74.18%   74.25%   +0.06%     
===========================================
  Files          401      401              
  Lines        43496    43496              
  Branches      3950     3950              
===========================================
+ Hits         32269    32296      +27     
+ Misses       11227    11200      -27     
Components Coverage Δ
cvat-ui 78.54% <ø> (+0.04%) ⬆️
cvat-server 70.57% <100.00%> (+0.07%) ⬆️

@SpecLad SpecLad merged commit 111feec into cvat-ai:develop Nov 14, 2024
34 checks passed
@SpecLad SpecLad deleted the deprecated-typing branch November 14, 2024 12:23
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