Skip to content

8185 test refactor 2 #8405

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

Open
wants to merge 80 commits into
base: dev
Choose a base branch
from

Conversation

garciadias
Copy link
Contributor

@garciadias garciadias commented Mar 28, 2025

Fixes #8185

Description

This PR solves items 2 and 3 on #8185 for a few test folders.
I would merge these and proceed with the same type of change in other files if @ericspod approves.

I would like to keep these PRs small, so even if they have the same pattern of changes, merging them bit by bit would make them more manageable.

A few sentences describing the changes proposed in this pull request.

Types of changes

  • Non-breaking change (fix or new feature that would not break existing functionality).
  • Breaking change (fix or new feature that would cause existing functionality to change).
  • New tests added to cover the changes.
  • Integration tests passed locally by running ./runtests.sh -f -u --net --coverage.
  • Quick tests passed locally by running ./runtests.sh --quick --unittests --disttests.
  • In-line docstrings updated.
  • Documentation updated, tested make html command in the docs/ folder.

Summary by CodeRabbit

  • Refactor

    • Simplified and unified test case generation across numerous test modules by replacing nested loops with a parameterized product utility, enhancing conciseness and maintainability.
    • Improved readability and maintainability of test code through a declarative approach for parameter combinations.
    • Introduced helper functions in select tests to streamline output size calculations.
    • Minor adjustments to expected output values in some tests for numerical consistency.
    • Restructured test case templates in spatial transform tests for clearer parameter-device combinations.
  • Style

    • Minor whitespace and formatting improvements in test files.
  • Chores

    • Updated imports to include the new parameterized product utility where needed.
    • Refined the utility function for generating Cartesian products with a clearer signature and documentation.

@garciadias
Copy link
Contributor Author

Hi @ericspod,

Could you please review this PR?
I think it is all good to follow your specification on the #8185 issue.
I am sending the modification to these few tests so we can limit the size of the PR.
If you approve, I will proceed with more of these simplifications.

@garciadias garciadias force-pushed the 8185-test-refactor-2 branch from 5ae6312 to 2edf166 Compare May 16, 2025 12:31
garciadias and others added 5 commits May 16, 2025 13:41
I, R. Garcia-Dias <[email protected]>, hereby add my Signed-off-by to this commit: 241e24c
I, R. Garcia-Dias <[email protected]>, hereby add my Signed-off-by to this commit: 2edf166
I, R. Garcia-Dias <[email protected]>, hereby add my Signed-off-by to this commit: 2430ac8
I, R. Garcia-Dias <[email protected]>, hereby add my Signed-off-by to this commit: bb54c57
I, R. Garcia-Dias <[email protected]>, hereby add my Signed-off-by to this commit: cd1b4fb

Signed-off-by: R. Garcia-Dias <[email protected]>
@KumoLiu KumoLiu self-requested a review May 23, 2025 14:17
Copy link
Member

@ericspod ericspod left a comment

Choose a reason for hiding this comment

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

Hi @garciadias it looks much better now compared to the current state of these test. I have made a few comments in places which are mostly code suggestions you can just accept and double check are correct, but in general it's good but there's a few places where fewer lines of code can be used or some things adjusted for clarity. Thanks!

@garciadias garciadias requested a review from Nic-Ma as a code owner July 18, 2025 09:05
Copy link

coderabbitai bot commented Jul 18, 2025

Walkthrough

The test suite was refactored to replace deeply nested for-loops for test case generation with the utility function dict_product, which creates the Cartesian product of parameter dictionaries. This approach was applied across various test files, resulting in more concise, readable, and maintainable test case definitions without altering test logic or coverage. The dict_product function itself was simplified, and some minor adjustments were made to test data structures for clarity.

Changes

