Skip to content

Conversation

@Czaki
Copy link
Collaborator

@Czaki Czaki commented Sep 19, 2024

Change pytest configuration to change warnings into errors in the tests.

Fix code that emites warning.

Summary by Sourcery

Convert warnings to errors in tests by updating the pytest configuration and refactor code to handle warnings appropriately. Enhance the sentry_sdk usage by replacing push_scope with new_scope. Improve data handling in batch_backend.py and update tests to align with these changes.

Bug Fixes:

  • Fix the test_no_update test to correctly handle URL errors by using urllib.error.URLError.
  • Correct the test_ignore_file_exists_old_date test to assert the correct release version and URL.

Enhancements:

  • Update the sentry_sdk usage to replace push_scope with new_scope for better scope management.
  • Improve the CheckVersionThread initialization by updating the default URL to a more relevant one.
  • Enhance the get_data_to_write method in batch_backend.py to handle empty data frames more efficiently.
  • Refactor the decode_zstd1 and decode_zstd0 functions to use np.frombuffer instead of np.fromstring for better performance and compatibility.

Tests:

  • Modify tests to treat warnings as errors by updating the pytest configuration.
  • Update tests to reflect changes in the sentry_sdk scope management.

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced handling of color information in ROI parameters, allowing for greater flexibility with color keys.
    • Improved compatibility with newer versions of napari by adjusting colormap settings.
  • Bug Fixes

    • Ensured default color values are returned correctly when no regions of interest are present.
  • Documentation

    • Updated type annotations for better clarity and usability.
  • Tests

    • Enhanced test cases related to color handling and ROI parameters to improve robustness.
    • Added version checks for napari to ensure correct behavior based on library version.

@Czaki Czaki added this to the 0.15.4 milestone Sep 19, 2024
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Sep 19, 2024

Reviewer's Guide by Sourcery

This pull request focuses on changing warnings into errors in tests and fixing code that emits warnings. The changes primarily involve updating the Sentry SDK usage, modifying pytest configurations, and addressing deprecated functions in various parts of the codebase.

File-Level Changes

Change Details Files
Update Sentry SDK usage
  • Replace Hub.current.bind_client(client) with scope.set_client(client)
  • Change sentry_sdk.push_scope() to sentry_sdk.new_scope()
  • Update error capturing and reporting logic
package/tests/test_PartSeg/test_sentry.py
package/PartSeg/_launcher/check_version.py
package/PartSeg/common_gui/error_report.py
package/tests/test_PartSeg/test_common_gui.py
package/PartSeg/common_backend/except_hook.py
Modify pytest configurations and test cases
  • Update test cases to use sentry_sdk.new_scope()
  • Modify test assertions and mocking
  • Add error handling for URL errors in version checking
package/tests/test_PartSeg/test_check_release.py
package/tests/test_PartSeg/test_common_gui.py
Address deprecated functions and improve error handling
  • Replace np.fromstring() with np.frombuffer().copy()
  • Add warning filters for deprecated napari viewer access
  • Improve pandas DataFrame concatenation logic
package/PartSegImage/image_reader.py
package/PartSeg/plugins/napari_widgets/search_label_widget.py
package/PartSegCore/analysis/batch_processing/batch_backend.py
Update default URL and minor improvements
  • Change default URL in CheckVersionThread
  • Update Excel writer sheet_name parameter
  • Modify PImage initialization in test case
package/PartSeg/_launcher/check_version.py
package/PartSegCore/analysis/batch_processing/batch_backend.py
package/tests/test_PartSegCore/test_napari_plugins.py

Tips
  • Trigger a new Sourcery review by commenting @sourcery-ai review on the pull request.
  • Continue your discussion with Sourcery by replying directly to review comments.
  • You can change your review settings at any time by accessing your dashboard:
    • Enable or disable the Sourcery-generated pull request summary or reviewer's guide;
    • Change the review language;
  • You can always contact us if you have any questions or feedback.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 19, 2024

Walkthrough

The pull request introduces enhancements to type annotations and color handling in the napari_image_view.py file. The ColorInfo type has been updated to allow Optional[int] as keys, enabling None to be a valid key. The get_roi_view_parameters method now accommodates this change by returning a default color for both 0 and None keys. Additionally, the logic for setting the ROI colormap has been modified to ensure compatibility with different versions of napari. The test files have also been updated to reflect these version-specific changes, and the tox.ini file has been adjusted for more flexible test command execution.

Changes

