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 crepr.py #51 #63

Merged
merged 7 commits into from
Oct 3, 2024
Merged

Update crepr.py #51 #63

merged 7 commits into from
Oct 3, 2024

Conversation

Sohammhatre10
Copy link
Contributor

@Sohammhatre10 Sohammhatre10 commented Oct 2, 2024

User description

Summary
This pull request introduces a new command report_missing t which reports classes in specified Python files that do not have a custom repr method defined mentioned in #51

Changes Made
Command Definition: A new command report_missing has been added, which takes a list of file paths as input.
Module Inspection: The command iterates through the provided files, attempts to load each module, and checks for classes that either lack a repr method or use the default implementation from the object class.
Error handling using CreprError.
Output: Classes missing a custom repr method are reported with their file paths and line numbers for easy identification.
Motivation
Having a custom repr method improves the readability and debugging of classes by providing meaningful string representations. This command helps developers ensure that their classes follow this best practice.

How to Test
Run the command in the terminal with a specified Python file as follows:

!crepr report-missing <your-filename>

Expected output is of the form

file-name : line-number : class-name 

PR Type

enhancement, error handling


Description

  • Introduced a new command report_missing to identify classes in specified Python files that do not have a custom __repr__ method.
  • Implemented error handling using CreprError to manage exceptions during module inspection.
  • Added report_missing_classes function to iterate through modules and report classes missing a __repr__ method with their file paths and line numbers.

Changes walkthrough 📝

Relevant files
Enhancement
crepr.py
Add command to report missing __repr__ methods in classes