File(s) Change Summary
tests/test_utils.py Refactored dict_product to return a list of dicts representing parameter combinations; simplified signature and usage.
tests/apps/detection/networks/test_retinanet.py Replaced nested loops for test case generation with dict_product-based list comprehensions.
tests/data/meta_tensor/test_meta_tensor.py Simplified device and dtype test parameter generation using dict_product.
tests/networks/blocks/test_CABlock.py, test_crossattention.py, test_dynunet_block.py, test_patchembedding.py, test_segresnet_block.py, test_transformerblock.py, test_unetr_block.py Refactored nested loops to use dict_product for test case generation; added helper function _get_out_size in test_unetr_block.py.
tests/networks/nets/test_dynunet.py, test_mednext.py, test_segresnet.py, test_segresnet_ds.py, test_swin_unetr.py, test_transchex.py, test_unetr.py, test_vit.py, test_vitautoenc.py Converted nested loop test case generation to concise list comprehensions using dict_product.
tests/test_masked_autoencoder_vit.py Refactored nested loops to use dict_product; renamed scalar parameters and adjusted test case construction accordingly.
tests/transforms/spatial/test_spatial_resampled.py, test_spatial_resample.py, test_gibbs_noise.py, test_spacing.py Replaced nested loops with dict_product-based comprehensions for test case generation; restructured test data templates and adjusted expected outputs for clarity.
tests/transforms/utility/test_splitdimd.py Simplified parameter generation using dict_product; removed input type conversion in test method.
tests/utils/test_pad_mode.py Consolidated nested loops into single loop over dict_product output for test parameter iteration.
CONTRIBUTING.md Added a blank line before the coding style checking instructions for formatting clarity.

Sequence Diagram(s)

sequenceDiagram
    participant TestFile
    participant dict_product
    participant ParameterizedTest

    TestFile->>dict_product: Provide parameter lists as kwargs
    dict_product-->>TestFile: Return list of parameter dicts (Cartesian product)
    loop For each param_dict in product
        TestFile->>ParameterizedTest: Construct test case from param_dict
    end
    Note over TestFile,ParameterizedTest: Test logic and assertions remain unchanged
Loading

Poem

🐇
From tangled loops, we now are free,
With dict_product, we hop with glee!
Test cases bloom in tidy rows,
Simpler code, as every bunny knows.
The garden’s neat, the tests robust—
In code refactor, we all trust!
🌱


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2762cd5 and afb62d4.