File Path Change Summary
package/PartSeg/common_gui/napari_image_view.py Updated ColorInfo type to allow Optional[int] as keys, modified return statement in get_roi_view_parameters to include None as a key, and adjusted ROI colormap logic to use DirectLabelColormap for napari versions ≥ 0.4.19.
package/tests/test_PartSeg/test_napari_image_view.py Added version checks for napari to adjust EXPECTED_RANGE and defined get_color_dict(layer) with different implementations based on the napari version.
package/PartSeg/plugins/napari_widgets/lables_control.py Introduced a new version check for napari and added NAPARI_GE_4_19 to manage colormap settings based on version.
package/tests/test_PartSeg/test_napari_widgets.py Updated version checks in check_auto_mode and modified test_napari_label_show to include a context manager for button click synchronization.
tox.ini Modified test command executions to include {posargs} for flexibility in passing additional arguments.

Possibly related PRs

Poem

🐰 In the meadow where colors play,
Changes bloom in a vibrant array.
With None and 0, colors align,
In napari's garden, they brightly shine.
Each update hops with joy anew,
PartSeg's magic, forever true! 🌈


Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a16bb59 and 0c99573.

Files selected for processing (2)
  • package/PartSeg/plugins/napari_widgets/lables_control.py (2 hunks)
  • package/tests/test_PartSeg/test_napari_widgets.py (2 hunks)
Additional comments not posted (4)
package/PartSeg/plugins/napari_widgets/lables_control.py (2)

14-14: LGTM!

The introduction of the NAPARI_GE_4_19 version check variable is a good addition to handle version-specific behavior in the code. It follows the existing naming convention and allows the code to adapt to different Napari versions.


45-48: LGTM!

The version-specific handling of setting the colormap or color for the layer is a good approach to maintain compatibility with different Napari versions. The use of DirectLabelColormap for newer versions allows for more flexible color mapping, while defaulting to setting layer.color for older versions ensures backward compatibility.

package/tests/test_PartSeg/test_napari_widgets.py (2)

61-61: LGTM!

The version check for napari is implemented correctly using the parse_version function. This allows for conditional execution of code based on the available features or APIs in the specific napari version.


63-63: LGTM!

The conditional block at line 63 correctly handles the colormap checks based on the napari version. The check_auto_mode and check_direct_mode functions are defined appropriately to verify the expected colormap types or color modes depending on the version.

The usage of qtbot.waitSignal at lines 391-392 is a good practice to synchronize the test execution with the button click event. It ensures that the test waits for the button to be clicked before proceeding, preventing potential race conditions or timing issues.

Also applies to: 391-392


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
Contributor

@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 @Czaki - I've reviewed your changes - here's some feedback:

Overall Comments:

  • The PR title and description don't fully capture the scope of changes. Consider providing more details about the updates to sentry-sdk usage, numpy/pandas changes, and any configuration changes for turning warnings into errors.
  • The change from np.fromstring() to np.frombuffer().copy() is a good update. Consider mentioning this explicitly in the PR description as it addresses a deprecation warning.
Here's what I looked at during the review
  • 🟡 General issues: 2 issues found
  • 🟢 Security: all looks good
  • 🟡 Testing: 3 issues found
  • 🟢 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 to tell me if it was helpful.

array = array.view(dtype)
else:
array = np.fromstring(imagecodecs.zstd_decode(data[header.header_size :]), dtype)
array = np.frombuffer(imagecodecs.zstd_decode(data[header.header_size :]), dtype).copy()
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (performance): Profile the performance impact of added .copy() operations

While changing from fromstring to frombuffer is good, the added .copy() might impact performance. Consider profiling this change and evaluate if a copy-on-write approach could be more efficient in some scenarios.

Suggested change
array = np.frombuffer(imagecodecs.zstd_decode(data[header.header_size :]), dtype).copy()
array = np.frombuffer(imagecodecs.zstd_decode(data[header.header_size :]), dtype)
if array.flags['WRITEABLE']:
return array
return array.copy()

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I know that this buffer is not writable

assert len(clipped["exception"]["values"][0]["stacktrace"]["frames"][0]["vars"]) == len(vars_dict)
assert len(clipped["exception"]["values"][0]["stacktrace"]["frames"][0]["vars"]) > 10
client = Client("https://aaa@test.pl/77")
Hub.current.bind_client(client)
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (testing): Update test to use new_scope() instead of push_scope()

The test has been updated to use sentry_sdk.new_scope() instead of sentry_sdk.push_scope(). This change reflects updates in the Sentry SDK. Ensure that all other tests using Sentry scopes are updated similarly for consistency.