crepr/crepr.py

  • Added a new command report_missing to identify classes without a
    custom __repr__ method.
  • Implemented error handling using CreprError for the new command.
  • Introduced report_missing_classes function to inspect modules and
    report missing __repr__ methods.
  • +27/-0   

    💡 PR-Agent usage: Comment /help "your question" on any pull request to receive relevant information

    Summary by Sourcery

    Add a new command 'report_missing' to the crepr tool, which reports classes without a custom repr method in specified Python files, enhancing code readability and debugging.

    New Features:

    • Introduce a new command 'report_missing' that identifies classes in specified Python files lacking a custom repr method.

    Summary by CodeRabbit

    • New Features

      • Introduced a report_missing command to identify classes lacking a __repr__ method.
      • Users can input file paths to check for classes without a defined __repr__.
    • Bug Fixes

      • Enhanced test coverage for the report_missing command with new test cases for various scenarios.
    • Documentation

      • Added docstrings for the new command and helper function to clarify their purpose and usage.

    Signed-off-by: Soham Mhatre <[email protected]>
    Copy link

    semanticdiff-com bot commented Oct 2, 2024

    Review changes with SemanticDiff.

    Analyzed 5 of 5 files.

    Overall, the semantic diff is 10% smaller than the GitHub diff.

    Filename Status
    ✔️ tests/run_test.py Analyzed
    ✔️ tests/classes/class_with_repr_test.py Analyzed
    ✔️ tests/classes/class_without_repr.py 35.71% smaller
    ✔️ tests/classes/module_error.py 33.33% smaller
    ✔️ crepr/crepr.py Analyzed

    Copy link

    sourcery-ai bot commented Oct 2, 2024

    Reviewer's Guide by Sourcery

    This pull request introduces a new command 'report_missing' to the crepr tool. The command identifies and reports classes in specified Python files that lack a custom repr method. This feature aids developers in ensuring their classes follow the best practice of having meaningful string representations for improved readability and debugging.

    Sequence diagram for the report_missing command

    sequenceDiagram
        actor User
        participant CreprTool as Crepr Tool
        participant FileSystem as File System
        participant ModuleLoader as Module Loader
        participant Reporter as Reporter
    
        User->>CreprTool: Run `crepr report-missing <file>`
        CreprTool->>FileSystem: Read file paths
        FileSystem-->>CreprTool: File paths
        CreprTool->>ModuleLoader: Load module from file
        ModuleLoader-->>CreprTool: Module
        CreprTool->>Reporter: Check classes for __repr__
        Reporter-->>CreprTool: Report missing __repr__
        CreprTool->>User: Display report
    
    Loading

    Class diagram for the updated crepr.py

    classDiagram
        class CreprTool {
            +report_missing(files: list[pathlib.Path])
        }
        class ModuleLoader {
            +get_module(file_path: pathlib.Path) : ModuleType
        }
        class Reporter {
            +report_missing_classes(module: ModuleType, file_path: pathlib.Path)
        }
        CreprTool --> ModuleLoader
        CreprTool --> Reporter
        Reporter --> CreprError
        class CreprError {
            +message: str
        }
    
    Loading

    File-Level Changes

    Change Details Files
    Implement new 'report_missing' command
    • Add a new command 'report_missing' that takes a list of file paths as input
    • Implement logic to iterate through provided files and load modules
    • Add functionality to check for classes without a custom repr method
    • Implement error handling using CreprError
    • Add output formatting for reporting missing repr methods with file paths and line numbers
    crepr/crepr.py
    Create helper function for reporting missing classes
    • Implement 'report_missing_classes' function to inspect modules for classes without repr
    • Use inspect.getattr_static to check for the presence of repr method
    • Add logic to identify classes using the default object.repr
    crepr/crepr.py

    Tips and commands

    Interacting with Sourcery

    • Trigger a new review: Comment @sourcery-ai review on the pull request.
    • Continue discussions: Reply directly to Sourcery's review comments.
    • Generate a GitHub issue from a review comment: Ask Sourcery to create an
      issue from a review comment by replying to it.

    Customizing Your Experience

    Access your dashboard to:

    • Enable or disable review features such as the Sourcery-generated pull request
      summary, the reviewer's guide, and others.
    • Change the review language.
    • Add, remove or edit custom review instructions.
    • Adjust other review settings.

    Getting Help

    Copy link

    coderabbitai bot commented Oct 2, 2024

    Walkthrough

    The pull request introduces a new command, report_missing, to the typer application in crepr/crepr.py. This command allows users to identify classes that lack a __repr__ method by processing a list of specified file paths. It includes a helper function, report_missing_classes, which checks each class in the module for the presence of a __repr__ method. If a class is found without this method, its name and line number are printed. The existing commands remain unchanged.

    Changes

    File Change Summary
    crepr/crepr.py Added report_missing command and report_missing_classes helper function.
    tests/classes/class_with_repr_test.py Added MyClassWithRepr class with __init__ and __repr__ methods.
    tests/classes/class_without_repr.py Added MyClassWithoutRepr class with __init__ method, no __repr__.
    tests/classes/module_error.py Created module_error.py for testing, includes an import for a non-existent module.
    tests/run_test.py Added tests for report_missing command: test_report_missing, test_report_missing_error, test_report_missing_with_repr.

    Possibly related PRs

    • v 0.3.0 #30: The changes in crepr/crepr.py related to the addition of the report_missing command are directly connected to the updates made in the same file in this PR, which also enhances functionality within the crepr module.

    Suggested labels

    documentation, Review effort [1-5]: 4

    🐇 In the meadow, I hop with glee,
    Reporting classes, come see,
    If __repr__ is missing, don't despair,
    My new command will find it there!
    With paths and line numbers, I'll share,
    A tidy output, for all to care!
    🌼


    📜 Recent review details

    Configuration used: CodeRabbit UI
    Review profile: CHILL

    📥 Commits

    Files that changed from the base of the PR and between 38b190a and e664a7c.

    📒 Files selected for processing (1)
    • tests/classes/class_with_repr_test.py (1 hunks)
    🚧 Files skipped from review as they are similar to previous changes (1)
    • tests/classes/class_with_repr_test.py

    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.

    @qodo-merge-pro qodo-merge-pro bot added enhancement New feature or request error handling labels Oct 2, 2024
    Copy link

    @ellipsis-dev ellipsis-dev bot left a comment

    Choose a reason for hiding this comment

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

    👍 Looks good to me! Reviewed everything up to 9bae721 in 9 seconds

    More details
    • Looked at 37 lines of code in 1 files
    • Skipped 0 files when reviewing.
    • Skipped posting 1 drafted comments based on config settings.
    1. crepr/crepr.py:401
    • Draft comment:
      The get_all_init_args function filters out classes without __init__ methods or with non-keyword arguments. This may cause report_missing_classes to miss classes that should be reported. Consider using a function that iterates over all classes in the module.
    • Reason this comment was not posted:
      Comment was on unchanged code.

    Workflow ID: wflow_YLyCDhbfxTF2i2uW


    You can customize Ellipsis with 👍 / 👎 feedback, review rules, user-specific overrides, quiet mode, and more.

    Copy link

    qodo-merge-pro bot commented Oct 2, 2024

    PR-Agent was enabled for this repository. To continue using it, please link your git user with your CodiumAI identity here.

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Error Handling
    The error handling in the report_missing function catches CreprError, but it's unclear where this exception is raised. Consider adding more specific error handling or documenting where CreprError is expected to be raised.

    Code Duplication
    The report_missing_classes function uses get_all_init_args(module), which is likely similar to existing code for other commands. Consider refactoring to reduce duplication if possible.

    Performance Consideration
    The report_missing_classes function checks each class's __repr__ method individually. For large modules with many classes, this could be inefficient. Consider optimizing this process for better performance with large codebases.

    Copy link

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Error Handling
    The error handling in the report_missing function catches CreprError, but it's unclear if this covers all possible exceptions that could occur during module inspection.

    Code Duplication
    The get_module function is called in report_missing, but its implementation is not visible in this diff. Ensure it's not duplicating functionality already present in the codebase.

    Performance Consideration
    The report_missing_classes function uses inspect.getattr_static for each object, which might be inefficient for large modules with many classes.

    Copy link

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Score
    Enhancement
    Improve variable naming for better code readability

    Consider using a more descriptive variable name instead of obj in the
    report_missing_classes function. Since we're dealing with classes, a name like
    class_obj or cls would be more appropriate and improve code readability.

    crepr/crepr.py [401-404]

    -for obj, _, lineno, _ in get_all_init_args(module):
    -    repr_method = inspect.getattr_static(obj, "__repr__", None)
    +for cls, _, lineno, _ in get_all_init_args(module):
    +    repr_method = inspect.getattr_static(cls, "__repr__", None)
         if repr_method is None or repr_method is object.__repr__:
    -        typer.echo(f"{file_path}: {lineno}: {obj.__name__}")
    +        typer.echo(f"{file_path}: {lineno}: {cls.__name__}")
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why:

    7
    Possible issue
    Add a check for None module to prevent potential errors

    Consider adding a check to ensure that module is not None before proceeding with the
    inspection in the report_missing_classes function. This can help prevent potential
    AttributeErrors if get_module returns None for some reason.

    crepr/crepr.py [393-401]

     def report_missing_classes(module: ModuleType, file_path: pathlib.Path) -> None:
         """Report classes missing a __repr__ method in the specified module.
     
         Args:
             module (ModuleType): The module to inspect for classes.
             file_path (pathlib.Path): File path for the class.
     
         """
    +    if module is None:
    +        typer.echo(f"Error: Could not inspect module for {file_path}")
    +        return
         for obj, _, lineno, _ in get_all_init_args(module):
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why:

    7
    Error handling
    Add error handling for potential exceptions during module inspection

    Consider adding error handling for the get_all_init_args function call in
    report_missing_classes. If this function raises an exception, it will propagate and
    potentially crash the entire command. Adding a try-except block would make the
    function more robust.

    crepr/crepr.py [393-404]

     def report_missing_classes(module: ModuleType, file_path: pathlib.Path) -> None:
         """Report classes missing a __repr__ method in the specified module.
     
         Args:
             module (ModuleType): The module to inspect for classes.
             file_path (pathlib.Path): File path for the class.
     
         """
    -    for obj, _, lineno, _ in get_all_init_args(module):
    -        repr_method = inspect.getattr_static(obj, "__repr__", None)
    -        if repr_method is None or repr_method is object.__repr__:
    -            typer.echo(f"{file_path}: {lineno}: {obj.__name__}")
    +    try:
    +        for obj, _, lineno, _ in get_all_init_args(module):
    +            repr_method = inspect.getattr_static(obj, "__repr__", None)
    +            if repr_method is None or repr_method is object.__repr__:
    +                typer.echo(f"{file_path}: {lineno}: {obj.__name__}")
    +    except Exception as e:
    +        typer.echo(f"Error inspecting {file_path}: {str(e)}", err=True)
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why:

    7

    💡 Need additional feedback ? start a PR chat

    Copy link

    qodo-merge-pro bot commented Oct 2, 2024

    PR-Agent was enabled for this repository. To continue using it, please link your git user with your CodiumAI identity here.

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Score
    Error handling
    Add error handling for potential exceptions in the function

    Consider adding error handling for the case where get_all_init_args(module) might
    raise an exception. This will make the report_missing_classes function more robust
    and prevent unexpected crashes.

    crepr/crepr.py [393-404]

     def report_missing_classes(module: ModuleType, file_path: pathlib.Path) -> None:
         """Report classes missing a __repr__ method in the specified module.
     
         Args:
             module (ModuleType): The module to inspect for classes.
             file_path (pathlib.Path): File path for the class.
     
         """
    -    for obj, _, lineno, _ in get_all_init_args(module):
    -        repr_method = inspect.getattr_static(obj, "__repr__", None)
    -        if repr_method is None or repr_method is object.__repr__:
    -            typer.echo(f"{file_path}: {lineno}: {obj.__name__}")
    +    try:
    +        for obj, _, lineno, _ in get_all_init_args(module):
    +            repr_method = inspect.getattr_static(obj, "__repr__", None)
    +            if repr_method is None or repr_method is object.__repr__:
    +                typer.echo(f"{file_path}: {lineno}: {obj.__name__}")
    +    except Exception as e:
    +        typer.secho(f"Error processing {file_path}: {str(e)}", fg="red", err=True)
    • Apply this suggestion
    Suggestion importance[1-10]: 9

    Why: Adding error handling for potential exceptions is highly beneficial. It enhances the robustness of the function and prevents unexpected crashes, which is crucial for maintaining stability.

    9
    Possible issue
    Add a check to ensure the object is a class before processing

    Consider adding a check to ensure that obj is actually a class before processing it.
    This will make the function more robust and prevent potential errors if non-class
    objects are encountered.

    crepr/crepr.py [401-404]

     for obj, _, lineno, _ in get_all_init_args(module):
    -    repr_method = inspect.getattr_static(obj, "__repr__", None)
    -    if repr_method is None or repr_method is object.__repr__:
    -        typer.echo(f"{file_path}: {lineno}: {obj.__name__}")
    +    if inspect.isclass(obj):
    +        repr_method = inspect.getattr_static(obj, "__repr__", None)
    +        if repr_method is None or repr_method is object.__repr__:
    +            typer.echo(f"{file_path}: {lineno}: {obj.__name__}")
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: Adding a check to ensure the object is a class before processing is a significant improvement. It prevents potential errors and makes the function more robust, which is crucial for reliability.

    8
    Maintainability
    Use a more descriptive variable name for clarity

    Consider using a more descriptive variable name instead of obj in the
    report_missing_classes function. This will make the code more readable and
    self-explanatory. For example, you could use class_obj or potential_class.

    crepr/crepr.py [401-404]

    -for obj, _, lineno, _ in get_all_init_args(module):
    -    repr_method = inspect.getattr_static(obj, "__repr__", None)
    +for class_obj, _, lineno, _ in get_all_init_args(module):
    +    repr_method = inspect.getattr_static(class_obj, "__repr__", None)
         if repr_method is None or repr_method is object.__repr__:
    -        typer.echo(f"{file_path}: {lineno}: {obj.__name__}")
    +        typer.echo(f"{file_path}: {lineno}: {class_obj.__name__}")
    • Apply this suggestion
    Suggestion importance[1-10]: 5

    Why: The suggestion to use a more descriptive variable name improves code readability and maintainability. While not critical, it enhances understanding of the code's purpose.

    5
    Best practice
    Use f-strings for string formatting

    Consider using f-strings for string formatting in the report_missing function. This
    can make the code more readable and consistent with modern Python practices.

    crepr/crepr.py [390]

    -typer.secho(e.message, fg="red", err=True)
    +typer.secho(f"{e.message}", fg="red", err=True)
    • Apply this suggestion
    Suggestion importance[1-10]: 3

    Why: The suggestion to use f-strings for string formatting is a minor improvement. It aligns with modern Python practices but does not significantly impact functionality or readability.

    3

    💡 Need additional feedback ? start a PR chat

    Copy link

    @sourcery-ai sourcery-ai bot left a comment

    Choose a reason for hiding this comment

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

    Hey @Sohammhatre10 - I've reviewed your changes and they look great!

    Here's what I looked at during the review
    • 🟡 General issues: 1 issue found
    • 🟢 Security: all looks good
    • 🟢 Testing: all looks good
    • 🟢 Complexity: all looks good
    • 🟢 Documentation: all looks good

    Sourcery is free for open source - if you like our reviews please consider sharing them ✨
    Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

    crepr/crepr.py Show resolved Hide resolved
    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: 1

    🧹 Outside diff range and nitpick comments (2)
    crepr/crepr.py (2)

    380-391: LGTM! Consider enhancing error handling.

    The report_missing function is well-implemented and aligns with the PR objectives. It correctly uses existing functionality and delegates the reporting to a separate function.

    Consider adding a try-except block around the report_missing_classes call to handle any unexpected errors that might occur during the reporting process. This would make the function more robust:

    try:
        module = get_module(file_path)
        report_missing_classes(module, file_path)
    except CreprError as e:
        typer.secho(e.message, fg="red", err=True)
    except Exception as e:
        typer.secho(f"Unexpected error processing {file_path}: {str(e)}", fg="red", err=True)

    393-404: LGTM! Consider enhancing readability.

    The report_missing_classes function is well-implemented and correctly identifies classes without custom __repr__ methods. The output format aligns with the PR objectives.

    To improve readability, consider extracting the condition for checking if a class is missing a custom __repr__ method into a separate function. This would make the main loop easier to understand at a glance:

    def is_missing_custom_repr(obj: type) -> bool:
        repr_method = inspect.getattr_static(obj, "__repr__", None)
        return repr_method is None or repr_method is object.__repr__
    
    def report_missing_classes(module: ModuleType, file_path: pathlib.Path) -> None:
        for obj, _, lineno, _ in get_all_init_args(module):
            if is_missing_custom_repr(obj):
                typer.echo(f"{file_path}: {lineno}: {obj.__name__}")

    This change would make the function more modular and easier to test.

    📜 Review details

    Configuration used: CodeRabbit UI
    Review profile: CHILL

    📥 Commits

    Files that changed from the base of the PR and between 73edf14 and 9bae721.

    📒 Files selected for processing (1)
    • crepr/crepr.py (1 hunks)

    crepr/crepr.py Outdated Show resolved Hide resolved
    Copy link

    codecov bot commented Oct 2, 2024

    Codecov Report

    Attention: Patch coverage is 92.00000% with 2 lines in your changes missing coverage. Please review.

    Project coverage is 99.37%. Comparing base (73edf14) to head (e664a7c).
    Report is 8 commits behind head on develop.

    Files with missing lines Patch % Lines
    tests/run_test.py 87.50% 1 Missing and 1 partial ⚠️
    Additional details and impacted files
    @@             Coverage Diff             @@
    ##           develop      #63      +/-   ##
    ===========================================
    + Coverage    98.97%   99.37%   +0.39%     
    ===========================================
      Files            4        4              
      Lines          294      319      +25     
      Branches        38       44       +6     
    ===========================================
    + Hits           291      317      +26     
    + Misses           3        1       -2     
    - Partials         0        1       +1     

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

    @Sohammhatre10
    Copy link
    Contributor Author

    Hello @cleder,
    Codecov is flagging lines 390, 402, and 404 in crepr/crepr.py as not covered by tests, leading to the coverage error. Could you provide some guidance on the best approach to resolve this?

    @cleder cleder changed the title Update crepr.py Update crepr.py #51 Oct 2, 2024
    @cleder
    Copy link
    Owner

    cleder commented Oct 2, 2024

    Run pytest --cov=crepr --cov-report=term-missing to produce the test coverage report see also

    crepr/crepr.py Outdated Show resolved Hide resolved
    crepr/crepr.py Outdated Show resolved Hide resolved
    @cleder cleder linked an issue Oct 2, 2024 that may be closed by this pull request
    Signed-off-by: Soham Mhatre <[email protected]>
    Signed-off-by: Soham Mhatre <[email protected]>
    Signed-off-by: Soham Mhatre <[email protected]>
    @Sohammhatre10
    Copy link
    Contributor Author

    1. Have added tests for report-missing and report_missing_classes functions along with a check for CreprError error handle call.
    2. Have implemented the changes mentioned here Update crepr.py #51 #63 (comment)

    @Sohammhatre10 Sohammhatre10 requested a review from cleder October 3, 2024 07:07
    @cleder cleder enabled auto-merge October 3, 2024 08:25
    auto-merge was automatically disabled October 3, 2024 10:37

    Head branch was pushed to by a user without write access

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

    🧹 Outside diff range and nitpick comments (6)
    tests/classes/class_without_repr.py (1)

    12-14: LGTM! Well-implemented __init__ method with modern type hinting.

    The __init__ method is correctly implemented:

    • Clear method signature with type hints
    • Concise docstring
    • Proper initialization of instance variable

    Minor suggestion: Consider adding a comment or note in the project documentation about the minimum required Python version (3.11+) due to the use of Self type hint. This ensures compatibility awareness for users or contributors.

    tests/classes/class_with_repr_test.py (2)

    1-8: LGTM with a minor suggestion.

    The module docstring clearly describes the purpose of the module, and the import of Self from typing is appropriate for type hinting. However, there's an extra blank line (line 8) that could be removed for better code organization.

    Consider removing the extra blank line at line 8.


    16-22: LGTM with a minor docstring correction.

    The __repr__ method is well-implemented, providing a clear and informative string representation of the object. The use of type hinting and f-strings is correct, and the formatting follows best practices for __repr__ methods.

    There's a minor typo in the docstring. Please update it as follows:

    def __repr__(self: Self) -> str:
        """Create a string representation for MyClassWithRepr."""
    tests/run_test.py (3)

    291-300: LGTM with a suggestion for improvement.

    The test correctly verifies the basic functionality of the report-missing command. It checks both the exit code and the presence of expected content in the output.

    Consider enhancing the test to verify the exact format of the output, including the line number. This would ensure that the command is providing all the required information in the correct format. You could add an assertion like:

    assert re.match(r'class_without_repr\.py : \d+ : MyClassWithoutRepr', result.stdout)

    This would verify that the output matches the expected format: file-name : line-number : class-name.


    311-320: LGTM with a minor correction needed.

    The test correctly verifies the behavior of the report-missing command when all classes have a __repr__ method. It checks for a successful exit code and ensures that there is no output.

    There's a minor inconsistency in the assertion message. The message suggests expecting 1 line of output, but the assertion checks for 0 lines. Please update the assertion message to reflect the correct expectation:

    assert len(lines) == 0, "Expected 0 lines of output, but got more"

    This will make the test more clear and consistent with its actual expectations.


    291-320: Summary of the new test additions

    The new tests for the report-missing command are a valuable addition to the test suite, covering various scenarios including:

    1. Classes without __repr__
    2. Files that cause import errors
    3. Classes with __repr__

    While these tests improve coverage, there are opportunities for enhancement:

    1. In test_report_missing, consider verifying the exact output format, including line numbers.
    2. test_report_missing_error needs restructuring to properly assert the expected error behavior.
    3. test_report_missing_with_repr has a minor inconsistency in its assertion message.

    Addressing these points will result in a more robust and informative test suite for the new functionality.

    As you continue to develop and refine these tests, consider the following best practices:

    1. Use parameterized tests to cover multiple scenarios efficiently.
    2. Ensure consistent error handling and assertion styles across all tests.
    3. Mock external dependencies when appropriate to isolate the functionality being tested.
    4. Maintain clear and accurate documentation within the tests to explain the purpose and expected outcomes.
    📜 Review details

    Configuration used: CodeRabbit UI
    Review profile: CHILL

    📥 Commits

    Files that changed from the base of the PR and between 9bae721 and 38b190a.

    📒 Files selected for processing (5)
    • crepr/crepr.py (1 hunks)
    • tests/classes/class_with_repr_test.py (1 hunks)
    • tests/classes/class_without_repr.py (1 hunks)
    • tests/classes/module_error.py (1 hunks)
    • tests/run_test.py (1 hunks)
    ✅ Files skipped from review due to trivial changes (1)
    • tests/classes/module_error.py
    🚧 Files skipped from review as they are similar to previous changes (1)
    • crepr/crepr.py
    🔇 Additional comments (5)
    tests/classes/class_without_repr.py (3)

    1-8: LGTM! Well-structured file with clear documentation.

    The file structure follows best practices:

    • Informative module-level docstring
    • Correct import placement
    • Proper use of whitespace

    9-11: LGTM! Class definition aligns with its intended purpose.

    The MyClassWithoutRepr class is well-defined:

    • Clear and descriptive class name
    • Concise class-level docstring
    • Intentional absence of __repr__ method for testing purposes

    1-14: Summary: Excellent implementation of test class for report_missing command.

    This new test file aligns perfectly with the PR objectives:

    1. It provides a class without a custom __repr__ method, which is ideal for testing the report_missing command.
    2. The clear structure and documentation contribute to the overall quality of the test suite.
    3. This addition will help ensure the reliability of the new report_missing functionality.

    Great job on implementing this test class! It will be valuable for verifying the behavior of the new command.

    tests/classes/class_with_repr_test.py (2)

    12-14: LGTM! Well-implemented __init__ method.

    The __init__ method is correctly implemented with proper type hinting, including the use of Self. The docstring accurately describes the method's purpose, and the initialization of the value attribute is straightforward and correct.


    1-22: Summary: Well-implemented test class with minor docstring improvements needed.

    This new file successfully implements a test class MyClassWithRepr with a custom __repr__ method, which aligns with the PR objectives. The implementation is generally good, with proper use of type hinting and following Python best practices.

    A few minor improvements are suggested:

    1. Remove the extra blank line (line 8).
    2. Correct the class docstring to accurately describe the class.
    3. Fix the typo in the __repr__ method docstring.

    These changes will enhance the clarity and accuracy of the code documentation.

    tests/classes/class_with_repr_test.py Outdated Show resolved Hide resolved
    tests/run_test.py Show resolved Hide resolved
    @Sohammhatre10
    Copy link
    Contributor Author

    Sohammhatre10 commented Oct 3, 2024

    @cleder Apologies for the oversight here had mixed up the class_with_repr.py test file and class_without_repr.py test file which caused cpython 3.12 to fail

    @cleder cleder merged commit c3ec795 into cleder:develop Oct 3, 2024
    10 of 11 checks passed
    @Sohammhatre10
    Copy link
    Contributor Author

    @cleder Will you please add the hacktoberfest-accepted tag on this.
    Thanks!

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

    Successfully merging this pull request may close these issues.

    Add command to report classes without a __repr__
    2 participants