📒 Files selected for processing (1)
  • CONTRIBUTING.md (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • CONTRIBUTING.md
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (18)
  • GitHub Check: quick-py3 (windows-latest)
  • GitHub Check: build-docs
  • GitHub Check: flake8-py3 (mypy)
  • GitHub Check: quick-py3 (macOS-latest)
  • GitHub Check: flake8-py3 (codeformat)
  • GitHub Check: flake8-py3 (pytype)
  • GitHub Check: quick-py3 (ubuntu-latest)
  • GitHub Check: packaging
  • GitHub Check: min-dep-py3 (3.12)
  • GitHub Check: min-dep-py3 (3.11)
  • GitHub Check: min-dep-py3 (3.10)
  • GitHub Check: min-dep-os (ubuntu-latest)
  • GitHub Check: min-dep-py3 (3.9)
  • GitHub Check: min-dep-pytorch (2.5.1)
  • GitHub Check: min-dep-os (macOS-latest)
  • GitHub Check: min-dep-os (windows-latest)
  • GitHub Check: min-dep-pytorch (2.4.1)
  • GitHub Check: min-dep-pytorch (2.6.0)

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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

@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

♻️ Duplicate comments (7)
tests/networks/blocks/test_patchembedding.py (1)

29-46: Excellent refactoring using dict_product utility!

The refactoring successfully replaces nested loops with a concise list comprehension while preserving all test parameter combinations. The logic for computing input and expected shapes remains intact.

Note: The past review comment suggests a potential further optimization by using the dictionary from dict_product more directly to eliminate the need for creating a separate args dictionary, but the current implementation is correct and functional.

tests/networks/blocks/test_crossattention.py (1)

29-50: Successful refactoring maintaining conditional logic.

The refactoring correctly preserves the conditional assignment of rel_pos_embedding based on the flash_attn parameter while using the dict_product utility for cleaner test case generation. The parameter mapping from flash_attn to use_flash_attention is handled appropriately.

This implementation aligns well with the suggested approach in the past review comments.

tests/transforms/test_gibbs_noise.py (1)

28-30: The refactoring is correct and maintains equivalent test coverage.

The use of dict_product successfully replaces the previous nested loop approach while preserving the same parameter combinations. However, there's a past review comment suggesting itertools.product might be more concise.

tests/networks/blocks/test_dynunet_block.py (2)

24-54: The refactoring is functionally correct and maintains equivalent test coverage.

The use of dict_product successfully replaces nested loops. The parameter extraction and computation logic (padding, output sizes) is preserved correctly.


58-89: Test case generation is correct but could be more concise.

The refactoring maintains the same test coverage. The past review comment suggests a more compact approach that could reduce the verbosity of parameter extraction.

tests/networks/nets/test_vit.py (1)

38-39: Address the readability concerns with dictionary unpacking expressions.

The ** bracketed expressions with conditional logic reduce readability, as previously noted. Consider using a for-loop approach or the {**params,...} pattern to construct the dictionary more clearly.

tests/transforms/utility/test_splitdimd.py (1)

26-31: Consider the simpler approach suggested in previous review.

The current list comprehension can be simplified to just dict_product(...) as suggested in the previous review, which would be more concise and direct.

🧹 Nitpick comments (1)
tests/networks/blocks/test_CABlock.py (1)

27-40: Good refactoring of test case generation with room for further improvement.

The replacement of nested for-loops with dict_product improves code readability and maintainability. The implementation correctly preserves all original test parameter combinations and maintains the same test case structure.

As suggested in the past review comment, you could make this even more concise using Python's ** syntax:

TEST_CASES_CAB = [
    [
-        {
-            "spatial_dims": params["spatial_dims"],
-            "dim": params["dim"],
-            "num_heads": params["num_heads"],
-            "bias": params["bias"],
-            "flash_attention": False,
-        },
+        {**params, "flash_attention": False},
        (2, params["dim"], *([16] * params["spatial_dims"])),
        (2, params["dim"], *([16] * params["spatial_dims"])),
    ]
    for params in dict_product(spatial_dims=[2, 3], dim=[32, 64, 128], num_heads=[2, 4, 8], bias=[True, False])
]
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e499362 and 6460e86.

📒 Files selected for processing (26)
  • tests/apps/detection/networks/test_retinanet.py (2 hunks)
  • tests/data/meta_tensor/test_meta_tensor.py (1 hunks)
  • tests/networks/blocks/test_CABlock.py (1 hunks)
  • tests/networks/blocks/test_crossattention.py (1 hunks)
  • tests/networks/blocks/test_dynunet_block.py (1 hunks)
  • tests/networks/blocks/test_patchembedding.py (1 hunks)
  • tests/networks/blocks/test_segresnet_block.py (1 hunks)
  • tests/networks/blocks/test_transformerblock.py (1 hunks)
  • tests/networks/blocks/test_unetr_block.py (1 hunks)
  • tests/networks/nets/test_dynunet.py (2 hunks)
  • tests/networks/nets/test_mednext.py (1 hunks)
  • tests/networks/nets/test_segresnet.py (1 hunks)
  • tests/networks/nets/test_segresnet_ds.py (1 hunks)
  • tests/networks/nets/test_swin_unetr.py (2 hunks)
  • tests/networks/nets/test_transchex.py (1 hunks)
  • tests/networks/nets/test_unetr.py (1 hunks)
  • tests/networks/nets/test_vit.py (1 hunks)
  • tests/networks/nets/test_vitautoenc.py (1 hunks)
  • tests/test_masked_autoencoder_vit.py (1 hunks)
  • tests/test_utils.py (2 hunks)
  • tests/transforms/spatial/test_spatial_resampled.py (3 hunks)
  • tests/transforms/test_gibbs_noise.py (1 hunks)
  • tests/transforms/test_spacing.py (1 hunks)
  • tests/transforms/test_spatial_resample.py (2 hunks)
  • tests/transforms/utility/test_splitdimd.py (1 hunks)
  • tests/utils/test_pad_mode.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (22)
tests/networks/blocks/test_CABlock.py (1)
tests/test_utils.py (3)
  • SkipIfBeforePyTorchVersion (266-277)
  • assert_allclose (100-140)
  • dict_product (868-885)
tests/networks/nets/test_transchex.py (1)
tests/test_utils.py (3)
  • dict_product (868-885)
  • skip_if_downloading_fails (144-169)
  • skip_if_quick (204-211)
tests/networks/blocks/test_transformerblock.py (1)
tests/test_utils.py (1)
  • dict_product (868-885)
tests/transforms/test_gibbs_noise.py (1)
tests/test_utils.py (1)
  • dict_product (868-885)
tests/networks/nets/test_vitautoenc.py (1)
tests/test_utils.py (3)
  • dict_product (868-885)
  • skip_if_quick (204-211)
  • skip_if_windows (252-256)
tests/networks/blocks/test_dynunet_block.py (2)
tests/test_utils.py (2)
  • dict_product (868-885)
  • test_script_save (739-758)
monai/networks/blocks/dynunet_block.py (1)
  • get_padding (304-312)
tests/networks/blocks/test_segresnet_block.py (1)
tests/test_utils.py (1)
  • dict_product (868-885)
tests/networks/blocks/test_patchembedding.py (1)
tests/test_utils.py (2)
  • SkipIfBeforePyTorchVersion (266-277)
  • dict_product (868-885)
tests/networks/nets/test_vit.py (1)
tests/test_utils.py (4)
  • SkipIfBeforePyTorchVersion (266-277)
  • dict_product (868-885)
  • skip_if_quick (204-211)
  • test_script_save (739-758)
tests/networks/nets/test_segresnet_ds.py (1)
tests/test_utils.py (3)
  • SkipIfBeforePyTorchVersion (266-277)
  • dict_product (868-885)
  • test_script_save (739-758)
tests/networks/nets/test_mednext.py (1)
tests/test_utils.py (1)
  • dict_product (868-885)
tests/transforms/test_spatial_resample.py (1)
tests/test_utils.py (2)
  • assert_allclose (100-140)
  • dict_product (868-885)
tests/apps/detection/networks/test_retinanet.py (2)
tests/test_utils.py (5)
  • SkipIfBeforePyTorchVersion (266-277)
  • dict_product (868-885)
  • skip_if_quick (204-211)
  • test_onnx_save (761-782)
  • test_script_save (739-758)
monai/networks/nets/resnet.py (7)
  • resnet10 (536-545)
  • resnet18 (548-557)
  • resnet34 (560-569)
  • resnet50 (572-581)
  • resnet101 (584-593)
  • resnet152 (596-605)
  • resnet200 (608-617)
tests/networks/blocks/test_crossattention.py (1)
tests/test_utils.py (3)
  • SkipIfBeforePyTorchVersion (266-277)
  • assert_allclose (100-140)
  • dict_product (868-885)
tests/networks/nets/test_unetr.py (1)
tests/test_utils.py (4)
  • SkipIfBeforePyTorchVersion (266-277)
  • dict_product (868-885)
  • skip_if_quick (204-211)
  • test_script_save (739-758)
tests/networks/nets/test_swin_unetr.py (1)
tests/test_utils.py (1)
  • dict_product (868-885)
tests/networks/nets/test_segresnet.py (2)
tests/test_utils.py (1)
  • dict_product (868-885)
monai/utils/enums.py (1)
  • UpsampleMode (174-182)
tests/networks/nets/test_dynunet.py (1)
tests/test_utils.py (5)
  • assert_allclose (100-140)
  • dict_product (868-885)
  • skip_if_no_cuda (245-249)
  • skip_if_windows (252-256)
  • test_script_save (739-758)
tests/transforms/spatial/test_spatial_resampled.py (1)
tests/test_utils.py (2)
  • assert_allclose (100-140)
  • dict_product (868-885)
tests/transforms/test_spacing.py (1)
tests/test_utils.py (3)
  • assert_allclose (100-140)
  • dict_product (868-885)
  • skip_if_quick (204-211)
tests/data/meta_tensor/test_meta_tensor.py (1)
tests/test_utils.py (4)
  • SkipIfBeforePyTorchVersion (266-277)
  • assert_allclose (100-140)
  • dict_product (868-885)
  • skip_if_no_cuda (245-249)
tests/networks/blocks/test_unetr_block.py (2)
tests/test_utils.py (2)
  • dict_product (868-885)
  • test_script_save (739-758)
monai/networks/blocks/dynunet_block.py (1)
  • get_padding (304-312)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (18)
  • GitHub Check: quick-py3 (ubuntu-latest)
  • GitHub Check: min-dep-pytorch (2.5.1)
  • GitHub Check: packaging
  • GitHub Check: flake8-py3 (codeformat)
  • GitHub Check: build-docs
  • GitHub Check: quick-py3 (windows-latest)
  • GitHub Check: quick-py3 (macOS-latest)
  • GitHub Check: flake8-py3 (pytype)
  • GitHub Check: flake8-py3 (mypy)
  • GitHub Check: min-dep-pytorch (2.6.0)
  • GitHub Check: min-dep-os (windows-latest)
  • GitHub Check: min-dep-pytorch (2.4.1)
  • GitHub Check: min-dep-py3 (3.10)
  • GitHub Check: min-dep-py3 (3.9)
  • GitHub Check: min-dep-py3 (3.11)
  • GitHub Check: min-dep-os (macOS-latest)
  • GitHub Check: min-dep-os (ubuntu-latest)
  • GitHub Check: min-dep-py3 (3.12)
🔇 Additional comments (41)
tests/test_utils.py (2)

868-885: Excellent refactoring of the dict_product utility function!

The new implementation is significantly cleaner and more maintainable than the previous version. The function correctly generates the Cartesian product of input iterables and returns a list of dictionaries, which is exactly what's needed for the test case refactoring across the codebase.

The implementation is correct:

  • Uses itertools.product for efficient Cartesian product generation
  • Clear type hints with Iterable[Any] inputs and list[dict] output
  • Comprehensive docstring with example usage
  • Simple list comprehension makes the logic easy to understand

31-31: Import changes align perfectly with the dict_product refactoring.

The addition of Iterable from collections.abc and Any from typing supports the new function signature, while removing the unused Literal import keeps the imports clean.

Also applies to: 37-37

tests/networks/blocks/test_transformerblock.py (2)

24-24: Correct import addition for the refactoring.

The dict_product import is properly added to support the test case generation refactoring.


27-46: Excellent refactoring of test case generation!

The replacement of nested for-loops with dict_product significantly improves code readability and maintainability. The implementation correctly:

  • Preserves all original test parameter combinations
  • Maintains the same test case structure with parameter dictionaries and shape tuples
  • Uses dict_product appropriately to generate the Cartesian product
  • Aligns with the past review comment suggesting this exact pattern

The refactored code is much more concise and declarative than the previous nested loop approach.

tests/networks/blocks/test_CABlock.py (1)

23-23: Correct import addition for the refactoring.

The dict_product import is properly added to support the test case generation refactoring.

tests/data/meta_tensor/test_meta_tensor.py (2)

35-35: Correct import addition for the refactoring.

The dict_product import is properly added along with other test utilities to support the test case generation refactoring.


39-41: Perfect refactoring of test parameter generation!

The replacement of nested loops with dict_product significantly improves code readability. The implementation correctly:

  • Uses dict_product to generate the Cartesian product of device and dtype combinations
  • Unpacks the dictionary values with *p["device"], *p["dtype"] to maintain the expected tuple format
  • Preserves all original test parameter combinations
  • Aligns exactly with the past review comment suggestion

The refactored code is much more concise and declarative than the previous nested loop approach.

tests/networks/blocks/test_segresnet_block.py (2)

21-21: Correct import addition for the refactoring.

The dict_product import is properly added to support the test case generation refactoring.


23-40: Excellent refactoring of test case generation!

The replacement of nested for-loops with dict_product significantly improves code readability and maintainability. The implementation correctly:

  • Preserves all original test parameter combinations including complex norm configurations
  • Uses dict_product appropriately to generate the Cartesian product
  • Maintains the same test case structure with parameter dictionaries and shape tuples
  • Aligns perfectly with the past review comment suggesting this exact pattern

The refactored code is much more concise and declarative, making it easier to understand the test parameter space at a glance.

tests/networks/blocks/test_patchembedding.py (1)

48-58: Clean refactoring with consistent pattern.

The TEST_CASE_PATCHEMBED generation follows the same improved pattern as the previous test case, maintaining all parameter combinations while using the more readable dict_product approach.

tests/apps/detection/networks/test_retinanet.py (1)

89-94: Effective refactoring using dict_product for test case combinations.

The refactoring successfully replaces nested loops with a cleaner approach using dict_product. The logic correctly generates all combinations of models and test cases while preserving the original test case structure through proper unpacking syntax.

tests/test_masked_autoencoder_vit.py (1)

25-66: Well-structured refactoring handling complex parameter combinations.

The refactoring successfully uses dict_product to generate base parameter combinations while preserving the more complex logic for handling different spatial dimensions. The renaming of parameters to img_size_scalar and patch_size_scalar improves clarity, and the subsequent processing correctly handles the tuple expansion and conditional parameter addition.

tests/networks/nets/test_transchex.py (1)

23-47: Clean and straightforward refactoring with dict_product.

The refactoring successfully replaces nested loops with a concise list comprehension using dict_product. All parameter combinations are preserved, and the tuple expansion logic for img_size and patch_size is correctly maintained.

tests/networks/nets/test_segresnet_ds.py (2)

25-44: Excellent refactoring that improves code readability and maintainability.

The conversion from nested loops to dict_product with list comprehension is well-executed. The parameter combinations are clearly defined and the test case structure is preserved correctly.


46-58: Clean and concise test case generation.

The second test case list follows the same pattern effectively, maintaining all parameter combinations while being more readable than nested loops.

tests/utils/test_pad_mode.py (1)

28-41: Excellent refactoring that improves code clarity and reduces nesting.

The conversion from nested loops to dict_product with a single loop is well-executed. All parameter combinations are preserved, and the test logic remains unchanged while being more readable.

tests/networks/nets/test_vitautoenc.py (1)

22-42: Clean and maintainable refactoring that preserves test coverage.

The use of dict_product with list comprehension is well-implemented. The parameter combinations are clearly defined, and the test case structure correctly handles the broadcasting of image and patch sizes to match spatial dimensions.

tests/networks/nets/test_vit.py (1)

23-63: Refactoring successfully simplifies test case generation.

The use of dict_product effectively replaces the nested for-loops with a more concise and maintainable approach. The parameter combinations and test coverage remain unchanged.

tests/transforms/test_spatial_resample.py (1)

71-87: Clean refactoring improves code maintainability.

The replacement of nested for-loops with dict_product creates a more concise and readable test case generation. The parameter combinations and test coverage are preserved.

tests/networks/nets/test_mednext.py (1)

25-67: Comprehensive refactoring enhances code consistency.

All three test case lists have been successfully refactored using dict_product, creating a consistent and maintainable approach to test case generation. The parameter combinations and test coverage remain unchanged.

tests/networks/nets/test_swin_unetr.py (1)

41-69: Elegant refactoring with clever parameter handling.

The use of enumerate with modulo operation to handle cyclic assignment of the downsample parameter is well-implemented. The refactoring maintains the original parameter combinations while significantly improving code readability.

tests/networks/nets/test_dynunet.py (4)

23-23: Import addition looks good.

The addition of dict_product to the imports is necessary for the refactoring and correctly sourced from tests.test_utils.


35-67: Excellent refactoring of 2D test case generation.

The replacement of nested loops with dict_product significantly improves code readability and maintainability while preserving all original test parameters and logic.


69-93: Good refactoring of 3D test case generation.

The use of dict_product for 3D test cases is consistent with the 2D approach and maintains all original test parameters while improving code clarity.


95-124: Well-executed refactoring of deep supervision test cases.

The refactoring successfully handles the more complex parameter combinations for deep supervision tests, maintaining all original logic while improving code organization and readability.

tests/transforms/spatial/test_spatial_resampled.py (3)

25-25: Import addition is correct.

The addition of dict_product to the imports is necessary for the refactoring and properly sourced from tests.test_utils.


44-68: Excellent implementation following past review guidance.

The refactoring successfully implements the approach suggested in the past review comment, using dict_product to generate parameter combinations in a more concise and maintainable way.


77-100: Good consistency in 2D test case refactoring.

The 2D test case generation follows the same pattern as the 3D cases, maintaining consistency while correctly handling the hardcoded padding mode for 2D scenarios.

tests/networks/nets/test_segresnet.py (4)

22-22: Import addition is appropriate.

The addition of dict_product to the imports is necessary for the refactoring and correctly sourced from tests.test_utils.


26-46: Excellent refactoring that reduces code complexity.

The refactoring successfully uses dict_product to generate all parameter combinations in a much more concise way, addressing the past review comment about reducing the number of lines while maintaining full test coverage.


48-62: Consistent refactoring pattern applied.

The second SegResNet test case follows the same refactoring pattern as the first, maintaining consistency and readability while preserving all original test parameters.


64-85: Well-executed VAE test case refactoring.

The SegResNetVAE test cases are properly refactored using dict_product, maintaining all original parameters including the complex VAE-specific configurations while improving code organization.

tests/networks/nets/test_unetr.py (2)

21-21: Import addition is correct.

The addition of dict_product to the imports is necessary for the refactoring and properly sourced from tests.test_utils.


23-56: Excellent refactoring with clever conditional parameter handling.

The refactoring successfully uses dict_product to generate parameter combinations while employing a clever conditional dictionary unpacking pattern **({"spatial_dims": 2} if params["nd"] == 2 else {}) to handle the 2D spatial dimensions case. This maintains all original test logic while significantly improving code readability.

tests/networks/blocks/test_unetr_block.py (4)

22-22: Import addition is appropriate.

The addition of dict_product to the imports is necessary for the refactoring and correctly sourced from tests.test_utils.


25-32: Well-implemented helper function for output size calculation.

The _get_out_size helper function correctly implements the standard convolution output size formula and properly handles both integer and tuple padding values. This follows the past review comment suggestion to break up the code into reusable pieces.


35-55: Excellent refactoring with improved organization.

The refactoring successfully uses dict_product for parameter combinations and leverages the helper function for output size calculations, following the past review comment suggestion to improve code organization and readability.


85-123: Complex refactoring handled well.

The refactoring successfully manages the complex output size calculation through multiple upsampling layers while using dict_product for parameter combinations. The descriptive variable names and preserved logic maintain clarity despite the complexity.

tests/transforms/test_spacing.py (3)

27-27: LGTM - Import addition aligns with refactoring objective.

The addition of dict_product import is consistent with the PR's goal of replacing nested for-loops with this utility function.


29-206: LGTM - Well-structured test data reorganization.

The refactoring successfully consolidates test case definitions into a clear, declarative structure:

  • The _template_5_expected_output variable extraction improves readability by removing inline conditional logic
  • The all_template_parts list provides a clean separation of test case parameters
  • Each test case is well-documented with clear parameter dictionaries
  • The structure maintains all original test logic while improving maintainability

This approach makes it easier to add new test cases and understand existing ones.


207-220: LGTM - Excellent use of dict_product for test case generation.

The refactoring successfully replaces manual test case construction with clean, declarative list comprehensions:

  • TESTS generation uses dict_product to create Cartesian products of templates and devices
  • TESTS_TORCH and TEST_INVERSE follow the same pattern for their respective parameter combinations
  • The approach eliminates nested loops while maintaining identical test coverage
  • Code is more readable and maintainable

This perfectly aligns with the PR objective of standardizing test case generation across the codebase.

garciadias and others added 12 commits July 18, 2025 10:43
Co-authored-by: Eric Kerfoot <[email protected]>
Signed-off-by: Rafael Garcia-Dias <[email protected]>
Co-authored-by: Eric Kerfoot <[email protected]>
Signed-off-by: Rafael Garcia-Dias <[email protected]>
Co-authored-by: Eric Kerfoot <[email protected]>
Signed-off-by: Rafael Garcia-Dias <[email protected]>
DCO Remediation Commit for R. Garcia-Dias <[email protected]>

I, R. Garcia-Dias <[email protected]>, hereby add my Signed-off-by to this commit: c594e27
I, R. Garcia-Dias <[email protected]>, hereby add my Signed-off-by to this commit: 6580ee4
I, R. Garcia-Dias <[email protected]>, hereby add my Signed-off-by to this commit: 14a58c0
I, R. Garcia-Dias <[email protected]>, hereby add my Signed-off-by to this commit: 69f5133
I, R. Garcia-Dias <[email protected]>, hereby add my Signed-off-by to this commit: 5c6171d
I, R. Garcia-Dias <[email protected]>, hereby add my Signed-off-by to this commit: 2762cd5

Signed-off-by: R. Garcia-Dias <[email protected]>
@garciadias
Copy link
Contributor Author

Hi @ericspod, I think now this PR is ready. Can you take a look, please?
Thank you for your comments. It greatly reduced the number of lines. Now the PR really remove a number of lines from the code.

@garciadias garciadias requested a review from ericspod July 18, 2025 16:45
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.

Test Refactor
2 participants