assert "body=This" in mock_web.call_args.args[0]

@patch("requests.post")
@patch("sentry_sdk.push_scope")
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (testing): Update mock to use new_scope instead of push_scope

The test has been updated to mock sentry_sdk.new_scope() instead of sentry_sdk.push_scope(). This change aligns with the updates in the Sentry SDK usage. Ensure all other tests mocking Sentry scopes are updated similarly for consistency.


def test_project_to_layers_roi():
data = np.zeros((1, 1, 10, 10, 10), dtype=np.uint8)
img = PImage(data, image_spacing=(1, 1, 1), name="ROI")
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (testing): Add axes_order parameter to PImage in test_project_to_layers_roi

The test has been updated to include the axes_order parameter when creating a PImage object. This change likely reflects an update in the PImage class or a more explicit test setup. Consider adding assertions to verify that the axes order is correctly handled in the resulting layers.

    img = PImage(data, image_spacing=(1, 1, 1), name="ROI", axes_order="CTZYX")
    assert img.axes_order == "CTZYX"
    assert res.image.axes_order == "CTZYX"

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

axes_order argument is to told of axes order of data array.

Copy link
Contributor

Choose a reason for hiding this comment

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

Thank you for your feedback, we will generate more comments like this in the future according to the following instructions:

- Ensure the comment suggests a meaningful improvement or addition to the test, such as adding parameters or assertions.
- Verify that the comment provides a clear rationale for the suggested change, explaining its relevance or necessity.
- Check that the comment includes specific code examples or snippets to illustrate the suggestion.
- Confirm that the comment is related to the functionality or correctness of the code being tested.

Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
@Czaki Czaki changed the title Make warnings an errors in tests refactor: Make warnings error in tests Sep 19, 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 (1)
pyproject.toml (1)

209-223: Suppressing pydantic deprecation warnings is fine for now, but create GitHub issues to track and address them.

The added filters suppress various deprecation warnings related to the pydantic library, allowing the tests to pass without being affected by the deprecated features or syntax.

However, suppressing these warnings may mask potential issues related to the use of deprecated features or syntax in the codebase. It is important to gradually address these deprecations and update the codebase to use the recommended alternatives to ensure future compatibility and maintainability.

Do you want me to open GitHub issues to track the suppressed deprecations and plan their resolution?

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between c6888dc and 6546936.

Files selected for processing (1)
  • pyproject.toml (3 hunks)
Additional comments not posted (4)
pyproject.toml (4)

64-64: LGTM!

Constraining the pydantic dependency to versions less than 3 ensures compatibility with existing code while allowing for updates within the major version.


67-67: LGTM!

Upgrading the requests dependency to version 2.25.0 allows for minor and patch version updates while staying within the same major version, which is unlikely to introduce any breaking changes.


69-69: Verify the impact of the major version upgrade on error tracking and reporting.

The sentry-sdk dependency has been significantly upgraded from version 0.14.3 to 2.4.0. This major version bump may introduce new features, changes in behavior, or breaking changes that could impact the application's error tracking and reporting functionality.

Please ensure that:

  1. The application's error tracking and reporting continue to function as expected after the upgrade.
  2. Any necessary changes in the codebase have been made to adapt to breaking changes or to utilize new features introduced in the newer versions of sentry-sdk.

194-195: LGTM! But be prepared to address warnings in existing tests.

Escalating warnings to errors in the PartSeg module and tests indicates a more stringent approach to handling warnings during testing. This change ensures that potential issues are addressed more rigorously and are not overlooked as mere warnings.

However, please note that this change may cause existing tests to fail if they currently generate warnings. Be prepared to address these warnings by making necessary code changes in the PartSeg module and tests to eliminate the warning-generating code or to explicitly handle the warnings.

@codecov
Copy link

codecov bot commented Sep 19, 2024

Codecov Report

Attention: Patch coverage is 98.46154% with 1 line in your changes missing coverage. Please review.

Project coverage is 93.07%. Comparing base (a7ab81f) to head (0c99573).
Report is 35 commits behind head on develop.

Files with missing lines Patch % Lines
package/PartSeg/common_gui/napari_image_view.py 92.30% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #1192      +/-   ##
===========================================
+ Coverage    93.05%   93.07%   +0.01%     
===========================================
  Files          209      209              
  Lines        32909    32927      +18     
===========================================
+ Hits         30625    30646      +21     
+ Misses        2284     2281       -3     

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

@sonarqubecloud
Copy link

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