diff --git a/monai/transforms/io/array.py b/monai/transforms/io/array.py index 1023cd7a7d..49b0665a90 100644 --- a/monai/transforms/io/array.py +++ b/monai/transforms/io/array.py @@ -11,7 +11,6 @@ """ A collection of "vanilla" transforms for IO functions. """ - from __future__ import annotations import inspect diff --git a/runtests.sh b/runtests.sh index 65e3a2bb6b..2a399d5c3a 100755 --- a/runtests.sh +++ b/runtests.sh @@ -728,7 +728,7 @@ if [ $doDistTests = true ] then echo "${separator}${blue}run distributed unit test cases${noColor}" torch_validate - for i in tests/test_*_dist.py + for i in $(find ./tests/ -name "*_dist.py") do echo "$i" ${cmdPrefix}${cmd} "$i" @@ -740,7 +740,7 @@ if [ $doNetTests = true ] then set +e # disable exit on failure so that diagnostics can be given on failure echo "${separator}${blue}integration${noColor}" - for i in tests/*integration_*.py + for i in tests/integration/*.py do echo "$i" ${cmdPrefix}${cmd} "$i" diff --git a/tests/apps/__init__.py b/tests/apps/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/apps/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/apps/deepedit/__init__.py b/tests/apps/deepedit/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/apps/deepedit/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_deepedit_transforms.py b/tests/apps/deepedit/test_deepedit_transforms.py similarity index 100% rename from tests/test_deepedit_transforms.py rename to tests/apps/deepedit/test_deepedit_transforms.py diff --git a/tests/apps/deepgrow/__init__.py b/tests/apps/deepgrow/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/apps/deepgrow/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_deepgrow_dataset.py b/tests/apps/deepgrow/test_deepgrow_dataset.py similarity index 100% rename from tests/test_deepgrow_dataset.py rename to tests/apps/deepgrow/test_deepgrow_dataset.py diff --git a/tests/apps/deepgrow/transforms/__init__.py b/tests/apps/deepgrow/transforms/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/apps/deepgrow/transforms/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_deepgrow_interaction.py b/tests/apps/deepgrow/transforms/test_deepgrow_interaction.py similarity index 100% rename from tests/test_deepgrow_interaction.py rename to tests/apps/deepgrow/transforms/test_deepgrow_interaction.py diff --git a/tests/test_deepgrow_transforms.py b/tests/apps/deepgrow/transforms/test_deepgrow_transforms.py similarity index 100% rename from tests/test_deepgrow_transforms.py rename to tests/apps/deepgrow/transforms/test_deepgrow_transforms.py diff --git a/tests/apps/detection/__init__.py b/tests/apps/detection/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/apps/detection/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/apps/detection/metrics/__init__.py b/tests/apps/detection/metrics/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/apps/detection/metrics/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_detection_coco_metrics.py b/tests/apps/detection/metrics/test_detection_coco_metrics.py similarity index 100% rename from tests/test_detection_coco_metrics.py rename to tests/apps/detection/metrics/test_detection_coco_metrics.py diff --git a/tests/apps/detection/networks/__init__.py b/tests/apps/detection/networks/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/apps/detection/networks/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_retinanet.py b/tests/apps/detection/networks/test_retinanet.py similarity index 98% rename from tests/test_retinanet.py rename to tests/apps/detection/networks/test_retinanet.py index f36708d5b3..240fd3a9e2 100644 --- a/tests/test_retinanet.py +++ b/tests/apps/detection/networks/test_retinanet.py @@ -20,7 +20,7 @@ from monai.networks import eval_mode from monai.networks.nets import resnet10, resnet18, resnet34, resnet50, resnet101, resnet152, resnet200 from monai.utils import ensure_tuple, optional_import -from tests.utils import SkipIfBeforePyTorchVersion, skip_if_quick, test_onnx_save, test_script_save +from tests.test_utils import SkipIfBeforePyTorchVersion, skip_if_quick, test_onnx_save, test_script_save _, has_torchvision = optional_import("torchvision") @@ -101,7 +101,6 @@ @unittest.skipUnless(has_torchvision, "Requires torchvision") @skip_if_quick class TestRetinaNet(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_retina_shape(self, model, input_param, input_shape): backbone = model(**input_param) diff --git a/tests/test_retinanet_detector.py b/tests/apps/detection/networks/test_retinanet_detector.py similarity index 98% rename from tests/test_retinanet_detector.py rename to tests/apps/detection/networks/test_retinanet_detector.py index 691254fd87..b91ea46b4b 100644 --- a/tests/test_retinanet_detector.py +++ b/tests/apps/detection/networks/test_retinanet_detector.py @@ -21,7 +21,7 @@ from monai.apps.detection.utils.anchor_utils import AnchorGeneratorWithAnchorShape from monai.networks import eval_mode, train_mode from monai.utils import optional_import -from tests.utils import SkipIfBeforePyTorchVersion, skip_if_quick, test_script_save +from tests.test_utils import SkipIfBeforePyTorchVersion, skip_if_quick, test_script_save _, has_torchvision = optional_import("torchvision") @@ -93,7 +93,6 @@ class NaiveNetwork(torch.nn.Module): - def __init__(self, spatial_dims, num_classes, **kwargs): super().__init__() self.spatial_dims = spatial_dims @@ -115,7 +114,6 @@ def forward(self, images): @unittest.skipUnless(has_torchvision, "Requires torchvision") @skip_if_quick class TestRetinaNetDetector(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_retina_detector_resnet_backbone_shape(self, input_param, input_shape): returned_layers = [1] diff --git a/tests/test_box_transform.py b/tests/apps/detection/test_box_transform.py similarity index 99% rename from tests/test_box_transform.py rename to tests/apps/detection/test_box_transform.py index e99f95fa32..56929eafc2 100644 --- a/tests/test_box_transform.py +++ b/tests/apps/detection/test_box_transform.py @@ -36,7 +36,7 @@ ) from monai.data.meta_tensor import MetaTensor from monai.transforms import CastToTyped, Invertd -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS_3D = [] boxes = [[0, 0, 0, 0, 0, 0], [0, 1, 0, 2, 3, 3], [0, 1, 1, 2, 3, 4]] @@ -79,7 +79,6 @@ class TestBoxTransform(unittest.TestCase): - @parameterized.expand(TESTS_2D_mask) def test_value_2d_mask(self, mask, expected_box_label): box_label = convert_mask_to_box(mask) diff --git a/tests/apps/detection/utils/__init__.py b/tests/apps/detection/utils/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/apps/detection/utils/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_anchor_box.py b/tests/apps/detection/utils/test_anchor_box.py similarity index 97% rename from tests/test_anchor_box.py rename to tests/apps/detection/utils/test_anchor_box.py index 301ce78361..7543c84ed9 100644 --- a/tests/test_anchor_box.py +++ b/tests/apps/detection/utils/test_anchor_box.py @@ -18,7 +18,7 @@ from monai.apps.detection.utils.anchor_utils import AnchorGenerator, AnchorGeneratorWithAnchorShape from monai.utils import optional_import -from tests.utils import SkipIfBeforePyTorchVersion, assert_allclose, test_script_save +from tests.test_utils import SkipIfBeforePyTorchVersion, assert_allclose, test_script_save _, has_torchvision = optional_import("torchvision") @@ -42,7 +42,6 @@ @SkipIfBeforePyTorchVersion((1, 11)) @unittest.skipUnless(has_torchvision, "Requires torchvision") class TestAnchorGenerator(unittest.TestCase): - @parameterized.expand(TEST_CASES_2D) def test_anchor_2d(self, input_param, image_shape, feature_maps_shapes): torch_anchor_utils, _ = optional_import("torchvision.models.detection.anchor_utils") diff --git a/tests/test_atss_box_matcher.py b/tests/apps/detection/utils/test_atss_box_matcher.py similarity index 97% rename from tests/test_atss_box_matcher.py rename to tests/apps/detection/utils/test_atss_box_matcher.py index 6133d4839d..1a28f0d211 100644 --- a/tests/test_atss_box_matcher.py +++ b/tests/apps/detection/utils/test_atss_box_matcher.py @@ -18,7 +18,7 @@ from monai.apps.detection.utils.ATSS_matcher import ATSSMatcher from monai.data.box_utils import box_iou -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_CASES = [ [ @@ -33,7 +33,6 @@ class TestATSS(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_atss(self, input_param, boxes, anchors, num_anchors_per_level, num_anchors_per_loc, expected_matches): matcher = ATSSMatcher(**input_param, debug=True) diff --git a/tests/test_box_coder.py b/tests/apps/detection/utils/test_box_coder.py similarity index 97% rename from tests/test_box_coder.py rename to tests/apps/detection/utils/test_box_coder.py index 75ff650d6c..90d9444355 100644 --- a/tests/test_box_coder.py +++ b/tests/apps/detection/utils/test_box_coder.py @@ -17,11 +17,10 @@ from monai.apps.detection.utils.box_coder import BoxCoder from monai.transforms import CastToType -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose class TestBoxTransform(unittest.TestCase): - def test_value(self): box_coder = BoxCoder(weights=[1, 1, 1, 1, 1, 1]) test_dtype = [torch.float32, torch.float16] diff --git a/tests/test_detector_boxselector.py b/tests/apps/detection/utils/test_detector_boxselector.py similarity index 98% rename from tests/test_detector_boxselector.py rename to tests/apps/detection/utils/test_detector_boxselector.py index 326ecd5773..6ddcc85b7e 100644 --- a/tests/test_detector_boxselector.py +++ b/tests/apps/detection/utils/test_detector_boxselector.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.apps.detection.utils.box_selector import BoxSelector -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose device = "cuda" if torch.cuda.is_available() else "cpu" num_anchors = 7 @@ -56,7 +56,6 @@ class TestBoxSelector(unittest.TestCase): - @parameterized.expand(TEST_CASE) def test_box_selector(self, input_param, boxes, logits, image_shape, expected_results): box_selector = BoxSelector(**input_param) diff --git a/tests/test_detector_utils.py b/tests/apps/detection/utils/test_detector_utils.py similarity index 98% rename from tests/test_detector_utils.py rename to tests/apps/detection/utils/test_detector_utils.py index 352e1c2faf..56bea31ff4 100644 --- a/tests/test_detector_utils.py +++ b/tests/apps/detection/utils/test_detector_utils.py @@ -19,7 +19,7 @@ from monai.apps.detection.utils.detector_utils import preprocess_images from monai.utils import ensure_tuple -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_CASE_1 = [ # 3D, batch 3, 2 input channel { @@ -79,7 +79,6 @@ class TestDetectorUtils(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_detector_utils(self, input_param, input_shape, expected_shape): size_divisible = 32 * ensure_tuple(input_param["conv1_t_stride"])[0] diff --git a/tests/test_hardnegsampler.py b/tests/apps/detection/utils/test_hardnegsampler.py similarity index 97% rename from tests/test_hardnegsampler.py rename to tests/apps/detection/utils/test_hardnegsampler.py index 5385abd1db..4a3c03bcad 100644 --- a/tests/test_hardnegsampler.py +++ b/tests/apps/detection/utils/test_hardnegsampler.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.apps.detection.utils.hard_negative_sampler import HardNegativeSampler -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_CASE = [ [[], [], [], [torch.tensor([]), torch.tensor([])], [torch.tensor([]), torch.tensor([])]], @@ -37,7 +37,6 @@ class TestSampleSlices(unittest.TestCase): - @parameterized.expand(TEST_CASE) def test_shape(self, target_label0, target_label1, concat_fg_probs, expected_result_pos, expected_result_neg): compute_dtypes = [torch.float16, torch.float32] diff --git a/tests/apps/maisi/networks/__init__.py b/tests/apps/maisi/networks/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/apps/maisi/networks/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_autoencoderkl_maisi.py b/tests/apps/maisi/networks/test_autoencoderkl_maisi.py similarity index 99% rename from tests/test_autoencoderkl_maisi.py rename to tests/apps/maisi/networks/test_autoencoderkl_maisi.py index 0e9f427fb6..6b9aae1d17 100644 --- a/tests/test_autoencoderkl_maisi.py +++ b/tests/apps/maisi/networks/test_autoencoderkl_maisi.py @@ -19,7 +19,7 @@ from monai.apps.generation.maisi.networks.autoencoderkl_maisi import AutoencoderKlMaisi from monai.networks import eval_mode from monai.utils import optional_import -from tests.utils import SkipIfBeforePyTorchVersion +from tests.test_utils import SkipIfBeforePyTorchVersion tqdm, has_tqdm = optional_import("tqdm", name="tqdm") _, has_einops = optional_import("einops") @@ -77,7 +77,6 @@ class TestAutoencoderKlMaisi(unittest.TestCase): - @parameterized.expand(CASES) def test_shape(self, input_param, input_shape, expected_shape, expected_latent_shape): net = AutoencoderKlMaisi(**input_param).to(device) diff --git a/tests/test_controlnet_maisi.py b/tests/apps/maisi/networks/test_controlnet_maisi.py similarity index 99% rename from tests/test_controlnet_maisi.py rename to tests/apps/maisi/networks/test_controlnet_maisi.py index bfdf25ec6e..2668398350 100644 --- a/tests/test_controlnet_maisi.py +++ b/tests/apps/maisi/networks/test_controlnet_maisi.py @@ -20,7 +20,7 @@ from monai.apps.generation.maisi.networks.controlnet_maisi import ControlNetMaisi from monai.networks import eval_mode from monai.utils import optional_import -from tests.utils import SkipIfBeforePyTorchVersion +from tests.test_utils import SkipIfBeforePyTorchVersion _, has_einops = optional_import("einops") @@ -129,7 +129,6 @@ @SkipIfBeforePyTorchVersion((2, 0)) class TestControlNet(unittest.TestCase): - @parameterized.expand(TEST_CASES) @skipUnless(has_einops, "Requires einops") def test_shape_unconditioned_models(self, input_param, expected_num_down_blocks_residuals, expected_shape): diff --git a/tests/test_diffusion_model_unet_maisi.py b/tests/apps/maisi/networks/test_diffusion_model_unet_maisi.py similarity index 100% rename from tests/test_diffusion_model_unet_maisi.py rename to tests/apps/maisi/networks/test_diffusion_model_unet_maisi.py diff --git a/tests/apps/nuclick/__init__.py b/tests/apps/nuclick/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/apps/nuclick/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_nuclick_transforms.py b/tests/apps/nuclick/test_nuclick_transforms.py similarity index 100% rename from tests/test_nuclick_transforms.py rename to tests/apps/nuclick/test_nuclick_transforms.py diff --git a/tests/apps/pathology/__init__.py b/tests/apps/pathology/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/apps/pathology/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/apps/pathology/handlers/__init__.py b/tests/apps/pathology/handlers/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/apps/pathology/handlers/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_from_engine_hovernet.py b/tests/apps/pathology/handlers/test_from_engine_hovernet.py similarity index 96% rename from tests/test_from_engine_hovernet.py rename to tests/apps/pathology/handlers/test_from_engine_hovernet.py index 7d1a784466..5e9c319205 100644 --- a/tests/test_from_engine_hovernet.py +++ b/tests/apps/pathology/handlers/test_from_engine_hovernet.py @@ -16,7 +16,7 @@ from parameterized import parameterized from monai.apps.pathology.handlers.utils import from_engine_hovernet -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_CASE_0 = [ [{"A": {"C": 1, "D": 2}, "B": {"C": 2, "D": 2}}, {"A": {"C": 3, "D": 2}, "B": {"C": 4, "D": 2}}], @@ -28,7 +28,6 @@ class TestFromEngineHovernet(unittest.TestCase): - @parameterized.expand(CASES) def test_results(self, input, expected): output = from_engine_hovernet(keys=["A", "B"], nested_key="C")(input) diff --git a/tests/test_lesion_froc.py b/tests/apps/pathology/test_lesion_froc.py similarity index 100% rename from tests/test_lesion_froc.py rename to tests/apps/pathology/test_lesion_froc.py diff --git a/tests/test_pathology_prob_nms.py b/tests/apps/pathology/test_pathology_prob_nms.py similarity index 100% rename from tests/test_pathology_prob_nms.py rename to tests/apps/pathology/test_pathology_prob_nms.py diff --git a/tests/test_prepare_batch_hovernet.py b/tests/apps/pathology/test_prepare_batch_hovernet.py similarity index 98% rename from tests/test_prepare_batch_hovernet.py rename to tests/apps/pathology/test_prepare_batch_hovernet.py index ae9554a3e8..d29aed2312 100644 --- a/tests/test_prepare_batch_hovernet.py +++ b/tests/apps/pathology/test_prepare_batch_hovernet.py @@ -19,7 +19,7 @@ from monai.apps.pathology.engines import PrepareBatchHoVerNet from monai.engines import SupervisedEvaluator from monai.utils.enums import HoVerNetBranch -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_CASE_0 = [ {"extra_keys": ["extra_label1", "extra_label2"]}, @@ -35,7 +35,6 @@ def forward(self, x: torch.Tensor): class TestPrepareBatchHoVerNet(unittest.TestCase): - @parameterized.expand([TEST_CASE_0]) def test_content(self, input_args, expected_value): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") diff --git a/tests/test_sliding_window_hovernet_inference.py b/tests/apps/pathology/test_sliding_window_hovernet_inference.py similarity index 99% rename from tests/test_sliding_window_hovernet_inference.py rename to tests/apps/pathology/test_sliding_window_hovernet_inference.py index 6fc9240a13..ce39c905d2 100644 --- a/tests/test_sliding_window_hovernet_inference.py +++ b/tests/apps/pathology/test_sliding_window_hovernet_inference.py @@ -21,7 +21,7 @@ from monai.data import MetaTensor from monai.inferers import sliding_window_inference from monai.utils import optional_import -from tests.test_sliding_window_inference import TEST_CASES +from tests.inferers.test_sliding_window_inference import TEST_CASES _, has_tqdm = optional_import("tqdm") @@ -36,7 +36,6 @@ class TestSlidingWindowHoVerNetInference(unittest.TestCase): - @parameterized.expand(TEST_CASES_PADDING) def test_sliding_window_with_padding( self, key, image_shape, roi_shape, sw_batch_size, overlap, mode, device, extra_input_padding diff --git a/tests/apps/pathology/transforms/__init__.py b/tests/apps/pathology/transforms/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/apps/pathology/transforms/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/apps/pathology/transforms/post/__init__.py b/tests/apps/pathology/transforms/post/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/apps/pathology/transforms/post/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_generate_distance_map.py b/tests/apps/pathology/transforms/post/test_generate_distance_map.py similarity index 97% rename from tests/test_generate_distance_map.py rename to tests/apps/pathology/transforms/post/test_generate_distance_map.py index 42f5664647..c41f2036c5 100644 --- a/tests/test_generate_distance_map.py +++ b/tests/apps/pathology/transforms/post/test_generate_distance_map.py @@ -18,7 +18,7 @@ from monai.apps.pathology.transforms.post.array import GenerateDistanceMap from monai.transforms.intensity.array import GaussianSmooth -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS EXCEPTION_TESTS = [] TESTS = [] @@ -36,7 +36,6 @@ class TestGenerateDistanceMap(unittest.TestCase): - @parameterized.expand(EXCEPTION_TESTS) def test_value(self, arguments, mask, probmap, exception_type): with self.assertRaises(exception_type): diff --git a/tests/test_generate_distance_mapd.py b/tests/apps/pathology/transforms/post/test_generate_distance_mapd.py similarity index 98% rename from tests/test_generate_distance_mapd.py rename to tests/apps/pathology/transforms/post/test_generate_distance_mapd.py index 2bddadf5b8..44a7809034 100644 --- a/tests/test_generate_distance_mapd.py +++ b/tests/apps/pathology/transforms/post/test_generate_distance_mapd.py @@ -18,7 +18,7 @@ from monai.apps.pathology.transforms.post.dictionary import GenerateDistanceMapd from monai.transforms.intensity.array import GaussianSmooth -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS EXCEPTION_TESTS = [] TESTS = [] @@ -55,7 +55,6 @@ class TestGenerateDistanceMapd(unittest.TestCase): - @parameterized.expand(EXCEPTION_TESTS) def test_value(self, arguments, mask, border_map, exception_type): with self.assertRaises(exception_type): diff --git a/tests/test_generate_instance_border.py b/tests/apps/pathology/transforms/post/test_generate_instance_border.py similarity index 97% rename from tests/test_generate_instance_border.py rename to tests/apps/pathology/transforms/post/test_generate_instance_border.py index fc1035dfe5..3ebf6a90b5 100644 --- a/tests/test_generate_instance_border.py +++ b/tests/apps/pathology/transforms/post/test_generate_instance_border.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.apps.pathology.transforms.post.array import GenerateInstanceBorder -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS EXCEPTION_TESTS = [] TESTS = [] @@ -34,7 +34,6 @@ class TestGenerateInstanceBorder(unittest.TestCase): - @parameterized.expand(EXCEPTION_TESTS) def test_value(self, arguments, mask, hover_map, exception_type): with self.assertRaises(exception_type): diff --git a/tests/test_generate_instance_borderd.py b/tests/apps/pathology/transforms/post/test_generate_instance_borderd.py similarity index 98% rename from tests/test_generate_instance_borderd.py rename to tests/apps/pathology/transforms/post/test_generate_instance_borderd.py index cdfbee4193..6f85b43313 100644 --- a/tests/test_generate_instance_borderd.py +++ b/tests/apps/pathology/transforms/post/test_generate_instance_borderd.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.apps.pathology.transforms.post.dictionary import GenerateInstanceBorderd -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS EXCEPTION_TESTS = [] TESTS = [] @@ -44,7 +44,6 @@ class TestGenerateInstanceBorderd(unittest.TestCase): - @parameterized.expand(EXCEPTION_TESTS) def test_value(self, arguments, mask, hover_map, exception_type): with self.assertRaises(exception_type): diff --git a/tests/test_generate_instance_centroid.py b/tests/apps/pathology/transforms/post/test_generate_instance_centroid.py similarity index 96% rename from tests/test_generate_instance_centroid.py rename to tests/apps/pathology/transforms/post/test_generate_instance_centroid.py index 6b4d533401..78cdfaed09 100644 --- a/tests/test_generate_instance_centroid.py +++ b/tests/apps/pathology/transforms/post/test_generate_instance_centroid.py @@ -19,7 +19,7 @@ from monai.apps.pathology.transforms.post.array import GenerateInstanceCentroid from monai.transforms import BoundingRect from monai.utils import min_version, optional_import -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose _, has_skimage = optional_import("skimage", "0.19.3", min_version) @@ -41,7 +41,6 @@ @unittest.skipUnless(has_skimage, "Requires scikit-image library.") class TestGenerateInstanceCentroid(unittest.TestCase): - @parameterized.expand(TEST_CASE) def test_shape(self, in_type, test_data, offset, expected): inst_bbox = get_bbox(test_data[None]) diff --git a/tests/test_generate_instance_centroidd.py b/tests/apps/pathology/transforms/post/test_generate_instance_centroidd.py similarity index 97% rename from tests/test_generate_instance_centroidd.py rename to tests/apps/pathology/transforms/post/test_generate_instance_centroidd.py index d381ad8c0e..568bd6348c 100644 --- a/tests/test_generate_instance_centroidd.py +++ b/tests/apps/pathology/transforms/post/test_generate_instance_centroidd.py @@ -19,7 +19,7 @@ from monai.apps.pathology.transforms.post.dictionary import GenerateInstanceCentroidd from monai.transforms import BoundingRect from monai.utils import min_version, optional_import -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose _, has_skimage = optional_import("skimage", "0.19.3", min_version) @@ -41,7 +41,6 @@ @unittest.skipUnless(has_skimage, "Requires scikit-image library.") class TestGenerateInstanceCentroidd(unittest.TestCase): - @parameterized.expand(TEST_CASE) def test_shape(self, in_type, test_data, offset, expected): inst_bbox = get_bbox(test_data[None]) diff --git a/tests/test_generate_instance_contour.py b/tests/apps/pathology/transforms/post/test_generate_instance_contour.py similarity index 97% rename from tests/test_generate_instance_contour.py rename to tests/apps/pathology/transforms/post/test_generate_instance_contour.py index 7f4290747d..43808a559d 100644 --- a/tests/test_generate_instance_contour.py +++ b/tests/apps/pathology/transforms/post/test_generate_instance_contour.py @@ -19,7 +19,7 @@ from monai.apps.pathology.transforms.post.array import GenerateInstanceContour from monai.transforms import BoundingRect from monai.utils import min_version, optional_import -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose _, has_skimage = optional_import("skimage", "0.19.3", min_version) @@ -46,7 +46,6 @@ @unittest.skipUnless(has_skimage, "Requires scikit-image library.") class TestGenerateInstanceContour(unittest.TestCase): - @parameterized.expand(TEST_CASE) def test_shape(self, in_type, test_data, min_num_points, offset, expected): inst_bbox = get_bbox(test_data[None]) diff --git a/tests/test_generate_instance_contourd.py b/tests/apps/pathology/transforms/post/test_generate_instance_contourd.py similarity index 97% rename from tests/test_generate_instance_contourd.py rename to tests/apps/pathology/transforms/post/test_generate_instance_contourd.py index 5c831ee680..640ca81c0b 100644 --- a/tests/test_generate_instance_contourd.py +++ b/tests/apps/pathology/transforms/post/test_generate_instance_contourd.py @@ -19,7 +19,7 @@ from monai.apps.pathology.transforms.post.dictionary import GenerateInstanceContourd from monai.transforms import BoundingRect from monai.utils import min_version, optional_import -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose _, has_skimage = optional_import("skimage", "0.19.3", min_version) @@ -46,7 +46,6 @@ @unittest.skipUnless(has_skimage, "Requires scikit-image library.") class TestGenerateInstanceContourd(unittest.TestCase): - @parameterized.expand(TEST_CASE) def test_shape(self, in_type, test_data, min_num_points, offset, expected): inst_bbox = get_bbox(test_data[None]) diff --git a/tests/test_generate_instance_type.py b/tests/apps/pathology/transforms/post/test_generate_instance_type.py similarity index 96% rename from tests/test_generate_instance_type.py rename to tests/apps/pathology/transforms/post/test_generate_instance_type.py index 24e1d1b6d0..8628d941e1 100644 --- a/tests/test_generate_instance_type.py +++ b/tests/apps/pathology/transforms/post/test_generate_instance_type.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.apps.pathology.transforms.post.array import GenerateInstanceType -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose y, x = np.ogrid[0:30, 0:30] @@ -41,7 +41,6 @@ class TestGenerateInstanceType(unittest.TestCase): - @parameterized.expand(TEST_CASE) def test_shape(self, in_type, type_pred, seg_pred, bbox, expected): result = GenerateInstanceType()(in_type(type_pred[None]), in_type(seg_pred[None]), bbox, 1) diff --git a/tests/test_generate_instance_typed.py b/tests/apps/pathology/transforms/post/test_generate_instance_typed.py similarity index 96% rename from tests/test_generate_instance_typed.py rename to tests/apps/pathology/transforms/post/test_generate_instance_typed.py index 958f68d6bb..d293d66ebb 100644 --- a/tests/test_generate_instance_typed.py +++ b/tests/apps/pathology/transforms/post/test_generate_instance_typed.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.apps.pathology.transforms.post.dictionary import GenerateInstanceTyped -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose y, x = np.ogrid[0:30, 0:30] @@ -41,7 +41,6 @@ class TestGenerateInstanceTyped(unittest.TestCase): - @parameterized.expand(TEST_CASE) def test_shape(self, in_type, type_pred, seg_pred, bbox, expected): test_data = {"type_pred": in_type(type_pred[None]), "seg": in_type(seg_pred[None]), "bbox": bbox, "id": 1} diff --git a/tests/test_generate_succinct_contour.py b/tests/apps/pathology/transforms/post/test_generate_succinct_contour.py similarity index 100% rename from tests/test_generate_succinct_contour.py rename to tests/apps/pathology/transforms/post/test_generate_succinct_contour.py diff --git a/tests/test_generate_succinct_contourd.py b/tests/apps/pathology/transforms/post/test_generate_succinct_contourd.py similarity index 100% rename from tests/test_generate_succinct_contourd.py rename to tests/apps/pathology/transforms/post/test_generate_succinct_contourd.py diff --git a/tests/test_generate_watershed_markers.py b/tests/apps/pathology/transforms/post/test_generate_watershed_markers.py similarity index 97% rename from tests/test_generate_watershed_markers.py rename to tests/apps/pathology/transforms/post/test_generate_watershed_markers.py index 238fb00ee0..e03f9e0652 100644 --- a/tests/test_generate_watershed_markers.py +++ b/tests/apps/pathology/transforms/post/test_generate_watershed_markers.py @@ -18,7 +18,7 @@ from monai.apps.pathology.transforms.post.array import GenerateWatershedMarkers from monai.utils import min_version, optional_import -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS _, has_skimage = optional_import("skimage", "0.19.3", min_version) _, has_scipy = optional_import("scipy", "1.8.1", min_version) @@ -38,7 +38,6 @@ @unittest.skipUnless(has_skimage, "Requires scikit-image library.") @unittest.skipUnless(has_scipy, "Requires scipy library.") class TestGenerateWatershedMarkers(unittest.TestCase): - @parameterized.expand(EXCEPTION_TESTS) def test_value(self, arguments, mask, probmap, exception_type): with self.assertRaises(exception_type): diff --git a/tests/test_generate_watershed_markersd.py b/tests/apps/pathology/transforms/post/test_generate_watershed_markersd.py similarity index 98% rename from tests/test_generate_watershed_markersd.py rename to tests/apps/pathology/transforms/post/test_generate_watershed_markersd.py index a3c2b9c231..d4b59a63a4 100644 --- a/tests/test_generate_watershed_markersd.py +++ b/tests/apps/pathology/transforms/post/test_generate_watershed_markersd.py @@ -18,7 +18,7 @@ from monai.apps.pathology.transforms.post.dictionary import GenerateWatershedMarkersd from monai.utils import min_version, optional_import -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS _, has_skimage = optional_import("skimage", "0.19.3", min_version) _, has_scipy = optional_import("scipy", "1.8.1", min_version) @@ -68,7 +68,6 @@ @unittest.skipUnless(has_skimage, "Requires scikit-image library.") @unittest.skipUnless(has_scipy, "Requires scipy library.") class TestGenerateWatershedMarkersd(unittest.TestCase): - @parameterized.expand(EXCEPTION_TESTS) def test_value(self, arguments, mask, border_map, exception_type): with self.assertRaises(exception_type): diff --git a/tests/test_generate_watershed_mask.py b/tests/apps/pathology/transforms/post/test_generate_watershed_mask.py similarity index 98% rename from tests/test_generate_watershed_mask.py rename to tests/apps/pathology/transforms/post/test_generate_watershed_mask.py index 5224a912b0..10429cbf12 100644 --- a/tests/test_generate_watershed_mask.py +++ b/tests/apps/pathology/transforms/post/test_generate_watershed_mask.py @@ -19,7 +19,7 @@ from monai.apps.pathology.transforms.post.array import GenerateWatershedMask from monai.utils import min_version, optional_import -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS _, has_scipy = optional_import("scipy", "1.8.1", min_version) @@ -58,7 +58,6 @@ @unittest.skipUnless(has_scipy, "Requires scipy library.") class TestGenerateWatershedMask(unittest.TestCase): - @parameterized.expand(EXCEPTION_TESTS) def test_value(self, arguments, exception_type): with self.assertRaises(exception_type): diff --git a/tests/test_generate_watershed_maskd.py b/tests/apps/pathology/transforms/post/test_generate_watershed_maskd.py similarity index 98% rename from tests/test_generate_watershed_maskd.py rename to tests/apps/pathology/transforms/post/test_generate_watershed_maskd.py index 9d0f2c274a..24caa7b4b9 100644 --- a/tests/test_generate_watershed_maskd.py +++ b/tests/apps/pathology/transforms/post/test_generate_watershed_maskd.py @@ -19,7 +19,7 @@ from monai.apps.pathology.transforms.post.dictionary import GenerateWatershedMaskd from monai.utils import min_version, optional_import -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS _, has_scipy = optional_import("scipy", "1.8.1", min_version) @@ -58,7 +58,6 @@ @unittest.skipUnless(has_scipy, "Requires scipy library.") class TestGenerateWatershedMaskd(unittest.TestCase): - @parameterized.expand(EXCEPTION_TESTS) def test_value(self, arguments, exception_type): with self.assertRaises(exception_type): diff --git a/tests/test_hovernet_instance_map_post_processing.py b/tests/apps/pathology/transforms/post/test_hovernet_instance_map_post_processing.py similarity index 97% rename from tests/test_hovernet_instance_map_post_processing.py rename to tests/apps/pathology/transforms/post/test_hovernet_instance_map_post_processing.py index ce272fba1a..f9df25f2e2 100644 --- a/tests/test_hovernet_instance_map_post_processing.py +++ b/tests/apps/pathology/transforms/post/test_hovernet_instance_map_post_processing.py @@ -19,7 +19,7 @@ from monai.apps.pathology.transforms.post.array import HoVerNetInstanceMapPostProcessing from monai.transforms import ComputeHoVerMaps, FillHoles, GaussianSmooth from monai.utils import min_version, optional_import -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose _, has_scipy = optional_import("scipy", "1.8.1", min_version) _, has_skimage = optional_import("skimage", "0.19.3", min_version) @@ -42,7 +42,6 @@ @unittest.skipUnless(has_scipy, "Requires scipy library.") @unittest.skipUnless(has_skimage, "Requires scikit-image library.") class TestHoVerNetInstanceMapPostProcessing(unittest.TestCase): - @parameterized.expand(TEST_CASE) def test_value(self, in_type, test_data, kwargs, expected_info, expected_map): nuclear_prediction = in_type(test_data.astype(float)) diff --git a/tests/test_hovernet_instance_map_post_processingd.py b/tests/apps/pathology/transforms/post/test_hovernet_instance_map_post_processingd.py similarity index 97% rename from tests/test_hovernet_instance_map_post_processingd.py rename to tests/apps/pathology/transforms/post/test_hovernet_instance_map_post_processingd.py index c982156caa..216c13476c 100644 --- a/tests/test_hovernet_instance_map_post_processingd.py +++ b/tests/apps/pathology/transforms/post/test_hovernet_instance_map_post_processingd.py @@ -20,7 +20,7 @@ from monai.transforms import ComputeHoVerMaps, FillHoles, GaussianSmooth from monai.utils import min_version, optional_import from monai.utils.enums import HoVerNetBranch -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose _, has_scipy = optional_import("scipy", "1.8.1", min_version) _, has_skimage = optional_import("skimage", "0.19.3", min_version) @@ -43,7 +43,6 @@ @unittest.skipUnless(has_scipy, "Requires scipy library.") @unittest.skipUnless(has_skimage, "Requires scikit-image library.") class TestHoVerNetInstanceMapPostProcessingd(unittest.TestCase): - @parameterized.expand(TEST_CASE) def test_value(self, in_type, test_data, kwargs, expected_info, expected_map): input = { diff --git a/tests/test_hovernet_nuclear_type_post_processing.py b/tests/apps/pathology/transforms/post/test_hovernet_nuclear_type_post_processing.py similarity index 97% rename from tests/test_hovernet_nuclear_type_post_processing.py rename to tests/apps/pathology/transforms/post/test_hovernet_nuclear_type_post_processing.py index e97b7abd2c..289a6e4fcf 100644 --- a/tests/test_hovernet_nuclear_type_post_processing.py +++ b/tests/apps/pathology/transforms/post/test_hovernet_nuclear_type_post_processing.py @@ -22,7 +22,7 @@ ) from monai.transforms import ComputeHoVerMaps from monai.utils import min_version, optional_import -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose _, has_scipy = optional_import("scipy", "1.8.1", min_version) _, has_skimage = optional_import("skimage", "0.19.3", min_version) @@ -41,7 +41,6 @@ @unittest.skipUnless(has_scipy, "Requires scipy library.") @unittest.skipUnless(has_skimage, "Requires scikit-image library.") class TestHoVerNetNuclearTypePostProcessing(unittest.TestCase): - @parameterized.expand(TEST_CASE) def test_value(self, in_type, test_data, kwargs, expected_info, expected_map): nuclear_prediction = in_type(test_data.astype(float)) diff --git a/tests/test_watershed.py b/tests/apps/pathology/transforms/post/test_watershed.py similarity index 97% rename from tests/test_watershed.py rename to tests/apps/pathology/transforms/post/test_watershed.py index 3f7a29bfe7..57fc6393ef 100644 --- a/tests/test_watershed.py +++ b/tests/apps/pathology/transforms/post/test_watershed.py @@ -24,7 +24,7 @@ Watershed, ) from monai.utils import min_version, optional_import -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS _, has_skimage = optional_import("skimage", "0.19.3", min_version) _, has_scipy = optional_import("scipy", "1.8.1", min_version) @@ -43,7 +43,6 @@ @unittest.skipUnless(has_skimage, "Requires scikit-image library.") @unittest.skipUnless(has_scipy, "Requires scipy library.") class TestWatershed(unittest.TestCase): - @parameterized.expand(TESTS) def test_output(self, args, image, hover_map, expected_shape): mask = GenerateWatershedMask()(image) diff --git a/tests/test_watershedd.py b/tests/apps/pathology/transforms/post/test_watershedd.py similarity index 98% rename from tests/test_watershedd.py rename to tests/apps/pathology/transforms/post/test_watershedd.py index fc44996be4..2162802c36 100644 --- a/tests/test_watershedd.py +++ b/tests/apps/pathology/transforms/post/test_watershedd.py @@ -25,7 +25,7 @@ ) from monai.transforms import Compose from monai.utils import min_version, optional_import -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS _, has_skimage = optional_import("skimage", "0.19.3", min_version) _, has_scipy = optional_import("scipy", "1.8.1", min_version) @@ -48,7 +48,6 @@ @unittest.skipUnless(has_skimage, "Requires scikit-image library.") @unittest.skipUnless(has_scipy, "Requires scipy library.") class TestWatershedd(unittest.TestCase): - @parameterized.expand(TESTS) def test_output(self, args, image, hover_map, expected_shape): data = {"output": image, "hover_map": hover_map} diff --git a/tests/test_pathology_he_stain.py b/tests/apps/pathology/transforms/test_pathology_he_stain.py similarity index 100% rename from tests/test_pathology_he_stain.py rename to tests/apps/pathology/transforms/test_pathology_he_stain.py diff --git a/tests/test_pathology_he_stain_dict.py b/tests/apps/pathology/transforms/test_pathology_he_stain_dict.py similarity index 100% rename from tests/test_pathology_he_stain_dict.py rename to tests/apps/pathology/transforms/test_pathology_he_stain_dict.py diff --git a/tests/apps/reconstruction/__init__.py b/tests/apps/reconstruction/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/apps/reconstruction/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/apps/reconstruction/nets/__init__.py b/tests/apps/reconstruction/nets/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/apps/reconstruction/nets/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_recon_net_utils.py b/tests/apps/reconstruction/nets/test_recon_net_utils.py similarity index 95% rename from tests/test_recon_net_utils.py rename to tests/apps/reconstruction/nets/test_recon_net_utils.py index 48d3b59a17..6d1c17f851 100644 --- a/tests/test_recon_net_utils.py +++ b/tests/apps/reconstruction/nets/test_recon_net_utils.py @@ -27,7 +27,7 @@ sensitivity_map_expand, sensitivity_map_reduce, ) -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose # no need for checking devices, these functions don't change device format # reshape test case @@ -35,7 +35,7 @@ TEST_RESHAPE = [(im_2d,), (im_3d,)] # normalize test case -im_2d, im_3d = torch.randint(0, 3, [3, 4, 50, 70]).float(), torch.randint(0, 3, [3, 4, 50, 70, 80]).float() +im_2d, im_3d = (torch.randint(0, 3, [3, 4, 50, 70]).float(), torch.randint(0, 3, [3, 4, 50, 70, 80]).float()) TEST_NORMALIZE = [(im_2d,), (im_3d,)] # pad test case @@ -49,7 +49,6 @@ class TestReconNetUtils(unittest.TestCase): - @parameterized.expand(TEST_RESHAPE) def test_reshape_channel_complex(self, test_data): result = reshape_complex_to_channel_dim(test_data) diff --git a/tests/test_complex_utils.py b/tests/apps/reconstruction/test_complex_utils.py similarity index 97% rename from tests/test_complex_utils.py rename to tests/apps/reconstruction/test_complex_utils.py index fdcee4babe..e8ca4e0742 100644 --- a/tests/test_complex_utils.py +++ b/tests/apps/reconstruction/test_complex_utils.py @@ -18,7 +18,7 @@ from monai.apps.reconstruction.complex_utils import complex_abs, complex_conj, complex_mul, convert_to_tensor_complex from monai.utils.type_conversion import convert_data_type -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose # test case for convert_to_tensor_complex im_complex = [[1.0 + 1.0j, 1.0 + 1.0j], [1.0 + 1.0j, 1.0 + 1.0j]] @@ -51,7 +51,6 @@ class TestMRIUtils(unittest.TestCase): - @parameterized.expand(TESTS) def test_to_tensor_complex(self, test_data, expected_shape): result = convert_to_tensor_complex(test_data) diff --git a/tests/test_fastmri_reader.py b/tests/apps/reconstruction/test_fastmri_reader.py similarity index 97% rename from tests/test_fastmri_reader.py rename to tests/apps/reconstruction/test_fastmri_reader.py index 06c3954eae..f1d60ac630 100644 --- a/tests/test_fastmri_reader.py +++ b/tests/apps/reconstruction/test_fastmri_reader.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.apps.reconstruction.fastmri_reader import FastMRIReader -from tests.utils import SkipIfNoModule, assert_allclose +from tests.test_utils import SkipIfNoModule, assert_allclose TEST_CASE1 = [ { @@ -66,7 +66,6 @@ @SkipIfNoModule("h5py") class TestMRIUtils(unittest.TestCase): - @parameterized.expand([TEST_CASE1, TEST_CASE2]) def test_get_data(self, test_data, test_res, test_meta): reader = FastMRIReader() diff --git a/tests/test_mri_utils.py b/tests/apps/reconstruction/test_mri_utils.py similarity index 95% rename from tests/test_mri_utils.py rename to tests/apps/reconstruction/test_mri_utils.py index aabf06d02e..9102de2e68 100644 --- a/tests/test_mri_utils.py +++ b/tests/apps/reconstruction/test_mri_utils.py @@ -16,7 +16,7 @@ from parameterized import parameterized from monai.apps.reconstruction.mri_utils import root_sum_of_squares -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose # root_sum_of_squares im = [[3.0, 4.0], [3.0, 4.0]] @@ -27,7 +27,6 @@ class TestMRIUtils(unittest.TestCase): - @parameterized.expand(TESTS) def test_rss(self, test_data, res_data): result = root_sum_of_squares(test_data, spatial_dim=1) diff --git a/tests/apps/reconstruction/transforms/__init__.py b/tests/apps/reconstruction/transforms/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/apps/reconstruction/transforms/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_kspace_mask.py b/tests/apps/reconstruction/transforms/test_kspace_mask.py similarity index 100% rename from tests/test_kspace_mask.py rename to tests/apps/reconstruction/transforms/test_kspace_mask.py diff --git a/tests/test_reference_based_normalize_intensity.py b/tests/apps/reconstruction/transforms/test_reference_based_normalize_intensity.py similarity index 97% rename from tests/test_reference_based_normalize_intensity.py rename to tests/apps/reconstruction/transforms/test_reference_based_normalize_intensity.py index 2d946af118..8afc10ec37 100644 --- a/tests/test_reference_based_normalize_intensity.py +++ b/tests/apps/reconstruction/transforms/test_reference_based_normalize_intensity.py @@ -18,7 +18,7 @@ from monai.apps.reconstruction.transforms.dictionary import ReferenceBasedNormalizeIntensityd from monai.utils.type_conversion import convert_to_numpy -from tests.utils import TEST_NDARRAYS_NO_META_TENSOR, assert_allclose +from tests.test_utils import TEST_NDARRAYS_NO_META_TENSOR, assert_allclose # see test_normalize_intensityd for typical tests (like non-zero # normalization, device test, etc.) @@ -52,7 +52,6 @@ class TestDetailedNormalizeIntensityd(unittest.TestCase): - @parameterized.expand(TESTS) def test_target_mean_std(self, args, data, normalized_data, normalized_target, mean, std): dtype = data[args["keys"][0]].dtype diff --git a/tests/test_reference_based_spatial_cropd.py b/tests/apps/reconstruction/transforms/test_reference_based_spatial_cropd.py similarity index 97% rename from tests/test_reference_based_spatial_cropd.py rename to tests/apps/reconstruction/transforms/test_reference_based_spatial_cropd.py index 83cd9c4a5d..157da654ab 100644 --- a/tests/test_reference_based_spatial_cropd.py +++ b/tests/apps/reconstruction/transforms/test_reference_based_spatial_cropd.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.apps.reconstruction.transforms.dictionary import ReferenceBasedSpatialCropd -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS # see test_spatial_cropd for typical tests (like roi_start, # roi_slices, etc.) @@ -46,7 +46,6 @@ class TestTargetBasedSpatialCropd(unittest.TestCase): - @parameterized.expand(TESTS) def test_shape(self, args, data, expected_shape): cropper = ReferenceBasedSpatialCropd(keys=args["keys"], ref_key=args["ref_key"]) diff --git a/tests/test_auto3dseg_bundlegen.py b/tests/apps/test_auto3dseg_bundlegen.py similarity index 99% rename from tests/test_auto3dseg_bundlegen.py rename to tests/apps/test_auto3dseg_bundlegen.py index e7bf6820bc..f82782c21f 100644 --- a/tests/test_auto3dseg_bundlegen.py +++ b/tests/apps/test_auto3dseg_bundlegen.py @@ -26,7 +26,7 @@ from monai.bundle.config_parser import ConfigParser from monai.data import create_test_image_3d from monai.utils import set_determinism -from tests.utils import ( +from tests.test_utils import ( SkipIfBeforePyTorchVersion, get_testing_algo_template_path, skip_if_downloading_fails, @@ -107,7 +107,6 @@ def run_auto3dseg_before_bundlegen(test_path, work_dir): @SkipIfBeforePyTorchVersion((1, 11, 1)) @skip_if_quick class TestBundleGen(unittest.TestCase): - def setUp(self) -> None: set_determinism(0) self.test_dir = tempfile.TemporaryDirectory() diff --git a/tests/test_check_hash.py b/tests/apps/test_check_hash.py similarity index 100% rename from tests/test_check_hash.py rename to tests/apps/test_check_hash.py diff --git a/tests/test_cross_validation.py b/tests/apps/test_cross_validation.py similarity index 94% rename from tests/test_cross_validation.py rename to tests/apps/test_cross_validation.py index 6d0f2319fb..d776aef9b6 100644 --- a/tests/test_cross_validation.py +++ b/tests/apps/test_cross_validation.py @@ -11,20 +11,19 @@ from __future__ import annotations -import os import unittest +from pathlib import Path from monai.apps import CrossValidation, DecathlonDataset from monai.data import MetaTensor from monai.transforms import Compose, EnsureChannelFirstd, LoadImaged, ScaleIntensityd -from tests.utils import skip_if_downloading_fails, skip_if_quick +from tests.test_utils import skip_if_downloading_fails, skip_if_quick class TestCrossValidation(unittest.TestCase): - @skip_if_quick def test_values(self): - testing_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "testing_data") + testing_dir = Path(__file__).parents[1] / "testing_data" train_transform = Compose( [ LoadImaged(keys=["image", "label"]), diff --git a/tests/test_decathlondataset.py b/tests/apps/test_decathlondataset.py similarity index 95% rename from tests/test_decathlondataset.py rename to tests/apps/test_decathlondataset.py index 70a2a6c06c..a40e3b753c 100644 --- a/tests/test_decathlondataset.py +++ b/tests/apps/test_decathlondataset.py @@ -19,14 +19,13 @@ from monai.apps import DecathlonDataset from monai.data import MetaTensor from monai.transforms import Compose, EnsureChannelFirstd, LoadImaged, ScaleIntensityd -from tests.utils import skip_if_downloading_fails, skip_if_quick +from tests.test_utils import skip_if_downloading_fails, skip_if_quick class TestDecathlonDataset(unittest.TestCase): - @skip_if_quick def test_values(self): - testing_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "testing_data") + testing_dir = Path(__file__).resolve().parents[1] / "testing_data" transform = Compose( [ LoadImaged(keys=["image", "label"]), diff --git a/tests/test_download_and_extract.py b/tests/apps/test_download_and_extract.py similarity index 93% rename from tests/test_download_and_extract.py rename to tests/apps/test_download_and_extract.py index 439a11bbc1..190e32fc79 100644 --- a/tests/test_download_and_extract.py +++ b/tests/apps/test_download_and_extract.py @@ -11,7 +11,6 @@ from __future__ import annotations -import os import tempfile import unittest from pathlib import Path @@ -20,15 +19,14 @@ from parameterized import parameterized from monai.apps import download_and_extract, download_url, extractall -from tests.utils import SkipIfNoModule, skip_if_downloading_fails, skip_if_quick, testing_data_config +from tests.test_utils import SkipIfNoModule, skip_if_downloading_fails, skip_if_quick, testing_data_config @SkipIfNoModule("requests") class TestDownloadAndExtract(unittest.TestCase): - @skip_if_quick def test_actions(self): - testing_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "testing_data") + testing_dir = Path(__file__).parents[1] / "testing_data" config_dict = testing_data_config("images", "mednist") url = config_dict["url"] filepath = Path(testing_dir) / "MedNIST.tar.gz" diff --git a/tests/test_download_url_yandex.py b/tests/apps/test_download_url_yandex.py similarity index 100% rename from tests/test_download_url_yandex.py rename to tests/apps/test_download_url_yandex.py diff --git a/tests/test_mednistdataset.py b/tests/apps/test_mednistdataset.py similarity index 94% rename from tests/test_mednistdataset.py rename to tests/apps/test_mednistdataset.py index c1b21e9373..53da28911f 100644 --- a/tests/test_mednistdataset.py +++ b/tests/apps/test_mednistdataset.py @@ -19,16 +19,15 @@ from monai.apps import MedNISTDataset from monai.data import MetaTensor from monai.transforms import Compose, EnsureChannelFirstd, LoadImaged, ScaleIntensityd -from tests.utils import skip_if_downloading_fails, skip_if_quick +from tests.test_utils import skip_if_downloading_fails, skip_if_quick MEDNIST_FULL_DATASET_LENGTH = 58954 class TestMedNISTDataset(unittest.TestCase): - @skip_if_quick def test_values(self): - testing_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "testing_data") + testing_dir = Path(__file__).parents[1] / "testing_data" transform = Compose( [ LoadImaged(keys="image"), diff --git a/tests/test_mmar_download.py b/tests/apps/test_mmar_download.py similarity index 98% rename from tests/test_mmar_download.py rename to tests/apps/test_mmar_download.py index 2ac73a8149..bca3fa2a30 100644 --- a/tests/test_mmar_download.py +++ b/tests/apps/test_mmar_download.py @@ -25,7 +25,7 @@ from monai.apps.mmars import MODEL_DESC from monai.apps.mmars.mmars import _get_val from monai.utils import version_leq -from tests.utils import skip_if_downloading_fails, skip_if_quick +from tests.test_utils import skip_if_downloading_fails, skip_if_quick TEST_CASES = [["clara_pt_prostate_mri_segmentation"], ["clara_pt_covid19_ct_lesion_segmentation"]] TEST_EXTRACT_CASES = [ @@ -116,7 +116,6 @@ @unittest.skip("deprecating mmar tests") class TestMMMARDownload(unittest.TestCase): - @parameterized.expand(TEST_CASES) @skip_if_quick def test_download(self, idx): diff --git a/tests/test_tciadataset.py b/tests/apps/test_tciadataset.py similarity index 96% rename from tests/test_tciadataset.py rename to tests/apps/test_tciadataset.py index 5a16bb4816..c624aec5cf 100644 --- a/tests/test_tciadataset.py +++ b/tests/apps/test_tciadataset.py @@ -14,19 +14,19 @@ import os import shutil import unittest +from pathlib import Path from monai.apps import TciaDataset from monai.apps.tcia import DCM_FILENAME_REGEX, TCIA_LABEL_DICT from monai.data import MetaTensor from monai.transforms import Compose, EnsureChannelFirstd, LoadImaged, ScaleIntensityd -from tests.utils import skip_if_downloading_fails, skip_if_quick +from tests.test_utils import skip_if_downloading_fails, skip_if_quick class TestTciaDataset(unittest.TestCase): - @skip_if_quick def test_values(self): - testing_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "testing_data") + testing_dir = Path(__file__).parents[1] / "testing_data" download_len = 1 val_frac = 1.0 collection = "QIN-PROSTATE-Repeatability" diff --git a/tests/apps/vista3d/__init__.py b/tests/apps/vista3d/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/apps/vista3d/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_point_based_window_inferer.py b/tests/apps/vista3d/test_point_based_window_inferer.py similarity index 97% rename from tests/test_point_based_window_inferer.py rename to tests/apps/vista3d/test_point_based_window_inferer.py index 1b293288c4..de57d39606 100644 --- a/tests/test_point_based_window_inferer.py +++ b/tests/apps/vista3d/test_point_based_window_inferer.py @@ -20,7 +20,7 @@ from monai.networks import eval_mode from monai.networks.nets.vista3d import vista3d132 from monai.utils import optional_import -from tests.utils import SkipIfBeforePyTorchVersion, skip_if_quick +from tests.test_utils import SkipIfBeforePyTorchVersion, skip_if_quick device = "cuda" if torch.cuda.is_available() else "cpu" diff --git a/tests/test_vista3d_sampler.py b/tests/apps/vista3d/test_vista3d_sampler.py similarity index 100% rename from tests/test_vista3d_sampler.py rename to tests/apps/vista3d/test_vista3d_sampler.py diff --git a/tests/test_vista3d_transforms.py b/tests/apps/vista3d/test_vista3d_transforms.py similarity index 100% rename from tests/test_vista3d_transforms.py rename to tests/apps/vista3d/test_vista3d_transforms.py diff --git a/tests/bundle/__init__.py b/tests/bundle/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/bundle/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_bundle_ckpt_export.py b/tests/bundle/test_bundle_ckpt_export.py similarity index 91% rename from tests/test_bundle_ckpt_export.py rename to tests/bundle/test_bundle_ckpt_export.py index cfcadcfc4c..929c509b95 100644 --- a/tests/test_bundle_ckpt_export.py +++ b/tests/bundle/test_bundle_ckpt_export.py @@ -15,13 +15,16 @@ import os import tempfile import unittest +from pathlib import Path from parameterized import parameterized from monai.bundle import ConfigParser from monai.data import load_net_with_metadata from monai.networks import save_state -from tests.utils import command_line_tests, skip_if_windows +from tests.test_utils import command_line_tests, skip_if_windows + +TESTS_PATH = Path(__file__).parents[1] TEST_CASE_1 = ["", ""] @@ -46,8 +49,8 @@ def tearDown(self): @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3]) def test_export(self, key_in_ckpt, use_trace): - meta_file = os.path.join(os.path.dirname(__file__), "testing_data", "metadata.json") - config_file = os.path.join(os.path.dirname(__file__), "testing_data", "inference.json") + meta_file = os.path.join(TESTS_PATH, "testing_data", "metadata.json") + config_file = os.path.join(TESTS_PATH, "testing_data", "inference.json") with tempfile.TemporaryDirectory() as tempdir: def_args = {"meta_file": "will be replaced by `meta_file` arg"} def_args_file = os.path.join(tempdir, "def_args.yaml") @@ -78,7 +81,7 @@ def test_export(self, key_in_ckpt, use_trace): @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3]) def test_default_value(self, key_in_ckpt, use_trace): - config_file = os.path.join(os.path.dirname(__file__), "testing_data", "inference.json") + config_file = os.path.join(TESTS_PATH, "testing_data", "inference.json") with tempfile.TemporaryDirectory() as tempdir: def_args = {"meta_file": "will be replaced by `meta_file` arg"} def_args_file = os.path.join(tempdir, "def_args.yaml") diff --git a/tests/test_bundle_download.py b/tests/bundle/test_bundle_download.py similarity index 99% rename from tests/test_bundle_download.py rename to tests/bundle/test_bundle_download.py index 399c61b117..38620d98ff 100644 --- a/tests/test_bundle_download.py +++ b/tests/bundle/test_bundle_download.py @@ -27,7 +27,7 @@ from monai.bundle import ConfigParser, create_workflow, load from monai.bundle.scripts import _examine_monai_version, _list_latest_versions, download from monai.utils import optional_import -from tests.utils import ( +from tests.test_utils import ( SkipIfBeforePyTorchVersion, assert_allclose, command_line_tests, @@ -95,7 +95,6 @@ class TestDownload(unittest.TestCase): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2]) @skip_if_quick def test_github_download_bundle(self, bundle_name, version): @@ -261,7 +260,6 @@ def test_download_ngc(self, mock_get_versions): @skip_if_no_cuda class TestLoad(unittest.TestCase): - @parameterized.expand([TEST_CASE_7]) @skip_if_quick def test_load_weights(self, bundle_files, bundle_name, repo, device, model_file): @@ -406,7 +404,6 @@ def test_load_ts_module(self, bundle_files, bundle_name, version, repo, device, class TestDownloadLargefiles(unittest.TestCase): - @parameterized.expand([TEST_CASE_10]) @skip_if_quick def test_url_download_large_files(self, bundle_files, bundle_name, url, hash_val): diff --git a/tests/test_bundle_get_data.py b/tests/bundle/test_bundle_get_data.py similarity index 97% rename from tests/test_bundle_get_data.py rename to tests/bundle/test_bundle_get_data.py index f84713fbe3..7675d85a7d 100644 --- a/tests/test_bundle_get_data.py +++ b/tests/bundle/test_bundle_get_data.py @@ -17,7 +17,7 @@ from monai.bundle import get_all_bundles_list, get_bundle_info, get_bundle_versions from monai.utils import optional_import -from tests.utils import SkipIfNoModule, skip_if_downloading_fails, skip_if_quick, skip_if_windows +from tests.test_utils import SkipIfNoModule, skip_if_downloading_fails, skip_if_quick, skip_if_windows requests, _ = optional_import("requests") @@ -45,7 +45,6 @@ @skip_if_windows @SkipIfNoModule("requests") class TestGetBundleData(unittest.TestCase): - @parameterized.expand([TEST_CASE_3, TEST_CASE_4]) @skip_if_quick def test_get_all_bundles_list(self, params): diff --git a/tests/test_bundle_push_to_hf_hub.py b/tests/bundle/test_bundle_push_to_hf_hub.py similarity index 97% rename from tests/test_bundle_push_to_hf_hub.py rename to tests/bundle/test_bundle_push_to_hf_hub.py index 39368c6f40..d6f448af71 100644 --- a/tests/test_bundle_push_to_hf_hub.py +++ b/tests/bundle/test_bundle_push_to_hf_hub.py @@ -20,7 +20,7 @@ from monai.bundle import push_to_hf_hub from monai.utils import optional_import -from tests.utils import skip_if_quick +from tests.test_utils import skip_if_quick huggingface_hub, has_huggingface_hub = optional_import("huggingface_hub") @@ -28,7 +28,6 @@ class TestPushToHuggingFaceHub(unittest.TestCase): - @parameterized.expand([TEST_CASE_1]) @skip_if_quick @skipUnless(has_huggingface_hub, "Requires `huggingface_hub` package.") diff --git a/tests/test_bundle_trt_export.py b/tests/bundle/test_bundle_trt_export.py similarity index 92% rename from tests/test_bundle_trt_export.py rename to tests/bundle/test_bundle_trt_export.py index 27e1ee97a8..a7c570438d 100644 --- a/tests/test_bundle_trt_export.py +++ b/tests/bundle/test_bundle_trt_export.py @@ -15,6 +15,7 @@ import os import tempfile import unittest +from pathlib import Path from parameterized import parameterized @@ -22,7 +23,7 @@ from monai.data import load_net_with_metadata from monai.networks import save_state from monai.utils import optional_import -from tests.utils import ( +from tests.test_utils import ( SkipIfBeforeComputeCapabilityVersion, command_line_tests, skip_if_no_cuda, @@ -55,7 +56,6 @@ @skip_if_quick @SkipIfBeforeComputeCapabilityVersion((7, 5)) class TestTRTExport(unittest.TestCase): - def setUp(self): self.device = os.environ.get("CUDA_VISIBLE_DEVICES") if not self.device: @@ -70,8 +70,9 @@ def tearDown(self): @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4]) @unittest.skipUnless(has_torchtrt and has_tensorrt, "Torch-TensorRT is required for conversion!") def test_trt_export(self, convert_precision, input_shape, dynamic_batch): - meta_file = os.path.join(os.path.dirname(__file__), "testing_data", "metadata.json") - config_file = os.path.join(os.path.dirname(__file__), "testing_data", "inference.json") + tests_dir = Path(__file__).resolve().parent + meta_file = os.path.join(tests_dir, "testing_data", "metadata.json") + config_file = os.path.join(tests_dir, "testing_data", "inference.json") with tempfile.TemporaryDirectory() as tempdir: def_args = {"meta_file": "will be replaced by `meta_file` arg"} def_args_file = os.path.join(tempdir, "def_args.yaml") @@ -107,8 +108,9 @@ def test_trt_export(self, convert_precision, input_shape, dynamic_batch): has_onnx and has_torchtrt and has_tensorrt, "Onnx and TensorRT are required for onnx-trt conversion!" ) def test_onnx_trt_export(self, convert_precision, input_shape, dynamic_batch): - meta_file = os.path.join(os.path.dirname(__file__), "testing_data", "metadata.json") - config_file = os.path.join(os.path.dirname(__file__), "testing_data", "inference.json") + tests_dir = Path(__file__).resolve().parent + meta_file = os.path.join(tests_dir, "testing_data", "metadata.json") + config_file = os.path.join(tests_dir, "testing_data", "inference.json") with tempfile.TemporaryDirectory() as tempdir: def_args = {"meta_file": "will be replaced by `meta_file` arg"} def_args_file = os.path.join(tempdir, "def_args.yaml") diff --git a/tests/test_bundle_utils.py b/tests/bundle/test_bundle_utils.py similarity index 98% rename from tests/test_bundle_utils.py rename to tests/bundle/test_bundle_utils.py index 47c534f3b6..ec12262eb7 100644 --- a/tests/test_bundle_utils.py +++ b/tests/bundle/test_bundle_utils.py @@ -22,7 +22,7 @@ from monai.bundle.utils import load_bundle_config from monai.networks.nets import UNet from monai.utils import pprint_edges -from tests.utils import command_line_tests, skip_if_windows +from tests.test_utils import command_line_tests, skip_if_windows metadata = """ { @@ -51,7 +51,6 @@ @skip_if_windows class TestLoadBundleConfig(unittest.TestCase): - def setUp(self): self.bundle_dir = tempfile.TemporaryDirectory() self.dir_name = os.path.join(self.bundle_dir.name, "TestBundle") @@ -135,7 +134,6 @@ def test_load_config_ts(self): class TestPPrintEdges(unittest.TestCase): - def test_str(self): self.assertEqual(pprint_edges("", 0), "''") self.assertEqual(pprint_edges({"a": 1, "b": 2}, 0), "{'a': 1, 'b': 2}") diff --git a/tests/test_bundle_verify_metadata.py b/tests/bundle/test_bundle_verify_metadata.py similarity index 87% rename from tests/test_bundle_verify_metadata.py rename to tests/bundle/test_bundle_verify_metadata.py index f6c2192621..fd8535eb10 100644 --- a/tests/test_bundle_verify_metadata.py +++ b/tests/bundle/test_bundle_verify_metadata.py @@ -15,20 +15,21 @@ import os import tempfile import unittest +from pathlib import Path from parameterized import parameterized from monai.bundle import ConfigParser, verify_metadata -from tests.utils import command_line_tests, download_url_or_skip_test, skip_if_windows, testing_data_config +from tests.test_utils import command_line_tests, download_url_or_skip_test, skip_if_windows, testing_data_config -SCHEMA_FILE = os.path.join(os.path.dirname(__file__), "testing_data", "schema.json") +TESTS_DIR = Path(__file__).parents[1] +SCHEMA_FILE = os.path.join(TESTS_DIR, "testing_data", "schema.json") -TEST_CASE_1 = [os.path.join(os.path.dirname(__file__), "testing_data", "metadata.json"), SCHEMA_FILE] +TEST_CASE_1 = [os.path.join(TESTS_DIR, "testing_data", "metadata.json"), SCHEMA_FILE] @skip_if_windows class TestVerifyMetaData(unittest.TestCase): - def setUp(self): self.config = testing_data_config("configs", "test_meta_file") download_url_or_skip_test( diff --git a/tests/test_bundle_verify_net.py b/tests/bundle/test_bundle_verify_net.py similarity index 91% rename from tests/test_bundle_verify_net.py rename to tests/bundle/test_bundle_verify_net.py index f55fdd597b..f06f36a5a1 100644 --- a/tests/test_bundle_verify_net.py +++ b/tests/bundle/test_bundle_verify_net.py @@ -14,21 +14,23 @@ import os import tempfile import unittest +from pathlib import Path from parameterized import parameterized from monai.bundle import ConfigParser, verify_net_in_out -from tests.utils import command_line_tests, skip_if_no_cuda, skip_if_windows +from tests.test_utils import command_line_tests, skip_if_no_cuda, skip_if_windows + +TESTS_PATH = Path(__file__).parents[1].as_posix() TEST_CASE_1 = [ - os.path.join(os.path.dirname(__file__), "testing_data", "metadata.json"), - os.path.join(os.path.dirname(__file__), "testing_data", "inference.json"), + os.path.join(TESTS_PATH, "testing_data", "metadata.json"), + os.path.join(TESTS_PATH, "testing_data", "inference.json"), ] @skip_if_windows class TestVerifyNetwork(unittest.TestCase): - @parameterized.expand([TEST_CASE_1]) def test_verify(self, meta_file, config_file): with tempfile.TemporaryDirectory() as tempdir: diff --git a/tests/test_bundle_workflow.py b/tests/bundle/test_bundle_workflow.py similarity index 88% rename from tests/test_bundle_workflow.py rename to tests/bundle/test_bundle_workflow.py index 893b9dc991..ceb034ecff 100644 --- a/tests/test_bundle_workflow.py +++ b/tests/bundle/test_bundle_workflow.py @@ -17,6 +17,7 @@ import tempfile import unittest from copy import deepcopy +from pathlib import Path import nibabel as nib import numpy as np @@ -30,19 +31,20 @@ from monai.transforms import Compose, LoadImage, LoadImaged, SaveImaged from tests.nonconfig_workflow import NonConfigWorkflow, PythonicWorkflowImpl -TEST_CASE_1 = [os.path.join(os.path.dirname(__file__), "testing_data", "inference.json")] +MODULE_PATH = Path(__file__).resolve().parents[1] -TEST_CASE_2 = [os.path.join(os.path.dirname(__file__), "testing_data", "inference.yaml")] +TEST_CASE_1 = [os.path.join(MODULE_PATH, "testing_data", "inference.json")] -TEST_CASE_3 = [os.path.join(os.path.dirname(__file__), "testing_data", "config_fl_train.json")] +TEST_CASE_2 = [os.path.join(MODULE_PATH, "testing_data", "inference.yaml")] -TEST_CASE_4 = [os.path.join(os.path.dirname(__file__), "testing_data", "responsive_inference.json")] +TEST_CASE_3 = [os.path.join(MODULE_PATH, "testing_data", "config_fl_train.json")] + +TEST_CASE_4 = [os.path.join(MODULE_PATH, "testing_data", "responsive_inference.json")] TEST_CASE_NON_CONFIG_WRONG_LOG = [None, "logging.conf", "Cannot find the logging config file: logging.conf."] class TestBundleWorkflow(unittest.TestCase): - def setUp(self): self.data_dir = tempfile.mkdtemp() self.expected_shape = (128, 128, 128) @@ -105,7 +107,7 @@ def test_inference_config(self, config_file): inferer = ConfigWorkflow( workflow_type="infer", config_file=config_file, - logging_file=os.path.join(os.path.dirname(__file__), "testing_data", "logging.conf"), + logging_file=os.path.join(MODULE_PATH, "testing_data", "logging.conf"), **override, ) self._test_inferer(inferer) @@ -114,8 +116,8 @@ def test_inference_config(self, config_file): inferer = ConfigWorkflow( config_file=config_file, workflow_type="infer", - properties_path=os.path.join(os.path.dirname(__file__), "testing_data", "fl_infer_properties.json"), - logging_file=os.path.join(os.path.dirname(__file__), "testing_data", "logging.conf"), + properties_path=os.path.join(MODULE_PATH, "testing_data", "fl_infer_properties.json"), + logging_file=os.path.join(MODULE_PATH, "testing_data", "logging.conf"), **override, ) self._test_inferer(inferer) @@ -130,7 +132,7 @@ def test_responsive_inference_config(self, config_file): inferer = ConfigWorkflow( workflow_type="infer", config_file=config_file, - logging_file=os.path.join(os.path.dirname(__file__), "testing_data", "logging.conf"), + logging_file=os.path.join(MODULE_PATH, "testing_data", "logging.conf"), ) # FIXME: temp add the property for test, we should add it to some formal realtime infer properties inferer.add_property(name="dataflow", required=True, config_id="dataflow") @@ -156,7 +158,7 @@ def test_train_config(self, config_file): trainer = ConfigWorkflow( workflow_type="train", config_file=config_file, - logging_file=os.path.join(os.path.dirname(__file__), "testing_data", "logging.conf"), + logging_file=os.path.join(MODULE_PATH, "testing_data", "logging.conf"), init_id="initialize", run_id="run", final_id="finalize", @@ -202,8 +204,8 @@ def test_non_config_wrong_log_cases(self, meta_file, logging_file, expected_erro def test_pythonic_workflow(self): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") config_file = {"roi_size": (64, 64, 32)} - meta_file = os.path.join(os.path.dirname(__file__), "testing_data", "metadata.json") - property_path = os.path.join(os.path.dirname(__file__), "testing_data", "python_workflow_properties.json") + meta_file = os.path.join(MODULE_PATH, "testing_data", "metadata.json") + property_path = os.path.join(MODULE_PATH, "testing_data", "python_workflow_properties.json") workflow = PythonicWorkflowImpl( workflow_type="infer", config_file=config_file, meta_file=meta_file, properties_path=property_path ) @@ -228,11 +230,11 @@ def test_pythonic_workflow(self): def test_create_pythonic_workflow(self): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") config_file = {"roi_size": (64, 64, 32)} - meta_file = os.path.join(os.path.dirname(__file__), "testing_data", "metadata.json") - property_path = os.path.join(os.path.dirname(__file__), "testing_data", "python_workflow_properties.json") - sys.path.append(os.path.dirname(__file__)) + meta_file = os.path.join(MODULE_PATH, "testing_data", "metadata.json") + property_path = os.path.join(MODULE_PATH, "testing_data", "python_workflow_properties.json") + sys.path.append(MODULE_PATH) workflow = create_workflow( - "nonconfig_workflow.PythonicWorkflowImpl", + "tests.nonconfig_workflow.PythonicWorkflowImpl", workflow_type="infer", config_file=config_file, meta_file=meta_file, diff --git a/tests/test_component_locator.py b/tests/bundle/test_component_locator.py similarity index 100% rename from tests/test_component_locator.py rename to tests/bundle/test_component_locator.py diff --git a/tests/test_config_item.py b/tests/bundle/test_config_item.py similarity index 100% rename from tests/test_config_item.py rename to tests/bundle/test_config_item.py diff --git a/tests/test_config_parser.py b/tests/bundle/test_config_parser.py similarity index 97% rename from tests/test_config_parser.py rename to tests/bundle/test_config_parser.py index 2b00c9f9d1..5ead2af382 100644 --- a/tests/test_config_parser.py +++ b/tests/bundle/test_config_parser.py @@ -26,7 +26,7 @@ from monai.data import DataLoader, Dataset from monai.transforms import Compose, LoadImaged, RandTorchVisiond from monai.utils import min_version, optional_import -from tests.utils import TimedCall +from tests.test_utils import TimedCall _, has_tv = optional_import("torchvision", "0.8.0", min_version) _, has_yaml = optional_import("yaml") @@ -72,7 +72,6 @@ def case_pdb_inst(sarg=None): class TestClass: - @staticmethod def compute(a, b, func=lambda x, y: x + y): return func(a, b) @@ -92,9 +91,9 @@ def __call__(self, a, b): "cls_func": "$TestClass.cls_compute", "lambda_static_func": "$lambda x, y: TestClass.compute(x, y)", "lambda_cls_func": "$lambda x, y: TestClass.cls_compute(x, y)", - "compute": {"_target_": "tests.test_config_parser.TestClass.compute", "func": "@basic_func"}, - "cls_compute": {"_target_": "tests.test_config_parser.TestClass.cls_compute", "func": "@basic_func"}, - "call_compute": {"_target_": "tests.test_config_parser.TestClass"}, + "compute": {"_target_": "tests.bundle.test_config_parser.TestClass.compute", "func": "@basic_func"}, + "cls_compute": {"_target_": "tests.bundle.test_config_parser.TestClass.cls_compute", "func": "@basic_func"}, + "call_compute": {"_target_": "tests.bundle.test_config_parser.TestClass"}, "error_func": "$TestClass.__call__", "": "$lambda x, y: x + y", } @@ -143,7 +142,6 @@ def __call__(self, a, b): class TestConfigParser(unittest.TestCase): - def test_config_content(self): test_config = {"preprocessing": [{"_target_": "LoadImage"}], "dataset": {"_target_": "Dataset"}} parser = ConfigParser(config=test_config) diff --git a/tests/test_reference_resolver.py b/tests/bundle/test_reference_resolver.py similarity index 100% rename from tests/test_reference_resolver.py rename to tests/bundle/test_reference_resolver.py diff --git a/tests/clang_format_utils.py b/tests/clang_format_utils.py index 11483e957d..fbdd1d980c 100644 --- a/tests/clang_format_utils.py +++ b/tests/clang_format_utils.py @@ -18,6 +18,7 @@ import platform import stat import sys +from pathlib import Path from monai.apps.utils import download_url @@ -25,7 +26,7 @@ HOST_PLATFORM = platform.system() # MONAI directory root, derived from the location of this file. -MONAI_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) +MONAI_ROOT = Path(__file__).resolve().parent.parent # This dictionary maps each platform to the S3 object URL for its clang-format binary. PLATFORM_TO_CF_URL = { diff --git a/tests/config/__init__.py b/tests/config/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/config/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_cv2_dist.py b/tests/config/test_cv2_dist.py similarity index 97% rename from tests/test_cv2_dist.py rename to tests/config/test_cv2_dist.py index 562c205763..2ef8e5b10f 100644 --- a/tests/test_cv2_dist.py +++ b/tests/config/test_cv2_dist.py @@ -20,7 +20,7 @@ # FIXME: test for the workaround of https://github.com/Project-MONAI/MONAI/issues/5291 from monai.config.deviceconfig import print_config -from tests.utils import skip_if_no_cuda +from tests.test_utils import skip_if_no_cuda def main_worker(rank, ngpus_per_node, port): @@ -42,7 +42,6 @@ def main_worker(rank, ngpus_per_node, port): @skip_if_no_cuda class TestCV2Dist(unittest.TestCase): - def test_cv2_cuda_ops(self): print_config() ngpus_per_node = torch.cuda.device_count() diff --git a/tests/croppers.py b/tests/croppers.py index cfececfa9f..fe06c2e2cb 100644 --- a/tests/croppers.py +++ b/tests/croppers.py @@ -20,11 +20,10 @@ from monai.transforms import Randomizable from monai.transforms.lazy.functional import apply_pending from monai.transforms.transform import MapTransform -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose class CropTest(unittest.TestCase): - @staticmethod def get_arr(shape): return np.random.randint(100, size=shape).astype(float) diff --git a/tests/test_meta_tensor.py b/tests/data/meta_tensor/test_meta_tensor.py similarity index 99% rename from tests/test_meta_tensor.py rename to tests/data/meta_tensor/test_meta_tensor.py index 60b6019703..d6a7ef9f0b 100644 --- a/tests/test_meta_tensor.py +++ b/tests/data/meta_tensor/test_meta_tensor.py @@ -34,7 +34,7 @@ from monai.transforms import BorderPadd, Compose, DivisiblePadd, FromMetaTensord, ToMetaTensord from monai.utils.enums import PostFix from monai.utils.module import pytorch_after -from tests.utils import TEST_DEVICES, SkipIfBeforePyTorchVersion, assert_allclose, skip_if_no_cuda +from tests.test_utils import TEST_DEVICES, SkipIfBeforePyTorchVersion, assert_allclose, skip_if_no_cuda DTYPES = [[torch.float32], [torch.float64], [torch.float16], [torch.int64], [torch.int32], [None]] TESTS = [] @@ -50,7 +50,6 @@ def rand_string(min_len=5, max_len=10): class TestMetaTensor(unittest.TestCase): - @staticmethod def get_im(shape=None, dtype=None, device=None): if shape is None: diff --git a/tests/test_to_from_meta_tensord.py b/tests/data/meta_tensor/test_to_from_meta_tensord.py similarity index 99% rename from tests/test_to_from_meta_tensord.py rename to tests/data/meta_tensor/test_to_from_meta_tensord.py index fe777cec77..64b64728cc 100644 --- a/tests/test_to_from_meta_tensord.py +++ b/tests/data/meta_tensor/test_to_from_meta_tensord.py @@ -24,7 +24,7 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms import FromMetaTensord, ToMetaTensord from monai.utils.enums import PostFix -from tests.utils import TEST_DEVICES, assert_allclose +from tests.test_utils import TEST_DEVICES, assert_allclose DTYPES = [[torch.float32], [torch.float64], [torch.float16], [torch.int64], [torch.int32]] TESTS = [] @@ -42,7 +42,6 @@ def rand_string(min_len=5, max_len=10): @unittest.skipIf(config.USE_META_DICT, "skipping not metatensor") class TestToFromMetaTensord(unittest.TestCase): - @staticmethod def get_im(shape=None, dtype=None, device=None): if shape is None: diff --git a/tests/test_arraydataset.py b/tests/data/test_arraydataset.py similarity index 100% rename from tests/test_arraydataset.py rename to tests/data/test_arraydataset.py diff --git a/tests/test_box_utils.py b/tests/data/test_box_utils.py similarity index 99% rename from tests/test_box_utils.py rename to tests/data/test_box_utils.py index 3c05efe0d0..390fd901fd 100644 --- a/tests/test_box_utils.py +++ b/tests/data/test_box_utils.py @@ -35,7 +35,7 @@ non_max_suppression, ) from monai.utils.type_conversion import convert_data_type -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -140,7 +140,6 @@ class TestCreateBoxList(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, input_data, mode2, expected_box, expected_area): expected_box = convert_data_type(expected_box, dtype=np.float32)[0] diff --git a/tests/test_cachedataset.py b/tests/data/test_cachedataset.py similarity index 100% rename from tests/test_cachedataset.py rename to tests/data/test_cachedataset.py diff --git a/tests/test_cachedataset_parallel.py b/tests/data/test_cachedataset_parallel.py similarity index 100% rename from tests/test_cachedataset_parallel.py rename to tests/data/test_cachedataset_parallel.py diff --git a/tests/test_cachedataset_persistent_workers.py b/tests/data/test_cachedataset_persistent_workers.py similarity index 100% rename from tests/test_cachedataset_persistent_workers.py rename to tests/data/test_cachedataset_persistent_workers.py diff --git a/tests/test_cachentransdataset.py b/tests/data/test_cachentransdataset.py similarity index 100% rename from tests/test_cachentransdataset.py rename to tests/data/test_cachentransdataset.py diff --git a/tests/test_check_missing_files.py b/tests/data/test_check_missing_files.py similarity index 100% rename from tests/test_check_missing_files.py rename to tests/data/test_check_missing_files.py diff --git a/tests/test_create_cross_validation_datalist.py b/tests/data/test_create_cross_validation_datalist.py similarity index 100% rename from tests/test_create_cross_validation_datalist.py rename to tests/data/test_create_cross_validation_datalist.py diff --git a/tests/test_csv_dataset.py b/tests/data/test_csv_dataset.py similarity index 100% rename from tests/test_csv_dataset.py rename to tests/data/test_csv_dataset.py diff --git a/tests/test_csv_iterable_dataset.py b/tests/data/test_csv_iterable_dataset.py similarity index 99% rename from tests/test_csv_iterable_dataset.py rename to tests/data/test_csv_iterable_dataset.py index e06da0c41b..ed71cb39d4 100644 --- a/tests/test_csv_iterable_dataset.py +++ b/tests/data/test_csv_iterable_dataset.py @@ -21,12 +21,11 @@ from monai.data import CSVIterableDataset, DataLoader from monai.transforms import ToNumpyd -from tests.utils import skip_if_windows +from tests.test_utils import skip_if_windows @skip_if_windows class TestCSVIterableDataset(unittest.TestCase): - def test_values(self): with tempfile.TemporaryDirectory() as tempdir: test_data1 = [ diff --git a/tests/test_csv_saver.py b/tests/data/test_csv_saver.py similarity index 100% rename from tests/test_csv_saver.py rename to tests/data/test_csv_saver.py diff --git a/tests/test_dataloader.py b/tests/data/test_dataloader.py similarity index 98% rename from tests/test_dataloader.py rename to tests/data/test_dataloader.py index 73e27799f7..32e624a860 100644 --- a/tests/test_dataloader.py +++ b/tests/data/test_dataloader.py @@ -21,7 +21,7 @@ from monai.data import CacheDataset, DataLoader, Dataset, ZipDataset from monai.transforms import Compose, DataStatsd, Randomizable, SimulateDelayd from monai.utils import convert_to_numpy, set_determinism -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_CASE_1 = [[{"image": np.asarray([1, 2, 3])}, {"image": np.asarray([4, 5])}]] @@ -29,7 +29,6 @@ class TestDataLoader(unittest.TestCase): - def test_values(self): datalist = [ {"image": "spleen_19.nii.gz", "label": "spleen_label_19.nii.gz"}, @@ -60,7 +59,6 @@ def test_exception(self, datalist): class _RandomDataset(torch.utils.data.Dataset, Randomizable): - def __getitem__(self, index): return self.R.randint(0, 1000, (1,)) diff --git a/tests/test_dataset.py b/tests/data/test_dataset.py similarity index 98% rename from tests/test_dataset.py rename to tests/data/test_dataset.py index 0d37ae2efd..572dccc53b 100644 --- a/tests/test_dataset.py +++ b/tests/data/test_dataset.py @@ -24,13 +24,12 @@ from monai.data import Dataset from monai.transforms import Compose, Lambda, LoadImage, LoadImaged, SimulateDelay, SimulateDelayd -from tests.test_compose import TEST_COMPOSE_LAZY_ON_CALL_LOGGING_TEST_CASES, data_from_keys +from tests.transforms.compose.test_compose import TEST_COMPOSE_LAZY_ON_CALL_LOGGING_TEST_CASES, data_from_keys TEST_CASE_1 = [(128, 128, 128)] class TestDataset(unittest.TestCase): - @parameterized.expand([TEST_CASE_1]) def test_shape(self, expected_shape): test_image = nib.Nifti1Image(np.random.randint(0, 2, size=[128, 128, 128]).astype(float), np.eye(4)) @@ -100,7 +99,6 @@ def test_dataset_lazy_on_call(self): class TestTupleDataset(unittest.TestCase): - @parameterized.expand([TEST_CASE_1]) def test_shape(self, expected_shape): test_image = nib.Nifti1Image(np.random.randint(0, 2, size=[128, 128, 128]).astype(float), np.eye(4)) diff --git a/tests/test_dataset_func.py b/tests/data/test_dataset_func.py similarity index 100% rename from tests/test_dataset_func.py rename to tests/data/test_dataset_func.py diff --git a/tests/test_dataset_summary.py b/tests/data/test_dataset_summary.py similarity index 100% rename from tests/test_dataset_summary.py rename to tests/data/test_dataset_summary.py diff --git a/tests/test_fft_utils.py b/tests/data/test_fft_utils.py similarity index 97% rename from tests/test_fft_utils.py rename to tests/data/test_fft_utils.py index 7c7035770a..f09cb26ae4 100644 --- a/tests/test_fft_utils.py +++ b/tests/data/test_fft_utils.py @@ -16,7 +16,7 @@ from parameterized import parameterized from monai.data.fft_utils import fftn_centered, ifftn_centered -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose # im = [[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]] @@ -42,7 +42,6 @@ class TestFFT(unittest.TestCase): - @parameterized.expand(TESTS) def test(self, test_data, res_data): result = fftn_centered(test_data, spatial_dims=2, is_complex=False) diff --git a/tests/test_folder_layout.py b/tests/data/test_folder_layout.py similarity index 100% rename from tests/test_folder_layout.py rename to tests/data/test_folder_layout.py diff --git a/tests/test_gdsdataset.py b/tests/data/test_gdsdataset.py similarity index 99% rename from tests/test_gdsdataset.py rename to tests/data/test_gdsdataset.py index 5d2e2aa013..b4acb3bf55 100644 --- a/tests/test_gdsdataset.py +++ b/tests/data/test_gdsdataset.py @@ -23,7 +23,7 @@ from monai.data import GDSDataset, json_hashing from monai.transforms import Compose, Flip, Identity, LoadImaged, SimulateDelayd, Transform from monai.utils import optional_import -from tests.utils import TEST_NDARRAYS, assert_allclose, skip_if_no_cuda +from tests.test_utils import TEST_NDARRAYS, assert_allclose, skip_if_no_cuda _, has_cp = optional_import("cupy") nib, has_nib = optional_import("nibabel") @@ -64,7 +64,6 @@ class _InplaceXform(Transform): - def __call__(self, data): data[0] = data[0] + 1 return data @@ -74,7 +73,6 @@ def __call__(self, data): @unittest.skipUnless(has_cp, "Requires CuPy library.") @unittest.skipUnless(has_cp and has_kvikio_numpy, "Requires CuPy and kvikio library.") class TestDataset(unittest.TestCase): - def test_cache(self): """testing no inplace change to the hashed item""" for p in TEST_NDARRAYS[:2]: diff --git a/tests/test_grid_dataset.py b/tests/data/test_grid_dataset.py similarity index 99% rename from tests/test_grid_dataset.py rename to tests/data/test_grid_dataset.py index 4a3b4b6340..0b44564834 100644 --- a/tests/test_grid_dataset.py +++ b/tests/data/test_grid_dataset.py @@ -20,7 +20,7 @@ from monai.data import DataLoader, GridPatchDataset, PatchIter, PatchIterd, iter_patch from monai.transforms import RandShiftIntensity, RandShiftIntensityd from monai.utils import set_determinism -from tests.utils import TEST_NDARRAYS, assert_allclose, get_arange_img +from tests.test_utils import TEST_NDARRAYS, assert_allclose, get_arange_img def identity_generator(x): @@ -58,7 +58,6 @@ def identity_generator(x): class TestGridPatchDataset(unittest.TestCase): - def setUp(self): set_determinism(seed=1234) diff --git a/tests/test_handler_smartcache.py b/tests/data/test_handler_smartcache.py similarity index 100% rename from tests/test_handler_smartcache.py rename to tests/data/test_handler_smartcache.py diff --git a/tests/test_hashing.py b/tests/data/test_hashing.py similarity index 100% rename from tests/test_hashing.py rename to tests/data/test_hashing.py diff --git a/tests/test_header_correct.py b/tests/data/test_header_correct.py similarity index 100% rename from tests/test_header_correct.py rename to tests/data/test_header_correct.py diff --git a/tests/test_image_dataset.py b/tests/data/test_image_dataset.py similarity index 100% rename from tests/test_image_dataset.py rename to tests/data/test_image_dataset.py diff --git a/tests/test_image_rw.py b/tests/data/test_image_rw.py similarity index 99% rename from tests/test_image_rw.py rename to tests/data/test_image_rw.py index 7e1c1deecc..d90c1c8571 100644 --- a/tests/test_image_rw.py +++ b/tests/data/test_image_rw.py @@ -26,14 +26,13 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms import LoadImage, SaveImage, moveaxis from monai.utils import MetaKeys, OptionalImportError, optional_import -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose _, has_itk = optional_import("itk", allow_namespace_pkg=True) @unittest.skipUnless(has_itk, "itk not installed") class TestLoadSaveNifti(unittest.TestCase): - def setUp(self): self.test_dir = tempfile.mkdtemp() @@ -98,7 +97,6 @@ def test_4d(self, reader, writer): @unittest.skipUnless(has_itk, "itk not installed") class TestLoadSavePNG(unittest.TestCase): - def setUp(self): self.test_dir = tempfile.mkdtemp() @@ -139,7 +137,6 @@ def test_rgb(self, reader, writer): class TestRegRes(unittest.TestCase): - def test_0_default(self): self.assertTrue(len(resolve_writer(".png")) > 0, "has png writer") self.assertTrue(len(resolve_writer(".nrrd")) > 0, "has nrrd writer") @@ -156,7 +153,6 @@ def test_1_new(self): @unittest.skipUnless(has_itk, "itk not installed") class TestLoadSaveNrrd(unittest.TestCase): - def setUp(self): self.test_dir = tempfile.mkdtemp() diff --git a/tests/test_init_reader.py b/tests/data/test_init_reader.py similarity index 98% rename from tests/test_init_reader.py rename to tests/data/test_init_reader.py index 8331f742ec..4170412207 100644 --- a/tests/test_init_reader.py +++ b/tests/data/test_init_reader.py @@ -15,11 +15,10 @@ from monai.data import ITKReader, NibabelReader, NrrdReader, NumpyReader, PILReader, PydicomReader from monai.transforms import LoadImage, LoadImaged -from tests.utils import SkipIfNoModule +from tests.test_utils import SkipIfNoModule class TestInitLoadImage(unittest.TestCase): - def test_load_image(self): instance1 = LoadImage(image_only=False, dtype=None) instance2 = LoadImage(image_only=True, dtype=None) diff --git a/tests/test_is_supported_format.py b/tests/data/test_is_supported_format.py similarity index 100% rename from tests/test_is_supported_format.py rename to tests/data/test_is_supported_format.py diff --git a/tests/test_iterable_dataset.py b/tests/data/test_iterable_dataset.py similarity index 100% rename from tests/test_iterable_dataset.py rename to tests/data/test_iterable_dataset.py diff --git a/tests/test_itk_torch_bridge.py b/tests/data/test_itk_torch_bridge.py similarity index 98% rename from tests/test_itk_torch_bridge.py rename to tests/data/test_itk_torch_bridge.py index 22ae019271..a8b35b61cb 100644 --- a/tests/test_itk_torch_bridge.py +++ b/tests/data/test_itk_torch_bridge.py @@ -15,6 +15,7 @@ import os import tempfile import unittest +from pathlib import Path import numpy as np import torch @@ -35,7 +36,13 @@ from monai.networks.blocks import Warp from monai.transforms import Affine from monai.utils import optional_import, set_determinism -from tests.utils import assert_allclose, skip_if_downloading_fails, skip_if_quick, test_is_quick, testing_data_config +from tests.test_utils import ( + assert_allclose, + skip_if_downloading_fails, + skip_if_quick, + test_is_quick, + testing_data_config, +) itk, has_itk = optional_import("itk") _, has_nib = optional_import("nibabel") @@ -49,10 +56,9 @@ @unittest.skipUnless(has_itk, "Requires `itk` package.") class TestITKTorchAffineMatrixBridge(unittest.TestCase): - def setUp(self): set_determinism(seed=0) - self.data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "testing_data") + self.data_dir = Path(__file__).parents[1] / "testing_data" self.reader = ITKReader(pixel_type=itk.F) for file_name in RW_TESTS: @@ -494,7 +500,6 @@ def test_use_reference_space(self, ref_filepath, filepath): @unittest.skipUnless(has_nib, "Requires `nibabel` package.") @skip_if_quick class TestITKTorchRW(unittest.TestCase): - def setUp(self): TestITKTorchAffineMatrixBridge.setUp(self) diff --git a/tests/test_itk_writer.py b/tests/data/test_itk_writer.py similarity index 100% rename from tests/test_itk_writer.py rename to tests/data/test_itk_writer.py diff --git a/tests/test_list_data_collate.py b/tests/data/test_list_data_collate.py similarity index 100% rename from tests/test_list_data_collate.py rename to tests/data/test_list_data_collate.py diff --git a/tests/test_lmdbdataset.py b/tests/data/test_lmdbdataset.py similarity index 99% rename from tests/test_lmdbdataset.py rename to tests/data/test_lmdbdataset.py index 9d128dd728..04fbf95cc3 100644 --- a/tests/test_lmdbdataset.py +++ b/tests/data/test_lmdbdataset.py @@ -21,7 +21,7 @@ from monai.data import LMDBDataset, json_hashing from monai.transforms import Compose, LoadImaged, SimulateDelayd, Transform -from tests.utils import skip_if_windows +from tests.test_utils import skip_if_windows TEST_CASE_1 = [ Compose( @@ -81,7 +81,6 @@ class _InplaceXform(Transform): - def __call__(self, data): if data: data[0] = data[0] + np.pi @@ -92,7 +91,6 @@ def __call__(self, data): @skip_if_windows class TestLMDBDataset(unittest.TestCase): - def test_cache(self): """testing no inplace change to the hashed item""" items = [[list(range(i))] for i in range(5)] diff --git a/tests/test_lmdbdataset_dist.py b/tests/data/test_lmdbdataset_dist.py similarity index 97% rename from tests/test_lmdbdataset_dist.py rename to tests/data/test_lmdbdataset_dist.py index 1acb89beb3..0ebe206205 100644 --- a/tests/test_lmdbdataset_dist.py +++ b/tests/data/test_lmdbdataset_dist.py @@ -19,11 +19,10 @@ from monai.data import LMDBDataset, json_hashing from monai.transforms import Transform -from tests.utils import DistCall, DistTestCase, skip_if_windows +from tests.test_utils import DistCall, DistTestCase, skip_if_windows class _InplaceXform(Transform): - def __call__(self, data): if data: data[0] = data[0] + np.pi @@ -34,7 +33,6 @@ def __call__(self, data): @skip_if_windows class TestMPLMDBDataset(DistTestCase): - def setUp(self): self.tempdir = tempfile.mkdtemp() diff --git a/tests/test_load_decathlon_datalist.py b/tests/data/test_load_decathlon_datalist.py similarity index 100% rename from tests/test_load_decathlon_datalist.py rename to tests/data/test_load_decathlon_datalist.py diff --git a/tests/test_make_nifti.py b/tests/data/test_make_nifti.py similarity index 96% rename from tests/test_make_nifti.py rename to tests/data/test_make_nifti.py index 08d3a731ab..f604eab76f 100644 --- a/tests/test_make_nifti.py +++ b/tests/data/test_make_nifti.py @@ -21,7 +21,7 @@ from monai.data.synthetic import create_test_image_2d from monai.utils import optional_import -from tests.utils import make_nifti_image +from tests.test_utils import make_nifti_image _, has_nib = optional_import("nibabel") @@ -34,7 +34,6 @@ @unittest.skipUnless(has_nib, "Requires nibabel") class TestMakeNifti(unittest.TestCase): - @parameterized.expand(TESTS) def test_make_nifti(self, params): im, _ = create_test_image_2d(100, 88) diff --git a/tests/test_mapping_file.py b/tests/data/test_mapping_file.py similarity index 100% rename from tests/test_mapping_file.py rename to tests/data/test_mapping_file.py diff --git a/tests/test_masked_patch_wsi_dataset.py b/tests/data/test_masked_patch_wsi_dataset.py similarity index 95% rename from tests/test_masked_patch_wsi_dataset.py rename to tests/data/test_masked_patch_wsi_dataset.py index 8d24075595..f2ff86c365 100644 --- a/tests/test_masked_patch_wsi_dataset.py +++ b/tests/data/test_masked_patch_wsi_dataset.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path from unittest import skipUnless from numpy.testing import assert_array_equal @@ -21,7 +22,7 @@ from monai.data import Dataset, MaskedPatchWSIDataset from monai.transforms import Lambdad from monai.utils import ProbMapKeys, WSIPatchKeys, optional_import, set_determinism -from tests.utils import download_url_or_skip_test, testing_data_config +from tests.test_utils import download_url_or_skip_test, testing_data_config set_determinism(0) @@ -34,7 +35,8 @@ FILE_KEY = "wsi_generic_tiff" FILE_URL = testing_data_config("images", FILE_KEY, "url") -FILE_PATH = os.path.join(os.path.dirname(__file__), "testing_data", f"temp_{FILE_KEY}.tiff") +TESTS_PATH = Path(__file__).parents[1] +FILE_PATH = os.path.join(TESTS_PATH, "testing_data", f"temp_{FILE_KEY}.tiff") TEST_CASE_0 = [ {"data": [{"image": FILE_PATH, WSIPatchKeys.LEVEL: 8, WSIPatchKeys.SIZE: (2, 2)}], "mask_level": 8}, @@ -74,7 +76,6 @@ def setUpModule(): class MaskedPatchWSIDatasetTests: - class Tests(unittest.TestCase): backend = None @@ -101,7 +102,6 @@ def test_gen_patches(self, input_parameters, expected): @skipUnless(has_cucim, "Requires cucim") class TestSlidingPatchWSIDatasetCuCIM(MaskedPatchWSIDatasetTests.Tests): - @classmethod def setUpClass(cls): cls.backend = "cucim" @@ -109,7 +109,6 @@ def setUpClass(cls): @skipUnless(has_osl, "Requires openslide") class TestSlidingPatchWSIDatasetOpenSlide(MaskedPatchWSIDatasetTests.Tests): - @classmethod def setUpClass(cls): cls.backend = "openslide" diff --git a/tests/test_nifti_header_revise.py b/tests/data/test_nifti_header_revise.py similarity index 100% rename from tests/test_nifti_header_revise.py rename to tests/data/test_nifti_header_revise.py diff --git a/tests/test_nifti_rw.py b/tests/data/test_nifti_rw.py similarity index 99% rename from tests/test_nifti_rw.py rename to tests/data/test_nifti_rw.py index 8543fcea30..cd75bef93d 100644 --- a/tests/test_nifti_rw.py +++ b/tests/data/test_nifti_rw.py @@ -21,7 +21,7 @@ from monai.data import NibabelWriter from monai.transforms import LoadImage, Orientation, Spacing -from tests.utils import TEST_NDARRAYS, assert_allclose, make_nifti_image +from tests.test_utils import TEST_NDARRAYS, assert_allclose, make_nifti_image TESTS = [] for p in TEST_NDARRAYS: @@ -72,7 +72,6 @@ class TestNiftiLoadRead(unittest.TestCase): - @parameterized.expand(TESTS) def test_orientation(self, array, affine, reader_param, expected): test_image = make_nifti_image(array, affine) diff --git a/tests/test_npzdictitemdataset.py b/tests/data/test_npzdictitemdataset.py similarity index 100% rename from tests/test_npzdictitemdataset.py rename to tests/data/test_npzdictitemdataset.py diff --git a/tests/test_nrrd_reader.py b/tests/data/test_nrrd_reader.py similarity index 100% rename from tests/test_nrrd_reader.py rename to tests/data/test_nrrd_reader.py diff --git a/tests/test_numpy_reader.py b/tests/data/test_numpy_reader.py similarity index 99% rename from tests/test_numpy_reader.py rename to tests/data/test_numpy_reader.py index 6303598bb7..c427778c67 100644 --- a/tests/test_numpy_reader.py +++ b/tests/data/test_numpy_reader.py @@ -20,11 +20,10 @@ from monai.data import DataLoader, Dataset, NumpyReader from monai.transforms import LoadImage, LoadImaged -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose class TestNumpyReader(unittest.TestCase): - def test_npy(self): test_data = np.random.randint(0, 256, size=[3, 4, 4]) with tempfile.TemporaryDirectory() as tempdir: diff --git a/tests/test_partition_dataset.py b/tests/data/test_partition_dataset.py similarity index 100% rename from tests/test_partition_dataset.py rename to tests/data/test_partition_dataset.py diff --git a/tests/test_partition_dataset_classes.py b/tests/data/test_partition_dataset_classes.py similarity index 100% rename from tests/test_partition_dataset_classes.py rename to tests/data/test_partition_dataset_classes.py diff --git a/tests/test_patch_dataset.py b/tests/data/test_patch_dataset.py similarity index 100% rename from tests/test_patch_dataset.py rename to tests/data/test_patch_dataset.py diff --git a/tests/test_patch_wsi_dataset.py b/tests/data/test_patch_wsi_dataset.py similarity index 97% rename from tests/test_patch_wsi_dataset.py rename to tests/data/test_patch_wsi_dataset.py index 70e01eaaf4..0d520e56e8 100644 --- a/tests/test_patch_wsi_dataset.py +++ b/tests/data/test_patch_wsi_dataset.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path from unittest import skipUnless import numpy as np @@ -23,7 +24,7 @@ from monai.data.wsi_reader import CuCIMWSIReader, OpenSlideWSIReader from monai.utils import optional_import from monai.utils.enums import WSIPatchKeys -from tests.utils import download_url_or_skip_test, testing_data_config +from tests.test_utils import download_url_or_skip_test, testing_data_config cucim, has_cim = optional_import("cucim") has_cim = has_cim and hasattr(cucim, "CuImage") @@ -34,7 +35,8 @@ FILE_KEY = "wsi_generic_tiff" FILE_URL = testing_data_config("images", FILE_KEY, "url") -FILE_PATH = os.path.join(os.path.dirname(__file__), "testing_data", f"temp_{FILE_KEY}.tiff") +TESTS_PATH = Path(__file__).parents[1].as_posix() +FILE_PATH = os.path.join(TESTS_PATH, "testing_data", f"temp_{FILE_KEY}.tiff") TEST_CASE_0 = [ { @@ -128,7 +130,6 @@ def setUpModule(): class PatchWSIDatasetTests: - class Tests(unittest.TestCase): backend = None @@ -183,7 +184,6 @@ def test_read_patches_str_multi(self, input_parameters, expected): @skipUnless(has_cim, "Requires cucim") class TestPatchWSIDatasetCuCIM(PatchWSIDatasetTests.Tests): - @classmethod def setUpClass(cls): cls.backend = "cucim" @@ -191,7 +191,6 @@ def setUpClass(cls): @skipUnless(has_osl, "Requires openslide") class TestPatchWSIDatasetOpenSlide(PatchWSIDatasetTests.Tests): - @classmethod def setUpClass(cls): cls.backend = "openslide" diff --git a/tests/test_persistentdataset.py b/tests/data/test_persistentdataset.py similarity index 100% rename from tests/test_persistentdataset.py rename to tests/data/test_persistentdataset.py diff --git a/tests/test_persistentdataset_dist.py b/tests/data/test_persistentdataset_dist.py similarity index 98% rename from tests/test_persistentdataset_dist.py rename to tests/data/test_persistentdataset_dist.py index c369af9e92..ab36979f5e 100644 --- a/tests/test_persistentdataset_dist.py +++ b/tests/data/test_persistentdataset_dist.py @@ -21,11 +21,10 @@ from monai.data import PersistentDataset, json_hashing from monai.transforms import Transform -from tests.utils import DistCall, DistTestCase +from tests.test_utils import DistCall, DistTestCase class _InplaceXform(Transform): - def __call__(self, data): if data: data[0] = data[0] + np.pi @@ -35,7 +34,6 @@ def __call__(self, data): class TestDistDataset(DistTestCase): - def setUp(self): self.tempdir = tempfile.mkdtemp() @@ -60,7 +58,6 @@ def test_mp_dataset(self): class TestDistCreateDataset(DistTestCase): - def setUp(self): self.tempdir = tempfile.mkdtemp() diff --git a/tests/test_pil_reader.py b/tests/data/test_pil_reader.py similarity index 100% rename from tests/test_pil_reader.py rename to tests/data/test_pil_reader.py diff --git a/tests/test_png_rw.py b/tests/data/test_png_rw.py similarity index 100% rename from tests/test_png_rw.py rename to tests/data/test_png_rw.py diff --git a/tests/test_resample_datalist.py b/tests/data/test_resample_datalist.py similarity index 100% rename from tests/test_resample_datalist.py rename to tests/data/test_resample_datalist.py diff --git a/tests/test_sampler_dist.py b/tests/data/test_sampler_dist.py similarity index 98% rename from tests/test_sampler_dist.py rename to tests/data/test_sampler_dist.py index b8bd1c7a9f..7059a44e6b 100644 --- a/tests/test_sampler_dist.py +++ b/tests/data/test_sampler_dist.py @@ -20,11 +20,10 @@ from monai.data import CacheDataset, DataLoader, DistributedSampler from monai.transforms import ToTensor -from tests.utils import DistCall, DistTestCase, assert_allclose +from tests.test_utils import DistCall, DistTestCase, assert_allclose class DistributedSamplerTest(DistTestCase): - @DistCall(nnodes=1, nproc_per_node=2) def test_even(self): data = [1, 2, 3, 4, 5] diff --git a/tests/test_select_cross_validation_folds.py b/tests/data/test_select_cross_validation_folds.py similarity index 100% rename from tests/test_select_cross_validation_folds.py rename to tests/data/test_select_cross_validation_folds.py diff --git a/tests/test_shuffle_buffer.py b/tests/data/test_shuffle_buffer.py similarity index 97% rename from tests/test_shuffle_buffer.py rename to tests/data/test_shuffle_buffer.py index e75321616b..ee0ce9e2d1 100644 --- a/tests/test_shuffle_buffer.py +++ b/tests/data/test_shuffle_buffer.py @@ -18,12 +18,11 @@ from monai.data import DataLoader, ShuffleBuffer from monai.utils import convert_data_type -from tests.utils import SkipIfBeforePyTorchVersion +from tests.test_utils import SkipIfBeforePyTorchVersion @SkipIfBeforePyTorchVersion((1, 12)) class TestShuffleBuffer(unittest.TestCase): - def test_shape(self): buffer = ShuffleBuffer([1, 2, 3, 4], seed=0) num_workers = 2 if sys.platform == "linux" else 0 diff --git a/tests/test_sliding_patch_wsi_dataset.py b/tests/data/test_sliding_patch_wsi_dataset.py similarity index 96% rename from tests/test_sliding_patch_wsi_dataset.py rename to tests/data/test_sliding_patch_wsi_dataset.py index 6369613426..8e27f7ad0e 100644 --- a/tests/test_sliding_patch_wsi_dataset.py +++ b/tests/data/test_sliding_patch_wsi_dataset.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path from unittest import skipUnless import numpy as np @@ -21,7 +22,7 @@ from monai.data import SlidingPatchWSIDataset from monai.utils import WSIPatchKeys, optional_import, set_determinism -from tests.utils import download_url_or_skip_test, testing_data_config +from tests.test_utils import download_url_or_skip_test, testing_data_config set_determinism(0) @@ -34,10 +35,11 @@ FILE_KEY = "wsi_generic_tiff" FILE_URL = testing_data_config("images", FILE_KEY, "url") -FILE_PATH = os.path.join(os.path.dirname(__file__), "testing_data", f"temp_{FILE_KEY}.tiff") +TESTS_PATH = Path(__file__).parents[1].as_posix() +FILE_PATH = os.path.join(TESTS_PATH, "testing_data", f"temp_{FILE_KEY}.tiff") -FILE_PATH_SMALL_0 = os.path.join(os.path.dirname(__file__), "testing_data", "temp_wsi_inference_0.tiff") -FILE_PATH_SMALL_1 = os.path.join(os.path.dirname(__file__), "testing_data", "temp_wsi_inference_1.tiff") +FILE_PATH_SMALL_0 = os.path.join(TESTS_PATH, "testing_data", "temp_wsi_inference_0.tiff") +FILE_PATH_SMALL_1 = os.path.join(TESTS_PATH, "testing_data", "temp_wsi_inference_1.tiff") ARRAY_SMALL_0 = np.random.randint(low=0, high=255, size=(3, 4, 4), dtype=np.uint8) ARRAY_SMALL_1 = np.random.randint(low=0, high=255, size=(3, 5, 5), dtype=np.uint8) @@ -213,7 +215,6 @@ def setUpModule(): class SlidingPatchWSIDatasetTests: - class Tests(unittest.TestCase): backend = None @@ -253,7 +254,6 @@ def test_read_patches_large(self, input_parameters, expected): @skipUnless(has_cucim, "Requires cucim") class TestSlidingPatchWSIDatasetCuCIM(SlidingPatchWSIDatasetTests.Tests): - @classmethod def setUpClass(cls): cls.backend = "cucim" @@ -261,7 +261,6 @@ def setUpClass(cls): @skipUnless(has_osl, "Requires openslide") class TestSlidingPatchWSIDatasetOpenSlide(SlidingPatchWSIDatasetTests.Tests): - @classmethod def setUpClass(cls): cls.backend = "openslide" diff --git a/tests/test_smartcachedataset.py b/tests/data/test_smartcachedataset.py similarity index 99% rename from tests/test_smartcachedataset.py rename to tests/data/test_smartcachedataset.py index bb43060469..7e59747c5c 100644 --- a/tests/test_smartcachedataset.py +++ b/tests/data/test_smartcachedataset.py @@ -24,7 +24,7 @@ from monai.data import DataLoader, SmartCacheDataset from monai.transforms import Compose, Lambda, LoadImaged -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_CASE_1 = [0.1, 0, Compose([LoadImaged(keys=["image", "label", "extra"])])] @@ -38,7 +38,6 @@ class TestSmartCacheDataset(unittest.TestCase): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5]) def test_shape(self, replace_rate, num_replace_workers, transform): test_image = nib.Nifti1Image(np.random.randint(0, 2, size=[8, 8, 8]).astype(float), np.eye(4)) diff --git a/tests/test_synthetic.py b/tests/data/test_synthetic.py similarity index 100% rename from tests/test_synthetic.py rename to tests/data/test_synthetic.py diff --git a/tests/test_thread_buffer.py b/tests/data/test_thread_buffer.py similarity index 99% rename from tests/test_thread_buffer.py rename to tests/data/test_thread_buffer.py index 2b7da2c0b0..71c6c889d7 100644 --- a/tests/test_thread_buffer.py +++ b/tests/data/test_thread_buffer.py @@ -20,11 +20,10 @@ from monai.data import DataLoader, Dataset, ThreadBuffer, ThreadDataLoader from monai.transforms import Compose, SimulateDelayd from monai.utils import PerfContext, set_determinism -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose class TestDataLoader(unittest.TestCase): - def setUp(self): super().setUp() diff --git a/tests/test_threadcontainer.py b/tests/data/test_threadcontainer.py similarity index 94% rename from tests/test_threadcontainer.py rename to tests/data/test_threadcontainer.py index 568461748b..519f8350a0 100644 --- a/tests/test_threadcontainer.py +++ b/tests/data/test_threadcontainer.py @@ -15,13 +15,14 @@ import tempfile import time import unittest +from pathlib import Path import torch from monai.data import DataLoader from monai.utils import optional_import, set_determinism from monai.utils.enums import CommonKeys -from tests.utils import SkipIfNoModule +from tests.test_utils import SkipIfNoModule try: _, has_ignite = optional_import("ignite") @@ -36,7 +37,6 @@ class TestThreadContainer(unittest.TestCase): - @SkipIfNoModule("ignite") def test_container(self): net = torch.nn.Conv2d(1, 1, 3, padding=1) @@ -70,8 +70,8 @@ def test_container(self): @SkipIfNoModule("matplotlib") def test_plot(self): set_determinism(0) - - testing_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "testing_data") + test_dir = Path(__file__).parents[1] + testing_dir = os.path.join(test_dir, "testing_data") net = torch.nn.Conv2d(1, 1, 3, padding=1) diff --git a/tests/test_video_datasets.py b/tests/data/test_video_datasets.py similarity index 95% rename from tests/test_video_datasets.py rename to tests/data/test_video_datasets.py index 6e344e1caa..b338885511 100644 --- a/tests/test_video_datasets.py +++ b/tests/data/test_video_datasets.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path import torch @@ -20,7 +21,7 @@ from monai.data.dataloader import DataLoader from monai.data.video_dataset import CameraDataset, VideoDataset, VideoFileDataset from monai.utils.module import optional_import -from tests.utils import assert_allclose, download_url_or_skip_test, testing_data_config +from tests.test_utils import assert_allclose, download_url_or_skip_test, testing_data_config cv2, has_cv2 = optional_import("cv2") @@ -31,7 +32,6 @@ class Base: - class TestVideoDataset(unittest.TestCase): video_source: int | str ds: type[VideoDataset] @@ -116,7 +116,8 @@ def setUpClass(cls): cls.known_num_frames = None cls.video_source = None return - cls.video_source = os.path.join(os.path.dirname(__file__), "testing_data", fname) + tests_path = Path(__file__).parents[1].as_posix() + cls.video_source = os.path.join(tests_path, "testing_data", fname) download_url_or_skip_test( url=config["url"], filepath=cls.video_source, diff --git a/tests/test_weighted_random_sampler_dist.py b/tests/data/test_weighted_random_sampler_dist.py similarity index 96% rename from tests/test_weighted_random_sampler_dist.py rename to tests/data/test_weighted_random_sampler_dist.py index 8e37482da6..cbcbc6821a 100644 --- a/tests/test_weighted_random_sampler_dist.py +++ b/tests/data/test_weighted_random_sampler_dist.py @@ -18,13 +18,12 @@ import torch.distributed as dist from monai.data import DistributedWeightedRandomSampler -from tests.utils import DistCall, DistTestCase, skip_if_darwin, skip_if_windows +from tests.test_utils import DistCall, DistTestCase, skip_if_darwin, skip_if_windows @skip_if_windows @skip_if_darwin class DistributedWeightedRandomSamplerTest(DistTestCase): - @DistCall(nnodes=1, nproc_per_node=2) def test_sampling(self): data = [1, 2, 3, 4, 5] diff --git a/tests/test_zipdataset.py b/tests/data/test_zipdataset.py similarity index 100% rename from tests/test_zipdataset.py rename to tests/data/test_zipdataset.py diff --git a/tests/test_decollate.py b/tests/data/utils/test_decollate.py similarity index 99% rename from tests/test_decollate.py rename to tests/data/utils/test_decollate.py index 92f7c89e28..9adb3f267d 100644 --- a/tests/test_decollate.py +++ b/tests/data/utils/test_decollate.py @@ -40,7 +40,7 @@ from monai.transforms.spatial.dictionary import RandAffined, RandRotate90d from monai.utils import optional_import, set_determinism from monai.utils.enums import PostFix, TraceKeys -from tests.utils import make_nifti_image +from tests.test_utils import make_nifti_image _, has_nib = optional_import("nibabel") @@ -81,7 +81,6 @@ class TestDeCollate(unittest.TestCase): - def setUp(self) -> None: set_determinism(seed=0) @@ -160,7 +159,6 @@ def test_decollation_list(self, *transforms): class TestBasicDeCollate(unittest.TestCase): - @parameterized.expand(TEST_BASIC) def test_decollation_examples(self, input_val, expected_out): out = decollate_batch(input_val) diff --git a/tests/test_dev_collate.py b/tests/data/utils/test_dev_collate.py similarity index 100% rename from tests/test_dev_collate.py rename to tests/data/utils/test_dev_collate.py diff --git a/tests/test_file_basename.py b/tests/data/utils/test_file_basename.py similarity index 100% rename from tests/test_file_basename.py rename to tests/data/utils/test_file_basename.py diff --git a/tests/test_ori_ras_lps.py b/tests/data/utils/test_ori_ras_lps.py similarity index 74% rename from tests/test_ori_ras_lps.py rename to tests/data/utils/test_ori_ras_lps.py index 39c0a57877..3d69982b1e 100644 --- a/tests/test_ori_ras_lps.py +++ b/tests/data/utils/test_ori_ras_lps.py @@ -17,20 +17,22 @@ from parameterized import parameterized from monai.data.utils import orientation_ras_lps -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TEST_CASES_AFFINE = [] for p in TEST_NDARRAYS: case_1d = p([[1.0, 0.0], [1.0, 1.0]]), p([[-1.0, 0.0], [1.0, 1.0]]) TEST_CASES_AFFINE.append(case_1d) - case_2d_1 = p([[1.0, 0.0, 1.0], [1.0, 1.0, 1.0]]), p([[-1.0, 0.0, -1.0], [1.0, 1.0, 1.0]]) + case_2d_1 = (p([[1.0, 0.0, 1.0], [1.0, 1.0, 1.0]]), p([[-1.0, 0.0, -1.0], [1.0, 1.0, 1.0]])) TEST_CASES_AFFINE.append(case_2d_1) - case_2d_2 = p([[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [1.0, 1.0, 1.0]]), p( - [[-1.0, 0.0, -1.0], [0.0, -1.0, -1.0], [1.0, 1.0, 1.0]] + case_2d_2 = ( + p([[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [1.0, 1.0, 1.0]]), + p([[-1.0, 0.0, -1.0], [0.0, -1.0, -1.0], [1.0, 1.0, 1.0]]), ) TEST_CASES_AFFINE.append(case_2d_2) - case_3d = p([[1.0, 0.0, 1.0, 1.0], [0.0, 1.0, 1.0, 2.0], [1.0, 1.0, 1.0, 3.0]]), p( - [[-1.0, 0.0, -1.0, -1.0], [0.0, -1.0, -1.0, -2.0], [1.0, 1.0, 1.0, 3.0]] + case_3d = ( + p([[1.0, 0.0, 1.0, 1.0], [0.0, 1.0, 1.0, 2.0], [1.0, 1.0, 1.0, 3.0]]), + p([[-1.0, 0.0, -1.0, -1.0], [0.0, -1.0, -1.0, -2.0], [1.0, 1.0, 1.0, 3.0]]), ) TEST_CASES_AFFINE.append(case_3d) case_4d = p(np.ones((5, 5))), p([[-1] * 5, [-1] * 5, [1] * 5, [1] * 5, [1] * 5]) @@ -38,7 +40,6 @@ class TestITKWriter(unittest.TestCase): - @parameterized.expand(TEST_CASES_AFFINE) def test_ras_to_lps(self, param, expected): assert_allclose(orientation_ras_lps(param), expected) diff --git a/tests/test_zoom_affine.py b/tests/data/utils/test_zoom_affine.py similarity index 100% rename from tests/test_zoom_affine.py rename to tests/data/utils/test_zoom_affine.py diff --git a/tests/engines/__init__.py b/tests/engines/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/engines/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_ensemble_evaluator.py b/tests/engines/test_ensemble_evaluator.py similarity index 98% rename from tests/test_ensemble_evaluator.py rename to tests/engines/test_ensemble_evaluator.py index ad81d35d52..581d04e36e 100644 --- a/tests/test_ensemble_evaluator.py +++ b/tests/engines/test_ensemble_evaluator.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.engines import EnsembleEvaluator -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_CASE_1 = [["pred_0", "pred_1", "pred_2", "pred_3", "pred_4"]] @@ -26,13 +26,11 @@ class TestEnsembleEvaluator(unittest.TestCase): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2]) def test_content(self, pred_keys): device = torch.device("cpu:0") class TestDataset(torch.utils.data.Dataset): - def __len__(self): return 8 @@ -42,7 +40,6 @@ def __getitem__(self, index): val_loader = torch.utils.data.DataLoader(TestDataset()) class TestNet(torch.nn.Module): - def __init__(self, func): super().__init__() self.func = func diff --git a/tests/test_prepare_batch_default.py b/tests/engines/test_prepare_batch_default.py similarity index 98% rename from tests/test_prepare_batch_default.py rename to tests/engines/test_prepare_batch_default.py index 093468ce27..b132554889 100644 --- a/tests/test_prepare_batch_default.py +++ b/tests/engines/test_prepare_batch_default.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.engines import PrepareBatchDefault, SupervisedEvaluator -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose class TestNet(torch.nn.Module): @@ -28,7 +28,6 @@ def forward(self, x: torch.Tensor): class TestPrepareBatchDefault(unittest.TestCase): - @parameterized.expand( [ ( diff --git a/tests/test_prepare_batch_default_dist.py b/tests/engines/test_prepare_batch_default_dist.py similarity index 97% rename from tests/test_prepare_batch_default_dist.py rename to tests/engines/test_prepare_batch_default_dist.py index 53a79575e6..be425dca78 100644 --- a/tests/test_prepare_batch_default_dist.py +++ b/tests/engines/test_prepare_batch_default_dist.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.engines import PrepareBatchDefault, SupervisedEvaluator -from tests.utils import DistCall, DistTestCase, assert_allclose +from tests.test_utils import DistCall, DistTestCase, assert_allclose TEST_CASE_1 = [ [ @@ -50,7 +50,6 @@ def forward(self, x: torch.Tensor): class DistributedPrepareBatchDefault(DistTestCase): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2]) @DistCall(nnodes=1, nproc_per_node=2, node_rank=0) def test_compute(self, dataloaders): diff --git a/tests/test_prepare_batch_diffusion.py b/tests/engines/test_prepare_batch_diffusion.py similarity index 100% rename from tests/test_prepare_batch_diffusion.py rename to tests/engines/test_prepare_batch_diffusion.py diff --git a/tests/test_prepare_batch_extra_input.py b/tests/engines/test_prepare_batch_extra_input.py similarity index 98% rename from tests/test_prepare_batch_extra_input.py rename to tests/engines/test_prepare_batch_extra_input.py index 3c53cc6481..241da09701 100644 --- a/tests/test_prepare_batch_extra_input.py +++ b/tests/engines/test_prepare_batch_extra_input.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.engines import PrepareBatchExtraInput, SupervisedEvaluator -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_CASE_0 = [ {"extra_keys": "extra1"}, @@ -43,7 +43,6 @@ def forward(self, x: torch.Tensor, t1=None, t2=None, t3=None): class TestPrepareBatchExtraInput(unittest.TestCase): - @parameterized.expand([TEST_CASE_0, TEST_CASE_1, TEST_CASE_2]) def test_content(self, input_args, expected_value): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") diff --git a/tests/fl/__init__.py b/tests/fl/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/fl/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/fl/monai_algo/__init__.py b/tests/fl/monai_algo/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/fl/monai_algo/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_fl_monai_algo.py b/tests/fl/monai_algo/test_fl_monai_algo.py similarity index 98% rename from tests/test_fl_monai_algo.py rename to tests/fl/monai_algo/test_fl_monai_algo.py index c8cb3451fc..2c1a8488cc 100644 --- a/tests/test_fl_monai_algo.py +++ b/tests/fl/monai_algo/test_fl_monai_algo.py @@ -17,6 +17,7 @@ import unittest from copy import deepcopy from os.path import join as pathjoin +from pathlib import Path from parameterized import parameterized @@ -26,9 +27,9 @@ from monai.fl.utils.constants import ExtraItems from monai.fl.utils.exchange_object import ExchangeObject from monai.utils import path_to_uri -from tests.utils import SkipIfNoModule +from tests.test_utils import SkipIfNoModule -_root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__))) +_root_dir = Path(__file__).resolve().parents[2] _data_dir = os.path.join(_root_dir, "testing_data") _logging_file = pathjoin(_data_dir, "logging.conf") @@ -181,7 +182,6 @@ @SkipIfNoModule("ignite") @SkipIfNoModule("mlflow") class TestFLMonaiAlgo(unittest.TestCase): - @parameterized.expand([TEST_TRAIN_1, TEST_TRAIN_2, TEST_TRAIN_3, TEST_TRAIN_4]) def test_train(self, input_params): # initialize algo diff --git a/tests/test_fl_monai_algo_dist.py b/tests/fl/monai_algo/test_fl_monai_algo_dist.py similarity index 94% rename from tests/test_fl_monai_algo_dist.py rename to tests/fl/monai_algo/test_fl_monai_algo_dist.py index d8dbfa5339..744169e10d 100644 --- a/tests/test_fl_monai_algo_dist.py +++ b/tests/fl/monai_algo/test_fl_monai_algo_dist.py @@ -14,6 +14,7 @@ import os import unittest from os.path import join as pathjoin +from pathlib import Path import torch.distributed as dist @@ -22,9 +23,10 @@ from monai.fl.utils.constants import ExtraItems from monai.fl.utils.exchange_object import ExchangeObject from monai.networks import get_state_dict -from tests.utils import DistCall, DistTestCase, SkipIfBeforePyTorchVersion, SkipIfNoModule, skip_if_no_cuda +from tests.test_utils import DistCall, DistTestCase, SkipIfBeforePyTorchVersion, SkipIfNoModule, skip_if_no_cuda -_root_dir = os.path.abspath(pathjoin(os.path.dirname(__file__))) +TESTS_PATH = TESTS_PATH = Path(__file__).parents[2].as_posix() +_root_dir = os.path.abspath(pathjoin(TESTS_PATH)) _data_dir = pathjoin(_root_dir, "testing_data") _logging_file = pathjoin(_data_dir, "logging.conf") @@ -32,7 +34,6 @@ @SkipIfNoModule("ignite") @SkipIfBeforePyTorchVersion((1, 11, 1)) class TestFLMonaiAlgo(DistTestCase): - @DistCall(nnodes=1, nproc_per_node=2, init_method="no_init") @skip_if_no_cuda def test_train(self): @@ -64,7 +65,7 @@ def test_train(self): data = ExchangeObject(weights=get_state_dict(network)) # test train for i in range(2): - print(f"Testing round {i+1} of {2}...") + print(f"Testing round {i + 1} of {2}...") # test evaluate metric_eo = algo.evaluate(data=data, extra={}) self.assertIsInstance(metric_eo, ExchangeObject) diff --git a/tests/test_fl_monai_algo_stats.py b/tests/fl/test_fl_monai_algo_stats.py similarity index 95% rename from tests/test_fl_monai_algo_stats.py rename to tests/fl/test_fl_monai_algo_stats.py index 6e58f8af88..917393be2c 100644 --- a/tests/test_fl_monai_algo_stats.py +++ b/tests/fl/test_fl_monai_algo_stats.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path from parameterized import parameterized @@ -20,9 +21,9 @@ from monai.fl.client import MonaiAlgoStats from monai.fl.utils.constants import ExtraItems, FlStatistics from monai.fl.utils.exchange_object import ExchangeObject -from tests.utils import SkipIfNoModule +from tests.test_utils import SkipIfNoModule -_root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__))) +_root_dir = Path(__file__).resolve().parents[1] _data_dir = os.path.join(_root_dir, "testing_data") _logging_file = os.path.join(_data_dir, "logging.conf") @@ -64,7 +65,6 @@ @SkipIfNoModule("ignite") class TestFLMonaiAlgo(unittest.TestCase): - @parameterized.expand([TEST_GET_DATA_STATS_1, TEST_GET_DATA_STATS_2, TEST_GET_DATA_STATS_3]) def test_get_data_stats(self, input_params): # initialize algo diff --git a/tests/fl/utils/__init__.py b/tests/fl/utils/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/fl/utils/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_fl_exchange_object.py b/tests/fl/utils/test_fl_exchange_object.py similarity index 98% rename from tests/test_fl_exchange_object.py rename to tests/fl/utils/test_fl_exchange_object.py index dab4eae037..f83e8eaf1f 100644 --- a/tests/test_fl_exchange_object.py +++ b/tests/fl/utils/test_fl_exchange_object.py @@ -19,7 +19,7 @@ from monai.fl.utils.constants import WeightType from monai.fl.utils.exchange_object import ExchangeObject from monai.utils.module import optional_import -from tests.utils import SkipIfNoModule +from tests.test_utils import SkipIfNoModule models, has_torchvision = optional_import("torchvision.models") @@ -46,7 +46,6 @@ @SkipIfNoModule("torchvision") @SkipIfNoModule("ignite") class TestFLExchangeObject(unittest.TestCase): - @parameterized.expand([TEST_INIT_1, TEST_INIT_2]) def test_init(self, input_params, expected_str): eo = ExchangeObject(**input_params) diff --git a/tests/handlers/__init__.py b/tests/handlers/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/handlers/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_handler_checkpoint_loader.py b/tests/handlers/test_handler_checkpoint_loader.py similarity index 99% rename from tests/test_handler_checkpoint_loader.py rename to tests/handlers/test_handler_checkpoint_loader.py index 7b281665b4..e16775a2ea 100644 --- a/tests/test_handler_checkpoint_loader.py +++ b/tests/handlers/test_handler_checkpoint_loader.py @@ -19,11 +19,10 @@ from ignite.engine import Engine, Events from monai.handlers import CheckpointLoader, CheckpointSaver -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose class TestHandlerCheckpointLoader(unittest.TestCase): - def test_one_save_one_load(self): net1 = torch.nn.PReLU() data1 = net1.state_dict() diff --git a/tests/test_handler_checkpoint_saver.py b/tests/handlers/test_handler_checkpoint_saver.py similarity index 100% rename from tests/test_handler_checkpoint_saver.py rename to tests/handlers/test_handler_checkpoint_saver.py diff --git a/tests/test_handler_classification_saver.py b/tests/handlers/test_handler_classification_saver.py similarity index 100% rename from tests/test_handler_classification_saver.py rename to tests/handlers/test_handler_classification_saver.py diff --git a/tests/test_handler_classification_saver_dist.py b/tests/handlers/test_handler_classification_saver_dist.py similarity index 98% rename from tests/test_handler_classification_saver_dist.py rename to tests/handlers/test_handler_classification_saver_dist.py index 47dca2d999..7942efb56e 100644 --- a/tests/test_handler_classification_saver_dist.py +++ b/tests/handlers/test_handler_classification_saver_dist.py @@ -23,11 +23,10 @@ from monai.data import decollate_batch from monai.handlers import ClassificationSaver -from tests.utils import DistCall, DistTestCase +from tests.test_utils import DistCall, DistTestCase class DistributedHandlerClassificationSaver(DistTestCase): - @DistCall(nnodes=1, nproc_per_node=2) def test_saved_content(self): with tempfile.TemporaryDirectory() as tempdir: diff --git a/tests/test_handler_clearml_image.py b/tests/handlers/test_handler_clearml_image.py similarity index 100% rename from tests/test_handler_clearml_image.py rename to tests/handlers/test_handler_clearml_image.py diff --git a/tests/test_handler_clearml_stats.py b/tests/handlers/test_handler_clearml_stats.py similarity index 100% rename from tests/test_handler_clearml_stats.py rename to tests/handlers/test_handler_clearml_stats.py diff --git a/tests/test_handler_confusion_matrix.py b/tests/handlers/test_handler_confusion_matrix.py similarity index 98% rename from tests/test_handler_confusion_matrix.py rename to tests/handlers/test_handler_confusion_matrix.py index 5f3ee3ae97..6ecc7c8250 100644 --- a/tests/test_handler_confusion_matrix.py +++ b/tests/handlers/test_handler_confusion_matrix.py @@ -19,7 +19,7 @@ from parameterized import parameterized from monai.handlers import ConfusionMatrix -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_CASE_1 = [{"include_background": True, "save_details": False, "metric_name": "f1"}, 0.75] TEST_CASE_2 = [{"include_background": False, "save_details": False, "metric_name": "ppv"}, 1.0] diff --git a/tests/test_handler_confusion_matrix_dist.py b/tests/handlers/test_handler_confusion_matrix_dist.py similarity index 97% rename from tests/test_handler_confusion_matrix_dist.py rename to tests/handlers/test_handler_confusion_matrix_dist.py index dd30f04142..626428c48e 100644 --- a/tests/test_handler_confusion_matrix_dist.py +++ b/tests/handlers/test_handler_confusion_matrix_dist.py @@ -19,11 +19,10 @@ from ignite.engine import Engine from monai.handlers import ConfusionMatrix -from tests.utils import DistCall, DistTestCase +from tests.test_utils import DistCall, DistTestCase class DistributedConfusionMatrix(DistTestCase): - @DistCall(nnodes=1, nproc_per_node=2) def test_compute(self): self._compute() diff --git a/tests/test_handler_decollate_batch.py b/tests/handlers/test_handler_decollate_batch.py similarity index 98% rename from tests/test_handler_decollate_batch.py rename to tests/handlers/test_handler_decollate_batch.py index 37ca7f6870..f0f1a36016 100644 --- a/tests/test_handler_decollate_batch.py +++ b/tests/handlers/test_handler_decollate_batch.py @@ -18,11 +18,10 @@ from monai.engines import SupervisedEvaluator from monai.handlers import DecollateBatch, PostProcessing from monai.transforms import Activationsd, AsDiscreted, Compose, CopyItemsd -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose class TestHandlerDecollateBatch(unittest.TestCase): - def test_compute(self): data = [ {"image": torch.tensor([[[[2.0], [3.0]]]]), "filename": ["test1"]}, diff --git a/tests/test_handler_early_stop.py b/tests/handlers/test_handler_early_stop.py similarity index 100% rename from tests/test_handler_early_stop.py rename to tests/handlers/test_handler_early_stop.py diff --git a/tests/test_handler_garbage_collector.py b/tests/handlers/test_handler_garbage_collector.py similarity index 100% rename from tests/test_handler_garbage_collector.py rename to tests/handlers/test_handler_garbage_collector.py diff --git a/tests/test_handler_hausdorff_distance.py b/tests/handlers/test_handler_hausdorff_distance.py similarity index 98% rename from tests/test_handler_hausdorff_distance.py rename to tests/handlers/test_handler_hausdorff_distance.py index 906db86d62..4e366d016a 100644 --- a/tests/test_handler_hausdorff_distance.py +++ b/tests/handlers/test_handler_hausdorff_distance.py @@ -18,7 +18,7 @@ from ignite.engine import Engine from monai.handlers import HausdorffDistance -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose def create_spherical_seg_3d( diff --git a/tests/test_handler_ignite_metric.py b/tests/handlers/test_handler_ignite_metric.py similarity index 98% rename from tests/test_handler_ignite_metric.py rename to tests/handlers/test_handler_ignite_metric.py index 3e42bda35d..d72db443e4 100644 --- a/tests/test_handler_ignite_metric.py +++ b/tests/handlers/test_handler_ignite_metric.py @@ -19,7 +19,7 @@ from monai.handlers import IgniteMetricHandler, from_engine from monai.losses import DiceLoss from monai.metrics import LossMetric -from tests.utils import SkipIfNoModule, assert_allclose, optional_import +from tests.test_utils import SkipIfNoModule, assert_allclose, optional_import try: _, has_ignite = optional_import("ignite") @@ -99,7 +99,6 @@ class TestHandlerIgniteMetricHandler(unittest.TestCase): - @SkipIfNoModule("ignite") @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3]) def test_metric_fn(self, loss_params, metric_params, handler_params, expected_avg): diff --git a/tests/test_handler_lr_scheduler.py b/tests/handlers/test_handler_lr_scheduler.py similarity index 100% rename from tests/test_handler_lr_scheduler.py rename to tests/handlers/test_handler_lr_scheduler.py diff --git a/tests/test_handler_mean_dice.py b/tests/handlers/test_handler_mean_dice.py similarity index 98% rename from tests/test_handler_mean_dice.py rename to tests/handlers/test_handler_mean_dice.py index 6f91b6d3af..abb016ca7b 100644 --- a/tests/test_handler_mean_dice.py +++ b/tests/handlers/test_handler_mean_dice.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.handlers import MeanDice, from_engine -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_CASE_1 = [{"include_background": True, "output_transform": from_engine(["pred", "label"])}, 0.75, (4, 2)] TEST_CASE_2 = [{"include_background": False, "output_transform": from_engine(["pred", "label"])}, 0.66666, (4, 1)] diff --git a/tests/test_handler_mean_iou.py b/tests/handlers/test_handler_mean_iou.py similarity index 98% rename from tests/test_handler_mean_iou.py rename to tests/handlers/test_handler_mean_iou.py index 89dae3af58..432cd8a51b 100644 --- a/tests/test_handler_mean_iou.py +++ b/tests/handlers/test_handler_mean_iou.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.handlers import MeanIoUHandler, from_engine -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_CASE_1 = [{"include_background": True, "output_transform": from_engine(["pred", "label"])}, 0.75, (4, 2)] TEST_CASE_2 = [{"include_background": False, "output_transform": from_engine(["pred", "label"])}, 2 / 3, (4, 1)] diff --git a/tests/test_handler_metrics_reloaded.py b/tests/handlers/test_handler_metrics_reloaded.py similarity index 99% rename from tests/test_handler_metrics_reloaded.py rename to tests/handlers/test_handler_metrics_reloaded.py index b8fb39d2e8..8c50ce7b59 100644 --- a/tests/test_handler_metrics_reloaded.py +++ b/tests/handlers/test_handler_metrics_reloaded.py @@ -19,7 +19,7 @@ from monai.handlers import MetricsReloadedBinaryHandler, MetricsReloadedCategoricalHandler, from_engine from monai.utils import optional_import -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose _, has_metrics = optional_import("MetricsReloaded") @@ -73,7 +73,6 @@ @unittest.skipIf(not has_metrics, "MetricsReloaded not available.") class TestHandlerMetricsReloadedBinary(unittest.TestCase): - @parameterized.expand([TEST_CASE_BIN_1, TEST_CASE_BIN_2, TEST_CASE_BIN_3]) def test_compute(self, input_params, y_pred, y, expected_value): input_params["output_transform"] = from_engine(["pred", "label"]) @@ -114,7 +113,6 @@ def test_shape_mismatch(self, input_params, _y_pred, _y, _expected_value): @unittest.skipIf(not has_metrics, "MetricsReloaded not available.") class TestMetricsReloadedCategorical(unittest.TestCase): - @parameterized.expand([TEST_CASE_CAT_1, TEST_CASE_CAT_2]) def test_compute(self, input_params, y_pred, y, expected_value): input_params["output_transform"] = from_engine(["pred", "label"]) diff --git a/tests/test_handler_metrics_saver.py b/tests/handlers/test_handler_metrics_saver.py similarity index 100% rename from tests/test_handler_metrics_saver.py rename to tests/handlers/test_handler_metrics_saver.py diff --git a/tests/test_handler_metrics_saver_dist.py b/tests/handlers/test_handler_metrics_saver_dist.py similarity index 96% rename from tests/test_handler_metrics_saver_dist.py rename to tests/handlers/test_handler_metrics_saver_dist.py index 2e12b08aa9..23de5e773a 100644 --- a/tests/test_handler_metrics_saver_dist.py +++ b/tests/handlers/test_handler_metrics_saver_dist.py @@ -23,11 +23,10 @@ from monai.handlers import MetricsSaver from monai.utils import evenly_divisible_all_gather from monai.utils.enums import PostFix -from tests.utils import DistCall, DistTestCase +from tests.test_utils import DistCall, DistTestCase class DistributedMetricsSaver(DistTestCase): - @DistCall(nnodes=1, nproc_per_node=2) def test_content(self): with tempfile.TemporaryDirectory() as tempdir: @@ -99,7 +98,7 @@ def _all_gather(engine): f_csv = csv.reader(f) for i, row in enumerate(f_csv): if i > 0: - expected = [f"{fnames[i-1]}\t{float(i):.4f}\t{float(i + 1):.4f}\t{i + 0.5:.4f}"] + expected = [f"{fnames[i - 1]}\t{float(i):.4f}\t{float(i + 1):.4f}\t{i + 0.5:.4f}"] self.assertEqual(row, expected) self.assertTrue(os.path.exists(os.path.join(tempdir, "metric3_summary.csv"))) # check the metric_summary.csv and content diff --git a/tests/test_handler_mlflow.py b/tests/handlers/test_handler_mlflow.py similarity index 99% rename from tests/test_handler_mlflow.py rename to tests/handlers/test_handler_mlflow.py index 36d59ff1bf..80630e6f5a 100644 --- a/tests/test_handler_mlflow.py +++ b/tests/handlers/test_handler_mlflow.py @@ -27,13 +27,12 @@ from monai.bundle import ConfigWorkflow, download from monai.handlers import MLFlowHandler from monai.utils import optional_import, path_to_uri -from tests.utils import skip_if_downloading_fails, skip_if_quick +from tests.test_utils import skip_if_downloading_fails, skip_if_quick _, has_dataset_tracking = optional_import("mlflow", "2.4.0") def get_event_filter(e): - def event_filter(_, event): if event in e: return True @@ -66,7 +65,6 @@ def _train_func(engine, batch): class TestHandlerMLFlow(unittest.TestCase): - def setUp(self): self.tmpdir_list = [] diff --git a/tests/test_handler_nvtx.py b/tests/handlers/test_handler_nvtx.py similarity index 98% rename from tests/test_handler_nvtx.py rename to tests/handlers/test_handler_nvtx.py index a0d1cdb4d5..0d38f8e4ef 100644 --- a/tests/test_handler_nvtx.py +++ b/tests/handlers/test_handler_nvtx.py @@ -21,7 +21,7 @@ from monai.handlers import StatsHandler, from_engine from monai.handlers.nvtx_handlers import MarkHandler, RangeHandler, RangePopHandler, RangePushHandler from monai.utils import optional_import -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose _, has_nvtx = optional_import("torch._C._nvtx", descriptor="NVTX is not installed. Are you sure you have a CUDA build?") @@ -36,7 +36,6 @@ class TestHandlerDecollateBatch(unittest.TestCase): - @parameterized.expand([TEST_CASE_0, TEST_CASE_1]) @unittest.skipUnless(has_nvtx, "CUDA is required for NVTX!") def test_compute(self, data, expected): diff --git a/tests/test_handler_panoptic_quality.py b/tests/handlers/test_handler_panoptic_quality.py similarity index 98% rename from tests/test_handler_panoptic_quality.py rename to tests/handlers/test_handler_panoptic_quality.py index 337f9c7b49..9c8ab93f36 100644 --- a/tests/test_handler_panoptic_quality.py +++ b/tests/handlers/test_handler_panoptic_quality.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.handlers import PanopticQuality, from_engine -from tests.utils import SkipIfNoModule, assert_allclose +from tests.test_utils import SkipIfNoModule, assert_allclose sample_1_pred = torch.as_tensor( [[[0, 1, 1, 1], [0, 0, 5, 5], [2, 0, 3, 3], [2, 2, 2, 0]], [[0, 1, 1, 1], [0, 0, 0, 0], [2, 0, 3, 3], [4, 2, 2, 0]]] @@ -60,7 +60,6 @@ @SkipIfNoModule("scipy.optimize") class TestHandlerPanopticQuality(unittest.TestCase): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3]) def test_compute(self, input_params, expected_avg): metric = PanopticQuality(**input_params) diff --git a/tests/test_handler_parameter_scheduler.py b/tests/handlers/test_handler_parameter_scheduler.py similarity index 99% rename from tests/test_handler_parameter_scheduler.py rename to tests/handlers/test_handler_parameter_scheduler.py index 0bcc794381..8f54bea3bb 100644 --- a/tests/test_handler_parameter_scheduler.py +++ b/tests/handlers/test_handler_parameter_scheduler.py @@ -17,11 +17,10 @@ from torch.nn import Module from monai.handlers.parameter_scheduler import ParamSchedulerHandler -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose class ToyNet(Module): - def __init__(self, value): super().__init__() self.value = value @@ -37,7 +36,6 @@ def set_value(self, value): class TestHandlerParameterScheduler(unittest.TestCase): - def test_linear_scheduler(self): # Testing step_constant net = ToyNet(value=-1) @@ -118,7 +116,6 @@ def test_multistep_scheduler(self): assert_allclose(net.get_value(), 10 * 0.99 * 0.99) def test_custom_scheduler(self): - def custom_logic(initial_value, gamma, current_step): return initial_value * gamma ** (current_step % 9) diff --git a/tests/test_handler_post_processing.py b/tests/handlers/test_handler_post_processing.py similarity index 98% rename from tests/test_handler_post_processing.py rename to tests/handlers/test_handler_post_processing.py index 0dd518325b..4103840e77 100644 --- a/tests/test_handler_post_processing.py +++ b/tests/handlers/test_handler_post_processing.py @@ -19,7 +19,7 @@ from monai.engines import SupervisedEvaluator from monai.handlers import PostProcessing from monai.transforms import Activationsd, AsDiscreted, Compose, CopyItemsd -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose # test lambda function as `transform` TEST_CASE_1 = [{"transform": lambda x: dict(pred=x["pred"] + 1.0)}, False, torch.tensor([[[[1.9975], [1.9997]]]])] @@ -40,7 +40,6 @@ class TestHandlerPostProcessing(unittest.TestCase): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2]) def test_compute(self, input_params, decollate, expected): data = [ diff --git a/tests/test_handler_prob_map_producer.py b/tests/handlers/test_handler_prob_map_producer.py similarity index 96% rename from tests/test_handler_prob_map_producer.py rename to tests/handlers/test_handler_prob_map_producer.py index 406fe77c8f..063f7984cb 100644 --- a/tests/test_handler_prob_map_producer.py +++ b/tests/handlers/test_handler_prob_map_producer.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path import numpy as np import torch @@ -72,7 +73,6 @@ def _iteration(self, engine, batchdata): class TestHandlerProbMapGenerator(unittest.TestCase): - @parameterized.expand([TEST_CASE_0, TEST_CASE_1, TEST_CASE_2]) def test_prob_map_generator(self, name, size): # set up dataset @@ -86,8 +86,9 @@ def inference(engine, batch): engine = Engine(inference) + tests_path = Path(__file__).parents[1].as_posix() # add ProbMapGenerator() to evaluator - output_dir = os.path.join(os.path.dirname(__file__), "testing_data") + output_dir = os.path.join(tests_path, "testing_data") prob_map_gen = ProbMapProducer(output_dir=output_dir) evaluator = TestEvaluator( diff --git a/tests/test_handler_regression_metrics.py b/tests/handlers/test_handler_regression_metrics.py similarity index 100% rename from tests/test_handler_regression_metrics.py rename to tests/handlers/test_handler_regression_metrics.py diff --git a/tests/test_handler_regression_metrics_dist.py b/tests/handlers/test_handler_regression_metrics_dist.py similarity index 99% rename from tests/test_handler_regression_metrics_dist.py rename to tests/handlers/test_handler_regression_metrics_dist.py index f57db429e8..98c1b373c6 100644 --- a/tests/test_handler_regression_metrics_dist.py +++ b/tests/handlers/test_handler_regression_metrics_dist.py @@ -20,7 +20,7 @@ from monai.handlers import MeanAbsoluteError, MeanSquaredError, PeakSignalToNoiseRatio, RootMeanSquaredError from monai.utils import set_determinism -from tests.utils import DistCall, DistTestCase +from tests.test_utils import DistCall, DistTestCase # define a numpy flatten function that only preserves batch dimension @@ -57,7 +57,6 @@ def psnrmetric_np(max_val, y_pred, y): class DistributedMeanSquaredError(DistTestCase): - @DistCall(nnodes=1, nproc_per_node=2) def test_compute(self): set_determinism(123) @@ -104,7 +103,6 @@ def _val_func(engine, batch): class DistributedMeanAbsoluteError(DistTestCase): - @DistCall(nnodes=1, nproc_per_node=2) def test_compute(self): set_determinism(123) @@ -151,7 +149,6 @@ def _val_func(engine, batch): class DistributedRootMeanSquaredError(DistTestCase): - @DistCall(nnodes=1, nproc_per_node=2) def test_compute(self): set_determinism(123) @@ -198,7 +195,6 @@ def _val_func(engine, batch): class DistributedPeakSignalToNoiseRatio(DistTestCase): - @DistCall(nnodes=1, nproc_per_node=2) def test_compute(self): set_determinism(123) diff --git a/tests/test_handler_rocauc.py b/tests/handlers/test_handler_rocauc.py similarity index 100% rename from tests/test_handler_rocauc.py rename to tests/handlers/test_handler_rocauc.py diff --git a/tests/test_handler_rocauc_dist.py b/tests/handlers/test_handler_rocauc_dist.py similarity index 97% rename from tests/test_handler_rocauc_dist.py rename to tests/handlers/test_handler_rocauc_dist.py index 6088251b11..cfc525ebc4 100644 --- a/tests/test_handler_rocauc_dist.py +++ b/tests/handlers/test_handler_rocauc_dist.py @@ -19,11 +19,10 @@ from monai.handlers import ROCAUC from monai.transforms import Activations, AsDiscrete -from tests.utils import DistCall, DistTestCase +from tests.test_utils import DistCall, DistTestCase class DistributedROCAUC(DistTestCase): - @DistCall(nnodes=1, nproc_per_node=2, node_rank=0) def test_compute(self): auc_metric = ROCAUC() diff --git a/tests/test_handler_stats.py b/tests/handlers/test_handler_stats.py similarity index 100% rename from tests/test_handler_stats.py rename to tests/handlers/test_handler_stats.py diff --git a/tests/test_handler_surface_distance.py b/tests/handlers/test_handler_surface_distance.py similarity index 98% rename from tests/test_handler_surface_distance.py rename to tests/handlers/test_handler_surface_distance.py index 736f7e251a..0253c1a8a4 100644 --- a/tests/test_handler_surface_distance.py +++ b/tests/handlers/test_handler_surface_distance.py @@ -18,7 +18,7 @@ from ignite.engine import Engine from monai.handlers import SurfaceDistance -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose def create_spherical_seg_3d( diff --git a/tests/test_handler_tb_image.py b/tests/handlers/test_handler_tb_image.py similarity index 97% rename from tests/test_handler_tb_image.py rename to tests/handlers/test_handler_tb_image.py index 197b175278..2ed37bdbc7 100644 --- a/tests/test_handler_tb_image.py +++ b/tests/handlers/test_handler_tb_image.py @@ -23,7 +23,7 @@ from monai.data import decollate_batch from monai.handlers import TensorBoardImageHandler from monai.utils import optional_import -from tests.utils import SkipIfBeforePyTorchVersion +from tests.test_utils import SkipIfBeforePyTorchVersion _, has_tb = optional_import("torch.utils.tensorboard", name="SummaryWriter") @@ -33,7 +33,6 @@ @unittest.skipUnless(has_tb, "Requires SummaryWriter installation") @SkipIfBeforePyTorchVersion((1, 13)) # issue 6683 class TestHandlerTBImage(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_tb_image_shape(self, shape): with tempfile.TemporaryDirectory() as tempdir: diff --git a/tests/test_handler_tb_stats.py b/tests/handlers/test_handler_tb_stats.py similarity index 100% rename from tests/test_handler_tb_stats.py rename to tests/handlers/test_handler_tb_stats.py diff --git a/tests/test_handler_validation.py b/tests/handlers/test_handler_validation.py similarity index 100% rename from tests/test_handler_validation.py rename to tests/handlers/test_handler_validation.py diff --git a/tests/test_trt_compile.py b/tests/handlers/test_trt_compile.py similarity index 98% rename from tests/test_trt_compile.py rename to tests/handlers/test_trt_compile.py index f7779fec9b..6b0d329af6 100644 --- a/tests/test_trt_compile.py +++ b/tests/handlers/test_trt_compile.py @@ -21,7 +21,7 @@ from monai.networks import trt_compile from monai.networks.nets import cell_sam_wrapper, vista3d132 from monai.utils import min_version, optional_import -from tests.utils import SkipIfBeforeComputeCapabilityVersion, skip_if_no_cuda, skip_if_quick, skip_if_windows +from tests.test_utils import SkipIfBeforeComputeCapabilityVersion, skip_if_no_cuda, skip_if_quick, skip_if_windows trt, trt_imported = optional_import("tensorrt", "10.1.0", min_version) torch_tensorrt, torch_trt_imported = optional_import("torch_tensorrt") @@ -52,7 +52,6 @@ def forward(self, x: list[torch.Tensor], y: torch.Tensor, z: torch.Tensor, bs: f @unittest.skipUnless(polygraphy_imported, "polygraphy is required") @SkipIfBeforeComputeCapabilityVersion((7, 5)) class TestTRTCompile(unittest.TestCase): - def setUp(self): self.gpu_device = torch.cuda.current_device() diff --git a/tests/test_write_metrics_reports.py b/tests/handlers/test_write_metrics_reports.py similarity index 100% rename from tests/test_write_metrics_reports.py rename to tests/handlers/test_write_metrics_reports.py diff --git a/tests/hvd_evenly_divisible_all_gather.py b/tests/hvd_evenly_divisible_all_gather.py index 732ad13b83..57c110a76d 100644 --- a/tests/hvd_evenly_divisible_all_gather.py +++ b/tests/hvd_evenly_divisible_all_gather.py @@ -15,13 +15,12 @@ from monai.utils import evenly_divisible_all_gather from monai.utils.module import optional_import -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose hvd, has_hvd = optional_import("horovod", name="torch") class HvdEvenlyDivisibleAllGather: - def test_data(self): # initialize Horovod hvd.init() diff --git a/tests/inferers/__init__.py b/tests/inferers/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/inferers/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_avg_merger.py b/tests/inferers/test_avg_merger.py similarity index 99% rename from tests/test_avg_merger.py rename to tests/inferers/test_avg_merger.py index 7995d63271..398ea33a00 100644 --- a/tests/test_avg_merger.py +++ b/tests/inferers/test_avg_merger.py @@ -18,7 +18,7 @@ from torch.nn.functional import pad from monai.inferers import AvgMerger -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TENSOR_4x4 = torch.randint(low=0, high=255, size=(2, 3, 4, 4), dtype=torch.float32) TENSOR_4x4_WITH_NAN = TENSOR_4x4.clone() @@ -137,7 +137,6 @@ class AvgMergerTests(unittest.TestCase): - @parameterized.expand( [ TEST_CASE_0_DEFAULT_DTYPE, diff --git a/tests/test_controlnet_inferers.py b/tests/inferers/test_controlnet_inferers.py similarity index 100% rename from tests/test_controlnet_inferers.py rename to tests/inferers/test_controlnet_inferers.py diff --git a/tests/test_diffusion_inferer.py b/tests/inferers/test_diffusion_inferer.py similarity index 100% rename from tests/test_diffusion_inferer.py rename to tests/inferers/test_diffusion_inferer.py diff --git a/tests/test_latent_diffusion_inferer.py b/tests/inferers/test_latent_diffusion_inferer.py similarity index 100% rename from tests/test_latent_diffusion_inferer.py rename to tests/inferers/test_latent_diffusion_inferer.py diff --git a/tests/test_patch_inferer.py b/tests/inferers/test_patch_inferer.py similarity index 99% rename from tests/test_patch_inferer.py rename to tests/inferers/test_patch_inferer.py index c6308224b0..964f08e6fe 100644 --- a/tests/test_patch_inferer.py +++ b/tests/inferers/test_patch_inferer.py @@ -19,7 +19,7 @@ from monai.data.meta_tensor import MetaTensor from monai.inferers import AvgMerger, PatchInferer, SlidingWindowSplitter -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TENSOR_4x4 = torch.randint(low=0, high=255, size=(2, 3, 4, 4), dtype=torch.float32) TENSOR_2x2 = avg_pool2d(TENSOR_4x4, 2, 2) @@ -245,7 +245,6 @@ class PatchInfererTests(unittest.TestCase): - @parameterized.expand( [ TEST_CASE_0_TENSOR, diff --git a/tests/test_saliency_inferer.py b/tests/inferers/test_saliency_inferer.py similarity index 100% rename from tests/test_saliency_inferer.py rename to tests/inferers/test_saliency_inferer.py diff --git a/tests/test_slice_inferer.py b/tests/inferers/test_slice_inferer.py similarity index 100% rename from tests/test_slice_inferer.py rename to tests/inferers/test_slice_inferer.py diff --git a/tests/test_sliding_window_inference.py b/tests/inferers/test_sliding_window_inference.py similarity index 99% rename from tests/test_sliding_window_inference.py rename to tests/inferers/test_sliding_window_inference.py index 33b38a5bc7..997822edd3 100644 --- a/tests/test_sliding_window_inference.py +++ b/tests/inferers/test_sliding_window_inference.py @@ -21,7 +21,7 @@ from monai.data.utils import list_data_collate from monai.inferers import SlidingWindowInferer, SlidingWindowInfererAdapt, sliding_window_inference from monai.utils import optional_import -from tests.utils import TEST_TORCH_AND_META_TENSORS, skip_if_no_cuda, test_is_quick +from tests.test_utils import TEST_TORCH_AND_META_TENSORS, skip_if_no_cuda, test_is_quick _, has_tqdm = optional_import("tqdm") @@ -70,10 +70,8 @@ class TestSlidingWindowInference(unittest.TestCase): - @parameterized.expand(BUFFER_CASES) def test_buffers(self, size_params, buffer_steps, buffer_dim, device_params): - def mult_two(patch, *args, **kwargs): return 2.0 * patch diff --git a/tests/test_sliding_window_splitter.py b/tests/inferers/test_sliding_window_splitter.py similarity index 99% rename from tests/test_sliding_window_splitter.py rename to tests/inferers/test_sliding_window_splitter.py index ad136c61a4..868e3f096f 100644 --- a/tests/test_sliding_window_splitter.py +++ b/tests/inferers/test_sliding_window_splitter.py @@ -18,7 +18,7 @@ from torch.nn.functional import pad from monai.inferers import SlidingWindowSplitter -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose # ---------------------------------------------------------------------------- # Tensor test cases @@ -236,7 +236,6 @@ def missing_parameter_filter(patch): class SlidingWindowSplitterTests(unittest.TestCase): - @parameterized.expand( [ TEST_CASE_TENSOR_0, diff --git a/tests/test_wsi_sliding_window_splitter.py b/tests/inferers/test_wsi_sliding_window_splitter.py similarity index 96% rename from tests/test_wsi_sliding_window_splitter.py rename to tests/inferers/test_wsi_sliding_window_splitter.py index c510ece272..228435f1b4 100644 --- a/tests/test_wsi_sliding_window_splitter.py +++ b/tests/inferers/test_wsi_sliding_window_splitter.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path from unittest import skipUnless import torch @@ -20,7 +21,7 @@ from monai.data import CuCIMWSIReader, ImageReader, OpenSlideWSIReader, WSIReader from monai.inferers import WSISlidingWindowSplitter -from tests.utils import download_url_or_skip_test, optional_import, testing_data_config +from tests.test_utils import download_url_or_skip_test, optional_import, testing_data_config cucim, has_cucim = optional_import("cucim") has_cucim = has_cucim and hasattr(cucim, "CuImage") @@ -36,7 +37,8 @@ WSI_READER_CLASS = OpenSlideWSIReader WSI_GENERIC_TIFF_KEY = "wsi_generic_tiff" -WSI_GENERIC_TIFF_PATH = os.path.join(os.path.dirname(__file__), "testing_data", f"temp_{WSI_GENERIC_TIFF_KEY}.tiff") +TESTS_PATH = Path(__file__).parents[1] +WSI_GENERIC_TIFF_PATH = os.path.join(TESTS_PATH, "testing_data", f"temp_{WSI_GENERIC_TIFF_KEY}.tiff") HEIGHT = 32914 WIDTH = 46000 @@ -102,7 +104,6 @@ # Filtering functions test cases def gen_location_filter(locations): - def my_filter(patch, loc): if loc in locations: return False @@ -199,7 +200,6 @@ def setUpModule(): class WSISlidingWindowSplitterTests(unittest.TestCase): - @parameterized.expand( [ TEST_CASE_WSI_0_BASE, diff --git a/tests/test_zarr_avg_merger.py b/tests/inferers/test_zarr_avg_merger.py similarity index 99% rename from tests/test_zarr_avg_merger.py rename to tests/inferers/test_zarr_avg_merger.py index 64e8fbde71..b5ba1d9902 100644 --- a/tests/test_zarr_avg_merger.py +++ b/tests/inferers/test_zarr_avg_merger.py @@ -20,7 +20,7 @@ from monai.inferers import ZarrAvgMerger from monai.utils import get_package_version, optional_import, version_geq -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose np.seterr(divide="ignore", invalid="ignore") zarr, has_zarr = optional_import("zarr") diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/integration/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_auto3dseg_ensemble.py b/tests/integration/test_auto3dseg_ensemble.py similarity index 99% rename from tests/test_auto3dseg_ensemble.py rename to tests/integration/test_auto3dseg_ensemble.py index 7ac553cc0c..08b059e3f7 100644 --- a/tests/test_auto3dseg_ensemble.py +++ b/tests/integration/test_auto3dseg_ensemble.py @@ -32,7 +32,7 @@ from monai.transforms import SaveImage from monai.utils import check_parent_dir, optional_import, set_determinism from monai.utils.enums import AlgoKeys -from tests.utils import ( +from tests.test_utils import ( SkipIfBeforePyTorchVersion, get_testing_algo_template_path, skip_if_downloading_fails, @@ -112,7 +112,6 @@ def create_sim_data(dataroot, sim_datalist, sim_dim, **kwargs): @SkipIfBeforePyTorchVersion((1, 11, 1)) @unittest.skipIf(not has_tb, "no tensorboard summary writer") class TestEnsembleBuilder(unittest.TestCase): - def setUp(self) -> None: set_determinism(0) self.test_dir = tempfile.TemporaryDirectory() diff --git a/tests/test_auto3dseg_hpo.py b/tests/integration/test_auto3dseg_hpo.py similarity index 99% rename from tests/test_auto3dseg_hpo.py rename to tests/integration/test_auto3dseg_hpo.py index 53d09defa0..f0d3492004 100644 --- a/tests/test_auto3dseg_hpo.py +++ b/tests/integration/test_auto3dseg_hpo.py @@ -25,7 +25,7 @@ from monai.data import create_test_image_3d from monai.utils import optional_import from monai.utils.enums import AlgoKeys -from tests.utils import ( +from tests.test_utils import ( SkipIfBeforePyTorchVersion, get_testing_algo_template_path, skip_if_downloading_fails, @@ -79,7 +79,6 @@ def skip_if_no_optuna(obj): @SkipIfBeforePyTorchVersion((1, 11, 1)) @unittest.skipIf(not has_tb, "no tensorboard summary writer") class TestHPO(unittest.TestCase): - def setUp(self) -> None: self.test_dir = tempfile.TemporaryDirectory() test_path = self.test_dir.name @@ -155,7 +154,6 @@ def test_run_optuna(self) -> None: algo = algo_dict[AlgoKeys.ALGO] class OptunaGenLearningRate(OptunaGen): - def get_hyperparameters(self): return {"learning_rate": self.trial.suggest_float("learning_rate", 0.00001, 0.1)} diff --git a/tests/test_deepedit_interaction.py b/tests/integration/test_deepedit_interaction.py similarity index 100% rename from tests/test_deepedit_interaction.py rename to tests/integration/test_deepedit_interaction.py diff --git a/tests/test_downsample_block.py b/tests/integration/test_downsample_block.py similarity index 100% rename from tests/test_downsample_block.py rename to tests/integration/test_downsample_block.py diff --git a/tests/test_hovernet_nuclear_type_post_processingd.py b/tests/integration/test_hovernet_nuclear_type_post_processingd.py similarity index 97% rename from tests/test_hovernet_nuclear_type_post_processingd.py rename to tests/integration/test_hovernet_nuclear_type_post_processingd.py index 26cf80592c..f2117dc15e 100644 --- a/tests/test_hovernet_nuclear_type_post_processingd.py +++ b/tests/integration/test_hovernet_nuclear_type_post_processingd.py @@ -23,7 +23,7 @@ from monai.transforms import ComputeHoVerMaps from monai.utils import min_version, optional_import from monai.utils.enums import HoVerNetBranch -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose _, has_scipy = optional_import("scipy", "1.8.1", min_version) _, has_skimage = optional_import("skimage", "0.19.3", min_version) @@ -42,7 +42,6 @@ @unittest.skipUnless(has_scipy, "Requires scipy library.") @unittest.skipUnless(has_skimage, "Requires scikit-image library.") class TestHoVerNetNuclearTypePostProcessingd(unittest.TestCase): - @parameterized.expand(TEST_CASE) def test_value(self, in_type, test_data, kwargs, expected): input = { diff --git a/tests/test_integration_autorunner.py b/tests/integration/test_integration_autorunner.py similarity index 99% rename from tests/test_integration_autorunner.py rename to tests/integration/test_integration_autorunner.py index 31a0813abc..52906bde05 100644 --- a/tests/test_integration_autorunner.py +++ b/tests/integration/test_integration_autorunner.py @@ -23,7 +23,7 @@ from monai.bundle.config_parser import ConfigParser from monai.data import create_test_image_3d from monai.utils import optional_import -from tests.utils import ( +from tests.test_utils import ( SkipIfBeforePyTorchVersion, get_testing_algo_template_path, skip_if_downloading_fails, @@ -71,7 +71,6 @@ @SkipIfBeforePyTorchVersion((1, 11, 1)) # for mem_get_info @unittest.skipIf(not has_tb, "no tensorboard summary writer") class TestAutoRunner(unittest.TestCase): - def setUp(self) -> None: self.test_dir = tempfile.TemporaryDirectory() test_path = self.test_dir.name diff --git a/tests/test_integration_bundle_run.py b/tests/integration/test_integration_bundle_run.py similarity index 94% rename from tests/test_integration_bundle_run.py rename to tests/integration/test_integration_bundle_run.py index 60aaef05bf..cfbbcfe154 100644 --- a/tests/test_integration_bundle_run.py +++ b/tests/integration/test_integration_bundle_run.py @@ -19,6 +19,7 @@ import tempfile import unittest from glob import glob +from pathlib import Path import nibabel as nib import numpy as np @@ -29,15 +30,15 @@ from monai.bundle.utils import DEFAULT_HANDLERS_ID from monai.transforms import LoadImage from monai.utils import path_to_uri -from tests.utils import command_line_tests +from tests.test_utils import command_line_tests -TEST_CASE_1 = [os.path.join(os.path.dirname(__file__), "testing_data", "inference.json"), (128, 128, 128)] +TESTS_PATH = Path(__file__).parents[1] +TEST_CASE_1 = [os.path.join(TESTS_PATH, "testing_data", "inference.json"), (128, 128, 128)] -TEST_CASE_2 = [os.path.join(os.path.dirname(__file__), "testing_data", "inference.yaml"), (128, 128, 128)] +TEST_CASE_2 = [os.path.join(TESTS_PATH, "testing_data", "inference.yaml"), (128, 128, 128)] class _Runnable42: - def __init__(self, val=1): self.val = val @@ -47,7 +48,6 @@ def run(self): class _Runnable43: - def __init__(self, func): self.func = func @@ -56,7 +56,6 @@ def run(self): class TestBundleRun(unittest.TestCase): - def setUp(self): self.data_dir = tempfile.mkdtemp() @@ -69,7 +68,7 @@ def test_tiny(self): with open(config_file, "w") as f: json.dump( { - "trainer": {"_target_": "tests.test_integration_bundle_run._Runnable42", "val": 42}, + "trainer": {"_target_": "tests.integration.test_integration_bundle_run._Runnable42", "val": 42}, # keep this test case to cover the "run_id" arg "training": "$@trainer.run()", }, @@ -105,7 +104,7 @@ def test_scripts_fold(self): { "imports": ["$import scripts"], "trainer": { - "_target_": "tests.test_integration_bundle_run._Runnable43", + "_target_": "tests.integration.test_integration_bundle_run._Runnable43", "func": "$scripts.tiny_test", }, # keep this test case to cover the "run_id" arg @@ -161,7 +160,7 @@ def test_shape(self, config_file, expected_shape): nib.save(nib.Nifti1Image(test_image, np.eye(4)), filename) # generate default args in a JSON file - logging_conf = os.path.join(os.path.dirname(__file__), "testing_data", "logging.conf") + logging_conf = os.path.join(TESTS_PATH, "testing_data", "logging.conf") def_args = {"config_file": "will be replaced by `config_file` arg", "logging_file": logging_conf} def_args_file = os.path.join(tempdir, "def_args.json") ConfigParser.export_config_file(config=def_args, filepath=def_args_file) diff --git a/tests/test_integration_classification_2d.py b/tests/integration/test_integration_classification_2d.py similarity index 96% rename from tests/test_integration_classification_2d.py rename to tests/integration/test_integration_classification_2d.py index b137fc9b75..fd9e58aaf8 100644 --- a/tests/test_integration_classification_2d.py +++ b/tests/integration/test_integration_classification_2d.py @@ -38,14 +38,13 @@ Transpose, ) from monai.utils import set_determinism +from tests.test_utils import DistTestCase, TimedCall, skip_if_downloading_fails, skip_if_quick, testing_data_config from tests.testing_data.integration_answers import test_integration_value -from tests.utils import DistTestCase, TimedCall, skip_if_downloading_fails, skip_if_quick, testing_data_config TASK = "integration_classification_2d" class MedNISTDataset(torch.utils.data.Dataset): - def __init__(self, image_files, labels, transforms): self.image_files = image_files self.labels = labels @@ -95,7 +94,7 @@ def run_training_test(root_dir, train_x, train_y, val_x, val_y, device="cuda:0", model = DenseNet121(spatial_dims=2, in_channels=1, out_channels=len(np.unique(train_y))).to(device) loss_function = torch.nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), 1e-5) - epoch_num = 4 + epoch_num = 1 val_interval = 1 # start training validation @@ -128,7 +127,7 @@ def run_training_test(root_dir, train_x, train_y, val_x, val_y, device="cuda:0", y_pred = torch.tensor([], dtype=torch.float32, device=device) y = torch.tensor([], dtype=torch.long, device=device) for val_data in val_loader: - val_images, val_labels = val_data[0].to(device), val_data[1].to(device) + val_images, val_labels = (val_data[0].to(device), val_data[1].to(device)) y_pred = torch.cat([y_pred, model(val_images)], dim=0) y = torch.cat([y, val_labels], dim=0) @@ -149,7 +148,7 @@ def run_training_test(root_dir, train_x, train_y, val_x, val_y, device="cuda:0", torch.save(model.state_dict(), model_filename) print("saved new best metric model") print( - f"current epoch {epoch +1} current AUC: {auc_value:0.4f} " + f"current epoch {epoch + 1} current AUC: {auc_value:0.4f} " f"current accuracy: {acc_metric:0.4f} best AUC: {best_metric:0.4f} at epoch {best_metric_epoch}" ) print(f"train completed, best_metric: {best_metric:0.4f} at epoch: {best_metric_epoch}") @@ -183,10 +182,9 @@ def run_inference_test(root_dir, test_x, test_y, device="cuda:0", num_workers=10 @skip_if_quick class IntegrationClassification2D(DistTestCase): - def setUp(self): set_determinism(seed=0) - self.data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "testing_data") + self.data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../testing_data") data_dir = os.path.join(self.data_dir, "MedNIST") dataset_file = os.path.join(self.data_dir, "MedNIST.tar.gz") @@ -270,7 +268,7 @@ def train_and_infer(self, idx=0): def test_training(self): repeated = [] - for i in range(2): + for i in range(1): results = self.train_and_infer(i) repeated.append(results) np.testing.assert_allclose(repeated[0], repeated[1]) diff --git a/tests/test_integration_determinism.py b/tests/integration/test_integration_determinism.py similarity index 98% rename from tests/test_integration_determinism.py rename to tests/integration/test_integration_determinism.py index 3e88f05620..f48a35c70e 100644 --- a/tests/test_integration_determinism.py +++ b/tests/integration/test_integration_determinism.py @@ -22,13 +22,11 @@ from monai.networks.nets import UNet from monai.transforms import Compose, EnsureChannelFirst, RandRotate90, RandSpatialCrop, ScaleIntensity from monai.utils import set_determinism -from tests.utils import DistTestCase, TimedCall +from tests.test_utils import DistTestCase, TimedCall def run_test(batch_size=64, train_steps=200, device="cuda:0"): - class _TestBatch(Dataset): - def __init__(self, transforms): self.transforms = transforms @@ -78,7 +76,6 @@ def __len__(self): class TestDeterminism(DistTestCase): - def setUp(self): self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu:0") diff --git a/tests/test_integration_fast_train.py b/tests/integration/test_integration_fast_train.py similarity index 99% rename from tests/test_integration_fast_train.py rename to tests/integration/test_integration_fast_train.py index 071eb5cf78..f9beb5613d 100644 --- a/tests/test_integration_fast_train.py +++ b/tests/integration/test_integration_fast_train.py @@ -52,13 +52,12 @@ ToDeviced, ) from monai.utils import set_determinism -from tests.utils import DistTestCase, TimedCall, skip_if_no_cuda, skip_if_quick +from tests.test_utils import DistTestCase, TimedCall, skip_if_no_cuda, skip_if_quick @skip_if_no_cuda @skip_if_quick class IntegrationFastTrain(DistTestCase): - def setUp(self): set_determinism(seed=0) monai.config.print_config() diff --git a/tests/test_integration_gpu_customization.py b/tests/integration/test_integration_gpu_customization.py similarity index 99% rename from tests/test_integration_gpu_customization.py rename to tests/integration/test_integration_gpu_customization.py index 043405a580..42f7d52e21 100644 --- a/tests/test_integration_gpu_customization.py +++ b/tests/integration/test_integration_gpu_customization.py @@ -24,7 +24,7 @@ from monai.data import create_test_image_3d from monai.utils import optional_import from monai.utils.enums import AlgoKeys -from tests.utils import ( +from tests.test_utils import ( SkipIfBeforePyTorchVersion, get_testing_algo_template_path, skip_if_downloading_fails, @@ -70,7 +70,6 @@ @SkipIfBeforePyTorchVersion((1, 11, 1)) # module 'torch.cuda' has no attribute 'mem_get_info' @unittest.skipIf(not has_tb, "no tensorboard summary writer") class TestEnsembleGpuCustomization(unittest.TestCase): - def setUp(self) -> None: self.test_dir = tempfile.TemporaryDirectory() diff --git a/tests/test_integration_lazy_samples.py b/tests/integration/test_integration_lazy_samples.py similarity index 98% rename from tests/test_integration_lazy_samples.py rename to tests/integration/test_integration_lazy_samples.py index 51d80e7305..834e9ccb2a 100644 --- a/tests/test_integration_lazy_samples.py +++ b/tests/integration/test_integration_lazy_samples.py @@ -26,7 +26,7 @@ from monai.data import create_test_image_3d, decollate_batch from monai.transforms.utils import has_status_keys from monai.utils import TraceStatusKeys, set_determinism -from tests.utils import HAS_CUPY, DistTestCase, SkipIfBeforePyTorchVersion, skip_if_quick +from tests.test_utils import HAS_CUPY, DistTestCase, SkipIfBeforePyTorchVersion, skip_if_quick def _no_op(x): @@ -160,7 +160,6 @@ def run_training_test(root_dir, device="cuda:0", cachedataset=0, readers=(None, @skip_if_quick @SkipIfBeforePyTorchVersion((1, 11)) class IntegrationLazyResampling(DistTestCase): - def setUp(self): monai.config.print_config() set_determinism(seed=0) diff --git a/tests/test_integration_nnunetv2_runner.py b/tests/integration/test_integration_nnunetv2_runner.py similarity index 97% rename from tests/test_integration_nnunetv2_runner.py rename to tests/integration/test_integration_nnunetv2_runner.py index 822d454f52..9717e06170 100644 --- a/tests/test_integration_nnunetv2_runner.py +++ b/tests/integration/test_integration_nnunetv2_runner.py @@ -22,7 +22,7 @@ from monai.bundle.config_parser import ConfigParser from monai.data import create_test_image_3d from monai.utils import optional_import -from tests.utils import SkipIfBeforePyTorchVersion, skip_if_downloading_fails, skip_if_no_cuda, skip_if_quick +from tests.test_utils import SkipIfBeforePyTorchVersion, skip_if_downloading_fails, skip_if_no_cuda, skip_if_quick _, has_tb = optional_import("torch.utils.tensorboard", name="SummaryWriter") _, has_nnunet = optional_import("nnunetv2") @@ -49,7 +49,6 @@ @unittest.skipIf(not has_tb, "no tensorboard summary writer") @unittest.skipIf(not has_nnunet, "no nnunetv2") class TestnnUNetV2Runner(unittest.TestCase): - def setUp(self) -> None: self.test_dir = tempfile.TemporaryDirectory() test_path = self.test_dir.name diff --git a/tests/test_integration_segmentation_3d.py b/tests/integration/test_integration_segmentation_3d.py similarity index 96% rename from tests/test_integration_segmentation_3d.py rename to tests/integration/test_integration_segmentation_3d.py index c72369b151..fb2937739f 100644 --- a/tests/test_integration_segmentation_3d.py +++ b/tests/integration/test_integration_segmentation_3d.py @@ -41,8 +41,8 @@ ) from monai.utils import optional_import, set_determinism from monai.visualize import plot_2d_or_3d_image +from tests.test_utils import DistTestCase, TimedCall, skip_if_quick from tests.testing_data.integration_answers import test_integration_value -from tests.utils import DistTestCase, TimedCall, skip_if_quick SummaryWriter, _ = optional_import("torch.utils.tensorboard", name="SummaryWriter") @@ -139,7 +139,7 @@ def run_training_test(root_dir, device="cuda:0", cachedataset=0, readers=(None, writer.add_scalar("train_loss", loss.item(), epoch_len * epoch + step) epoch_loss /= step epoch_loss_values.append(epoch_loss) - print(f"epoch {epoch +1} average loss:{epoch_loss:0.4f}") + print(f"epoch {epoch + 1} average loss:{epoch_loss:0.4f}") if (epoch + 1) % val_interval == 0: with eval_mode(model): @@ -147,7 +147,7 @@ def run_training_test(root_dir, device="cuda:0", cachedataset=0, readers=(None, val_labels = None val_outputs = None for val_data in val_loader: - val_images, val_labels = val_data["img"].to(device), val_data["seg"].to(device) + val_images, val_labels = (val_data["img"].to(device), val_data["seg"].to(device)) sw_batch_size, roi_size = 4, (96, 96, 96) val_outputs = sliding_window_inference(val_images, roi_size, sw_batch_size, model) # decollate prediction into a list and execute post processing for every item @@ -164,7 +164,7 @@ def run_training_test(root_dir, device="cuda:0", cachedataset=0, readers=(None, torch.save(model.state_dict(), model_filename) print("saved new best metric model") print( - f"current epoch {epoch +1} current mean dice: {metric:0.4f} " + f"current epoch {epoch + 1} current mean dice: {metric:0.4f} " f"best mean dice: {best_metric:0.4f} at epoch {best_metric_epoch}" ) writer.add_scalar("val_mean_dice", metric, epoch + 1) @@ -221,7 +221,7 @@ def run_inference_test(root_dir, device="cuda:0"): # resampling with align_corners=True or dtype=float64 will generate # slight different results between PyTorch 1.5 an 1.6 for val_data in val_loader: - val_images, val_labels = val_data["img"].to(device), val_data["seg"].to(device) + val_images, val_labels = (val_data["img"].to(device), val_data["seg"].to(device)) # define sliding window size and batch size for windows inference sw_batch_size, roi_size = 4, (96, 96, 96) val_outputs = sliding_window_inference(val_images, roi_size, sw_batch_size, model) @@ -235,7 +235,6 @@ def run_inference_test(root_dir, device="cuda:0"): @skip_if_quick class IntegrationSegmentation3D(DistTestCase): - def setUp(self): set_determinism(seed=0) diff --git a/tests/test_integration_sliding_window.py b/tests/integration/test_integration_sliding_window.py similarity index 97% rename from tests/test_integration_sliding_window.py rename to tests/integration/test_integration_sliding_window.py index 8b53e94941..a3e95b1d87 100644 --- a/tests/test_integration_sliding_window.py +++ b/tests/integration/test_integration_sliding_window.py @@ -27,7 +27,7 @@ from monai.networks.nets import UNet from monai.transforms import EnsureChannelFirst, SaveImage from monai.utils import pytorch_after, set_determinism -from tests.utils import DistTestCase, TimedCall, make_nifti_image, skip_if_quick +from tests.test_utils import DistTestCase, TimedCall, make_nifti_image, skip_if_quick def run_test(batch_size, img_name, seg_name, output_dir, device="cuda:0"): @@ -72,7 +72,6 @@ def save_func(engine): @skip_if_quick class TestIntegrationSlidingWindow(DistTestCase): - def setUp(self): set_determinism(seed=0) diff --git a/tests/test_integration_stn.py b/tests/integration/test_integration_stn.py similarity index 98% rename from tests/test_integration_stn.py rename to tests/integration/test_integration_stn.py index 750a20ea5c..b9f0f975e8 100644 --- a/tests/test_integration_stn.py +++ b/tests/integration/test_integration_stn.py @@ -22,7 +22,7 @@ from monai.data import create_test_image_2d from monai.networks.layers import AffineTransform from monai.utils import set_determinism -from tests.utils import DistTestCase, TimedCall +from tests.test_utils import DistTestCase, TimedCall class STNBenchmark(nn.Module): @@ -98,7 +98,6 @@ def compare_2d(is_ref=True, device=None, reverse_indexing=False): class TestSpatialTransformerCore(DistTestCase): - def setUp(self): self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu:0") diff --git a/tests/test_integration_unet_2d.py b/tests/integration/test_integration_unet_2d.py similarity index 97% rename from tests/test_integration_unet_2d.py rename to tests/integration/test_integration_unet_2d.py index 3b40682de0..706b0e0afb 100644 --- a/tests/test_integration_unet_2d.py +++ b/tests/integration/test_integration_unet_2d.py @@ -21,13 +21,11 @@ from monai.data import create_test_image_2d from monai.losses import DiceLoss from monai.networks.nets import BasicUNet, UNet -from tests.utils import DistTestCase, TimedCall, skip_if_quick +from tests.test_utils import DistTestCase, TimedCall, skip_if_quick def run_test(net_name="basicunet", batch_size=64, train_steps=100, device="cuda:0"): - class _TestBatch(Dataset): - def __getitem__(self, _unused_id): im, seg = create_test_image_2d(128, 128, noise_max=1, num_objs=4, num_seg_classes=1) return im[None], seg[None].astype(np.float32) @@ -57,7 +55,6 @@ def __len__(self): @skip_if_quick class TestIntegrationUnet2D(DistTestCase): - @TimedCall(seconds=20, daemon=False) def test_unet_training(self): for n in ["basicunet", "unet"]: diff --git a/tests/test_integration_workers.py b/tests/integration/test_integration_workers.py similarity index 94% rename from tests/test_integration_workers.py rename to tests/integration/test_integration_workers.py index 123b1ddc6f..6b6ee057f5 100644 --- a/tests/test_integration_workers.py +++ b/tests/integration/test_integration_workers.py @@ -18,7 +18,7 @@ from monai.data import DataLoader from monai.utils import set_determinism -from tests.utils import DistTestCase, SkipIfBeforePyTorchVersion, TimedCall, skip_if_no_cuda, skip_if_quick +from tests.test_utils import DistTestCase, SkipIfBeforePyTorchVersion, TimedCall, skip_if_no_cuda, skip_if_quick def run_loading_test(num_workers=50, device=None, pw=False): @@ -44,7 +44,6 @@ def run_loading_test(num_workers=50, device=None, pw=False): @skip_if_no_cuda @SkipIfBeforePyTorchVersion((1, 9)) class IntegrationLoading(DistTestCase): - def tearDown(self): set_determinism(seed=None) diff --git a/tests/test_integration_workflows.py b/tests/integration/test_integration_workflows.py similarity index 99% rename from tests/test_integration_workflows.py rename to tests/integration/test_integration_workflows.py index fafb66f675..2e14209480 100644 --- a/tests/test_integration_workflows.py +++ b/tests/integration/test_integration_workflows.py @@ -53,8 +53,8 @@ ScaleIntensityd, ) from monai.utils import optional_import, set_determinism +from tests.test_utils import DistTestCase, TimedCall, assert_allclose, pytorch_after, skip_if_quick from tests.testing_data.integration_answers import test_integration_value -from tests.utils import DistTestCase, TimedCall, assert_allclose, pytorch_after, skip_if_quick SummaryWriter, _ = optional_import("torch.utils.tensorboard", name="SummaryWriter") @@ -118,7 +118,6 @@ def run_training_test(root_dir, device="cuda:0", amp=False, num_workers=4): ) class _TestEvalIterEvents: - def attach(self, engine): engine.add_event_handler(IterationEvents.FORWARD_COMPLETED, self._forward_completed) @@ -161,7 +160,6 @@ def _forward_completed(self, engine): ) class _TestTrainIterEvents: - def attach(self, engine): engine.add_event_handler(IterationEvents.FORWARD_COMPLETED, self._forward_completed) engine.add_event_handler(IterationEvents.LOSS_COMPLETED, self._loss_completed) @@ -286,7 +284,6 @@ def save_func(engine): @skip_if_quick class IntegrationWorkflows(DistTestCase): - def setUp(self): set_determinism(seed=0) diff --git a/tests/test_integration_workflows_adversarial.py b/tests/integration/test_integration_workflows_adversarial.py similarity index 98% rename from tests/test_integration_workflows_adversarial.py rename to tests/integration/test_integration_workflows_adversarial.py index f323fc9917..5badafcc41 100644 --- a/tests/test_integration_workflows_adversarial.py +++ b/tests/integration/test_integration_workflows_adversarial.py @@ -28,7 +28,7 @@ from monai.transforms import Compose, EnsureChannelFirstd, LoadImaged, RandFlipd, ScaleIntensityd from monai.utils import AdversarialKeys as Keys from monai.utils import CommonKeys, optional_import, set_determinism -from tests.utils import DistTestCase, TimedCall, skip_if_quick +from tests.test_utils import DistTestCase, TimedCall, skip_if_quick nib, has_nibabel = optional_import("nibabel") diff --git a/tests/test_integration_workflows_gan.py b/tests/integration/test_integration_workflows_gan.py similarity index 98% rename from tests/test_integration_workflows_gan.py rename to tests/integration/test_integration_workflows_gan.py index 1428506020..adf86df59b 100644 --- a/tests/test_integration_workflows_gan.py +++ b/tests/integration/test_integration_workflows_gan.py @@ -30,7 +30,7 @@ from monai.transforms import Compose, EnsureChannelFirstd, LoadImaged, RandFlipd, ScaleIntensityd from monai.utils import GanKeys as Keys from monai.utils import set_determinism -from tests.utils import DistTestCase, TimedCall, skip_if_quick +from tests.test_utils import DistTestCase, TimedCall, skip_if_quick def run_training_test(root_dir, device="cuda:0"): @@ -127,7 +127,6 @@ def generator_loss(gen_images): @skip_if_quick class IntegrationWorkflowsGAN(DistTestCase): - def setUp(self): set_determinism(seed=0) diff --git a/tests/test_loader_semaphore.py b/tests/integration/test_loader_semaphore.py similarity index 100% rename from tests/test_loader_semaphore.py rename to tests/integration/test_loader_semaphore.py diff --git a/tests/test_mapping_filed.py b/tests/integration/test_mapping_filed.py similarity index 100% rename from tests/test_mapping_filed.py rename to tests/integration/test_mapping_filed.py diff --git a/tests/test_meta_affine.py b/tests/integration/test_meta_affine.py similarity index 95% rename from tests/test_meta_affine.py rename to tests/integration/test_meta_affine.py index 890734391f..8c3b4f287e 100644 --- a/tests/test_meta_affine.py +++ b/tests/integration/test_meta_affine.py @@ -14,6 +14,7 @@ import os import unittest from copy import deepcopy +from pathlib import Path import numpy as np from parameterized import parameterized @@ -34,15 +35,16 @@ Transform, ) from monai.utils import convert_data_type, optional_import -from tests.utils import assert_allclose, download_url_or_skip_test, testing_data_config +from tests.test_utils import assert_allclose, download_url_or_skip_test, testing_data_config itk, has_itk = optional_import("itk") TINY_DIFF = 1e-4 keys = ("img1", "img2") key, key_1 = "ref_avg152T1_LR", "ref_avg152T1_RL" -FILE_PATH = os.path.join(os.path.dirname(__file__), "testing_data", f"{key}.nii.gz") -FILE_PATH_1 = os.path.join(os.path.dirname(__file__), "testing_data", f"{key_1}.nii.gz") +TESTS_PATH = Path(__file__).parents[1] +FILE_PATH = os.path.join(TESTS_PATH, "testing_data", f"{key}.nii.gz") +FILE_PATH_1 = os.path.join(TESTS_PATH, "testing_data", f"{key_1}.nii.gz") TEST_CASES_ARRAY = [ [Compose([Spacing(pixdim=(1.0, 1.1, 1.2)), Orientation(axcodes="RAS")]), {}, TINY_DIFF], @@ -123,7 +125,6 @@ def _resample_to_affine(itk_obj, ref_obj): @unittest.skipUnless(has_itk, "Requires itk package.") class TestAffineConsistencyITK(unittest.TestCase): - @classmethod def setUpClass(cls): super().setUpClass() diff --git a/tests/test_metatensor_integration.py b/tests/integration/test_metatensor_integration.py similarity index 92% rename from tests/test_metatensor_integration.py rename to tests/integration/test_metatensor_integration.py index d647e47e74..70ebc5174e 100644 --- a/tests/test_metatensor_integration.py +++ b/tests/integration/test_metatensor_integration.py @@ -15,6 +15,7 @@ import tempfile import unittest from copy import deepcopy +from pathlib import Path import numpy as np from parameterized import parameterized @@ -25,21 +26,21 @@ from monai.data.utils import TraceKeys from monai.transforms import InvertD, SaveImageD, reset_ops_id from monai.utils import optional_import, set_determinism -from tests.utils import assert_allclose, download_url_or_skip_test, testing_data_config +from tests.test_utils import assert_allclose, download_url_or_skip_test, testing_data_config nib, has_nib = optional_import("nibabel") TINY_DIFF = 0.1 keys = ("img", "seg") key, key_1 = "MNI152_T1_2mm", "MNI152_T1_2mm_strucseg" -FILE_PATH = os.path.join(os.path.dirname(__file__), "testing_data", f"{key}.nii.gz") -FILE_PATH_1 = os.path.join(os.path.dirname(__file__), "testing_data", f"{key_1}.nii.gz") -TEST_CASES = os.path.join(os.path.dirname(__file__), "testing_data", "transform_metatensor_cases.yaml") +TESTS_PATH = Path(__file__).parents[1] +FILE_PATH = os.path.join(TESTS_PATH, "testing_data", f"{key}.nii.gz") +FILE_PATH_1 = os.path.join(TESTS_PATH, "testing_data", f"{key_1}.nii.gz") +TEST_CASES = os.path.join(TESTS_PATH, "testing_data", "transform_metatensor_cases.yaml") @unittest.skipUnless(has_nib, "Requires nibabel package.") class TestMetaTensorIntegration(unittest.TestCase): - @classmethod def setUpClass(cls): super().setUpClass() diff --git a/tests/test_module_list.py b/tests/integration/test_module_list.py similarity index 100% rename from tests/test_module_list.py rename to tests/integration/test_module_list.py diff --git a/tests/test_one_of.py b/tests/integration/test_one_of.py similarity index 100% rename from tests/test_one_of.py rename to tests/integration/test_one_of.py diff --git a/tests/test_pad_collation.py b/tests/integration/test_pad_collation.py similarity index 100% rename from tests/test_pad_collation.py rename to tests/integration/test_pad_collation.py diff --git a/tests/test_reg_loss_integration.py b/tests/integration/test_reg_loss_integration.py similarity index 98% rename from tests/test_reg_loss_integration.py rename to tests/integration/test_reg_loss_integration.py index 8afc2da6ad..47d2a8df80 100644 --- a/tests/test_reg_loss_integration.py +++ b/tests/integration/test_reg_loss_integration.py @@ -19,7 +19,7 @@ from parameterized import parameterized from monai.losses import BendingEnergyLoss, GlobalMutualInformationLoss, LocalNormalizedCrossCorrelationLoss -from tests.utils import SkipIfBeforePyTorchVersion +from tests.test_utils import SkipIfBeforePyTorchVersion TEST_CASES = [ [BendingEnergyLoss, {}, ["pred"], 3], @@ -32,7 +32,6 @@ class TestRegLossIntegration(unittest.TestCase): - def setUp(self): torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False @@ -62,7 +61,6 @@ def test_convergence(self, loss_type, loss_args, forward_args, pred_channels=1): # define a one layer model class OnelayerNet(nn.Module): - def __init__(self): super().__init__() self.layer = nn.Sequential( diff --git a/tests/test_retinanet_predict_utils.py b/tests/integration/test_retinanet_predict_utils.py similarity index 100% rename from tests/test_retinanet_predict_utils.py rename to tests/integration/test_retinanet_predict_utils.py diff --git a/tests/test_seg_loss_integration.py b/tests/integration/test_seg_loss_integration.py similarity index 100% rename from tests/test_seg_loss_integration.py rename to tests/integration/test_seg_loss_integration.py diff --git a/tests/test_spatial_combine_transforms.py b/tests/integration/test_spatial_combine_transforms.py similarity index 99% rename from tests/test_spatial_combine_transforms.py rename to tests/integration/test_spatial_combine_transforms.py index 8479e9084b..c947f2f774 100644 --- a/tests/test_spatial_combine_transforms.py +++ b/tests/integration/test_spatial_combine_transforms.py @@ -24,7 +24,7 @@ from monai.transforms.transform import MapTransform from monai.utils import set_determinism from tests.lazy_transforms_utils import get_apply_param -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_2D = [ [ @@ -132,7 +132,6 @@ class CombineLazyTest(unittest.TestCase): - @parameterized.expand(TEST_2D + TEST_3D) def test_combine_transforms(self, input_shape, funcs): for device in ["cpu", "cuda"] if torch.cuda.is_available() else ["cpu"]: diff --git a/tests/test_testtimeaugmentation.py b/tests/integration/test_testtimeaugmentation.py similarity index 97% rename from tests/test_testtimeaugmentation.py rename to tests/integration/test_testtimeaugmentation.py index 746ad122b2..62e4b46282 100644 --- a/tests/test_testtimeaugmentation.py +++ b/tests/integration/test_testtimeaugmentation.py @@ -37,7 +37,7 @@ from monai.transforms.spatial.dictionary import RandFlipd from monai.utils import optional_import, set_determinism from monai.utils.enums import PostFix -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS if TYPE_CHECKING: import tqdm @@ -52,7 +52,6 @@ class TestTestTimeAugmentation(unittest.TestCase): - @staticmethod def get_data(num_examples, input_size, data_type=np.asarray, include_label=True): custom_create_test_image_2d = partial( @@ -114,7 +113,7 @@ def test_test_time_augmentation(self): epoch_loss = 0 for batch_data in train_loader: - inputs, labels = batch_data["image"].to(device), batch_data["label"].to(device) + inputs, labels = (batch_data["image"].to(device), batch_data["label"].to(device)) optimizer.zero_grad() outputs = model(inputs) loss = loss_function(outputs, labels) diff --git a/tests/test_vis_gradbased.py b/tests/integration/test_vis_gradbased.py similarity index 100% rename from tests/test_vis_gradbased.py rename to tests/integration/test_vis_gradbased.py diff --git a/tests/test_vista3d_utils.py b/tests/integration/test_vista3d_utils.py similarity index 99% rename from tests/test_vista3d_utils.py rename to tests/integration/test_vista3d_utils.py index 5a0caedd61..0ae8e28b4e 100644 --- a/tests/test_vista3d_utils.py +++ b/tests/integration/test_vista3d_utils.py @@ -21,7 +21,7 @@ from monai.transforms.utils import convert_points_to_disc, keep_merge_components_with_points, sample_points_from_label from monai.utils import min_version from monai.utils.module import optional_import -from tests.utils import skip_if_no_cuda, skip_if_quick +from tests.test_utils import skip_if_no_cuda, skip_if_quick cp, has_cp = optional_import("cupy") cucim_skimage, has_cucim = optional_import("cucim.skimage") @@ -114,7 +114,6 @@ @skipUnless(has_measure or cucim_skimage, "skimage or cucim.skimage required") class TestSamplePointsFromLabel(unittest.TestCase): - @parameterized.expand(TESTS_SAMPLE_POINTS_FROM_LABEL) def test_shape(self, input_data, expected_point_shape, expected_point_label_shape): point, point_label = sample_points_from_label(**input_data) @@ -123,7 +122,6 @@ def test_shape(self, input_data, expected_point_shape, expected_point_label_shap class TestConvertPointsToDisc(unittest.TestCase): - @parameterized.expand(TEST_CONVERT_POINTS_TO_DISC) def test_shape(self, input_data, expected_shape): result = convert_points_to_disc(**input_data) @@ -140,7 +138,6 @@ def test_value(self, input_data, points): @skipUnless(has_measure or cucim_skimage, "skimage or cucim.skimage required") class TestKeepMergeComponentsWithPoints(unittest.TestCase): - @skip_if_quick @skip_if_no_cuda @skipUnless(has_cp and cucim_skimage, "cupy and cucim.skimage required") diff --git a/tests/lazy_transforms_utils.py b/tests/lazy_transforms_utils.py index 1681e26037..3a737df201 100644 --- a/tests/lazy_transforms_utils.py +++ b/tests/lazy_transforms_utils.py @@ -16,7 +16,7 @@ from monai.data import MetaTensor, set_track_meta from monai.transforms import InvertibleTransform, MapTransform, Randomizable from monai.transforms.lazy.functional import apply_pending -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose apply_transforms_kwargs = ("pending", "mode", "padding_mode", "dtype", "align_corners") @@ -64,7 +64,7 @@ def test_resampler_lazy( resampler.lazy = True pending_output = resampler(**deepcopy(call_param)) if output_idx is not None: - expected_output, pending_output = expected_output[output_idx], pending_output[output_idx] + expected_output, pending_output = (expected_output[output_idx], pending_output[output_idx]) if output_key is not None: non_lazy_out, lazy_out = expected_output[output_key], pending_output[output_key] else: diff --git a/tests/losses/__init__.py b/tests/losses/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/losses/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/losses/deform/__init__.py b/tests/losses/deform/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/losses/deform/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_bending_energy.py b/tests/losses/deform/test_bending_energy.py similarity index 100% rename from tests/test_bending_energy.py rename to tests/losses/deform/test_bending_energy.py diff --git a/tests/test_diffusion_loss.py b/tests/losses/deform/test_diffusion_loss.py similarity index 100% rename from tests/test_diffusion_loss.py rename to tests/losses/deform/test_diffusion_loss.py diff --git a/tests/losses/image_dissimilarity/__init__.py b/tests/losses/image_dissimilarity/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/losses/image_dissimilarity/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_global_mutual_information_loss.py b/tests/losses/image_dissimilarity/test_global_mutual_information_loss.py similarity index 95% rename from tests/test_global_mutual_information_loss.py rename to tests/losses/image_dissimilarity/test_global_mutual_information_loss.py index 22f5e88431..44e73a477c 100644 --- a/tests/test_global_mutual_information_loss.py +++ b/tests/losses/image_dissimilarity/test_global_mutual_information_loss.py @@ -12,6 +12,7 @@ import os import unittest +from pathlib import Path import numpy as np import torch @@ -19,11 +20,12 @@ from monai import transforms from monai.losses.image_dissimilarity import GlobalMutualInformationLoss -from tests.utils import SkipIfBeforePyTorchVersion, download_url_or_skip_test, skip_if_quick, testing_data_config +from tests.test_utils import SkipIfBeforePyTorchVersion, download_url_or_skip_test, skip_if_quick, testing_data_config device = "cuda:0" if torch.cuda.is_available() else "cpu" -FILE_PATH = os.path.join(os.path.dirname(__file__), "testing_data", "temp_" + "mri.nii") +TESTS_PATH = Path(__file__).parents[2] +FILE_PATH = os.path.join(TESTS_PATH, "testing_data", "temp_" + "mri.nii") EXPECTED_VALUE = { "xyz_translation": [ @@ -55,7 +57,6 @@ @skip_if_quick class TestGlobalMutualInformationLoss(unittest.TestCase): - def setUp(self): config = testing_data_config("images", "Prostate_T2W_AX_1") download_url_or_skip_test( @@ -116,7 +117,6 @@ def transformation(translate_params=(0.0, 0.0, 0.0), rotate_params=(0.0, 0.0, 0. class TestGlobalMutualInformationLossIll(unittest.TestCase): - @parameterized.expand( [ (torch.ones((1, 2), dtype=torch.float), torch.ones((1, 3), dtype=torch.float)), # mismatched_simple_dims diff --git a/tests/test_local_normalized_cross_correlation_loss.py b/tests/losses/image_dissimilarity/test_local_normalized_cross_correlation_loss.py similarity index 100% rename from tests/test_local_normalized_cross_correlation_loss.py rename to tests/losses/image_dissimilarity/test_local_normalized_cross_correlation_loss.py diff --git a/tests/test_adversarial_loss.py b/tests/losses/test_adversarial_loss.py similarity index 100% rename from tests/test_adversarial_loss.py rename to tests/losses/test_adversarial_loss.py diff --git a/tests/test_barlow_twins_loss.py b/tests/losses/test_barlow_twins_loss.py similarity index 100% rename from tests/test_barlow_twins_loss.py rename to tests/losses/test_barlow_twins_loss.py diff --git a/tests/test_cldice_loss.py b/tests/losses/test_cldice_loss.py similarity index 100% rename from tests/test_cldice_loss.py rename to tests/losses/test_cldice_loss.py diff --git a/tests/test_contrastive_loss.py b/tests/losses/test_contrastive_loss.py similarity index 100% rename from tests/test_contrastive_loss.py rename to tests/losses/test_contrastive_loss.py diff --git a/tests/test_dice_ce_loss.py b/tests/losses/test_dice_ce_loss.py similarity index 100% rename from tests/test_dice_ce_loss.py rename to tests/losses/test_dice_ce_loss.py diff --git a/tests/test_dice_focal_loss.py b/tests/losses/test_dice_focal_loss.py similarity index 99% rename from tests/test_dice_focal_loss.py rename to tests/losses/test_dice_focal_loss.py index f769aac69f..98ea475ded 100644 --- a/tests/test_dice_focal_loss.py +++ b/tests/losses/test_dice_focal_loss.py @@ -18,11 +18,10 @@ from parameterized import parameterized from monai.losses import DiceFocalLoss, DiceLoss, FocalLoss -from tests.utils import test_script_save +from tests.test_utils import test_script_save class TestDiceFocalLoss(unittest.TestCase): - def test_result_onehot_target_include_bg(self): size = [3, 3, 5, 5] label = torch.randint(low=0, high=2, size=size) diff --git a/tests/test_dice_loss.py b/tests/losses/test_dice_loss.py similarity index 99% rename from tests/test_dice_loss.py rename to tests/losses/test_dice_loss.py index cea6ccf113..66c038783a 100644 --- a/tests/test_dice_loss.py +++ b/tests/losses/test_dice_loss.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.losses import DiceLoss -from tests.utils import test_script_save +from tests.test_utils import test_script_save TEST_CASES = [ [ # shape: (1, 1, 2, 2), (1, 1, 2, 2) @@ -184,7 +184,6 @@ class TestDiceLoss(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_shape(self, input_param, input_data, expected_val): result = DiceLoss(**input_param).forward(**input_data) diff --git a/tests/test_ds_loss.py b/tests/losses/test_ds_loss.py similarity index 98% rename from tests/test_ds_loss.py rename to tests/losses/test_ds_loss.py index daa4ed1e5e..6b91dff17a 100644 --- a/tests/test_ds_loss.py +++ b/tests/losses/test_ds_loss.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.losses import DeepSupervisionLoss, DiceCELoss, DiceFocalLoss, DiceLoss -from tests.utils import SkipIfBeforePyTorchVersion, test_script_save +from tests.test_utils import SkipIfBeforePyTorchVersion, test_script_save TEST_CASES_DICECE = [ [ @@ -135,7 +135,6 @@ class TestDSLossDiceCE(unittest.TestCase): - @parameterized.expand(TEST_CASES_DICECE) def test_result(self, input_param, input_param2, input_data, expected_val): diceceloss = DeepSupervisionLoss(DiceCELoss(**input_param), **input_param2) @@ -161,7 +160,6 @@ def test_script(self): @SkipIfBeforePyTorchVersion((1, 11)) class TestDSLossDiceCE2(unittest.TestCase): - @parameterized.expand(TEST_CASES_DICECE2) def test_result(self, input_param, input_param2, input_data, expected_val): diceceloss = DeepSupervisionLoss(DiceCELoss(**input_param), **input_param2) @@ -171,7 +169,6 @@ def test_result(self, input_param, input_param2, input_data, expected_val): @SkipIfBeforePyTorchVersion((1, 11)) class TestDSLossDice(unittest.TestCase): - @parameterized.expand(TEST_CASES_DICE) def test_result(self, input_param, input_data, expected_val): loss = DeepSupervisionLoss(DiceLoss(**input_param)) @@ -181,7 +178,6 @@ def test_result(self, input_param, input_data, expected_val): @SkipIfBeforePyTorchVersion((1, 11)) class TestDSLossDiceFocal(unittest.TestCase): - @parameterized.expand(TEST_CASES_DICEFOCAL) def test_result(self, input_param, input_data, expected_val): loss = DeepSupervisionLoss(DiceFocalLoss(**input_param)) diff --git a/tests/test_focal_loss.py b/tests/losses/test_focal_loss.py similarity index 99% rename from tests/test_focal_loss.py rename to tests/losses/test_focal_loss.py index 0bb8a078ae..e7f447d90e 100644 --- a/tests/test_focal_loss.py +++ b/tests/losses/test_focal_loss.py @@ -21,7 +21,7 @@ from monai.losses import FocalLoss from monai.networks import one_hot -from tests.utils import test_script_save +from tests.test_utils import test_script_save TEST_CASES = [] for device in ["cpu", "cuda"] if torch.cuda.is_available() else ["cpu"]: @@ -79,7 +79,6 @@ class TestFocalLoss(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_result(self, input_param, input_data, expected_val): focal_loss = FocalLoss(**input_param) diff --git a/tests/test_generalized_dice_focal_loss.py b/tests/losses/test_generalized_dice_focal_loss.py similarity index 98% rename from tests/test_generalized_dice_focal_loss.py rename to tests/losses/test_generalized_dice_focal_loss.py index 65252611ca..2af4aa68db 100644 --- a/tests/test_generalized_dice_focal_loss.py +++ b/tests/losses/test_generalized_dice_focal_loss.py @@ -17,11 +17,10 @@ import torch from monai.losses import FocalLoss, GeneralizedDiceFocalLoss, GeneralizedDiceLoss -from tests.utils import test_script_save +from tests.test_utils import test_script_save class TestGeneralizedDiceFocalLoss(unittest.TestCase): - def test_result_onehot_target_include_bg(self): size = [3, 3, 5, 5] label = torch.randint(low=0, high=2, size=size) diff --git a/tests/test_generalized_dice_loss.py b/tests/losses/test_generalized_dice_loss.py similarity index 99% rename from tests/test_generalized_dice_loss.py rename to tests/losses/test_generalized_dice_loss.py index 9706c2e746..8549e87482 100644 --- a/tests/test_generalized_dice_loss.py +++ b/tests/losses/test_generalized_dice_loss.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.losses import GeneralizedDiceLoss -from tests.utils import test_script_save +from tests.test_utils import test_script_save TEST_CASES = [ [ # shape: (1, 1, 2, 2), (1, 1, 2, 2) @@ -158,7 +158,6 @@ class TestGeneralizedDiceLoss(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_shape(self, input_param, input_data, expected_val): result = GeneralizedDiceLoss(**input_param).forward(**input_data) diff --git a/tests/test_generalized_wasserstein_dice_loss.py b/tests/losses/test_generalized_wasserstein_dice_loss.py similarity index 99% rename from tests/test_generalized_wasserstein_dice_loss.py rename to tests/losses/test_generalized_wasserstein_dice_loss.py index 6b9d57e831..6868c04775 100644 --- a/tests/test_generalized_wasserstein_dice_loss.py +++ b/tests/losses/test_generalized_wasserstein_dice_loss.py @@ -20,11 +20,10 @@ import torch.optim as optim from monai.losses import GeneralizedWassersteinDiceLoss -from tests.utils import test_script_save +from tests.test_utils import test_script_save class TestGeneralizedWassersteinDiceLoss(unittest.TestCase): - def test_bin_seg_2d(self): target = torch.tensor([[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]]) @@ -161,7 +160,6 @@ def test_convergence(self): # define a model with one layer class OnelayerNet(nn.Module): - def __init__(self): super().__init__() self.layer = nn.Linear(num_voxels, num_voxels * num_classes) diff --git a/tests/test_giou_loss.py b/tests/losses/test_giou_loss.py similarity index 100% rename from tests/test_giou_loss.py rename to tests/losses/test_giou_loss.py diff --git a/tests/test_hausdorff_loss.py b/tests/losses/test_hausdorff_loss.py similarity index 100% rename from tests/test_hausdorff_loss.py rename to tests/losses/test_hausdorff_loss.py diff --git a/tests/test_masked_dice_loss.py b/tests/losses/test_masked_dice_loss.py similarity index 100% rename from tests/test_masked_dice_loss.py rename to tests/losses/test_masked_dice_loss.py diff --git a/tests/test_masked_loss.py b/tests/losses/test_masked_loss.py similarity index 98% rename from tests/test_masked_loss.py rename to tests/losses/test_masked_loss.py index 3c04ffadcb..e9128a705c 100644 --- a/tests/test_masked_loss.py +++ b/tests/losses/test_masked_loss.py @@ -19,7 +19,7 @@ from monai.losses.dice import DiceFocalLoss, DiceLoss from monai.losses.spatial_mask import MaskedLoss from monai.utils import set_determinism -from tests.utils import test_script_save +from tests.test_utils import test_script_save device = "cuda" if torch.cuda.is_available() else "cpu" @@ -40,7 +40,6 @@ class TestMaskedLoss(unittest.TestCase): - def setUp(self): set_determinism(0) diff --git a/tests/test_multi_scale.py b/tests/losses/test_multi_scale.py similarity index 98% rename from tests/test_multi_scale.py rename to tests/losses/test_multi_scale.py index 0b49087216..348a9f9913 100644 --- a/tests/test_multi_scale.py +++ b/tests/losses/test_multi_scale.py @@ -18,7 +18,7 @@ from monai.losses import DiceLoss from monai.losses.multi_scale import MultiScaleLoss -from tests.utils import test_script_save +from tests.test_utils import test_script_save dice_loss = DiceLoss(include_background=True, sigmoid=True, smooth_nr=1e-5, smooth_dr=1e-5) device = "cuda" if torch.cuda.is_available() else "cpu" @@ -52,7 +52,6 @@ class TestMultiScale(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_shape(self, input_param, input_data, expected_val): result = MultiScaleLoss(**input_param).forward(**input_data) diff --git a/tests/test_nacl_loss.py b/tests/losses/test_nacl_loss.py similarity index 100% rename from tests/test_nacl_loss.py rename to tests/losses/test_nacl_loss.py diff --git a/tests/test_perceptual_loss.py b/tests/losses/test_perceptual_loss.py similarity index 97% rename from tests/test_perceptual_loss.py rename to tests/losses/test_perceptual_loss.py index b8aa2e5982..2d11d41bee 100644 --- a/tests/test_perceptual_loss.py +++ b/tests/losses/test_perceptual_loss.py @@ -18,7 +18,7 @@ from monai.losses import PerceptualLoss from monai.utils import optional_import -from tests.utils import SkipIfBeforePyTorchVersion, assert_allclose, skip_if_downloading_fails, skip_if_quick +from tests.test_utils import SkipIfBeforePyTorchVersion, assert_allclose, skip_if_downloading_fails, skip_if_quick _, has_torchvision = optional_import("torchvision") TEST_CASES = [ @@ -77,7 +77,6 @@ @unittest.skipUnless(has_torchvision, "Requires torchvision") @skip_if_quick class TestPerceptualLoss(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_shape(self, input_param, input_shape, target_shape): with skip_if_downloading_fails(): diff --git a/tests/test_spectral_loss.py b/tests/losses/test_spectral_loss.py similarity index 98% rename from tests/test_spectral_loss.py rename to tests/losses/test_spectral_loss.py index f62ae9030b..8a4988a30d 100644 --- a/tests/test_spectral_loss.py +++ b/tests/losses/test_spectral_loss.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.losses import JukeboxLoss -from tests.utils import test_script_save +from tests.test_utils import test_script_save TEST_CASES = [ [ @@ -63,7 +63,6 @@ class TestJukeboxLoss(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_results(self, input_param, input_data, expected_val): results = JukeboxLoss(**input_param).forward(**input_data) diff --git a/tests/test_ssim_loss.py b/tests/losses/test_ssim_loss.py similarity index 100% rename from tests/test_ssim_loss.py rename to tests/losses/test_ssim_loss.py diff --git a/tests/test_sure_loss.py b/tests/losses/test_sure_loss.py similarity index 100% rename from tests/test_sure_loss.py rename to tests/losses/test_sure_loss.py diff --git a/tests/test_tversky_loss.py b/tests/losses/test_tversky_loss.py similarity index 99% rename from tests/test_tversky_loss.py rename to tests/losses/test_tversky_loss.py index 73a841a55d..32303434ca 100644 --- a/tests/test_tversky_loss.py +++ b/tests/losses/test_tversky_loss.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.losses import TverskyLoss -from tests.utils import test_script_save +from tests.test_utils import test_script_save TEST_CASES = [ [ # shape: (1, 1, 2, 2), (1, 1, 2, 2) @@ -164,7 +164,6 @@ class TestTverskyLoss(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_shape(self, input_param, input_data, expected_val): result = TverskyLoss(**input_param).forward(**input_data) diff --git a/tests/test_unified_focal_loss.py b/tests/losses/test_unified_focal_loss.py similarity index 100% rename from tests/test_unified_focal_loss.py rename to tests/losses/test_unified_focal_loss.py diff --git a/tests/metrics/__init__.py b/tests/metrics/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/metrics/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_compute_confusion_matrix.py b/tests/metrics/test_compute_confusion_matrix.py similarity index 99% rename from tests/test_compute_confusion_matrix.py rename to tests/metrics/test_compute_confusion_matrix.py index 248f16a7fe..2486049d79 100644 --- a/tests/test_compute_confusion_matrix.py +++ b/tests/metrics/test_compute_confusion_matrix.py @@ -24,7 +24,7 @@ do_metric_reduction, get_confusion_matrix, ) -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose _device = "cuda:0" if torch.cuda.is_available() else "cpu" # input data @@ -220,7 +220,6 @@ class TestConfusionMatrix(unittest.TestCase): - @parameterized.expand([TEST_CASE_CONFUSION_MATRIX]) def test_value(self, input_data, expected_value): # include or ignore background diff --git a/tests/test_compute_f_beta.py b/tests/metrics/test_compute_f_beta.py similarity index 98% rename from tests/test_compute_f_beta.py rename to tests/metrics/test_compute_f_beta.py index be2a7fc176..21a4e3c22c 100644 --- a/tests/test_compute_f_beta.py +++ b/tests/metrics/test_compute_f_beta.py @@ -18,13 +18,12 @@ from parameterized import parameterized from monai.metrics import FBetaScore -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose _device = "cuda:0" if torch.cuda.is_available() else "cpu" class TestFBetaScore(unittest.TestCase): - def test_expecting_success_and_device(self): metric = FBetaScore() y_pred = torch.tensor([[1, 1, 1], [1, 1, 1], [1, 1, 1]], device=_device) diff --git a/tests/test_compute_fid_metric.py b/tests/metrics/test_compute_fid_metric.py similarity index 100% rename from tests/test_compute_fid_metric.py rename to tests/metrics/test_compute_fid_metric.py diff --git a/tests/test_compute_froc.py b/tests/metrics/test_compute_froc.py similarity index 100% rename from tests/test_compute_froc.py rename to tests/metrics/test_compute_froc.py diff --git a/tests/test_compute_generalized_dice.py b/tests/metrics/test_compute_generalized_dice.py similarity index 100% rename from tests/test_compute_generalized_dice.py rename to tests/metrics/test_compute_generalized_dice.py diff --git a/tests/test_compute_meandice.py b/tests/metrics/test_compute_meandice.py similarity index 100% rename from tests/test_compute_meandice.py rename to tests/metrics/test_compute_meandice.py diff --git a/tests/test_compute_meaniou.py b/tests/metrics/test_compute_meaniou.py similarity index 100% rename from tests/test_compute_meaniou.py rename to tests/metrics/test_compute_meaniou.py diff --git a/tests/test_compute_mmd_metric.py b/tests/metrics/test_compute_mmd_metric.py similarity index 100% rename from tests/test_compute_mmd_metric.py rename to tests/metrics/test_compute_mmd_metric.py diff --git a/tests/test_compute_multiscalessim_metric.py b/tests/metrics/test_compute_multiscalessim_metric.py similarity index 100% rename from tests/test_compute_multiscalessim_metric.py rename to tests/metrics/test_compute_multiscalessim_metric.py diff --git a/tests/test_compute_panoptic_quality.py b/tests/metrics/test_compute_panoptic_quality.py similarity index 98% rename from tests/test_compute_panoptic_quality.py rename to tests/metrics/test_compute_panoptic_quality.py index a916ea32b2..2c0946a822 100644 --- a/tests/test_compute_panoptic_quality.py +++ b/tests/metrics/test_compute_panoptic_quality.py @@ -12,14 +12,13 @@ from __future__ import annotations import unittest -from typing import List import numpy as np import torch from parameterized import parameterized from monai.metrics import PanopticQualityMetric, compute_panoptic_quality -from tests.utils import SkipIfNoModule +from tests.test_utils import SkipIfNoModule _device = "cuda:0" if torch.cuda.is_available() else "cpu" @@ -92,7 +91,6 @@ @SkipIfNoModule("scipy.optimize") class TestPanopticQualityMetric(unittest.TestCase): - @parameterized.expand([TEST_FUNC_CASE_1, TEST_FUNC_CASE_2, TEST_FUNC_CASE_3, TEST_FUNC_CASE_4]) def test_value(self, input_params, expected_value): result = compute_panoptic_quality(**input_params) @@ -104,7 +102,7 @@ def test_value_class(self, input_params, y_pred, y_gt, expected_value): metric = PanopticQualityMetric(**input_params) metric(y_pred, y_gt) outputs = metric.aggregate() - if isinstance(outputs, List): + if isinstance(outputs, list): for output, value in zip(outputs, expected_value): np.testing.assert_allclose(output.cpu().numpy(), np.asarray(value), atol=1e-4) else: diff --git a/tests/test_compute_regression_metrics.py b/tests/metrics/test_compute_regression_metrics.py similarity index 100% rename from tests/test_compute_regression_metrics.py rename to tests/metrics/test_compute_regression_metrics.py diff --git a/tests/test_compute_roc_auc.py b/tests/metrics/test_compute_roc_auc.py similarity index 100% rename from tests/test_compute_roc_auc.py rename to tests/metrics/test_compute_roc_auc.py diff --git a/tests/test_compute_variance.py b/tests/metrics/test_compute_variance.py similarity index 100% rename from tests/test_compute_variance.py rename to tests/metrics/test_compute_variance.py diff --git a/tests/test_cumulative.py b/tests/metrics/test_cumulative.py similarity index 97% rename from tests/test_cumulative.py rename to tests/metrics/test_cumulative.py index d3b6ba094c..bcacee9b22 100644 --- a/tests/test_cumulative.py +++ b/tests/metrics/test_cumulative.py @@ -16,11 +16,10 @@ import torch from monai.metrics import Cumulative -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose class TestCumulative(unittest.TestCase): - def test_single(self): c = Cumulative() c.extend([2, 3]) diff --git a/tests/test_cumulative_average.py b/tests/metrics/test_cumulative_average.py similarity index 100% rename from tests/test_cumulative_average.py rename to tests/metrics/test_cumulative_average.py diff --git a/tests/test_cumulative_average_dist.py b/tests/metrics/test_cumulative_average_dist.py similarity index 95% rename from tests/test_cumulative_average_dist.py rename to tests/metrics/test_cumulative_average_dist.py index 30c01c21ee..53e81b7d86 100644 --- a/tests/test_cumulative_average_dist.py +++ b/tests/metrics/test_cumulative_average_dist.py @@ -18,12 +18,11 @@ import torch.distributed as dist from monai.metrics import CumulativeAverage -from tests.utils import DistCall, DistTestCase, SkipIfBeforePyTorchVersion +from tests.test_utils import DistCall, DistTestCase, SkipIfBeforePyTorchVersion @SkipIfBeforePyTorchVersion((1, 8)) class DistributedCumulativeAverage(DistTestCase): - @DistCall(nnodes=1, nproc_per_node=2) def test_value(self): rank = dist.get_rank() diff --git a/tests/test_hausdorff_distance.py b/tests/metrics/test_hausdorff_distance.py similarity index 100% rename from tests/test_hausdorff_distance.py rename to tests/metrics/test_hausdorff_distance.py diff --git a/tests/test_label_quality_score.py b/tests/metrics/test_label_quality_score.py similarity index 100% rename from tests/test_label_quality_score.py rename to tests/metrics/test_label_quality_score.py diff --git a/tests/test_loss_metric.py b/tests/metrics/test_loss_metric.py similarity index 100% rename from tests/test_loss_metric.py rename to tests/metrics/test_loss_metric.py diff --git a/tests/test_metrics_reloaded.py b/tests/metrics/test_metrics_reloaded.py similarity index 100% rename from tests/test_metrics_reloaded.py rename to tests/metrics/test_metrics_reloaded.py diff --git a/tests/test_ssim_metric.py b/tests/metrics/test_ssim_metric.py similarity index 100% rename from tests/test_ssim_metric.py rename to tests/metrics/test_ssim_metric.py diff --git a/tests/test_surface_dice.py b/tests/metrics/test_surface_dice.py similarity index 98% rename from tests/test_surface_dice.py rename to tests/metrics/test_surface_dice.py index 2ef19a4eea..01f80bd01e 100644 --- a/tests/test_surface_dice.py +++ b/tests/metrics/test_surface_dice.py @@ -18,13 +18,12 @@ import torch.nn.functional as F from monai.metrics.surface_dice import SurfaceDiceMetric, compute_surface_dice -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose _device = "cuda:0" if torch.cuda.is_available() else "cpu" class TestAllSurfaceDiceMetrics(unittest.TestCase): - def test_tolerance_euclidean_distance_with_spacing(self): batch_size = 2 n_class = 2 @@ -384,7 +383,7 @@ def test_not_predicted_not_present(self): np.testing.assert_equal(not_nans, torch.tensor([0], dtype=torch.float)) def test_compute_surface_dice_subvoxel(self): - mask_gt, mask_pred = torch.zeros(1, 1, 128, 128, 128), torch.zeros(1, 1, 128, 128, 128) + mask_gt, mask_pred = (torch.zeros(1, 1, 128, 128, 128), torch.zeros(1, 1, 128, 128, 128)) mask_gt[0, 0, 50, 60, 70] = 1 res = compute_surface_dice( mask_pred, mask_gt, [1.0], include_background=True, spacing=(3, 2, 1), use_subvoxels=True @@ -404,7 +403,7 @@ def test_compute_surface_dice_subvoxel(self): assert_allclose(res, 0.5, type_test=False) d = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") - mask_gt, mask_pred = torch.zeros(1, 1, 100, 100, 100, device=d), torch.zeros(1, 1, 100, 100, 100, device=d) + mask_gt, mask_pred = (torch.zeros(1, 1, 100, 100, 100, device=d), torch.zeros(1, 1, 100, 100, 100, device=d)) mask_gt[0, 0, 0:50, :, :] = 1 mask_pred[0, 0, 0:51, :, :] = 1 res = compute_surface_dice( diff --git a/tests/test_surface_distance.py b/tests/metrics/test_surface_distance.py similarity index 100% rename from tests/test_surface_distance.py rename to tests/metrics/test_surface_distance.py diff --git a/tests/min_tests.py b/tests/min_tests.py index f39d3f9843..1fc3da4a19 100644 --- a/tests/min_tests.py +++ b/tests/min_tests.py @@ -11,10 +11,10 @@ from __future__ import annotations -import glob import os import sys import unittest +from pathlib import Path def run_testsuit(): @@ -216,17 +216,20 @@ def run_testsuit(): ] assert sorted(exclude_cases) == sorted(set(exclude_cases)), f"Duplicated items in {exclude_cases}" - files = glob.glob(os.path.join(os.path.dirname(__file__), "test_*.py")) + files = [f.relative_to(Path(__file__).parent.parent) for f in Path(__file__).parent.rglob("test_*.py")] + files = [str(f).replace(os.sep, ".").replace(".py", "") for f in files] cases = [] - for case in files: - test_module = os.path.basename(case)[:-3] - if test_module in exclude_cases: - exclude_cases.remove(test_module) - print(f"skipping tests.{test_module}.") + for test_module in files: + test_case = test_module.split(".")[-1] + if test_case in exclude_cases: + exclude_cases.remove(test_case) + print(f"skipping {test_module}") else: - cases.append(f"tests.{test_module}") - assert not exclude_cases, f"items in exclude_cases not used: {exclude_cases}." + print(f"adding {test_module}") + cases.append(test_module) + exclude_cases = [str(list(Path(__file__).parent.rglob(f"*{et}*"))[0]) for et in exclude_cases] + assert not exclude_cases, f"items in exclude_cases not used: {' '.join(exclude_cases)}" test_suite = unittest.TestLoader().loadTestsFromNames(cases) return test_suite diff --git a/tests/networks/__init__.py b/tests/networks/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/networks/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/networks/blocks/__init__.py b/tests/networks/blocks/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/networks/blocks/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/networks/blocks/dints_block/__init__.py b/tests/networks/blocks/dints_block/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/networks/blocks/dints_block/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_acn_block.py b/tests/networks/blocks/dints_block/test_acn_block.py similarity index 100% rename from tests/test_acn_block.py rename to tests/networks/blocks/dints_block/test_acn_block.py diff --git a/tests/test_factorized_increase.py b/tests/networks/blocks/dints_block/test_factorized_increase.py similarity index 100% rename from tests/test_factorized_increase.py rename to tests/networks/blocks/dints_block/test_factorized_increase.py diff --git a/tests/test_factorized_reduce.py b/tests/networks/blocks/dints_block/test_factorized_reduce.py similarity index 100% rename from tests/test_factorized_reduce.py rename to tests/networks/blocks/dints_block/test_factorized_reduce.py diff --git a/tests/test_p3d_block.py b/tests/networks/blocks/dints_block/test_p3d_block.py similarity index 100% rename from tests/test_p3d_block.py rename to tests/networks/blocks/dints_block/test_p3d_block.py diff --git a/tests/test_adn.py b/tests/networks/blocks/test_adn.py similarity index 97% rename from tests/test_adn.py rename to tests/networks/blocks/test_adn.py index 327bf7b20c..d2839957fd 100644 --- a/tests/test_adn.py +++ b/tests/networks/blocks/test_adn.py @@ -16,7 +16,7 @@ from parameterized import parameterized from monai.networks.blocks import ADN -from tests.utils import TorchImageTestCase2D, TorchImageTestCase3D +from tests.test_utils import TorchImageTestCase2D, TorchImageTestCase3D TEST_CASES_2D = [ [{"act": None}], @@ -59,7 +59,6 @@ class TestADN2D(TorchImageTestCase2D): - @parameterized.expand(TEST_CASES_2D) def test_adn_2d(self, args): adn = ADN(**args) @@ -74,7 +73,6 @@ def test_no_input(self): class TestADN3D(TorchImageTestCase3D): - @parameterized.expand(TEST_CASES_3D) def test_adn_3d(self, args): adn = ADN(**args) diff --git a/tests/test_convolutions.py b/tests/networks/blocks/test_convolutions.py similarity index 98% rename from tests/test_convolutions.py rename to tests/networks/blocks/test_convolutions.py index 77bc12770f..f882f133e9 100644 --- a/tests/test_convolutions.py +++ b/tests/networks/blocks/test_convolutions.py @@ -14,11 +14,10 @@ import unittest from monai.networks.blocks import Convolution, ResidualUnit -from tests.utils import TorchImageTestCase2D, TorchImageTestCase3D +from tests.test_utils import TorchImageTestCase2D, TorchImageTestCase3D class TestConvolution2D(TorchImageTestCase2D): - def test_conv1(self): conv = Convolution(2, self.input_channels, self.output_channels) out = conv(self.imt) @@ -70,7 +69,6 @@ def test_transpose2(self): class TestConvolution3D(TorchImageTestCase3D): - def test_conv1(self): conv = Convolution(3, self.input_channels, self.output_channels, dropout=0.1, adn_ordering="DAN") out = conv(self.imt) @@ -128,7 +126,6 @@ def test_transpose2(self): class TestResidualUnit2D(TorchImageTestCase2D): - def test_conv_only1(self): conv = ResidualUnit(2, 1, self.output_channels) out = conv(self.imt) diff --git a/tests/test_crf_cpu.py b/tests/networks/blocks/test_crf_cpu.py similarity index 99% rename from tests/test_crf_cpu.py rename to tests/networks/blocks/test_crf_cpu.py index a7ae0ff2df..2001700e5d 100644 --- a/tests/test_crf_cpu.py +++ b/tests/networks/blocks/test_crf_cpu.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.networks.blocks import CRF -from tests.utils import skip_if_no_cpp_extension +from tests.test_utils import skip_if_no_cpp_extension TEST_CASES = [ [ @@ -495,7 +495,6 @@ @skip_if_no_cpp_extension class CRFTestCaseCpu(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test(self, test_case_description, params, input, features, expected): # Create input tensors diff --git a/tests/test_crf_cuda.py b/tests/networks/blocks/test_crf_cuda.py similarity index 99% rename from tests/test_crf_cuda.py rename to tests/networks/blocks/test_crf_cuda.py index d5329aab15..d1fc9472d2 100644 --- a/tests/test_crf_cuda.py +++ b/tests/networks/blocks/test_crf_cuda.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.networks.blocks import CRF -from tests.utils import skip_if_no_cpp_extension, skip_if_no_cuda +from tests.test_utils import skip_if_no_cpp_extension, skip_if_no_cuda TEST_CASES = [ [ @@ -496,7 +496,6 @@ @skip_if_no_cpp_extension @skip_if_no_cuda class CRFTestCaseCuda(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test(self, test_case_description, params, input, features, expected): # Create input tensors diff --git a/tests/test_crossattention.py b/tests/networks/blocks/test_crossattention.py similarity index 99% rename from tests/test_crossattention.py rename to tests/networks/blocks/test_crossattention.py index e034e42290..32cd655d4c 100644 --- a/tests/test_crossattention.py +++ b/tests/networks/blocks/test_crossattention.py @@ -22,7 +22,7 @@ from monai.networks.blocks.crossattention import CrossAttentionBlock from monai.networks.layers.factories import RelPosEmbedding from monai.utils import optional_import -from tests.utils import SkipIfBeforePyTorchVersion, assert_allclose +from tests.test_utils import SkipIfBeforePyTorchVersion, assert_allclose einops, has_einops = optional_import("einops") @@ -49,7 +49,6 @@ class TestResBlock(unittest.TestCase): - @parameterized.expand(TEST_CASE_CABLOCK) @skipUnless(has_einops, "Requires einops") @SkipIfBeforePyTorchVersion((2, 0)) diff --git a/tests/test_denseblock.py b/tests/networks/blocks/test_denseblock.py similarity index 98% rename from tests/test_denseblock.py rename to tests/networks/blocks/test_denseblock.py index b741582422..884df1d511 100644 --- a/tests/test_denseblock.py +++ b/tests/networks/blocks/test_denseblock.py @@ -16,11 +16,10 @@ import torch.nn as nn from monai.networks.blocks import ConvDenseBlock, DenseBlock -from tests.utils import TorchImageTestCase2D, TorchImageTestCase3D +from tests.test_utils import TorchImageTestCase2D, TorchImageTestCase3D class TestDenseBlock2D(TorchImageTestCase2D): - def test_block_empty(self): block = DenseBlock([]) out = block(self.imt) @@ -37,7 +36,6 @@ def test_block_conv(self): class TestDenseBlock3D(TorchImageTestCase3D): - def test_block_conv(self): conv1 = nn.Conv3d(self.input_channels, self.output_channels, 3, padding=1) conv2 = nn.Conv3d(self.input_channels + self.output_channels, self.input_channels, 3, padding=1) @@ -54,7 +52,6 @@ def test_block_conv(self): class TestConvDenseBlock2D(TorchImageTestCase2D): - def test_block_empty(self): conv = ConvDenseBlock(spatial_dims=2, in_channels=self.input_channels, channels=[]) out = conv(self.imt) @@ -82,7 +79,6 @@ def test_block2(self): class TestConvDenseBlock3D(TorchImageTestCase3D): - def test_block_empty(self): conv = ConvDenseBlock(spatial_dims=3, in_channels=self.input_channels, channels=[]) out = conv(self.imt) diff --git a/tests/test_dynunet_block.py b/tests/networks/blocks/test_dynunet_block.py similarity index 99% rename from tests/test_dynunet_block.py rename to tests/networks/blocks/test_dynunet_block.py index 4d9e06670b..d469c6f3e9 100644 --- a/tests/test_dynunet_block.py +++ b/tests/networks/blocks/test_dynunet_block.py @@ -18,7 +18,7 @@ from monai.networks import eval_mode from monai.networks.blocks.dynunet_block import UnetBasicBlock, UnetResBlock, UnetUpBlock, get_padding -from tests.utils import test_script_save +from tests.test_utils import test_script_save TEST_CASE_RES_BASIC_BLOCK = [] for spatial_dims in range(2, 4): @@ -73,7 +73,6 @@ class TestResBasicBlock(unittest.TestCase): - @parameterized.expand(TEST_CASE_RES_BASIC_BLOCK) def test_shape(self, input_param, input_shape, expected_shape): for net in [UnetResBlock(**input_param), UnetBasicBlock(**input_param)]: @@ -97,7 +96,6 @@ def test_script(self): class TestUpBlock(unittest.TestCase): - @parameterized.expand(TEST_UP_BLOCK) def test_shape(self, input_param, input_shape, expected_shape, skip_shape): net = UnetUpBlock(**input_param) diff --git a/tests/test_fpn_block.py b/tests/networks/blocks/test_fpn_block.py similarity index 97% rename from tests/test_fpn_block.py rename to tests/networks/blocks/test_fpn_block.py index 969800e80a..6980889433 100644 --- a/tests/test_fpn_block.py +++ b/tests/networks/blocks/test_fpn_block.py @@ -21,7 +21,7 @@ from monai.networks.blocks.feature_pyramid_network import FeaturePyramidNetwork from monai.networks.nets.resnet import resnet50 from monai.utils import optional_import -from tests.utils import SkipIfBeforePyTorchVersion, test_script_save +from tests.test_utils import SkipIfBeforePyTorchVersion, test_script_save _, has_torchvision = optional_import("torchvision") @@ -44,7 +44,6 @@ class TestFPNBlock(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_fpn_block(self, input_param, input_shape, expected_shape): net = FeaturePyramidNetwork(**input_param) @@ -68,7 +67,6 @@ def test_script(self, input_param, input_shape, expected_shape): @unittest.skipUnless(has_torchvision, "Requires torchvision") class TestFPN(unittest.TestCase): - @parameterized.expand(TEST_CASES2) def test_fpn(self, input_param, input_shape, expected_shape): net = _resnet_fpn_extractor(backbone=resnet50(), spatial_dims=input_param["spatial_dims"], returned_layers=[1]) diff --git a/tests/test_localnet_block.py b/tests/networks/blocks/test_localnet_block.py similarity index 100% rename from tests/test_localnet_block.py rename to tests/networks/blocks/test_localnet_block.py diff --git a/tests/test_mlp.py b/tests/networks/blocks/test_mlp.py similarity index 100% rename from tests/test_mlp.py rename to tests/networks/blocks/test_mlp.py diff --git a/tests/test_patchembedding.py b/tests/networks/blocks/test_patchembedding.py similarity index 99% rename from tests/test_patchembedding.py rename to tests/networks/blocks/test_patchembedding.py index 71ac767966..95ca95b36a 100644 --- a/tests/test_patchembedding.py +++ b/tests/networks/blocks/test_patchembedding.py @@ -21,7 +21,7 @@ from monai.networks import eval_mode from monai.networks.blocks.patchembedding import PatchEmbed, PatchEmbeddingBlock from monai.utils import optional_import -from tests.utils import SkipIfBeforePyTorchVersion +from tests.test_utils import SkipIfBeforePyTorchVersion einops, has_einops = optional_import("einops") @@ -77,7 +77,6 @@ @SkipIfBeforePyTorchVersion((1, 11, 1)) class TestPatchEmbeddingBlock(unittest.TestCase): - def setUp(self): self.threads = torch.get_num_threads() torch.set_num_threads(4) @@ -189,7 +188,6 @@ def test_ill_arg(self): class TestPatchEmbed(unittest.TestCase): - def setUp(self): self.threads = torch.get_num_threads() torch.set_num_threads(4) diff --git a/tests/test_regunet_block.py b/tests/networks/blocks/test_regunet_block.py similarity index 100% rename from tests/test_regunet_block.py rename to tests/networks/blocks/test_regunet_block.py diff --git a/tests/test_se_block.py b/tests/networks/blocks/test_se_block.py similarity index 98% rename from tests/test_se_block.py rename to tests/networks/blocks/test_se_block.py index ca60643635..d799cd095c 100644 --- a/tests/test_se_block.py +++ b/tests/networks/blocks/test_se_block.py @@ -19,7 +19,7 @@ from monai.networks import eval_mode from monai.networks.blocks import SEBlock from monai.networks.layers.factories import Act, Norm -from tests.utils import test_script_save +from tests.test_utils import test_script_save device = "cuda" if torch.cuda.is_available() else "cpu" @@ -63,7 +63,6 @@ class TestSEBlockLayer(unittest.TestCase): - @parameterized.expand(TEST_CASES + TEST_CASES_3D) def test_shape(self, input_param, input_shape, expected_shape): net = SEBlock(**input_param).to(device) diff --git a/tests/test_se_blocks.py b/tests/networks/blocks/test_se_blocks.py similarity index 98% rename from tests/test_se_blocks.py rename to tests/networks/blocks/test_se_blocks.py index c1e72749cc..b40f3a0955 100644 --- a/tests/test_se_blocks.py +++ b/tests/networks/blocks/test_se_blocks.py @@ -18,7 +18,7 @@ from monai.networks import eval_mode from monai.networks.blocks import ChannelSELayer, ResidualSELayer -from tests.utils import test_script_save +from tests.test_utils import test_script_save TEST_CASES = [ # single channel 3D, batch 16 [{"spatial_dims": 2, "in_channels": 4, "r": 3}, (7, 4, 64, 48), (7, 4, 64, 48)], # 4-channel 2D, batch 7 @@ -41,7 +41,6 @@ class TestChannelSELayer(unittest.TestCase): - @parameterized.expand(TEST_CASES + TEST_CASES_3D) def test_shape(self, input_param, input_shape, expected_shape): net = ChannelSELayer(**input_param) @@ -61,7 +60,6 @@ def test_ill_arg(self): class TestResidualSELayer(unittest.TestCase): - @parameterized.expand(TEST_CASES[:1]) def test_shape(self, input_param, input_shape, expected_shape): net = ResidualSELayer(**input_param) diff --git a/tests/test_segresnet_block.py b/tests/networks/blocks/test_segresnet_block.py similarity index 100% rename from tests/test_segresnet_block.py rename to tests/networks/blocks/test_segresnet_block.py diff --git a/tests/test_selfattention.py b/tests/networks/blocks/test_selfattention.py similarity index 99% rename from tests/test_selfattention.py rename to tests/networks/blocks/test_selfattention.py index 338f1bf840..494f64cad8 100644 --- a/tests/test_selfattention.py +++ b/tests/networks/blocks/test_selfattention.py @@ -22,7 +22,7 @@ from monai.networks.blocks.selfattention import SABlock from monai.networks.layers.factories import RelPosEmbedding from monai.utils import optional_import -from tests.utils import SkipIfBeforePyTorchVersion, assert_allclose, test_script_save +from tests.test_utils import SkipIfBeforePyTorchVersion, assert_allclose, test_script_save einops, has_einops = optional_import("einops") @@ -52,7 +52,6 @@ class TestResBlock(unittest.TestCase): - @parameterized.expand(TEST_CASE_SABLOCK) @skipUnless(has_einops, "Requires einops") @SkipIfBeforePyTorchVersion((2, 0)) @@ -163,7 +162,6 @@ def test_access_attn_matrix(self): assert matrix_acess_blk.att_mat.shape == (input_shape[0], input_shape[0], input_shape[1], input_shape[1]) def test_number_of_parameters(self): - def count_sablock_params(*args, **kwargs): """Count the number of parameters in a SABlock.""" sablock = SABlock(*args, **kwargs) diff --git a/tests/test_simple_aspp.py b/tests/networks/blocks/test_simple_aspp.py similarity index 100% rename from tests/test_simple_aspp.py rename to tests/networks/blocks/test_simple_aspp.py diff --git a/tests/test_spatialattention.py b/tests/networks/blocks/test_spatialattention.py similarity index 100% rename from tests/test_spatialattention.py rename to tests/networks/blocks/test_spatialattention.py diff --git a/tests/test_subpixel_upsample.py b/tests/networks/blocks/test_subpixel_upsample.py similarity index 97% rename from tests/test_subpixel_upsample.py rename to tests/networks/blocks/test_subpixel_upsample.py index fe9fb1c328..9300ff2b43 100644 --- a/tests/test_subpixel_upsample.py +++ b/tests/networks/blocks/test_subpixel_upsample.py @@ -20,7 +20,7 @@ from monai.networks import eval_mode from monai.networks.blocks import SubpixelUpsample from monai.networks.layers.factories import Conv -from tests.utils import SkipIfBeforePyTorchVersion, test_script_save +from tests.test_utils import SkipIfBeforePyTorchVersion, test_script_save TEST_CASE_SUBPIXEL = [] for inch in range(1, 5): @@ -68,7 +68,6 @@ class TestSUBPIXEL(unittest.TestCase): - @parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self, input_param, input_shape, expected_shape): net = SubpixelUpsample(**input_param) diff --git a/tests/test_text_encoding.py b/tests/networks/blocks/test_text_encoding.py similarity index 97% rename from tests/test_text_encoding.py rename to tests/networks/blocks/test_text_encoding.py index 902f7a4b1d..f9112d9814 100644 --- a/tests/test_text_encoding.py +++ b/tests/networks/blocks/test_text_encoding.py @@ -14,11 +14,10 @@ import unittest from monai.networks.blocks.text_embedding import TextEncoder -from tests.utils import skip_if_downloading_fails +from tests.test_utils import skip_if_downloading_fails class TestTextEncoder(unittest.TestCase): - def test_test_encoding_shape(self): with skip_if_downloading_fails(): # test 2D encoder diff --git a/tests/test_transformerblock.py b/tests/networks/blocks/test_transformerblock.py similarity index 100% rename from tests/test_transformerblock.py rename to tests/networks/blocks/test_transformerblock.py diff --git a/tests/test_unetr_block.py b/tests/networks/blocks/test_unetr_block.py similarity index 99% rename from tests/test_unetr_block.py rename to tests/networks/blocks/test_unetr_block.py index 9701557ed6..1396a08193 100644 --- a/tests/test_unetr_block.py +++ b/tests/networks/blocks/test_unetr_block.py @@ -19,7 +19,7 @@ from monai.networks import eval_mode from monai.networks.blocks.dynunet_block import get_padding from monai.networks.blocks.unetr_block import UnetrBasicBlock, UnetrPrUpBlock, UnetrUpBlock -from tests.utils import test_script_save +from tests.test_utils import test_script_save TEST_CASE_UNETR_BASIC_BLOCK = [] for spatial_dims in range(1, 4): @@ -102,7 +102,6 @@ class TestResBasicBlock(unittest.TestCase): - @parameterized.expand(TEST_CASE_UNETR_BASIC_BLOCK) def test_shape(self, input_param, input_shape, expected_shape): for net in [UnetrBasicBlock(**input_param)]: @@ -125,7 +124,6 @@ def test_script(self): class TestUpBlock(unittest.TestCase): - @parameterized.expand(TEST_UP_BLOCK) def test_shape(self, input_param, input_shape, expected_shape, skip_shape): net = UnetrUpBlock(**input_param) @@ -142,7 +140,6 @@ def test_script(self): class TestPrUpBlock(unittest.TestCase): - @parameterized.expand(TEST_PRUP_BLOCK) def test_shape(self, input_param, input_shape, expected_shape): net = UnetrPrUpBlock(**input_param) diff --git a/tests/test_upsample_block.py b/tests/networks/blocks/test_upsample_block.py similarity index 100% rename from tests/test_upsample_block.py rename to tests/networks/blocks/test_upsample_block.py diff --git a/tests/networks/blocks/warp/__init__.py b/tests/networks/blocks/warp/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/networks/blocks/warp/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_dvf2ddf.py b/tests/networks/blocks/warp/test_dvf2ddf.py similarity index 100% rename from tests/test_dvf2ddf.py rename to tests/networks/blocks/warp/test_dvf2ddf.py diff --git a/tests/test_warp.py b/tests/networks/blocks/warp/test_warp.py similarity index 98% rename from tests/test_warp.py rename to tests/networks/blocks/warp/test_warp.py index 0e5f2466db..00ec4a3206 100644 --- a/tests/test_warp.py +++ b/tests/networks/blocks/warp/test_warp.py @@ -12,6 +12,7 @@ import os import unittest +from pathlib import Path import numpy as np import torch @@ -22,7 +23,7 @@ from monai.networks.blocks.warp import Warp from monai.transforms import LoadImaged from monai.utils import GridSampleMode, GridSamplePadMode -from tests.utils import ( +from tests.test_utils import ( SkipIfBeforePyTorchVersion, SkipIfNoModule, download_url_or_skip_test, @@ -106,7 +107,6 @@ @skip_if_quick class TestWarp(unittest.TestCase): - def setUp(self): config = testing_data_config("images", "Prostate_T2W_AX_1") download_url_or_skip_test( @@ -157,7 +157,8 @@ def test_grad(self): gradcheck(warp_layer, (input_image, ddf), atol=1e-2, eps=1e-2) -FILE_PATH = os.path.join(os.path.dirname(__file__), "testing_data", "temp_" + "mri.nii") +TESTS_PATH = Path(__file__).parents[3] +FILE_PATH = os.path.join(TESTS_PATH, "testing_data", "temp_" + "mri.nii") def load_img_and_sample_ddf(): diff --git a/tests/networks/layers/__init__.py b/tests/networks/layers/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/networks/layers/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/networks/layers/filtering/__init__.py b/tests/networks/layers/filtering/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/networks/layers/filtering/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_bilateral_approx_cpu.py b/tests/networks/layers/filtering/test_bilateral_approx_cpu.py similarity index 99% rename from tests/test_bilateral_approx_cpu.py rename to tests/networks/layers/filtering/test_bilateral_approx_cpu.py index e8a55e1f76..51d0f56f82 100644 --- a/tests/test_bilateral_approx_cpu.py +++ b/tests/networks/layers/filtering/test_bilateral_approx_cpu.py @@ -19,7 +19,7 @@ from torch.autograd import gradcheck from monai.networks.layers.filtering import BilateralFilter -from tests.utils import skip_if_no_cpp_extension +from tests.test_utils import skip_if_no_cpp_extension TEST_CASES = [ [ @@ -365,7 +365,6 @@ @skip_if_no_cpp_extension class BilateralFilterTestCaseCpuApprox(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_cpu_approx(self, test_case_description, sigmas, input, expected): # Params to determine the implementation to test diff --git a/tests/test_bilateral_approx_cuda.py b/tests/networks/layers/filtering/test_bilateral_approx_cuda.py similarity index 99% rename from tests/test_bilateral_approx_cuda.py rename to tests/networks/layers/filtering/test_bilateral_approx_cuda.py index 4ad15d9646..b98279f28e 100644 --- a/tests/test_bilateral_approx_cuda.py +++ b/tests/networks/layers/filtering/test_bilateral_approx_cuda.py @@ -19,7 +19,7 @@ from torch.autograd import gradcheck from monai.networks.layers.filtering import BilateralFilter -from tests.utils import skip_if_no_cpp_extension, skip_if_no_cuda +from tests.test_utils import skip_if_no_cpp_extension, skip_if_no_cuda TEST_CASES = [ [ @@ -366,7 +366,6 @@ @skip_if_no_cuda @skip_if_no_cpp_extension class BilateralFilterTestCaseCudaApprox(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_cuda_approx(self, test_case_description, sigmas, input, expected): # Skip this test diff --git a/tests/test_bilateral_precise.py b/tests/networks/layers/filtering/test_bilateral_precise.py similarity index 99% rename from tests/test_bilateral_precise.py rename to tests/networks/layers/filtering/test_bilateral_precise.py index e13ede5bfd..505f0a6303 100644 --- a/tests/test_bilateral_precise.py +++ b/tests/networks/layers/filtering/test_bilateral_precise.py @@ -19,7 +19,7 @@ from torch.autograd import gradcheck from monai.networks.layers.filtering import BilateralFilter -from tests.utils import skip_if_no_cpp_extension, skip_if_no_cuda, skip_if_quick +from tests.test_utils import skip_if_no_cpp_extension, skip_if_no_cuda, skip_if_quick TEST_CASES = [ [ @@ -366,7 +366,6 @@ @skip_if_no_cpp_extension @skip_if_quick class BilateralFilterTestCaseCpuPrecise(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_cpu_precise(self, test_case_description, sigmas, input, expected): # Params to determine the implementation to test @@ -400,7 +399,6 @@ def test_cpu_precise_backwards(self, test_case_description, sigmas, input, expec @skip_if_no_cuda @skip_if_no_cpp_extension class BilateralFilterTestCaseCudaPrecise(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_cuda_precise(self, test_case_description, sigmas, input, expected): # Skip this test diff --git a/tests/test_phl_cpu.py b/tests/networks/layers/filtering/test_phl_cpu.py similarity index 99% rename from tests/test_phl_cpu.py rename to tests/networks/layers/filtering/test_phl_cpu.py index 6f872a4776..f6905283a5 100644 --- a/tests/test_phl_cpu.py +++ b/tests/networks/layers/filtering/test_phl_cpu.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.networks.layers.filtering import PHLFilter -from tests.utils import skip_if_no_cpp_extension +from tests.test_utils import skip_if_no_cpp_extension TEST_CASES = [ [ @@ -242,7 +242,6 @@ @skip_if_no_cpp_extension class PHLFilterTestCaseCpu(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_cpu(self, test_case_description, sigmas, input, features, expected): # Create input tensors diff --git a/tests/test_phl_cuda.py b/tests/networks/layers/filtering/test_phl_cuda.py similarity index 98% rename from tests/test_phl_cuda.py rename to tests/networks/layers/filtering/test_phl_cuda.py index b410ea8722..e823639ffc 100644 --- a/tests/test_phl_cuda.py +++ b/tests/networks/layers/filtering/test_phl_cuda.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.networks.layers.filtering import PHLFilter -from tests.utils import skip_if_no_cpp_extension, skip_if_no_cuda +from tests.test_utils import skip_if_no_cpp_extension, skip_if_no_cuda TEST_CASES = [ [ @@ -150,7 +150,6 @@ @skip_if_no_cuda @skip_if_no_cpp_extension class PHLFilterTestCaseCuda(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_cuda(self, test_case_description, sigmas, input, features, expected): # Create input tensors diff --git a/tests/test_trainable_bilateral.py b/tests/networks/layers/filtering/test_trainable_bilateral.py similarity index 99% rename from tests/test_trainable_bilateral.py rename to tests/networks/layers/filtering/test_trainable_bilateral.py index c69eff4071..ed7e5a0a03 100644 --- a/tests/test_trainable_bilateral.py +++ b/tests/networks/layers/filtering/test_trainable_bilateral.py @@ -19,7 +19,7 @@ from torch.autograd import gradcheck from monai.networks.layers.filtering import TrainableBilateralFilterFunction -from tests.utils import skip_if_no_cpp_extension, skip_if_no_cuda +from tests.test_utils import skip_if_no_cpp_extension, skip_if_no_cuda TEST_CASES = [ [ @@ -273,7 +273,6 @@ @skip_if_no_cpp_extension class BilateralFilterTestCaseCpuPrecise(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_cpu_precise(self, test_case_description, sigmas, input, expected): # Params to determine the implementation to test @@ -372,7 +371,6 @@ def test_cpu_precise_backwards(self, test_case_description, sigmas, input, expec @skip_if_no_cuda @skip_if_no_cpp_extension class BilateralFilterTestCaseCudaPrecise(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_cuda_precise(self, test_case_description, sigmas, input, expected): # Skip this test diff --git a/tests/test_trainable_joint_bilateral.py b/tests/networks/layers/filtering/test_trainable_joint_bilateral.py similarity index 99% rename from tests/test_trainable_joint_bilateral.py rename to tests/networks/layers/filtering/test_trainable_joint_bilateral.py index 4263683ce2..fa7509b376 100644 --- a/tests/test_trainable_joint_bilateral.py +++ b/tests/networks/layers/filtering/test_trainable_joint_bilateral.py @@ -19,7 +19,7 @@ from torch.autograd import gradcheck from monai.networks.layers.filtering import TrainableJointBilateralFilterFunction -from tests.utils import skip_if_no_cpp_extension, skip_if_no_cuda, skip_if_quick +from tests.test_utils import skip_if_no_cpp_extension, skip_if_no_cuda, skip_if_quick TEST_CASES = [ [ @@ -358,7 +358,6 @@ @skip_if_no_cpp_extension @skip_if_quick class JointBilateralFilterTestCaseCpuPrecise(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_cpu_precise(self, test_case_description, sigmas, input, guide, expected): # Params to determine the implementation to test @@ -482,7 +481,6 @@ def test_cpu_precise_backwards(self, test_case_description, sigmas, input, guide @skip_if_no_cuda @skip_if_no_cpp_extension class JointBilateralFilterTestCaseCudaPrecise(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_cuda_precise(self, test_case_description, sigmas, input, guide, expected): # Skip this test diff --git a/tests/test_affine_transform.py b/tests/networks/layers/test_affine_transform.py similarity index 99% rename from tests/test_affine_transform.py rename to tests/networks/layers/test_affine_transform.py index 11464070e0..627a4cb1b9 100644 --- a/tests/test_affine_transform.py +++ b/tests/networks/layers/test_affine_transform.py @@ -19,7 +19,7 @@ from monai.networks import normalize_transform, to_norm_affine from monai.networks.layers import AffineTransform -from tests.utils import is_tf32_env +from tests.test_utils import is_tf32_env _rtol = 1e-4 if not is_tf32_env() else 5e-3 @@ -83,7 +83,6 @@ class TestNormTransform(unittest.TestCase): - @parameterized.expand(TEST_NORM_CASES) def test_norm_xform(self, input_shape, align_corners, expected, zero_centered=False): norm = normalize_transform( @@ -108,7 +107,6 @@ def test_norm_xform(self, input_shape, align_corners, expected, zero_centered=Fa class TestToNormAffine(unittest.TestCase): - @parameterized.expand(TEST_TO_NORM_AFFINE_CASES) def test_to_norm_affine(self, affine, src_size, dst_size, align_corners, expected, zero_centered=False): affine = torch.as_tensor(affine, device=torch.device("cpu:0"), dtype=torch.float32) @@ -132,7 +130,6 @@ def test_to_norm_affine_ill(self, affine, src_size, dst_size, align_corners): class TestAffineTransform(unittest.TestCase): - @parameterized.expand( [ (torch.as_tensor([[1.0, 0.0, 0.0], [0.0, 1.0, -1.0]]), [[[[0, 4, 1, 3], [0, 7, 6, 8], [0, 3, 5, 3]]]]), diff --git a/tests/test_apply_filter.py b/tests/networks/layers/test_apply_filter.py similarity index 100% rename from tests/test_apply_filter.py rename to tests/networks/layers/test_apply_filter.py diff --git a/tests/test_channel_pad.py b/tests/networks/layers/test_channel_pad.py similarity index 100% rename from tests/test_channel_pad.py rename to tests/networks/layers/test_channel_pad.py diff --git a/tests/test_conjugate_gradient.py b/tests/networks/layers/test_conjugate_gradient.py similarity index 100% rename from tests/test_conjugate_gradient.py rename to tests/networks/layers/test_conjugate_gradient.py diff --git a/tests/test_drop_path.py b/tests/networks/layers/test_drop_path.py similarity index 100% rename from tests/test_drop_path.py rename to tests/networks/layers/test_drop_path.py diff --git a/tests/test_gaussian.py b/tests/networks/layers/test_gaussian.py similarity index 100% rename from tests/test_gaussian.py rename to tests/networks/layers/test_gaussian.py diff --git a/tests/test_gaussian_filter.py b/tests/networks/layers/test_gaussian_filter.py similarity index 99% rename from tests/test_gaussian_filter.py rename to tests/networks/layers/test_gaussian_filter.py index 2167591c66..7ed99c3ed7 100644 --- a/tests/test_gaussian_filter.py +++ b/tests/networks/layers/test_gaussian_filter.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.networks.layers import GaussianFilter -from tests.utils import SkipIfAtLeastPyTorchVersion, skip_if_quick +from tests.test_utils import SkipIfAtLeastPyTorchVersion, skip_if_quick TEST_CASES = [[{"type": "erf", "gt": 2.0}], [{"type": "scalespace", "gt": 3.0}], [{"type": "sampled", "gt": 5.0}]] TEST_CASES_GPU = [[{"type": "erf", "gt": 0.8, "device": "cuda"}], [{"type": "sampled", "gt": 5.0, "device": "cuda"}]] @@ -36,7 +36,6 @@ @SkipIfAtLeastPyTorchVersion((2, 2, 0)) # https://github.com/Project-MONAI/MONAI/issues/7445 class TestGaussianFilterBackprop(unittest.TestCase): - def code_to_run(self, input_args): input_dims = input_args.get("dims", (2, 3, 8)) device = ( @@ -97,7 +96,6 @@ def test_train_slow(self, input_args): @SkipIfAtLeastPyTorchVersion((2, 2, 0)) # https://github.com/Project-MONAI/MONAI/issues/7445 class GaussianFilterTestCase(unittest.TestCase): - def test_1d(self): a = torch.ones(1, 8, 10) g = GaussianFilter(1, 3, 3).to(torch.device("cpu:0")) diff --git a/tests/test_get_layers.py b/tests/networks/layers/test_get_layers.py similarity index 100% rename from tests/test_get_layers.py rename to tests/networks/layers/test_get_layers.py diff --git a/tests/test_gmm.py b/tests/networks/layers/test_gmm.py similarity index 99% rename from tests/test_gmm.py rename to tests/networks/layers/test_gmm.py index 549e8f1ec4..c4e9f3c3f5 100644 --- a/tests/test_gmm.py +++ b/tests/networks/layers/test_gmm.py @@ -22,7 +22,7 @@ from monai._extensions import load_module from monai.networks.layers import GaussianMixtureModel -from tests.utils import skip_if_darwin, skip_if_no_cuda, skip_if_quick, skip_if_windows +from tests.test_utils import skip_if_darwin, skip_if_no_cuda, skip_if_quick, skip_if_windows TEST_CASES = [ [ @@ -261,7 +261,6 @@ @skip_if_quick class GMMTestCase(unittest.TestCase): - def setUp(self): self._var = os.environ.get("TORCH_EXTENSIONS_DIR") self.tempdir = tempfile.mkdtemp() diff --git a/tests/test_grid_pull.py b/tests/networks/layers/test_grid_pull.py similarity index 98% rename from tests/test_grid_pull.py rename to tests/networks/layers/test_grid_pull.py index f80874d216..99b9b40791 100644 --- a/tests/test_grid_pull.py +++ b/tests/networks/layers/test_grid_pull.py @@ -20,8 +20,8 @@ from monai.networks.layers import grid_pull from monai.networks.utils import meshgrid_ij from monai.utils import optional_import +from tests.test_utils import skip_if_no_cpp_extension from tests.testing_data.cpp_resample_answers import Expected_1D_GP_bwd, Expected_1D_GP_fwd -from tests.utils import skip_if_no_cpp_extension BType, has_b_type = optional_import("monai._C", name="BoundType") PType, has_p_type = optional_import("monai._C", name="InterpolationType") @@ -63,7 +63,6 @@ def make_grid(shape, dtype=None, device=None, requires_grad=True): @skip_if_no_cpp_extension class TestGridPull(unittest.TestCase): - @parameterized.expand(TEST_1D_GP, skip_on_empty=True) def test_grid_pull(self, input_param, expected): result = grid_pull(**input_param) diff --git a/tests/test_hilbert_transform.py b/tests/networks/layers/test_hilbert_transform.py similarity index 98% rename from tests/test_hilbert_transform.py rename to tests/networks/layers/test_hilbert_transform.py index b91ba3f6b7..c12136aecf 100644 --- a/tests/test_hilbert_transform.py +++ b/tests/networks/layers/test_hilbert_transform.py @@ -19,7 +19,7 @@ from monai.networks.layers import HilbertTransform from monai.utils import OptionalImportError -from tests.utils import SkipIfModule, SkipIfNoModule +from tests.test_utils import SkipIfModule, SkipIfNoModule def create_expected_numpy_output(input_datum, **kwargs): @@ -114,7 +114,6 @@ def create_expected_numpy_output(input_datum, **kwargs): @SkipIfNoModule("torch.fft") class TestHilbertTransformCPU(unittest.TestCase): - @parameterized.expand(TEST_CASES_CPU + TEST_CASES_GPU) def test_value(self, arguments, image, expected_data, atol): result = HilbertTransform(**arguments)(image) @@ -124,7 +123,6 @@ def test_value(self, arguments, image, expected_data, atol): @SkipIfModule("torch.fft") class TestHilbertTransformNoFFTMod(unittest.TestCase): - def test_no_fft_module_error(self): self.assertRaises(OptionalImportError, HilbertTransform(), torch.randn(1, 1, 10)) diff --git a/tests/test_lltm.py b/tests/networks/layers/test_lltm.py similarity index 96% rename from tests/test_lltm.py rename to tests/networks/layers/test_lltm.py index cc64672e77..c54488af85 100644 --- a/tests/test_lltm.py +++ b/tests/networks/layers/test_lltm.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.networks.layers import LLTM -from tests.utils import SkipIfNoModule, assert_allclose, is_tf32_env +from tests.test_utils import SkipIfNoModule, assert_allclose, is_tf32_env _rtol = 0.001 if is_tf32_env() else 0.0001 @@ -29,7 +29,6 @@ class TestLLTM(unittest.TestCase): - @parameterized.expand([TEST_CASE_1]) @SkipIfNoModule("monai._C") def test_value(self, input_param, expected_h, expected_c): diff --git a/tests/test_median_filter.py b/tests/networks/layers/test_median_filter.py similarity index 100% rename from tests/test_median_filter.py rename to tests/networks/layers/test_median_filter.py diff --git a/tests/test_polyval.py b/tests/networks/layers/test_polyval.py similarity index 100% rename from tests/test_polyval.py rename to tests/networks/layers/test_polyval.py diff --git a/tests/test_preset_filters.py b/tests/networks/layers/test_preset_filters.py similarity index 100% rename from tests/test_preset_filters.py rename to tests/networks/layers/test_preset_filters.py diff --git a/tests/test_savitzky_golay_filter.py b/tests/networks/layers/test_savitzky_golay_filter.py similarity index 99% rename from tests/test_savitzky_golay_filter.py rename to tests/networks/layers/test_savitzky_golay_filter.py index 7c60287e2d..ea4b97c80c 100644 --- a/tests/test_savitzky_golay_filter.py +++ b/tests/networks/layers/test_savitzky_golay_filter.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.networks.layers import SavitzkyGolayFilter -from tests.utils import skip_if_no_cuda +from tests.test_utils import skip_if_no_cuda # Zero-padding trivial tests @@ -100,7 +100,6 @@ class TestSavitzkyGolayCPU(unittest.TestCase): - @parameterized.expand( [TEST_CASE_SINGLE_VALUE, TEST_CASE_1D, TEST_CASE_2D_AXIS_2, TEST_CASE_2D_AXIS_3, TEST_CASE_SINE_SMOOTH] ) @@ -110,7 +109,6 @@ def test_value(self, arguments, image, expected_data, atol, rtol=1e-5): class TestSavitzkyGolayCPUREP(unittest.TestCase): - @parameterized.expand( [TEST_CASE_SINGLE_VALUE_REP, TEST_CASE_1D_REP, TEST_CASE_2D_AXIS_2_REP, TEST_CASE_2D_AXIS_3_REP] ) @@ -121,7 +119,6 @@ def test_value(self, arguments, image, expected_data, atol, rtol=1e-5): @skip_if_no_cuda class TestSavitzkyGolayGPU(unittest.TestCase): - @parameterized.expand( [TEST_CASE_SINGLE_VALUE, TEST_CASE_1D, TEST_CASE_2D_AXIS_2, TEST_CASE_2D_AXIS_3, TEST_CASE_SINE_SMOOTH] ) @@ -132,7 +129,6 @@ def test_value(self, arguments, image, expected_data, atol, rtol=1e-5): @skip_if_no_cuda class TestSavitzkyGolayGPUREP(unittest.TestCase): - @parameterized.expand( [TEST_CASE_SINGLE_VALUE_REP, TEST_CASE_1D_REP, TEST_CASE_2D_AXIS_2_REP, TEST_CASE_2D_AXIS_3_REP] ) diff --git a/tests/test_separable_filter.py b/tests/networks/layers/test_separable_filter.py similarity index 100% rename from tests/test_separable_filter.py rename to tests/networks/layers/test_separable_filter.py diff --git a/tests/test_skip_connection.py b/tests/networks/layers/test_skip_connection.py similarity index 100% rename from tests/test_skip_connection.py rename to tests/networks/layers/test_skip_connection.py diff --git a/tests/test_vector_quantizer.py b/tests/networks/layers/test_vector_quantizer.py similarity index 100% rename from tests/test_vector_quantizer.py rename to tests/networks/layers/test_vector_quantizer.py diff --git a/tests/test_weight_init.py b/tests/networks/layers/test_weight_init.py similarity index 100% rename from tests/test_weight_init.py rename to tests/networks/layers/test_weight_init.py diff --git a/tests/networks/nets/__init__.py b/tests/networks/nets/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/networks/nets/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/networks/nets/dints/__init__.py b/tests/networks/nets/dints/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/networks/nets/dints/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_dints_cell.py b/tests/networks/nets/dints/test_dints_cell.py similarity index 100% rename from tests/test_dints_cell.py rename to tests/networks/nets/dints/test_dints_cell.py diff --git a/tests/test_dints_mixop.py b/tests/networks/nets/dints/test_dints_mixop.py similarity index 98% rename from tests/test_dints_mixop.py rename to tests/networks/nets/dints/test_dints_mixop.py index 683a8d1005..ea78514fa5 100644 --- a/tests/test_dints_mixop.py +++ b/tests/networks/nets/dints/test_dints_mixop.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.networks.nets.dints import Cell, MixedOp -from tests.utils import test_script_save +from tests.test_utils import test_script_save TEST_CASES_3D = [ [ @@ -61,7 +61,6 @@ class TestMixOP(unittest.TestCase): - @parameterized.expand(TEST_CASES_3D) def test_mixop_3d(self, input_param, ops, weight, input_shape, expected_shape): net = MixedOp(ops=Cell.OPS3D, **input_param) diff --git a/tests/networks/nets/regunet/__init__.py b/tests/networks/nets/regunet/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/networks/nets/regunet/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_localnet.py b/tests/networks/nets/regunet/test_localnet.py similarity index 98% rename from tests/test_localnet.py rename to tests/networks/nets/regunet/test_localnet.py index 97aa94d2c5..d255934495 100644 --- a/tests/test_localnet.py +++ b/tests/networks/nets/regunet/test_localnet.py @@ -18,7 +18,7 @@ from monai.networks import eval_mode from monai.networks.nets.regunet import LocalNet -from tests.utils import test_script_save +from tests.test_utils import test_script_save device = "cuda" if torch.cuda.is_available() else "cpu" @@ -62,7 +62,6 @@ class TestLocalNet(unittest.TestCase): - @parameterized.expand(TEST_CASE_LOCALNET_2D + TEST_CASE_LOCALNET_3D) def test_shape(self, input_param, input_shape, expected_shape): net = LocalNet(**input_param).to(device) diff --git a/tests/test_regunet.py b/tests/networks/nets/regunet/test_regunet.py similarity index 98% rename from tests/test_regunet.py rename to tests/networks/nets/regunet/test_regunet.py index 3100d7660c..152a05fc62 100644 --- a/tests/test_regunet.py +++ b/tests/networks/nets/regunet/test_regunet.py @@ -18,7 +18,7 @@ from monai.networks import eval_mode from monai.networks.nets.regunet import RegUNet -from tests.utils import test_script_save +from tests.test_utils import test_script_save device = "cuda" if torch.cuda.is_available() else "cpu" @@ -63,7 +63,6 @@ class TestREGUNET(unittest.TestCase): - @parameterized.expand(TEST_CASE_REGUNET_2D + TEST_CASE_REGUNET_3D) def test_shape(self, input_param, input_shape, expected_shape): net = RegUNet(**input_param).to(device) diff --git a/tests/test_ahnet.py b/tests/networks/nets/test_ahnet.py similarity index 98% rename from tests/test_ahnet.py rename to tests/networks/nets/test_ahnet.py index 99a177f395..7facf9af24 100644 --- a/tests/test_ahnet.py +++ b/tests/networks/nets/test_ahnet.py @@ -19,7 +19,7 @@ from monai.networks import eval_mode from monai.networks.blocks import FCN, MCFCN from monai.networks.nets import AHNet -from tests.utils import skip_if_quick, test_pretrained_networks, test_script_save +from tests.test_utils import skip_if_quick, test_pretrained_networks, test_script_save device = "cuda" if torch.cuda.is_available() else "cpu" @@ -126,7 +126,6 @@ class TestFCN(unittest.TestCase): - @parameterized.expand([TEST_CASE_FCN_1, TEST_CASE_FCN_2, TEST_CASE_FCN_3]) @skip_if_quick def test_fcn_shape(self, input_param, input_shape, expected_shape): @@ -137,7 +136,6 @@ def test_fcn_shape(self, input_param, input_shape, expected_shape): class TestFCNWithPretrain(unittest.TestCase): - @parameterized.expand([TEST_CASE_FCN_WITH_PRETRAIN_1, TEST_CASE_FCN_WITH_PRETRAIN_2]) @skip_if_quick def test_fcn_shape(self, input_param, input_shape, expected_shape): @@ -148,7 +146,6 @@ def test_fcn_shape(self, input_param, input_shape, expected_shape): class TestMCFCN(unittest.TestCase): - @parameterized.expand([TEST_CASE_MCFCN_1, TEST_CASE_MCFCN_2, TEST_CASE_MCFCN_3]) def test_mcfcn_shape(self, input_param, input_shape, expected_shape): net = MCFCN(**input_param).to(device) @@ -158,7 +155,6 @@ def test_mcfcn_shape(self, input_param, input_shape, expected_shape): class TestMCFCNWithPretrain(unittest.TestCase): - @parameterized.expand([TEST_CASE_MCFCN_WITH_PRETRAIN_1, TEST_CASE_MCFCN_WITH_PRETRAIN_2]) def test_mcfcn_shape(self, input_param, input_shape, expected_shape): net = test_pretrained_networks(MCFCN, input_param, device) @@ -168,7 +164,6 @@ def test_mcfcn_shape(self, input_param, input_shape, expected_shape): class TestAHNET(unittest.TestCase): - @parameterized.expand([TEST_CASE_AHNET_2D_1, TEST_CASE_AHNET_2D_2, TEST_CASE_AHNET_2D_3]) def test_ahnet_shape_2d(self, input_param, input_shape, expected_shape): net = AHNet(**input_param).to(device) @@ -197,7 +192,6 @@ def test_script(self): class TestAHNETWithPretrain(unittest.TestCase): - @parameterized.expand( [TEST_CASE_AHNET_3D_WITH_PRETRAIN_1, TEST_CASE_AHNET_3D_WITH_PRETRAIN_2, TEST_CASE_AHNET_3D_WITH_PRETRAIN_3] ) diff --git a/tests/test_attentionunet.py b/tests/networks/nets/test_attentionunet.py similarity index 98% rename from tests/test_attentionunet.py rename to tests/networks/nets/test_attentionunet.py index 6a577f763f..30b9a76aad 100644 --- a/tests/test_attentionunet.py +++ b/tests/networks/nets/test_attentionunet.py @@ -17,7 +17,7 @@ import torch.nn as nn import monai.networks.nets.attentionunet as att -from tests.utils import skip_if_no_cuda, skip_if_quick +from tests.test_utils import skip_if_no_cuda, skip_if_quick def get_net_parameters(net: nn.Module) -> int: @@ -26,7 +26,6 @@ def get_net_parameters(net: nn.Module) -> int: class TestAttentionUnet(unittest.TestCase): - def test_attention_block(self): for dims in [2, 3]: block = att.AttentionBlock(dims, f_int=2, f_g=6, f_l=6) diff --git a/tests/test_autoencoder.py b/tests/networks/nets/test_autoencoder.py similarity index 98% rename from tests/test_autoencoder.py rename to tests/networks/nets/test_autoencoder.py index 6408f6a6d0..dcf90b809a 100644 --- a/tests/test_autoencoder.py +++ b/tests/networks/nets/test_autoencoder.py @@ -19,7 +19,7 @@ from monai.networks import eval_mode from monai.networks.layers import Act from monai.networks.nets import AutoEncoder -from tests.utils import test_script_save +from tests.test_utils import test_script_save device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") @@ -74,7 +74,6 @@ class TestAutoEncoder(unittest.TestCase): - @parameterized.expand(CASES) def test_shape(self, input_param, input_shape, expected_shape): net = AutoEncoder(**input_param).to(device) diff --git a/tests/test_autoencoderkl.py b/tests/networks/nets/test_autoencoderkl.py similarity index 99% rename from tests/test_autoencoderkl.py rename to tests/networks/nets/test_autoencoderkl.py index d15cb79084..0a3db60830 100644 --- a/tests/test_autoencoderkl.py +++ b/tests/networks/nets/test_autoencoderkl.py @@ -23,7 +23,7 @@ from monai.networks import eval_mode from monai.networks.nets import AutoencoderKL from monai.utils import optional_import -from tests.utils import SkipIfBeforePyTorchVersion, skip_if_downloading_fails, testing_data_config +from tests.test_utils import SkipIfBeforePyTorchVersion, skip_if_downloading_fails, testing_data_config tqdm, has_tqdm = optional_import("tqdm", name="tqdm") _, has_einops = optional_import("einops") diff --git a/tests/test_basic_unet.py b/tests/networks/nets/test_basic_unet.py similarity index 98% rename from tests/test_basic_unet.py rename to tests/networks/nets/test_basic_unet.py index 770750851f..edd7b599d4 100644 --- a/tests/test_basic_unet.py +++ b/tests/networks/nets/test_basic_unet.py @@ -18,7 +18,7 @@ from monai.networks import eval_mode from monai.networks.nets import BasicUNet -from tests.utils import test_script_save +from tests.test_utils import test_script_save CASES_1D = [] for mode in ["pixelshuffle", "nontrainable", "deconv", None]: @@ -83,7 +83,6 @@ class TestBasicUNET(unittest.TestCase): - @parameterized.expand(CASES_1D + CASES_2D + CASES_3D) def test_shape(self, input_param, input_shape, expected_shape): device = "cuda" if torch.cuda.is_available() else "cpu" diff --git a/tests/test_basic_unetplusplus.py b/tests/networks/nets/test_basic_unetplusplus.py similarity index 98% rename from tests/test_basic_unetplusplus.py rename to tests/networks/nets/test_basic_unetplusplus.py index 6438b5e0d4..37a2813f2e 100644 --- a/tests/test_basic_unetplusplus.py +++ b/tests/networks/nets/test_basic_unetplusplus.py @@ -18,7 +18,7 @@ from monai.networks import eval_mode from monai.networks.nets import BasicUNetPlusPlus -from tests.utils import test_script_save +from tests.test_utils import test_script_save CASES_1D = [] for mode in ["pixelshuffle", "nontrainable", "deconv", None]: @@ -83,7 +83,6 @@ class TestBasicUNETPlusPlus(unittest.TestCase): - @parameterized.expand(CASES_1D + CASES_2D + CASES_3D) def test_shape(self, input_param, input_shape, expected_shape): device = "cuda" if torch.cuda.is_available() else "cpu" diff --git a/tests/test_bundle_init_bundle.py b/tests/networks/nets/test_bundle_init_bundle.py similarity index 96% rename from tests/test_bundle_init_bundle.py rename to tests/networks/nets/test_bundle_init_bundle.py index eb831093d5..13212091cb 100644 --- a/tests/test_bundle_init_bundle.py +++ b/tests/networks/nets/test_bundle_init_bundle.py @@ -18,12 +18,11 @@ import torch from monai.networks.nets import UNet -from tests.utils import command_line_tests, skip_if_windows +from tests.test_utils import command_line_tests, skip_if_windows @skip_if_windows class TestBundleInit(unittest.TestCase): - def test_bundle(self): with tempfile.TemporaryDirectory() as tempdir: net = UNet(2, 1, 1, [4, 8], [2]) diff --git a/tests/test_cell_sam_wrapper.py b/tests/networks/nets/test_cell_sam_wrapper.py similarity index 100% rename from tests/test_cell_sam_wrapper.py rename to tests/networks/nets/test_cell_sam_wrapper.py diff --git a/tests/test_controlnet.py b/tests/networks/nets/test_controlnet.py similarity index 98% rename from tests/test_controlnet.py rename to tests/networks/nets/test_controlnet.py index 4746c7ce22..9503518762 100644 --- a/tests/test_controlnet.py +++ b/tests/networks/nets/test_controlnet.py @@ -23,7 +23,7 @@ from monai.networks import eval_mode from monai.networks.nets.controlnet import ControlNet from monai.utils import optional_import -from tests.utils import skip_if_downloading_fails, testing_data_config +from tests.test_utils import skip_if_downloading_fails, testing_data_config _, has_einops = optional_import("einops") UNCOND_CASES_2D = [ diff --git a/tests/test_daf3d.py b/tests/networks/nets/test_daf3d.py similarity index 98% rename from tests/test_daf3d.py rename to tests/networks/nets/test_daf3d.py index d20cb3cfd1..e707cfb272 100644 --- a/tests/test_daf3d.py +++ b/tests/networks/nets/test_daf3d.py @@ -19,7 +19,7 @@ from monai.networks import eval_mode from monai.networks.nets import DAF3D from monai.utils import optional_import -from tests.utils import test_script_save +from tests.test_utils import test_script_save _, has_tv = optional_import("torchvision") @@ -42,7 +42,6 @@ @unittest.skipUnless(has_tv, "torchvision not installed") class TestDAF3D(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_shape(self, input_param, input_shape, expected_shape): device = "cuda" if torch.cuda.is_available() else "cpu" diff --git a/tests/test_densenet.py b/tests/networks/nets/test_densenet.py similarity index 98% rename from tests/test_densenet.py rename to tests/networks/nets/test_densenet.py index ee4be9003b..b0f70a9bde 100644 --- a/tests/test_densenet.py +++ b/tests/networks/nets/test_densenet.py @@ -21,7 +21,7 @@ from monai.networks import eval_mode from monai.networks.nets import DenseNet121, Densenet169, DenseNet264, densenet201 from monai.utils import optional_import -from tests.utils import skip_if_downloading_fails, skip_if_quick, test_script_save +from tests.test_utils import skip_if_downloading_fails, skip_if_quick, test_script_save if TYPE_CHECKING: import torchvision @@ -79,7 +79,6 @@ class TestPretrainedDENSENET(unittest.TestCase): - @parameterized.expand([TEST_PRETRAINED_2D_CASE_1, TEST_PRETRAINED_2D_CASE_2]) @skip_if_quick def test_121_2d_shape_pretrain(self, model, input_param, input_shape, expected_shape): @@ -104,7 +103,6 @@ def test_pretrain_consistency(self, model, input_param, input_shape): class TestDENSENET(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_densenet_shape(self, model, input_param, input_shape, expected_shape): net = model(**input_param).to(device) diff --git a/tests/test_diffusion_model_unet.py b/tests/networks/nets/test_diffusion_model_unet.py similarity index 99% rename from tests/test_diffusion_model_unet.py rename to tests/networks/nets/test_diffusion_model_unet.py index 7f764d85de..a7c823709d 100644 --- a/tests/test_diffusion_model_unet.py +++ b/tests/networks/nets/test_diffusion_model_unet.py @@ -23,7 +23,7 @@ from monai.networks import eval_mode from monai.networks.nets import DiffusionModelUNet from monai.utils import optional_import -from tests.utils import skip_if_downloading_fails, testing_data_config +from tests.test_utils import skip_if_downloading_fails, testing_data_config _, has_einops = optional_import("einops") diff --git a/tests/test_dints_network.py b/tests/networks/nets/test_dints_network.py similarity index 98% rename from tests/test_dints_network.py rename to tests/networks/nets/test_dints_network.py index 5ee4db7a4e..449d5045fe 100644 --- a/tests/test_dints_network.py +++ b/tests/networks/nets/test_dints_network.py @@ -19,7 +19,7 @@ from monai.networks.nets import DiNTS, TopologyInstance, TopologySearch from monai.networks.nets.dints import Cell -from tests.utils import SkipIfBeforePyTorchVersion, skip_if_quick, test_script_save +from tests.test_utils import SkipIfBeforePyTorchVersion, skip_if_quick, test_script_save TEST_CASES_3D = [ [ @@ -115,7 +115,6 @@ @skip_if_quick class TestDints(unittest.TestCase): - @parameterized.expand(TEST_CASES_3D + TEST_CASES_2D) def test_dints_inference(self, dints_grid_params, dints_params, input_shape, expected_shape): grid = TopologySearch(**dints_grid_params) @@ -156,7 +155,6 @@ def test_dints_search(self, dints_grid_params, dints_params, input_shape, expect @SkipIfBeforePyTorchVersion((1, 9)) class TestDintsTS(unittest.TestCase): - @parameterized.expand(TEST_CASES_3D + TEST_CASES_2D) def test_script(self, dints_grid_params, dints_params, input_shape, _): grid = TopologyInstance(**dints_grid_params) diff --git a/tests/test_discriminator.py b/tests/networks/nets/test_discriminator.py similarity index 97% rename from tests/test_discriminator.py rename to tests/networks/nets/test_discriminator.py index f615605e56..8f460a2450 100644 --- a/tests/test_discriminator.py +++ b/tests/networks/nets/test_discriminator.py @@ -18,7 +18,7 @@ from monai.networks import eval_mode from monai.networks.nets import Discriminator -from tests.utils import test_script_save +from tests.test_utils import test_script_save TEST_CASE_0 = [ {"in_shape": (1, 64, 64), "channels": (2, 4, 8), "strides": (2, 2, 2), "num_res_units": 0}, @@ -42,7 +42,6 @@ class TestDiscriminator(unittest.TestCase): - @parameterized.expand(CASES) def test_shape(self, input_param, input_data, expected_shape): net = Discriminator(**input_param) diff --git a/tests/test_dynunet.py b/tests/networks/nets/test_dynunet.py similarity index 98% rename from tests/test_dynunet.py rename to tests/networks/nets/test_dynunet.py index 7c4882fcbb..a9dd588e13 100644 --- a/tests/test_dynunet.py +++ b/tests/networks/nets/test_dynunet.py @@ -22,7 +22,7 @@ from monai.networks import eval_mode from monai.networks.nets import DynUNet from monai.utils import optional_import -from tests.utils import assert_allclose, skip_if_no_cuda, skip_if_windows, test_script_save +from tests.test_utils import assert_allclose, skip_if_no_cuda, skip_if_windows, test_script_save InstanceNorm3dNVFuser, _ = optional_import("apex.normalization", name="InstanceNorm3dNVFuser") @@ -117,7 +117,6 @@ class TestDynUNet(unittest.TestCase): - @parameterized.expand(TEST_CASE_DYNUNET_3D) def test_shape(self, input_param, input_shape, expected_shape): net = DynUNet(**input_param).to(device) @@ -137,7 +136,6 @@ def test_script(self): @skip_if_no_cuda @skip_if_windows class TestDynUNetWithInstanceNorm3dNVFuser(unittest.TestCase): - def setUp(self): try: layer = InstanceNorm3dNVFuser(num_features=1, affine=False).to("cuda:0") @@ -171,7 +169,6 @@ def test_consistency(self, input_param, input_shape, _): class TestDynUNetDeepSupervision(unittest.TestCase): - @parameterized.expand(TEST_CASE_DEEP_SUPERVISION) def test_shape(self, input_param, input_shape, expected_shape): net = DynUNet(**input_param).to(device) diff --git a/tests/test_efficientnet.py b/tests/networks/nets/test_efficientnet.py similarity index 97% rename from tests/test_efficientnet.py rename to tests/networks/nets/test_efficientnet.py index c16526eaa3..e76d5a6d5a 100644 --- a/tests/test_efficientnet.py +++ b/tests/networks/nets/test_efficientnet.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path from typing import TYPE_CHECKING from unittest import skipUnless @@ -28,7 +29,9 @@ get_efficientnet_image_size, ) from monai.utils import optional_import -from tests.utils import skip_if_downloading_fails, skip_if_quick, test_pretrained_networks, test_script_save +from tests.test_utils import skip_if_downloading_fails, skip_if_quick, test_pretrained_networks, test_script_save + +TESTS_PATH = Path(__file__).parents[2] if TYPE_CHECKING: import torchvision @@ -162,7 +165,7 @@ def make_shape_cases( "norm": ("batch", {"eps": 1e-3, "momentum": 0.01}), "adv_prop": False, }, - os.path.join(os.path.dirname(__file__), "testing_data", "kitty_test.jpg"), + os.path.join(TESTS_PATH, "testing_data", "kitty_test.jpg"), 282, # ~ tiger cat ), ( @@ -174,7 +177,7 @@ def make_shape_cases( "in_channels": 3, "num_classes": 1000, }, - os.path.join(os.path.dirname(__file__), "testing_data", "kitty_test.jpg"), + os.path.join(TESTS_PATH, "testing_data", "kitty_test.jpg"), 282, # ~ tiger cat ), ( @@ -186,7 +189,7 @@ def make_shape_cases( "in_channels": 3, "num_classes": 1000, }, - os.path.join(os.path.dirname(__file__), "testing_data", "kitty_test.jpg"), + os.path.join(TESTS_PATH, "testing_data", "kitty_test.jpg"), 282, # ~ tiger cat ), ] @@ -248,7 +251,6 @@ def make_shape_cases( class TestEFFICIENTNET(unittest.TestCase): - @parameterized.expand(CASES_1D + CASES_2D + CASES_3D + CASES_VARIATIONS) def test_shape(self, input_param, input_shape, expected_shape): device = "cuda" if torch.cuda.is_available() else "cpu" @@ -377,7 +379,6 @@ def test_script(self): class TestExtractFeatures(unittest.TestCase): - @parameterized.expand(CASE_EXTRACT_FEATURES) def test_shape(self, input_param, input_shape, expected_shapes): device = "cuda" if torch.cuda.is_available() else "cpu" diff --git a/tests/test_flexible_unet.py b/tests/networks/nets/test_flexible_unet.py similarity index 99% rename from tests/test_flexible_unet.py rename to tests/networks/nets/test_flexible_unet.py index 42baa28b71..5efe436c27 100644 --- a/tests/test_flexible_unet.py +++ b/tests/networks/nets/test_flexible_unet.py @@ -27,14 +27,13 @@ ResNetFeatures, ) from monai.utils import optional_import -from tests.utils import SkipIfNoModule, skip_if_downloading_fails, skip_if_quick +from tests.test_utils import SkipIfNoModule, skip_if_downloading_fails, skip_if_quick torchvision, has_torchvision = optional_import("torchvision") PIL, has_pil = optional_import("PIL") class DummyEncoder(BaseEncoder): - @classmethod def get_encoder_parameters(cls): basic_dict = {"spatial_dims": 2, "in_channels": 3, "pretrained": False} @@ -282,7 +281,6 @@ def make_error_case(): @SkipIfNoModule("hf_hub_download") @skip_if_quick class TestFLEXIBLEUNET(unittest.TestCase): - @parameterized.expand(CASES_2D + CASES_3D + CASES_VARIATIONS) def test_shape(self, input_param, input_shape, expected_shape): device = "cuda" if torch.cuda.is_available() else "cpu" @@ -323,7 +321,6 @@ def test_error_raise(self, input_param): class TestFlexUNetEncoderRegister(unittest.TestCase): - @parameterized.expand(CASE_REGISTER_ENCODER) def test_regist(self, encoder): tmp_backbone = FlexUNetEncoderRegister() diff --git a/tests/test_fullyconnectednet.py b/tests/networks/nets/test_fullyconnectednet.py similarity index 100% rename from tests/test_fullyconnectednet.py rename to tests/networks/nets/test_fullyconnectednet.py diff --git a/tests/test_generator.py b/tests/networks/nets/test_generator.py similarity index 97% rename from tests/test_generator.py rename to tests/networks/nets/test_generator.py index f531f928da..9ec08194e9 100644 --- a/tests/test_generator.py +++ b/tests/networks/nets/test_generator.py @@ -18,7 +18,7 @@ from monai.networks import eval_mode from monai.networks.nets import Generator -from tests.utils import test_script_save +from tests.test_utils import test_script_save TEST_CASE_0 = [ {"latent_shape": (64,), "start_shape": (8, 8, 8), "channels": (8, 4, 1), "strides": (2, 2, 2), "num_res_units": 0}, @@ -42,7 +42,6 @@ class TestGenerator(unittest.TestCase): - @parameterized.expand(CASES) def test_shape(self, input_param, input_data, expected_shape): net = Generator(**input_param) diff --git a/tests/test_globalnet.py b/tests/networks/nets/test_globalnet.py similarity index 98% rename from tests/test_globalnet.py rename to tests/networks/nets/test_globalnet.py index 626053377c..ecb0243a1b 100644 --- a/tests/test_globalnet.py +++ b/tests/networks/nets/test_globalnet.py @@ -21,7 +21,7 @@ from monai.networks.blocks import Warp from monai.networks.nets import GlobalNet from monai.networks.nets.regunet import AffineHead -from tests.utils import assert_allclose, test_script_save +from tests.test_utils import assert_allclose, test_script_save TEST_CASES_AFFINE_TRANSFORM = [ [ @@ -65,7 +65,6 @@ class TestAffineHead(unittest.TestCase): - @parameterized.expand(TEST_CASES_AFFINE_TRANSFORM) def test_shape(self, input_param, theta, expected_val): layer = AffineHead(**input_param) @@ -79,7 +78,6 @@ def test_shape(self, input_param, theta, expected_val): class TestGlobalNet(unittest.TestCase): - @parameterized.expand(TEST_CASES_GLOBAL_NET) def test_shape(self, input_param, input_shape, expected_shape): net = GlobalNet(**input_param).to(device) diff --git a/tests/test_highresnet.py b/tests/networks/nets/test_highresnet.py similarity index 96% rename from tests/test_highresnet.py rename to tests/networks/nets/test_highresnet.py index bcc5739900..1384dfaeff 100644 --- a/tests/test_highresnet.py +++ b/tests/networks/nets/test_highresnet.py @@ -18,7 +18,7 @@ from monai.networks import eval_mode from monai.networks.nets import HighResNet -from tests.utils import DistTestCase, TimedCall, test_script_save +from tests.test_utils import DistTestCase, TimedCall, test_script_save device = "cuda" if torch.cuda.is_available() else "cpu" @@ -48,7 +48,6 @@ class TestHighResNet(DistTestCase): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4]) def test_shape(self, input_param, input_shape, expected_shape): net = HighResNet(**input_param).to(device) diff --git a/tests/test_hovernet.py b/tests/networks/nets/test_hovernet.py similarity index 99% rename from tests/test_hovernet.py rename to tests/networks/nets/test_hovernet.py index fb4946b011..58657e6dea 100644 --- a/tests/test_hovernet.py +++ b/tests/networks/nets/test_hovernet.py @@ -19,7 +19,7 @@ from monai.networks import eval_mode, train_mode from monai.networks.nets import HoVerNet from monai.networks.nets.hovernet import _DenseLayerDecoder -from tests.utils import test_script_save +from tests.test_utils import test_script_save device = "cuda" if torch.cuda.is_available() else "cpu" @@ -154,7 +154,6 @@ def check_kernels(net, mode): class TestHoverNet(unittest.TestCase): - @parameterized.expand(CASES) def test_shape(self, input_param, input_shape, expected_shapes): input_param["decoder_padding"] = False diff --git a/tests/test_mednext.py b/tests/networks/nets/test_mednext.py similarity index 100% rename from tests/test_mednext.py rename to tests/networks/nets/test_mednext.py diff --git a/tests/test_milmodel.py b/tests/networks/nets/test_milmodel.py similarity index 97% rename from tests/test_milmodel.py rename to tests/networks/nets/test_milmodel.py index 42116e8220..4e3c9056ef 100644 --- a/tests/test_milmodel.py +++ b/tests/networks/nets/test_milmodel.py @@ -19,7 +19,7 @@ from monai.networks import eval_mode from monai.networks.nets import MILModel from monai.utils.module import optional_import -from tests.utils import skip_if_downloading_fails, test_script_save +from tests.test_utils import skip_if_downloading_fails, test_script_save models, _ = optional_import("torchvision.models") @@ -63,7 +63,6 @@ class TestMilModel(unittest.TestCase): - @parameterized.expand(TEST_CASE_MILMODEL) def test_shape(self, input_param, input_shape, expected_shape): with skip_if_downloading_fails(): diff --git a/tests/test_net_adapter.py b/tests/networks/nets/test_net_adapter.py similarity index 98% rename from tests/test_net_adapter.py rename to tests/networks/nets/test_net_adapter.py index 242326e242..08344900e4 100644 --- a/tests/test_net_adapter.py +++ b/tests/networks/nets/test_net_adapter.py @@ -18,7 +18,7 @@ from monai.networks import eval_mode from monai.networks.nets import NetAdapter, resnet18 -from tests.utils import test_script_save +from tests.test_utils import test_script_save device = "cuda" if torch.cuda.is_available() else "cpu" @@ -42,7 +42,6 @@ class TestNetAdapter(unittest.TestCase): - @parameterized.expand([TEST_CASE_0, TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4]) def test_shape(self, input_param, input_shape, expected_shape): spatial_dims = input_param["dim"] diff --git a/tests/test_network_consistency.py b/tests/networks/nets/test_network_consistency.py similarity index 98% rename from tests/test_network_consistency.py rename to tests/networks/nets/test_network_consistency.py index bcfd448144..e09826de75 100644 --- a/tests/test_network_consistency.py +++ b/tests/networks/nets/test_network_consistency.py @@ -24,7 +24,7 @@ import monai.networks.nets as nets from monai.utils import set_determinism from monai.utils.misc import MONAIEnvVars -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose extra_test_data_dir = MONAIEnvVars.extra_test_data() @@ -38,7 +38,6 @@ class TestNetworkConsistency(unittest.TestCase): - def setUp(self): set_determinism(0) diff --git a/tests/test_patch_gan_dicriminator.py b/tests/networks/nets/test_patch_gan_dicriminator.py similarity index 99% rename from tests/test_patch_gan_dicriminator.py rename to tests/networks/nets/test_patch_gan_dicriminator.py index c19898e70d..184f76fa9d 100644 --- a/tests/test_patch_gan_dicriminator.py +++ b/tests/networks/nets/test_patch_gan_dicriminator.py @@ -18,7 +18,7 @@ from monai.networks import eval_mode from monai.networks.nets import MultiScalePatchDiscriminator, PatchDiscriminator -from tests.utils import test_script_save +from tests.test_utils import test_script_save TEST_PATCHGAN = [ [ diff --git a/tests/test_quicknat.py b/tests/networks/nets/test_quicknat.py similarity index 98% rename from tests/test_quicknat.py rename to tests/networks/nets/test_quicknat.py index f6786405d2..6653965c08 100644 --- a/tests/test_quicknat.py +++ b/tests/networks/nets/test_quicknat.py @@ -19,7 +19,7 @@ from monai.networks import eval_mode from monai.networks.nets import Quicknat from monai.utils import optional_import -from tests.utils import test_script_save +from tests.test_utils import test_script_save _, has_se = optional_import("squeeze_and_excitation") @@ -38,7 +38,6 @@ @unittest.skipUnless(has_se, "squeeze_and_excitation not installed") class TestQuicknat(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_shape(self, input_param, input_shape, expected_shape): device = "cuda" if torch.cuda.is_available() else "cpu" diff --git a/tests/test_resnet.py b/tests/networks/nets/test_resnet.py similarity index 99% rename from tests/test_resnet.py rename to tests/networks/nets/test_resnet.py index a55d18f5de..371ec89682 100644 --- a/tests/test_resnet.py +++ b/tests/networks/nets/test_resnet.py @@ -37,7 +37,7 @@ ) from monai.networks.nets.resnet import ResNetBlock from monai.utils import optional_import -from tests.utils import ( +from tests.test_utils import ( SkipIfNoModule, equal_state_dict, skip_if_downloading_fails, @@ -242,7 +242,6 @@ class TestResNet(unittest.TestCase): - def setUp(self): self.tmp_ckpt_filename = os.path.join("tests", "monai_unittest_tmp_ckpt.pth") @@ -320,7 +319,6 @@ def test_script(self, model, input_param, input_shape, expected_shape): @SkipIfNoModule("hf_hub_download") class TestExtractFeatures(unittest.TestCase): - @parameterized.expand(CASE_EXTRACT_FEATURES) def test_shape(self, input_param, input_shape, expected_shapes): device = "cuda" if torch.cuda.is_available() else "cpu" diff --git a/tests/test_segresnet.py b/tests/networks/nets/test_segresnet.py similarity index 99% rename from tests/test_segresnet.py rename to tests/networks/nets/test_segresnet.py index 728699c434..b3b3d1051a 100644 --- a/tests/test_segresnet.py +++ b/tests/networks/nets/test_segresnet.py @@ -19,7 +19,7 @@ from monai.networks import eval_mode from monai.networks.nets import SegResNet, SegResNetVAE from monai.utils import UpsampleMode -from tests.utils import test_script_save +from tests.test_utils import test_script_save device = "cuda" if torch.cuda.is_available() else "cpu" @@ -83,7 +83,6 @@ class TestResNet(unittest.TestCase): - @parameterized.expand(TEST_CASE_SEGRESNET + TEST_CASE_SEGRESNET_2) def test_shape(self, input_param, input_shape, expected_shape): net = SegResNet(**input_param).to(device) @@ -103,7 +102,6 @@ def test_script(self): class TestResNetVAE(unittest.TestCase): - @parameterized.expand(TEST_CASE_SEGRESNET_VAE) def test_vae_shape(self, input_param, input_shape, expected_shape): net = SegResNetVAE(**input_param).to(device) diff --git a/tests/test_segresnet_ds.py b/tests/networks/nets/test_segresnet_ds.py similarity index 98% rename from tests/test_segresnet_ds.py rename to tests/networks/nets/test_segresnet_ds.py index eab7bac9a0..064b2ba06c 100644 --- a/tests/test_segresnet_ds.py +++ b/tests/networks/nets/test_segresnet_ds.py @@ -18,7 +18,7 @@ from monai.networks import eval_mode from monai.networks.nets import SegResNetDS, SegResNetDS2 -from tests.utils import SkipIfBeforePyTorchVersion, test_script_save +from tests.test_utils import SkipIfBeforePyTorchVersion, test_script_save device = "cuda" if torch.cuda.is_available() else "cpu" TEST_CASE_SEGRESNET_DS = [] @@ -72,7 +72,6 @@ class TestSegResNetDS(unittest.TestCase): - @parameterized.expand(TEST_CASE_SEGRESNET_DS) def test_shape(self, input_param, input_shape, expected_shape): net = SegResNetDS(**input_param).to(device) diff --git a/tests/test_senet.py b/tests/networks/nets/test_senet.py similarity index 96% rename from tests/test_senet.py rename to tests/networks/nets/test_senet.py index 6809d4562b..90d711d0d9 100644 --- a/tests/test_senet.py +++ b/tests/networks/nets/test_senet.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path from typing import TYPE_CHECKING from unittest import skipUnless @@ -23,7 +24,7 @@ from monai.networks import eval_mode from monai.networks.nets import SENet, SENet154, SEResNet50, SEResNet101, SEResNet152, SEResNext50, SEResNext101 from monai.utils import optional_import -from tests.utils import test_is_quick, test_pretrained_networks, test_script_save, testing_data_config +from tests.test_utils import test_is_quick, test_pretrained_networks, test_script_save, testing_data_config if TYPE_CHECKING: import pretrainedmodels @@ -58,7 +59,6 @@ class TestSENET(unittest.TestCase): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5, TEST_CASE_6, TEST_CASE_7]) def test_senet_shape(self, net, net_args): input_data = torch.randn(2, 2, 64, 64, 64).to(device) @@ -76,7 +76,6 @@ def test_script(self, net, net_args): class TestPretrainedSENET(unittest.TestCase): - def setUp(self): self.original_urls = se_mod.SE_NET_MODELS.copy() replace_url = test_is_quick() @@ -88,7 +87,7 @@ def setUp(self): if "certificate" in str(rt_e): # [SSL: CERTIFICATE_VERIFY_FAILED] replace_url = True if replace_url: - testing_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "testing_data") + testing_dir = Path(__file__).parents[2] / "testing_data" testing_data_urls = { "senet154": { "url": testing_data_config("models", "senet154-c7b49a05", "url"), diff --git a/tests/test_spade_autoencoderkl.py b/tests/networks/nets/test_spade_autoencoderkl.py similarity index 100% rename from tests/test_spade_autoencoderkl.py rename to tests/networks/nets/test_spade_autoencoderkl.py diff --git a/tests/test_spade_diffusion_model_unet.py b/tests/networks/nets/test_spade_diffusion_model_unet.py similarity index 100% rename from tests/test_spade_diffusion_model_unet.py rename to tests/networks/nets/test_spade_diffusion_model_unet.py diff --git a/tests/test_spade_vaegan.py b/tests/networks/nets/test_spade_vaegan.py similarity index 100% rename from tests/test_spade_vaegan.py rename to tests/networks/nets/test_spade_vaegan.py diff --git a/tests/test_swin_unetr.py b/tests/networks/nets/test_swin_unetr.py similarity index 99% rename from tests/test_swin_unetr.py rename to tests/networks/nets/test_swin_unetr.py index 5b33475c7e..4c506a2861 100644 --- a/tests/test_swin_unetr.py +++ b/tests/networks/nets/test_swin_unetr.py @@ -24,7 +24,7 @@ from monai.networks.nets.swin_unetr import PatchMerging, PatchMergingV2, SwinUNETR, filter_swinunetr from monai.networks.utils import copy_model_state from monai.utils import optional_import -from tests.utils import ( +from tests.test_utils import ( assert_allclose, pytorch_after, skip_if_downloading_fails, @@ -76,7 +76,6 @@ class TestSWINUNETR(unittest.TestCase): - @parameterized.expand(TEST_CASE_SWIN_UNETR) @skipUnless(has_einops, "Requires einops") def test_shape(self, input_param, input_shape, expected_shape): diff --git a/tests/test_torchvision_fc_model.py b/tests/networks/nets/test_torchvision_fc_model.py similarity index 99% rename from tests/test_torchvision_fc_model.py rename to tests/networks/nets/test_torchvision_fc_model.py index 9cc19db62c..7e03b4ebb9 100644 --- a/tests/test_torchvision_fc_model.py +++ b/tests/networks/nets/test_torchvision_fc_model.py @@ -21,7 +21,7 @@ from monai.networks.nets import TorchVisionFCModel, UNet from monai.networks.utils import look_up_named_module, set_named_module from monai.utils import min_version, optional_import -from tests.utils import skip_if_downloading_fails +from tests.test_utils import skip_if_downloading_fails Inception_V3_Weights, has_enum = optional_import("torchvision.models.inception", name="Inception_V3_Weights") @@ -153,7 +153,6 @@ class TestTorchVisionFCModel(unittest.TestCase): - @parameterized.expand( [TEST_CASE_0, TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5, TEST_CASE_6, TEST_CASE_7] + ([TEST_CASE_8] if has_enum else []) @@ -188,7 +187,6 @@ def test_with_pretrained(self, input_param, input_shape, expected_shape, expecte class TestLookup(unittest.TestCase): - def test_get_module(self): net = UNet(spatial_dims=2, in_channels=1, out_channels=1, channels=(4, 8, 16, 32, 64), strides=(2, 2, 2, 2)) self.assertEqual(look_up_named_module("", net), net) diff --git a/tests/test_transchex.py b/tests/networks/nets/test_transchex.py similarity index 98% rename from tests/test_transchex.py rename to tests/networks/nets/test_transchex.py index 481c20e285..f10c914f0d 100644 --- a/tests/test_transchex.py +++ b/tests/networks/nets/test_transchex.py @@ -18,7 +18,7 @@ from monai.networks import eval_mode from monai.networks.nets.transchex import Transchex -from tests.utils import skip_if_quick +from tests.test_utils import skip_if_quick TEST_CASE_TRANSCHEX = [] for drop_out in [0.4]: @@ -47,7 +47,6 @@ @skip_if_quick class TestTranschex(unittest.TestCase): - @parameterized.expand(TEST_CASE_TRANSCHEX) def test_shape(self, input_param, expected_shape): net = Transchex(**input_param) diff --git a/tests/test_transformer.py b/tests/networks/nets/test_transformer.py similarity index 98% rename from tests/test_transformer.py rename to tests/networks/nets/test_transformer.py index b371809d47..f9264ba153 100644 --- a/tests/test_transformer.py +++ b/tests/networks/nets/test_transformer.py @@ -24,7 +24,7 @@ from monai.networks import eval_mode from monai.networks.nets import DecoderOnlyTransformer from monai.utils import optional_import -from tests.utils import skip_if_downloading_fails, testing_data_config +from tests.test_utils import skip_if_downloading_fails, testing_data_config _, has_einops = optional_import("einops") TEST_CASES = [] @@ -68,7 +68,6 @@ def test_attention_dim_not_multiple_of_heads(self): @skipUnless(has_einops, "Requires einops") def test_dropout_rate_negative(self): - with self.assertRaises(ValueError): DecoderOnlyTransformer( num_tokens=10, diff --git a/tests/test_unet.py b/tests/networks/nets/test_unet.py similarity index 99% rename from tests/test_unet.py rename to tests/networks/nets/test_unet.py index 1fb98f84b0..7a6d0e98bb 100644 --- a/tests/test_unet.py +++ b/tests/networks/nets/test_unet.py @@ -19,7 +19,7 @@ from monai.networks import eval_mode from monai.networks.layers import Act, Norm from monai.networks.nets import UNet -from tests.utils import test_script_save +from tests.test_utils import test_script_save device = "cuda" if torch.cuda.is_available() else "cpu" @@ -165,7 +165,6 @@ class TestUNET(unittest.TestCase): - @parameterized.expand(CASES) def test_shape(self, input_param, input_shape, expected_shape): net = UNet(**input_param).to(device) diff --git a/tests/test_unetr.py b/tests/networks/nets/test_unetr.py similarity index 98% rename from tests/test_unetr.py rename to tests/networks/nets/test_unetr.py index 8c5ecb32e1..9e37750b4a 100644 --- a/tests/test_unetr.py +++ b/tests/networks/nets/test_unetr.py @@ -18,7 +18,7 @@ from monai.networks import eval_mode from monai.networks.nets.unetr import UNETR -from tests.utils import SkipIfBeforePyTorchVersion, skip_if_quick, test_script_save +from tests.test_utils import SkipIfBeforePyTorchVersion, skip_if_quick, test_script_save TEST_CASE_UNETR = [] for dropout_rate in [0.4]: @@ -57,7 +57,6 @@ @skip_if_quick class TestUNETR(unittest.TestCase): - @parameterized.expand(TEST_CASE_UNETR) def test_shape(self, input_param, input_shape, expected_shape): net = UNETR(**input_param) diff --git a/tests/test_varautoencoder.py b/tests/networks/nets/test_varautoencoder.py similarity index 98% rename from tests/test_varautoencoder.py rename to tests/networks/nets/test_varautoencoder.py index e957dcfb61..459c537c55 100644 --- a/tests/test_varautoencoder.py +++ b/tests/networks/nets/test_varautoencoder.py @@ -19,7 +19,7 @@ from monai.networks import eval_mode from monai.networks.layers import Act from monai.networks.nets import VarAutoEncoder -from tests.utils import test_script_save +from tests.test_utils import test_script_save device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") @@ -108,7 +108,6 @@ class TestVarAutoEncoder(unittest.TestCase): - @parameterized.expand(CASES) def test_shape(self, input_param, input_shape, expected_shape): net = VarAutoEncoder(**input_param).to(device) diff --git a/tests/test_vista3d.py b/tests/networks/nets/test_vista3d.py similarity index 97% rename from tests/test_vista3d.py rename to tests/networks/nets/test_vista3d.py index d3b4e0c10e..bdf424f69e 100644 --- a/tests/test_vista3d.py +++ b/tests/networks/nets/test_vista3d.py @@ -19,7 +19,7 @@ from monai.networks import eval_mode from monai.networks.nets import VISTA3D, SegResNetDS2 from monai.networks.nets.vista3d import ClassMappingClassify, PointMappingSAM -from tests.utils import SkipIfBeforePyTorchVersion, skip_if_quick +from tests.test_utils import SkipIfBeforePyTorchVersion, skip_if_quick device = "cuda" if torch.cuda.is_available() else "cpu" @@ -57,7 +57,6 @@ @SkipIfBeforePyTorchVersion((1, 11)) @skip_if_quick class TestVista3d(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_vista3d_shape(self, args, input_params, input_shape, expected_shape): segresnet = SegResNetDS2( diff --git a/tests/test_vit.py b/tests/networks/nets/test_vit.py similarity index 98% rename from tests/test_vit.py rename to tests/networks/nets/test_vit.py index a3ffd0b2ef..56b7807449 100644 --- a/tests/test_vit.py +++ b/tests/networks/nets/test_vit.py @@ -18,7 +18,7 @@ from monai.networks import eval_mode from monai.networks.nets.vit import ViT -from tests.utils import SkipIfBeforePyTorchVersion, skip_if_quick, test_script_save +from tests.test_utils import SkipIfBeforePyTorchVersion, skip_if_quick, test_script_save TEST_CASE_Vit = [] for dropout_rate in [0.6]: @@ -61,7 +61,6 @@ @skip_if_quick class TestViT(unittest.TestCase): - @parameterized.expand(TEST_CASE_Vit) def test_shape(self, input_param, input_shape, expected_shape): net = ViT(**input_param) diff --git a/tests/test_vitautoenc.py b/tests/networks/nets/test_vitautoenc.py similarity index 98% rename from tests/test_vitautoenc.py rename to tests/networks/nets/test_vitautoenc.py index 9a503948d0..97f144aa2d 100644 --- a/tests/test_vitautoenc.py +++ b/tests/networks/nets/test_vitautoenc.py @@ -17,7 +17,7 @@ from monai.networks import eval_mode from monai.networks.nets.vitautoenc import ViTAutoEnc -from tests.utils import skip_if_quick, skip_if_windows +from tests.test_utils import skip_if_quick, skip_if_windows TEST_CASE_Vitautoenc = [] for in_channels in [1, 4]: @@ -66,7 +66,6 @@ @skip_if_quick class TestVitAutoenc(unittest.TestCase): - def setUp(self): self.threads = torch.get_num_threads() torch.set_num_threads(4) diff --git a/tests/test_vnet.py b/tests/networks/nets/test_vnet.py similarity index 98% rename from tests/test_vnet.py rename to tests/networks/nets/test_vnet.py index 0ebf060434..6c93893480 100644 --- a/tests/test_vnet.py +++ b/tests/networks/nets/test_vnet.py @@ -18,7 +18,7 @@ from monai.networks import eval_mode from monai.networks.nets import VNet -from tests.utils import test_script_save +from tests.test_utils import test_script_save device = "cuda" if torch.cuda.is_available() else "cpu" @@ -55,7 +55,6 @@ class TestVNet(unittest.TestCase): - @parameterized.expand( [ TEST_CASE_VNET_2D_1, diff --git a/tests/test_voxelmorph.py b/tests/networks/nets/test_voxelmorph.py similarity index 99% rename from tests/test_voxelmorph.py rename to tests/networks/nets/test_voxelmorph.py index ef420ef20c..1a04bab568 100644 --- a/tests/test_voxelmorph.py +++ b/tests/networks/nets/test_voxelmorph.py @@ -18,7 +18,7 @@ from monai.networks import eval_mode from monai.networks.nets import VoxelMorph, VoxelMorphUNet -from tests.utils import test_script_save +from tests.test_utils import test_script_save device = "cuda" if torch.cuda.is_available() else "cpu" @@ -245,7 +245,6 @@ class TestVOXELMORPH(unittest.TestCase): - @parameterized.expand(CASES) def test_shape(self, input_param, input_shape, expected_shape): net = VoxelMorphUNet(**input_param).to(device) diff --git a/tests/test_vqvae.py b/tests/networks/nets/test_vqvae.py similarity index 99% rename from tests/test_vqvae.py rename to tests/networks/nets/test_vqvae.py index 4916dc2faa..624fb37930 100644 --- a/tests/test_vqvae.py +++ b/tests/networks/nets/test_vqvae.py @@ -18,7 +18,7 @@ from monai.networks import eval_mode from monai.networks.nets.vqvae import VQVAE -from tests.utils import SkipIfBeforePyTorchVersion +from tests.test_utils import SkipIfBeforePyTorchVersion TEST_CASES = [ [ diff --git a/tests/test_vqvaetransformer_inferer.py b/tests/networks/nets/test_vqvaetransformer_inferer.py similarity index 100% rename from tests/test_vqvaetransformer_inferer.py rename to tests/networks/nets/test_vqvaetransformer_inferer.py diff --git a/tests/networks/schedulers/__init__.py b/tests/networks/schedulers/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/networks/schedulers/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_scheduler_ddim.py b/tests/networks/schedulers/test_scheduler_ddim.py similarity index 98% rename from tests/test_scheduler_ddim.py rename to tests/networks/schedulers/test_scheduler_ddim.py index 1a8f8cab67..aa246c3ee1 100644 --- a/tests/test_scheduler_ddim.py +++ b/tests/networks/schedulers/test_scheduler_ddim.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.networks.schedulers import DDIMScheduler -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_2D_CASE = [] for beta_schedule in ["linear_beta", "scaled_linear_beta"]: diff --git a/tests/test_scheduler_ddpm.py b/tests/networks/schedulers/test_scheduler_ddpm.py similarity index 99% rename from tests/test_scheduler_ddpm.py rename to tests/networks/schedulers/test_scheduler_ddpm.py index f0447aded2..60ccde1439 100644 --- a/tests/test_scheduler_ddpm.py +++ b/tests/networks/schedulers/test_scheduler_ddpm.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.networks.schedulers import DDPMScheduler -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_2D_CASE = [] for beta_schedule in ["linear_beta", "scaled_linear_beta"]: diff --git a/tests/test_scheduler_pndm.py b/tests/networks/schedulers/test_scheduler_pndm.py similarity index 99% rename from tests/test_scheduler_pndm.py rename to tests/networks/schedulers/test_scheduler_pndm.py index 69e5e403f5..9f48e2e383 100644 --- a/tests/test_scheduler_pndm.py +++ b/tests/networks/schedulers/test_scheduler_pndm.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.networks.schedulers import PNDMScheduler -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_2D_CASE = [] for beta_schedule in ["linear_beta", "scaled_linear_beta"]: diff --git a/tests/test_bundle_onnx_export.py b/tests/networks/test_bundle_onnx_export.py similarity index 88% rename from tests/test_bundle_onnx_export.py rename to tests/networks/test_bundle_onnx_export.py index ee22d7caef..85f908c185 100644 --- a/tests/test_bundle_onnx_export.py +++ b/tests/networks/test_bundle_onnx_export.py @@ -14,12 +14,13 @@ import os import tempfile import unittest +from pathlib import Path from parameterized import parameterized from monai.bundle import ConfigParser from monai.networks import save_state -from tests.utils import SkipIfBeforePyTorchVersion, SkipIfNoModule, command_line_tests, skip_if_windows +from tests.test_utils import SkipIfBeforePyTorchVersion, SkipIfNoModule, command_line_tests, skip_if_windows TEST_CASE_1 = ["True"] TEST_CASE_2 = ["False"] @@ -29,7 +30,6 @@ @SkipIfNoModule("onnx") @SkipIfBeforePyTorchVersion((1, 10)) class TestONNXExport(unittest.TestCase): - def setUp(self): self.device = os.environ.get("CUDA_VISIBLE_DEVICES") if not self.device: @@ -43,8 +43,9 @@ def tearDown(self): @parameterized.expand([TEST_CASE_1, TEST_CASE_2]) def test_onnx_export(self, use_trace): - meta_file = os.path.join(os.path.dirname(__file__), "testing_data", "metadata.json") - config_file = os.path.join(os.path.dirname(__file__), "testing_data", "inference.json") + tests_path = Path(__file__).parents[1] + meta_file = os.path.join(tests_path, "testing_data", "metadata.json") + config_file = os.path.join(tests_path, "testing_data", "inference.json") with tempfile.TemporaryDirectory() as tempdir: def_args = {"meta_file": "will be replaced by `meta_file` arg"} def_args_file = os.path.join(tempdir, "def_args.yaml") diff --git a/tests/test_convert_to_onnx.py b/tests/networks/test_convert_to_onnx.py similarity index 97% rename from tests/test_convert_to_onnx.py rename to tests/networks/test_convert_to_onnx.py index 798c510800..743630c67d 100644 --- a/tests/test_convert_to_onnx.py +++ b/tests/networks/test_convert_to_onnx.py @@ -21,7 +21,7 @@ from monai.networks import convert_to_onnx from monai.networks.nets import SegResNet, UNet from monai.utils.module import pytorch_after -from tests.utils import SkipIfBeforePyTorchVersion, SkipIfNoModule, optional_import, skip_if_quick +from tests.test_utils import SkipIfBeforePyTorchVersion, SkipIfNoModule, optional_import, skip_if_quick if torch.cuda.is_available(): TORCH_DEVICE_OPTIONS = ["cpu", "cuda"] @@ -43,7 +43,6 @@ @SkipIfBeforePyTorchVersion((1, 9)) @skip_if_quick class TestConvertToOnnx(unittest.TestCase): - @parameterized.expand(TESTS) def test_unet(self, device, use_trace, use_ort): if use_ort: diff --git a/tests/test_convert_to_torchscript.py b/tests/networks/test_convert_to_torchscript.py similarity index 100% rename from tests/test_convert_to_torchscript.py rename to tests/networks/test_convert_to_torchscript.py diff --git a/tests/test_convert_to_trt.py b/tests/networks/test_convert_to_trt.py similarity index 95% rename from tests/test_convert_to_trt.py rename to tests/networks/test_convert_to_trt.py index a7b1edec3c..8d3dd9e648 100644 --- a/tests/test_convert_to_trt.py +++ b/tests/networks/test_convert_to_trt.py @@ -20,7 +20,7 @@ from monai.networks import convert_to_trt from monai.networks.nets import UNet from monai.utils import optional_import -from tests.utils import SkipIfBeforeComputeCapabilityVersion, skip_if_no_cuda, skip_if_quick, skip_if_windows +from tests.test_utils import SkipIfBeforeComputeCapabilityVersion, skip_if_no_cuda, skip_if_quick, skip_if_windows _, has_torchtrt = optional_import( "torch_tensorrt", @@ -40,7 +40,6 @@ @skip_if_quick @SkipIfBeforeComputeCapabilityVersion((7, 5)) class TestConvertToTRT(unittest.TestCase): - def setUp(self): self.gpu_device = torch.cuda.current_device() diff --git a/tests/test_save_state.py b/tests/networks/test_save_state.py similarity index 100% rename from tests/test_save_state.py rename to tests/networks/test_save_state.py diff --git a/tests/test_to_onehot.py b/tests/networks/test_to_onehot.py similarity index 100% rename from tests/test_to_onehot.py rename to tests/networks/test_to_onehot.py diff --git a/tests/test_varnet.py b/tests/networks/test_varnet.py similarity index 97% rename from tests/test_varnet.py rename to tests/networks/test_varnet.py index a46d58d6a2..23e2ff5a36 100644 --- a/tests/test_varnet.py +++ b/tests/networks/test_varnet.py @@ -20,7 +20,7 @@ from monai.apps.reconstruction.networks.nets.complex_unet import ComplexUnet from monai.apps.reconstruction.networks.nets.varnet import VariationalNetworkModel from monai.networks import eval_mode -from tests.utils import SkipIfBeforePyTorchVersion, test_script_save +from tests.test_utils import SkipIfBeforePyTorchVersion, test_script_save device = torch.device("cuda" if torch.cuda.is_available() else "cpu") coil_sens_model = CoilSensitivityModel(spatial_dims=2, features=[8, 16, 32, 64, 128, 8]) @@ -32,7 +32,6 @@ class TestVarNet(unittest.TestCase): - @parameterized.expand(TESTS) def test_shape(self, coil_sens_model, refinement_model, num_cascades, input_shape, expected_shape): net = VariationalNetworkModel(coil_sens_model, refinement_model, num_cascades).to(device) diff --git a/tests/networks/utils/__init__.py b/tests/networks/utils/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/networks/utils/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_copy_model_state.py b/tests/networks/utils/test_copy_model_state.py similarity index 100% rename from tests/test_copy_model_state.py rename to tests/networks/utils/test_copy_model_state.py diff --git a/tests/test_eval_mode.py b/tests/networks/utils/test_eval_mode.py similarity index 100% rename from tests/test_eval_mode.py rename to tests/networks/utils/test_eval_mode.py diff --git a/tests/test_freeze_layers.py b/tests/networks/utils/test_freeze_layers.py similarity index 95% rename from tests/test_freeze_layers.py rename to tests/networks/utils/test_freeze_layers.py index 7be8e576bf..46b2e461f8 100644 --- a/tests/test_freeze_layers.py +++ b/tests/networks/utils/test_freeze_layers.py @@ -18,7 +18,7 @@ from monai.networks.utils import freeze_layers from monai.utils import set_determinism -from tests.test_copy_model_state import _TestModelOne, _TestModelTwo +from tests.networks.utils.test_copy_model_state import _TestModelOne, _TestModelTwo TEST_CASES = [] __devices = ("cpu", "cuda") if torch.cuda.is_available() else ("cpu",) @@ -27,7 +27,6 @@ class TestModuleState(unittest.TestCase): - def tearDown(self): set_determinism(None) diff --git a/tests/test_replace_module.py b/tests/networks/utils/test_replace_module.py similarity index 99% rename from tests/test_replace_module.py rename to tests/networks/utils/test_replace_module.py index f3964ac65d..9c0752d1c5 100644 --- a/tests/test_replace_module.py +++ b/tests/networks/utils/test_replace_module.py @@ -18,7 +18,7 @@ from monai.networks.nets import DenseNet121 from monai.networks.utils import replace_modules, replace_modules_temp -from tests.utils import TEST_DEVICES +from tests.test_utils import TEST_DEVICES TESTS = [] for device in TEST_DEVICES: @@ -32,7 +32,6 @@ class TestReplaceModule(unittest.TestCase): - def setUp(self): self.net = DenseNet121(spatial_dims=2, in_channels=1, out_channels=3) self.num_relus = self.get_num_modules(torch.nn.ReLU) diff --git a/tests/test_train_mode.py b/tests/networks/utils/test_train_mode.py similarity index 100% rename from tests/test_train_mode.py rename to tests/networks/utils/test_train_mode.py diff --git a/tests/ngc_bundle_download.py b/tests/ngc_bundle_download.py index 107114861c..7953f6201b 100644 --- a/tests/ngc_bundle_download.py +++ b/tests/ngc_bundle_download.py @@ -24,7 +24,7 @@ from monai.bundle import download, load from monai.config import print_debug_info from monai.networks.utils import copy_model_state -from tests.utils import assert_allclose, skip_if_downloading_fails, skip_if_quick, skip_if_windows +from tests.test_utils import assert_allclose, skip_if_downloading_fails, skip_if_quick, skip_if_windows TEST_CASE_NGC_1 = [ "spleen_ct_segmentation", @@ -70,7 +70,6 @@ @skip_if_windows class TestNgcBundleDownload(unittest.TestCase): - @parameterized.expand([TEST_CASE_NGC_1, TEST_CASE_NGC_2]) @skip_if_quick def test_ngc_download_bundle(self, bundle_name, version, remove_prefix, download_name, file_path, hash_val): @@ -102,7 +101,6 @@ def test_ngc_download_bundle(self, bundle_name, version, remove_prefix, download @unittest.skip("deprecating mmar tests") class TestAllDownloadingMMAR(unittest.TestCase): - def setUp(self): print_debug_info() self.test_dir = "./" diff --git a/tests/optimizers/__init__.py b/tests/optimizers/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/optimizers/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_generate_param_groups.py b/tests/optimizers/test_generate_param_groups.py similarity index 98% rename from tests/test_generate_param_groups.py rename to tests/optimizers/test_generate_param_groups.py index a78dba9f03..58e743a7f6 100644 --- a/tests/test_generate_param_groups.py +++ b/tests/optimizers/test_generate_param_groups.py @@ -19,7 +19,7 @@ from monai.networks.nets import Unet from monai.optimizers import generate_param_groups from monai.utils import ensure_tuple -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_CASE_1 = [{"layer_matches": [lambda x: x.model[-1]], "match_types": "select", "lr_values": [1]}, (1, 100), [5, 21]] @@ -68,7 +68,6 @@ class TestGenerateParamGroups(unittest.TestCase): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5, TEST_CASE_6]) def test_lr_values(self, input_param, expected_values, expected_groups): device = "cuda" if torch.cuda.is_available() else "cpu" diff --git a/tests/test_lr_finder.py b/tests/optimizers/test_lr_finder.py similarity index 95% rename from tests/test_lr_finder.py rename to tests/optimizers/test_lr_finder.py index d26cb23a90..15edeeb367 100644 --- a/tests/test_lr_finder.py +++ b/tests/optimizers/test_lr_finder.py @@ -11,11 +11,11 @@ from __future__ import annotations -import os import pickle import random import sys import unittest +from pathlib import Path from typing import TYPE_CHECKING import torch @@ -27,7 +27,7 @@ from monai.transforms import Compose, EnsureChannelFirstd, LoadImaged, ScaleIntensityd, ToTensord from monai.utils import optional_import, set_determinism from monai.utils.misc import MONAIEnvVars -from tests.utils import skip_if_downloading_fails +from tests.test_utils import skip_if_downloading_fails if TYPE_CHECKING: import matplotlib.pyplot as plt @@ -48,11 +48,10 @@ @unittest.skipUnless(sys.platform == "linux", "requires linux") @unittest.skipUnless(has_pil, "requires PIL") class TestLRFinder(unittest.TestCase): - def setUp(self): self.root_dir = MONAIEnvVars.data_dir() if not self.root_dir: - self.root_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "testing_data") + self.root_dir = Path(__file__).parents[1] / "testing_data" self.transforms = Compose( [ diff --git a/tests/test_lr_scheduler.py b/tests/optimizers/test_lr_scheduler.py similarity index 100% rename from tests/test_lr_scheduler.py rename to tests/optimizers/test_lr_scheduler.py diff --git a/tests/test_optim_novograd.py b/tests/optimizers/test_optim_novograd.py similarity index 100% rename from tests/test_optim_novograd.py rename to tests/optimizers/test_optim_novograd.py diff --git a/tests/padders.py b/tests/padders.py index a7dce263bb..67ae9cef08 100644 --- a/tests/padders.py +++ b/tests/padders.py @@ -21,7 +21,7 @@ from monai.transforms.lazy.functional import apply_pending from monai.transforms.transform import MapTransform from monai.utils.enums import NumpyPadMode, PytorchPadMode -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose MODES = [] # Test modes @@ -51,7 +51,6 @@ class PadTest(unittest.TestCase): - @staticmethod def get_arr(shape): return np.random.randint(100, size=shape).astype(float) diff --git a/tests/profile_subclass/__init__.py b/tests/profile_subclass/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/profile_subclass/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/runner.py b/tests/runner.py index 385ca4256f..bb872ec032 100644 --- a/tests/runner.py +++ b/tests/runner.py @@ -12,13 +12,13 @@ from __future__ import annotations import argparse -import glob import inspect import os import re import sys import time import unittest +from pathlib import Path from monai.utils import PerfContext @@ -45,7 +45,7 @@ def stopTest(self, test): # noqa: N802 name = self.getDescription(test) self.stream.write(f"Finished test: {name} ({elapsed:.03}s)\n") if name in results: - raise AssertionError("expected all keys to be unique") + raise AssertionError(f"expected all keys to be unique, but {name} is duplicated") results[name] = elapsed super().stopTest(test) @@ -124,13 +124,20 @@ def get_default_pattern(loader): # Get all test names (optionally from some path with some pattern) with PerfContext() as pc: # the files are searched from `tests/` folder, starting with `test_` - files = glob.glob(os.path.join(os.path.dirname(__file__), "test_*.py")) + tests_path = Path(__file__).parent / args.path + files = { + file.relative_to(tests_path).as_posix() + for file in tests_path.rglob("test_*py") + if re.search(args.pattern, file.name) + } + print(files) cases = [] - for test_module in {os.path.basename(f)[:-3] for f in files}: - if re.match(args.pattern, test_module): - cases.append(f"tests.{test_module}") + for test_module in tests_path.rglob("test_*py"): + case_str = str(test_module.relative_to(tests_path).as_posix()).replace("/", ".")[:-3] + if case_str in files: + cases.append(f"tests.{case_str}") else: - print(f"monai test runner: excluding tests.{test_module}") + print(f"monai test runner: excluding {test_module.name}") print(cases) tests = unittest.TestLoader().loadTestsFromNames(cases) discovery_time = pc.total_time @@ -139,7 +146,6 @@ def get_default_pattern(loader): test_runner = unittest.runner.TextTestRunner( resultclass=TimeLoggingTestResult, verbosity=args.verbosity, failfast=args.failfast ) - # Use try catches to print the current results if encountering exception or keyboard interruption try: test_result = test_runner.run(tests) diff --git a/tests/test_auto3dseg.py b/tests/test_auto3dseg.py index 5273f0663a..6c0d8123d7 100644 --- a/tests/test_auto3dseg.py +++ b/tests/test_auto3dseg.py @@ -54,7 +54,7 @@ ToDeviced, ) from monai.utils.enums import DataStatsKeys -from tests.utils import skip_if_no_cuda +from tests.test_utils import skip_if_no_cuda device = "cpu" n_workers = 2 @@ -171,7 +171,6 @@ def __call__(self, data): class TestDataAnalyzer(unittest.TestCase): - def setUp(self): self.test_dir = tempfile.TemporaryDirectory() work_dir = self.test_dir.name diff --git a/tests/test_call_dist.py b/tests/test_call_dist.py index 503cb5e792..4d547906a4 100644 --- a/tests/test_call_dist.py +++ b/tests/test_call_dist.py @@ -13,11 +13,10 @@ import unittest -from tests.utils import DistCall, DistTestCase +from tests.test_utils import DistCall, DistTestCase class DistributedCallTest(DistTestCase): - def test_constructor(self): with self.assertRaises(ValueError): DistCall(nnodes=1, nproc_per_node=0) diff --git a/tests/test_masked_autoencoder_vit.py b/tests/test_masked_autoencoder_vit.py index f8f6977cc2..b649c1266c 100644 --- a/tests/test_masked_autoencoder_vit.py +++ b/tests/test_masked_autoencoder_vit.py @@ -18,7 +18,7 @@ from monai.networks import eval_mode from monai.networks.nets.masked_autoencoder_vit import MaskedAutoEncoderViT -from tests.utils import skip_if_quick +from tests.test_utils import skip_if_quick TEST_CASE_MaskedAutoEncoderViT = [] for masking_ratio in [0.5]: @@ -81,7 +81,6 @@ @skip_if_quick class TestMaskedAutoencoderViT(unittest.TestCase): - @parameterized.expand(TEST_CASE_MaskedAutoEncoderViT) def test_shape(self, input_param, input_shape, expected_shape): net = MaskedAutoEncoderViT(**input_param) diff --git a/tests/test_query_memory.py b/tests/test_query_memory.py index 77c34ede39..97e618e015 100644 --- a/tests/test_query_memory.py +++ b/tests/test_query_memory.py @@ -13,11 +13,10 @@ import unittest -from tests.utils import query_memory +from tests.test_utils import query_memory class TestQueryMemory(unittest.TestCase): - def test_output_str(self): self.assertTrue(isinstance(query_memory(2), str)) all_device = query_memory(-1) diff --git a/tests/test_rand_torchiod.py b/tests/test_rand_torchiod.py index 52bcf7c576..97282eb6ba 100644 --- a/tests/test_rand_torchiod.py +++ b/tests/test_rand_torchiod.py @@ -20,7 +20,7 @@ from monai.transforms import RandTorchIOd from monai.utils import optional_import, set_determinism -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose _, has_torchio = optional_import("torchio") @@ -31,7 +31,6 @@ @skipUnless(has_torchio, "Requires torchio") class TestRandTorchIOd(unittest.TestCase): - @parameterized.expand(TEST_PARAMS) def test_random_transform(self, input_param, input_data): set_determinism(seed=0) diff --git a/tests/test_set_visible_devices.py b/tests/test_set_visible_devices.py index b4f44957a2..f02f3f690f 100644 --- a/tests/test_set_visible_devices.py +++ b/tests/test_set_visible_devices.py @@ -14,11 +14,10 @@ import os import unittest -from tests.utils import SkipIfAtLeastPyTorchVersion, skip_if_no_cuda +from tests.test_utils import SkipIfAtLeastPyTorchVersion, skip_if_no_cuda class TestVisibleDevices(unittest.TestCase): - @staticmethod def run_process_and_get_exit_code(code_to_execute): value = os.system(code_to_execute) diff --git a/tests/test_timedcall_dist.py b/tests/test_timedcall_dist.py index a814a99b25..28b4ab9306 100644 --- a/tests/test_timedcall_dist.py +++ b/tests/test_timedcall_dist.py @@ -16,7 +16,7 @@ import time import unittest -from tests.utils import TimedCall +from tests.test_utils import TimedCall @TimedCall(seconds=20 if sys.platform == "linux" else 60, force_quit=False) @@ -50,7 +50,6 @@ def case_1_seconds_bad(arg=None): class TestTimedCall(unittest.TestCase): - def test_good_call(self): output = case_1_seconds() self.assertEqual(output, "good") diff --git a/tests/test_torchiod.py b/tests/test_torchiod.py index 892287461c..fadde6848c 100644 --- a/tests/test_torchiod.py +++ b/tests/test_torchiod.py @@ -19,7 +19,7 @@ from monai.transforms import TorchIOd from monai.utils import optional_import -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose _, has_torchio = optional_import("torchio") @@ -36,7 +36,6 @@ @skipUnless(has_torchio, "Requires torchio") class TestTorchIOd(unittest.TestCase): - @parameterized.expand(TEST_PARAMS) def test_value(self, input_param, input_data, expected_value): result = TorchIOd(**input_param)(input_data) diff --git a/tests/utils.py b/tests/test_utils.py similarity index 99% rename from tests/utils.py rename to tests/test_utils.py index 2a00af50e9..c494bb547c 100644 --- a/tests/utils.py +++ b/tests/test_utils.py @@ -30,6 +30,7 @@ import warnings from contextlib import contextmanager from functools import partial, reduce +from pathlib import Path from subprocess import PIPE, Popen from typing import Callable from urllib.error import ContentTooShortError, HTTPError @@ -58,11 +59,13 @@ _tf32_enabled = None _test_data_config: dict = {} +MODULE_PATH = Path(__file__).resolve().parents[1] + def testing_data_config(*keys): """get _test_data_config[keys0][keys1]...[keysN]""" if not _test_data_config: - with open(os.path.join(os.path.dirname(__file__), "testing_data", "data_config.json")) as c: + with open(f"{MODULE_PATH}/tests/testing_data/data_config.json") as c: _config = json.load(c) for k, v in _config.items(): _test_data_config[k] = v diff --git a/tests/testing_data/anatomical_label.nii.gz b/tests/testing_data/anatomical_label.nii.gz deleted file mode 100644 index a31ef9f7a4..0000000000 Binary files a/tests/testing_data/anatomical_label.nii.gz and /dev/null differ diff --git a/tests/testing_data/reoriented_anat_moved_label.nii.gz b/tests/testing_data/reoriented_anat_moved_label.nii.gz deleted file mode 100644 index 2d148d1999..0000000000 Binary files a/tests/testing_data/reoriented_anat_moved_label.nii.gz and /dev/null differ diff --git a/tests/transforms/__init__.py b/tests/transforms/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/transforms/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/transforms/compose/__init__.py b/tests/transforms/compose/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/transforms/compose/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_compose.py b/tests/transforms/compose/test_compose.py similarity index 100% rename from tests/test_compose.py rename to tests/transforms/compose/test_compose.py diff --git a/tests/test_some_of.py b/tests/transforms/compose/test_some_of.py similarity index 98% rename from tests/test_some_of.py rename to tests/transforms/compose/test_some_of.py index 3723732d51..7eda815d37 100644 --- a/tests/test_some_of.py +++ b/tests/transforms/compose/test_some_of.py @@ -26,8 +26,8 @@ from monai.transforms.compose import Compose, SomeOf from monai.utils import set_determinism from monai.utils.enums import TraceKeys -from tests.test_one_of import NonInv -from tests.test_random_order import InvC, InvD +from tests.integration.test_one_of import NonInv +from tests.transforms.test_random_order import InvC, InvD class A(Transform): diff --git a/tests/transforms/croppad/__init__.py b/tests/transforms/croppad/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/transforms/croppad/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_rand_weighted_crop.py b/tests/transforms/croppad/test_rand_weighted_crop.py similarity index 98% rename from tests/test_rand_weighted_crop.py rename to tests/transforms/croppad/test_rand_weighted_crop.py index f509065a56..9d20faacb5 100644 --- a/tests/test_rand_weighted_crop.py +++ b/tests/transforms/croppad/test_rand_weighted_crop.py @@ -20,7 +20,7 @@ from monai.transforms.croppad.array import RandWeightedCrop from monai.transforms.lazy.functional import apply_pending from tests.croppers import CropTest -from tests.utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, NumpyImageTestCase3D, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, NumpyImageTestCase3D, assert_allclose def get_data(ndim): diff --git a/tests/test_rand_weighted_cropd.py b/tests/transforms/croppad/test_rand_weighted_cropd.py similarity index 98% rename from tests/test_rand_weighted_cropd.py rename to tests/transforms/croppad/test_rand_weighted_cropd.py index a1414df0ac..4fe0e1140a 100644 --- a/tests/test_rand_weighted_cropd.py +++ b/tests/transforms/croppad/test_rand_weighted_cropd.py @@ -19,7 +19,7 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms.croppad.dictionary import RandWeightedCropd from monai.transforms.lazy.functional import apply_pending -from tests.utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, NumpyImageTestCase3D, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, NumpyImageTestCase3D, assert_allclose def get_data(ndim): @@ -148,7 +148,6 @@ def get_data(ndim): class TestRandWeightedCrop(unittest.TestCase): - @parameterized.expand(TESTS) def test_rand_weighted_cropd(self, _, init_params, input_data, expected_shape, expected_centers): crop = RandWeightedCropd(**init_params) diff --git a/tests/transforms/functional/__init__.py b/tests/transforms/functional/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/transforms/functional/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_apply.py b/tests/transforms/functional/test_apply.py similarity index 98% rename from tests/test_apply.py rename to tests/transforms/functional/test_apply.py index ca37e945ba..c7a0678af6 100644 --- a/tests/test_apply.py +++ b/tests/transforms/functional/test_apply.py @@ -19,7 +19,7 @@ from monai.transforms.lazy.functional import apply_pending from monai.transforms.utils import create_rotate from monai.utils import LazyAttr, convert_to_tensor -from tests.utils import get_arange_img +from tests.test_utils import get_arange_img def single_2d_transform_cases(): @@ -39,7 +39,6 @@ def single_2d_transform_cases(): class TestApply(unittest.TestCase): - def _test_apply_impl(self, tensor, pending_transforms, expected_shape): result = apply_pending(tensor, pending_transforms) self.assertListEqual(result[1], pending_transforms) diff --git a/tests/test_resample.py b/tests/transforms/functional/test_resample.py similarity index 96% rename from tests/test_resample.py rename to tests/transforms/functional/test_resample.py index 68b08b8b87..40d264598d 100644 --- a/tests/test_resample.py +++ b/tests/transforms/functional/test_resample.py @@ -18,7 +18,7 @@ from monai.transforms.lazy.functional import resample from monai.utils import convert_to_tensor -from tests.utils import assert_allclose, get_arange_img +from tests.test_utils import assert_allclose, get_arange_img def rotate_90_2d(): @@ -35,7 +35,6 @@ def rotate_90_2d(): class TestResampleFunction(unittest.TestCase): - @parameterized.expand(RESAMPLE_FUNCTION_CASES) def test_resample_function_impl(self, img, matrix, expected): out = resample(convert_to_tensor(img), matrix, {"lazy_shape": img.shape[1:], "lazy_padding_mode": "border"}) diff --git a/tests/transforms/intensity/__init__.py b/tests/transforms/intensity/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/transforms/intensity/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_compute_ho_ver_maps.py b/tests/transforms/intensity/test_compute_ho_ver_maps.py similarity index 97% rename from tests/test_compute_ho_ver_maps.py rename to tests/transforms/intensity/test_compute_ho_ver_maps.py index 6e46cf2b1e..046299b63d 100644 --- a/tests/test_compute_ho_ver_maps.py +++ b/tests/transforms/intensity/test_compute_ho_ver_maps.py @@ -19,7 +19,7 @@ from monai.transforms.intensity.array import ComputeHoVerMaps from monai.utils import min_version, optional_import -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose _, has_skimage = optional_import("skimage", "0.19.0", min_version) @@ -62,7 +62,6 @@ @unittest.skipUnless(has_skimage, "Requires scikit-image library.") class ComputeHoVerMapsTests(unittest.TestCase): - @parameterized.expand(TESTS) def test_horizontal_certical_maps(self, in_type, arguments, mask, hv_mask): input_image = in_type(mask) diff --git a/tests/test_compute_ho_ver_maps_d.py b/tests/transforms/intensity/test_compute_ho_ver_maps_d.py similarity index 97% rename from tests/test_compute_ho_ver_maps_d.py rename to tests/transforms/intensity/test_compute_ho_ver_maps_d.py index 0734e2e731..b35a574c28 100644 --- a/tests/test_compute_ho_ver_maps_d.py +++ b/tests/transforms/intensity/test_compute_ho_ver_maps_d.py @@ -19,7 +19,7 @@ from monai.transforms.intensity.dictionary import ComputeHoVerMapsd from monai.utils import min_version, optional_import -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose _, has_skimage = optional_import("skimage", "0.19.0", min_version) @@ -63,7 +63,6 @@ @unittest.skipUnless(has_skimage, "Requires scikit-image library.") class ComputeHoVerMapsDictTests(unittest.TestCase): - @parameterized.expand(TESTS) def test_horizontal_certical_maps(self, in_type, arguments, mask, hv_mask): hv_key = list(hv_mask.keys())[0] diff --git a/tests/test_foreground_mask.py b/tests/transforms/intensity/test_foreground_mask.py similarity index 98% rename from tests/test_foreground_mask.py rename to tests/transforms/intensity/test_foreground_mask.py index 1aa54f4d3a..67543c832e 100644 --- a/tests/test_foreground_mask.py +++ b/tests/transforms/intensity/test_foreground_mask.py @@ -18,7 +18,7 @@ from monai.transforms.intensity.array import ForegroundMask from monai.utils import min_version, optional_import, set_determinism -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose skimage, has_skimage = optional_import("skimage", "0.19.0", min_version) set_determinism(1234) @@ -81,7 +81,6 @@ @unittest.skipUnless(has_skimage, "Requires sci-kit image") class TestForegroundMask(unittest.TestCase): - @parameterized.expand(TESTS) def test_foreground_mask(self, in_type, arguments, image, mask): input_image = in_type(image) diff --git a/tests/test_foreground_maskd.py b/tests/transforms/intensity/test_foreground_maskd.py similarity index 98% rename from tests/test_foreground_maskd.py rename to tests/transforms/intensity/test_foreground_maskd.py index dc7b6cfb24..888dd55b05 100644 --- a/tests/test_foreground_maskd.py +++ b/tests/transforms/intensity/test_foreground_maskd.py @@ -18,7 +18,7 @@ from monai.transforms.intensity.dictionary import ForegroundMaskd from monai.utils import min_version, optional_import, set_determinism -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose skimage, has_skimage = optional_import("skimage", "0.19.0", min_version) set_determinism(1234) @@ -89,7 +89,6 @@ @unittest.skipUnless(has_skimage, "Requires sci-kit image") class TestForegroundMaskd(unittest.TestCase): - @parameterized.expand(TESTS) def test_foreground_mask(self, in_type, arguments, data_dict, mask): data_dict[arguments["keys"]] = in_type(data_dict[arguments["keys"]]) diff --git a/tests/test_rand_histogram_shiftd.py b/tests/transforms/intensity/test_rand_histogram_shiftd.py similarity index 97% rename from tests/test_rand_histogram_shiftd.py rename to tests/transforms/intensity/test_rand_histogram_shiftd.py index fced270e90..75aafa7f08 100644 --- a/tests/test_rand_histogram_shiftd.py +++ b/tests/transforms/intensity/test_rand_histogram_shiftd.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms.intensity.dictionary import RandHistogramShiftd -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -61,7 +61,6 @@ class TestRandHistogramShiftD(unittest.TestCase): - @parameterized.expand(TESTS) def test_rand_histogram_shiftd(self, input_param, input_data, expected_val): g = RandHistogramShiftd(**input_param) diff --git a/tests/test_scale_intensity_range_percentiles.py b/tests/transforms/intensity/test_scale_intensity_range_percentiles.py similarity index 97% rename from tests/test_scale_intensity_range_percentiles.py rename to tests/transforms/intensity/test_scale_intensity_range_percentiles.py index a7390efe72..20fe59246b 100644 --- a/tests/test_scale_intensity_range_percentiles.py +++ b/tests/transforms/intensity/test_scale_intensity_range_percentiles.py @@ -17,11 +17,10 @@ import torch from monai.transforms.intensity.array import ScaleIntensityRangePercentiles -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class TestScaleIntensityRangePercentiles(NumpyImageTestCase2D): - def test_scaling(self): img = self.imt[0] lower = 10 diff --git a/tests/test_scale_intensity_range_percentilesd.py b/tests/transforms/intensity/test_scale_intensity_range_percentilesd.py similarity index 97% rename from tests/test_scale_intensity_range_percentilesd.py rename to tests/transforms/intensity/test_scale_intensity_range_percentilesd.py index ab0347fbbf..8e152d62ed 100644 --- a/tests/test_scale_intensity_range_percentilesd.py +++ b/tests/transforms/intensity/test_scale_intensity_range_percentilesd.py @@ -16,11 +16,10 @@ import numpy as np from monai.transforms.intensity.dictionary import ScaleIntensityRangePercentilesd -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class TestScaleIntensityRangePercentilesd(NumpyImageTestCase2D): - def test_scaling(self): img = self.imt lower = 10 diff --git a/tests/transforms/inverse/__init__.py b/tests/transforms/inverse/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/transforms/inverse/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_inverse_array.py b/tests/transforms/inverse/test_inverse_array.py similarity index 98% rename from tests/test_inverse_array.py rename to tests/transforms/inverse/test_inverse_array.py index 4da9ee34b9..3c5539bb96 100644 --- a/tests/test_inverse_array.py +++ b/tests/transforms/inverse/test_inverse_array.py @@ -20,7 +20,7 @@ from monai.transforms import Compose, EnsureChannelFirst, Flip, Orientation, Spacing from monai.transforms.inverse import InvertibleTransform from monai.utils import optional_import -from tests.utils import TEST_DEVICES +from tests.test_utils import TEST_DEVICES _, has_nib = optional_import("nibabel") @@ -33,7 +33,6 @@ @unittest.skipUnless(has_nib, "Requires nibabel") class TestInverseArray(unittest.TestCase): - @staticmethod def get_image(dtype, device) -> MetaTensor: affine = torch.tensor([[0, 0, 1, 0], [-1, 0, 0, 0], [0, 10, 0, 0], [0, 0, 0, 1]]).to(dtype).to(device) diff --git a/tests/test_traceable_transform.py b/tests/transforms/inverse/test_traceable_transform.py similarity index 100% rename from tests/test_traceable_transform.py rename to tests/transforms/inverse/test_traceable_transform.py diff --git a/tests/transforms/post/__init__.py b/tests/transforms/post/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/transforms/post/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_label_filterd.py b/tests/transforms/post/test_label_filterd.py similarity index 97% rename from tests/test_label_filterd.py rename to tests/transforms/post/test_label_filterd.py index fba8100f25..b2b575f9d2 100644 --- a/tests/test_label_filterd.py +++ b/tests/transforms/post/test_label_filterd.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms.post.dictionary import LabelFilterd -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose grid_1 = torch.tensor([[[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]]) @@ -58,7 +58,6 @@ class TestLabelFilter(unittest.TestCase): - @parameterized.expand(VALID_TESTS) def test_correct_results(self, _, args, input_image, expected): converter = LabelFilterd(keys="image", **args) diff --git a/tests/test_probnms.py b/tests/transforms/post/test_probnms.py similarity index 97% rename from tests/test_probnms.py rename to tests/transforms/post/test_probnms.py index 2b52583ad4..4e7cebe0e8 100644 --- a/tests/test_probnms.py +++ b/tests/transforms/post/test_probnms.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms.post.array import ProbNMS -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -61,7 +61,6 @@ class TestProbNMS(unittest.TestCase): - @parameterized.expand(TESTS) def test_output(self, class_args, probs_map, expected): nms = ProbNMS(**class_args) diff --git a/tests/test_probnmsd.py b/tests/transforms/post/test_probnmsd.py similarity index 98% rename from tests/test_probnmsd.py rename to tests/transforms/post/test_probnmsd.py index aeb32bdb79..8f18ad9788 100644 --- a/tests/test_probnmsd.py +++ b/tests/transforms/post/test_probnmsd.py @@ -19,7 +19,7 @@ from parameterized import parameterized from monai.transforms.post.dictionary import ProbNMSD -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS TESTS: list[Any] = [] for p in TEST_NDARRAYS: @@ -68,7 +68,6 @@ class TestProbNMS(unittest.TestCase): - @parameterized.expand(TESTS) def test_output(self, class_args, probs_map, expected): nms = ProbNMSD(keys="prob_map", **class_args) diff --git a/tests/test_remove_small_objects.py b/tests/transforms/post/test_remove_small_objects.py similarity index 98% rename from tests/test_remove_small_objects.py rename to tests/transforms/post/test_remove_small_objects.py index 633a6d9a99..c0d8f59be7 100644 --- a/tests/test_remove_small_objects.py +++ b/tests/transforms/post/test_remove_small_objects.py @@ -21,7 +21,7 @@ from monai.transforms.post.array import RemoveSmallObjects from monai.transforms.post.dictionary import RemoveSmallObjectsd from monai.utils import optional_import -from tests.utils import TEST_NDARRAYS, SkipIfNoModule, assert_allclose +from tests.test_utils import TEST_NDARRAYS, SkipIfNoModule, assert_allclose morphology, has_morphology = optional_import("skimage.morphology") @@ -55,7 +55,6 @@ @SkipIfNoModule("skimage.morphology") class TestRemoveSmallObjects(unittest.TestCase): - @parameterized.expand(TESTS) def test_remove_small_objects(self, dtype, im_type, lbl, expected, params=None): params = params or {} diff --git a/tests/transforms/spatial/__init__.py b/tests/transforms/spatial/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/transforms/spatial/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_convert_box_points.py b/tests/transforms/spatial/test_convert_box_points.py similarity index 98% rename from tests/test_convert_box_points.py rename to tests/transforms/spatial/test_convert_box_points.py index 5e3d7ee645..a3ef68962b 100644 --- a/tests/test_convert_box_points.py +++ b/tests/transforms/spatial/test_convert_box_points.py @@ -18,7 +18,7 @@ from monai.data.box_utils import convert_box_to_standard_mode from monai.transforms.spatial.array import ConvertBoxToPoints, ConvertPointsToBoxes -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_CASE_POINTS_2D = [ [ @@ -99,7 +99,6 @@ class TestConvertBoxToPoints(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_convert_box_to_points(self, boxes, mode, expected_points): transform = ConvertBoxToPoints(mode=mode) @@ -108,7 +107,6 @@ def test_convert_box_to_points(self, boxes, mode, expected_points): class TestConvertPointsToBoxes(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_convert_box_to_points(self, boxes, mode, points): transform = ConvertPointsToBoxes() diff --git a/tests/test_grid_patch.py b/tests/transforms/spatial/test_grid_patch.py similarity index 98% rename from tests/test_grid_patch.py rename to tests/transforms/spatial/test_grid_patch.py index 56af123548..f6edea4d54 100644 --- a/tests/test_grid_patch.py +++ b/tests/transforms/spatial/test_grid_patch.py @@ -19,7 +19,7 @@ from monai.data import MetaTensor, set_track_meta from monai.transforms.spatial.array import GridPatch -from tests.utils import TEST_NDARRAYS, SkipIfBeforePyTorchVersion, assert_allclose +from tests.test_utils import TEST_NDARRAYS, SkipIfBeforePyTorchVersion, assert_allclose A = np.arange(16).repeat(3).reshape(4, 4, 3).transpose(2, 0, 1) A11 = A[:, :2, :2] @@ -97,7 +97,6 @@ class TestGridPatch(unittest.TestCase): - @parameterized.expand(TEST_CASES) @SkipIfBeforePyTorchVersion((1, 11, 1)) def test_grid_patch(self, in_type, input_parameters, image, expected): diff --git a/tests/test_grid_patchd.py b/tests/transforms/spatial/test_grid_patchd.py similarity index 98% rename from tests/test_grid_patchd.py rename to tests/transforms/spatial/test_grid_patchd.py index 53313b3a8f..859a5a3890 100644 --- a/tests/test_grid_patchd.py +++ b/tests/transforms/spatial/test_grid_patchd.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms.spatial.dictionary import GridPatchd -from tests.utils import TEST_NDARRAYS, SkipIfBeforePyTorchVersion, assert_allclose +from tests.test_utils import TEST_NDARRAYS, SkipIfBeforePyTorchVersion, assert_allclose A = np.arange(16).repeat(3).reshape(4, 4, 3).transpose(2, 0, 1) A11 = A[:, :2, :2] @@ -77,7 +77,6 @@ class TestGridPatchd(unittest.TestCase): - @parameterized.expand(TEST_SINGLE) @SkipIfBeforePyTorchVersion((1, 11, 1)) def test_grid_patchd(self, in_type, input_parameters, image_dict, expected): diff --git a/tests/test_rand_grid_patch.py b/tests/transforms/spatial/test_rand_grid_patch.py similarity index 98% rename from tests/test_rand_grid_patch.py rename to tests/transforms/spatial/test_rand_grid_patch.py index 26863f01b2..b148f46c97 100644 --- a/tests/test_rand_grid_patch.py +++ b/tests/transforms/spatial/test_rand_grid_patch.py @@ -20,7 +20,7 @@ from monai.data import MetaTensor, set_track_meta from monai.transforms.spatial.array import RandGridPatch from monai.utils import set_determinism -from tests.utils import TEST_NDARRAYS, SkipIfBeforePyTorchVersion, assert_allclose +from tests.test_utils import TEST_NDARRAYS, SkipIfBeforePyTorchVersion, assert_allclose A = np.arange(16).repeat(3).reshape(4, 4, 3).transpose(2, 0, 1) A11 = A[:, :2, :2] @@ -105,7 +105,6 @@ class TestRandGridPatch(unittest.TestCase): - def setUp(self): set_determinism(seed=1234) diff --git a/tests/test_rand_grid_patchd.py b/tests/transforms/spatial/test_rand_grid_patchd.py similarity index 98% rename from tests/test_rand_grid_patchd.py rename to tests/transforms/spatial/test_rand_grid_patchd.py index 031e834512..b9e9589e6d 100644 --- a/tests/test_rand_grid_patchd.py +++ b/tests/transforms/spatial/test_rand_grid_patchd.py @@ -19,7 +19,7 @@ from monai.transforms.spatial.dictionary import RandGridPatchd from monai.utils import set_determinism -from tests.utils import TEST_NDARRAYS, SkipIfBeforePyTorchVersion, assert_allclose +from tests.test_utils import TEST_NDARRAYS, SkipIfBeforePyTorchVersion, assert_allclose A = np.arange(16).repeat(3).reshape(4, 4, 3).transpose(2, 0, 1) A11 = A[:, :2, :2] @@ -85,7 +85,6 @@ class TestRandGridPatchd(unittest.TestCase): - def setUp(self): set_determinism(seed=1234) diff --git a/tests/test_spatial_resampled.py b/tests/transforms/spatial/test_spatial_resampled.py similarity index 98% rename from tests/test_spatial_resampled.py rename to tests/transforms/spatial/test_spatial_resampled.py index d5c86258d7..12d54cabfc 100644 --- a/tests/test_spatial_resampled.py +++ b/tests/transforms/spatial/test_spatial_resampled.py @@ -22,7 +22,7 @@ from monai.data.utils import to_affine_nd from monai.transforms.spatial.dictionary import SpatialResampled from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_DEVICES, assert_allclose +from tests.test_utils import TEST_DEVICES, assert_allclose ON_AARCH64 = platform.machine() == "aarch64" if ON_AARCH64: @@ -94,7 +94,6 @@ class TestSpatialResample(unittest.TestCase): - @parameterized.expand(TESTS) def test_flips_inverse(self, img, device, dst_affine, kwargs, expected_output): img = MetaTensor(img, affine=torch.eye(4)).to(device) diff --git a/tests/test_activations.py b/tests/transforms/test_activations.py similarity index 98% rename from tests/test_activations.py rename to tests/transforms/test_activations.py index ad18e2bbec..1a7740e77a 100644 --- a/tests/test_activations.py +++ b/tests/transforms/test_activations.py @@ -18,7 +18,7 @@ from monai.networks.layers.factories import Act from monai.transforms import Activations -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TEST_CASES = [] for p in TEST_NDARRAYS: @@ -94,7 +94,6 @@ class TestActivations(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_value_shape(self, input_param, img, out, expected_shape): result = Activations(**input_param)(img) diff --git a/tests/test_activationsd.py b/tests/transforms/test_activationsd.py similarity index 97% rename from tests/test_activationsd.py rename to tests/transforms/test_activationsd.py index 74968c0bb4..b272f5f4ce 100644 --- a/tests/test_activationsd.py +++ b/tests/transforms/test_activationsd.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import Activationsd -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TEST_CASES = [] for p in TEST_NDARRAYS: @@ -50,7 +50,6 @@ class TestActivationsd(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_value_shape(self, input_param, test_input, output, expected_shape): result = Activationsd(**input_param)(test_input) diff --git a/tests/test_adaptors.py b/tests/transforms/test_adaptors.py similarity index 100% rename from tests/test_adaptors.py rename to tests/transforms/test_adaptors.py diff --git a/tests/test_add_coordinate_channels.py b/tests/transforms/test_add_coordinate_channels.py similarity index 97% rename from tests/test_add_coordinate_channels.py rename to tests/transforms/test_add_coordinate_channels.py index 199fe071e3..9a0e0dcd35 100644 --- a/tests/test_add_coordinate_channels.py +++ b/tests/transforms/test_add_coordinate_channels.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms import AddCoordinateChannels -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS, TEST_CASES_ERROR_1, TEST_CASES_ERROR_2 = [], [], [] for p in TEST_NDARRAYS: @@ -29,7 +29,6 @@ class TestAddCoordinateChannels(unittest.TestCase): - @parameterized.expand(TESTS) def test_shape(self, input_param, input, expected_shape): result = AddCoordinateChannels(**input_param)(input) diff --git a/tests/test_add_coordinate_channelsd.py b/tests/transforms/test_add_coordinate_channelsd.py similarity index 97% rename from tests/test_add_coordinate_channelsd.py rename to tests/transforms/test_add_coordinate_channelsd.py index c00240c2d5..4cc35142ef 100644 --- a/tests/test_add_coordinate_channelsd.py +++ b/tests/transforms/test_add_coordinate_channelsd.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms import AddCoordinateChannelsd -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS, TEST_CASES_ERROR_1, TEST_CASES_ERROR_2 = [], [], [] for p in TEST_NDARRAYS: @@ -42,7 +42,6 @@ class TestAddCoordinateChannels(unittest.TestCase): - @parameterized.expand(TESTS) def test_shape(self, input_param, input, expected_shape): result = AddCoordinateChannelsd(**input_param)(input)["img"] diff --git a/tests/test_add_extreme_points_channel.py b/tests/transforms/test_add_extreme_points_channel.py similarity index 97% rename from tests/test_add_extreme_points_channel.py rename to tests/transforms/test_add_extreme_points_channel.py index c453322d6b..5a405efd63 100644 --- a/tests/test_add_extreme_points_channel.py +++ b/tests/transforms/test_add_extreme_points_channel.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import AddExtremePointsChannel -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose IMG_CHANNEL = 3 TESTS = [] @@ -69,7 +69,6 @@ class TestAddExtremePointsChannel(unittest.TestCase): - @parameterized.expand(TESTS) def test_correct_results(self, input_data, expected): add_extreme_points_channel = AddExtremePointsChannel() diff --git a/tests/test_add_extreme_points_channeld.py b/tests/transforms/test_add_extreme_points_channeld.py similarity index 97% rename from tests/test_add_extreme_points_channeld.py rename to tests/transforms/test_add_extreme_points_channeld.py index 026f71200a..b11498385c 100644 --- a/tests/test_add_extreme_points_channeld.py +++ b/tests/transforms/test_add_extreme_points_channeld.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import AddExtremePointsChanneld -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose IMG_CHANNEL = 3 @@ -64,7 +64,6 @@ class TestAddExtremePointsChanneld(unittest.TestCase): - @parameterized.expand(TESTS) def test_correct_results(self, input_data, expected): add_extreme_points_channel = AddExtremePointsChanneld( diff --git a/tests/test_adjust_contrast.py b/tests/transforms/test_adjust_contrast.py similarity index 96% rename from tests/test_adjust_contrast.py rename to tests/transforms/test_adjust_contrast.py index 2236056558..3ea7074206 100644 --- a/tests/test_adjust_contrast.py +++ b/tests/transforms/test_adjust_contrast.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import AdjustContrast -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose TESTS = [] for invert_image in (True, False): @@ -30,7 +30,6 @@ class TestAdjustContrast(NumpyImageTestCase2D): - @parameterized.expand(TESTS) def test_correct_results(self, gamma, invert_image, retain_stats): adjuster = AdjustContrast(gamma=gamma, invert_image=invert_image, retain_stats=retain_stats) diff --git a/tests/test_adjust_contrastd.py b/tests/transforms/test_adjust_contrastd.py similarity index 96% rename from tests/test_adjust_contrastd.py rename to tests/transforms/test_adjust_contrastd.py index 38eb001226..16317b3ec3 100644 --- a/tests/test_adjust_contrastd.py +++ b/tests/transforms/test_adjust_contrastd.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import AdjustContrastd -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose TESTS = [] for invert_image in (True, False): @@ -30,7 +30,6 @@ class TestAdjustContrastd(NumpyImageTestCase2D): - @parameterized.expand(TESTS) def test_correct_results(self, gamma, invert_image, retain_stats): adjuster = AdjustContrastd("img", gamma=gamma, invert_image=invert_image, retain_stats=retain_stats) diff --git a/tests/test_affine.py b/tests/transforms/test_affine.py similarity index 99% rename from tests/test_affine.py rename to tests/transforms/test_affine.py index a08a22ae6f..90fb77e0ef 100644 --- a/tests/test_affine.py +++ b/tests/transforms/test_affine.py @@ -23,7 +23,7 @@ from monai.transforms.lazy.functional import apply_pending from monai.utils import optional_import from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose, test_local_inversion +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose, test_local_inversion TESTS = [] for p in TEST_NDARRAYS_ALL: @@ -167,7 +167,6 @@ class TestAffine(unittest.TestCase): - @parameterized.expand(TESTS) def test_affine(self, input_param, input_data, expected_val): input_copy = deepcopy(input_data["img"]) @@ -200,7 +199,6 @@ def test_affine(self, input_param, input_data, expected_val): @unittest.skipUnless(optional_import("scipy")[1], "Requires scipy library.") class TestAffineConsistency(unittest.TestCase): - @parameterized.expand([[7], [8], [9]]) def test_affine_resize(self, s): """s""" diff --git a/tests/test_affine_grid.py b/tests/transforms/test_affine_grid.py similarity index 98% rename from tests/test_affine_grid.py rename to tests/transforms/test_affine_grid.py index 2d89725bb7..0cb8e35d1f 100644 --- a/tests/test_affine_grid.py +++ b/tests/transforms/test_affine_grid.py @@ -19,7 +19,7 @@ from monai.data import MetaTensor, set_track_meta from monai.transforms import AffineGrid -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose, is_tf32_env +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose, is_tf32_env TESTS = [] for p in TEST_NDARRAYS_ALL: @@ -135,7 +135,6 @@ class TestAffineGrid(unittest.TestCase): - @parameterized.expand(TESTS) def test_affine_grid(self, input_param, input_data, expected_val): g = AffineGrid(**input_param) diff --git a/tests/test_affined.py b/tests/transforms/test_affined.py similarity index 98% rename from tests/test_affined.py rename to tests/transforms/test_affined.py index 94903ff8c7..05f918c728 100644 --- a/tests/test_affined.py +++ b/tests/transforms/test_affined.py @@ -20,7 +20,7 @@ from monai.transforms import Affined from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose, test_local_inversion +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose, test_local_inversion TESTS = [] for p in TEST_NDARRAYS_ALL: @@ -168,7 +168,6 @@ class TestAffined(unittest.TestCase): - @parameterized.expand(TESTS) def test_affine(self, input_param, input_data, expected_val): input_copy = deepcopy(input_data) diff --git a/tests/test_as_channel_last.py b/tests/transforms/test_as_channel_last.py similarity index 96% rename from tests/test_as_channel_last.py rename to tests/transforms/test_as_channel_last.py index 51e1a5c0fd..11bd688dae 100644 --- a/tests/test_as_channel_last.py +++ b/tests/transforms/test_as_channel_last.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import AsChannelLast -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS TESTS = [] for p in TEST_NDARRAYS: @@ -27,7 +27,6 @@ class TestAsChannelLast(unittest.TestCase): - @parameterized.expand(TESTS) def test_shape(self, in_type, input_param, expected_shape): test_data = in_type(np.random.randint(0, 2, size=[1, 2, 3, 4])) diff --git a/tests/test_as_channel_lastd.py b/tests/transforms/test_as_channel_lastd.py similarity index 97% rename from tests/test_as_channel_lastd.py rename to tests/transforms/test_as_channel_lastd.py index aa51ab6056..c3e5b31fb5 100644 --- a/tests/test_as_channel_lastd.py +++ b/tests/transforms/test_as_channel_lastd.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import AsChannelLastd -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS TESTS = [] for p in TEST_NDARRAYS: @@ -27,7 +27,6 @@ class TestAsChannelLastd(unittest.TestCase): - @parameterized.expand(TESTS) def test_shape(self, in_type, input_param, expected_shape): test_data = { diff --git a/tests/test_as_discrete.py b/tests/transforms/test_as_discrete.py similarity index 97% rename from tests/test_as_discrete.py rename to tests/transforms/test_as_discrete.py index bf59752920..a83870e514 100644 --- a/tests/test_as_discrete.py +++ b/tests/transforms/test_as_discrete.py @@ -16,7 +16,7 @@ from parameterized import parameterized from monai.transforms import AsDiscrete -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TEST_CASES = [] for p in TEST_NDARRAYS: @@ -65,7 +65,6 @@ class TestAsDiscrete(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_value_shape(self, input_param, img, out, expected_shape): result = AsDiscrete(**input_param)(img) diff --git a/tests/test_as_discreted.py b/tests/transforms/test_as_discreted.py similarity index 98% rename from tests/test_as_discreted.py rename to tests/transforms/test_as_discreted.py index ed1b3c5b3e..3c29e820d0 100644 --- a/tests/test_as_discreted.py +++ b/tests/transforms/test_as_discreted.py @@ -16,7 +16,7 @@ from parameterized import parameterized from monai.transforms import AsDiscreted -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TEST_CASES = [] for p in TEST_NDARRAYS: @@ -68,7 +68,6 @@ class TestAsDiscreted(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_value_shape(self, input_param, test_input, output, expected_shape): result = AsDiscreted(**input_param)(test_input) diff --git a/tests/test_border_pad.py b/tests/transforms/test_border_pad.py similarity index 100% rename from tests/test_border_pad.py rename to tests/transforms/test_border_pad.py diff --git a/tests/test_border_padd.py b/tests/transforms/test_border_padd.py similarity index 100% rename from tests/test_border_padd.py rename to tests/transforms/test_border_padd.py diff --git a/tests/test_bounding_rect.py b/tests/transforms/test_bounding_rect.py similarity index 97% rename from tests/test_bounding_rect.py rename to tests/transforms/test_bounding_rect.py index b879fa6093..4443f3dd1d 100644 --- a/tests/test_bounding_rect.py +++ b/tests/transforms/test_bounding_rect.py @@ -18,7 +18,7 @@ import monai from monai.transforms import BoundingRect -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS TEST_CASE_1 = [(2, 3), [[0, 0], [1, 2]]] @@ -28,7 +28,6 @@ class TestBoundingRect(unittest.TestCase): - def setUp(self): monai.utils.set_determinism(1) diff --git a/tests/test_bounding_rectd.py b/tests/transforms/test_bounding_rectd.py similarity index 97% rename from tests/test_bounding_rectd.py rename to tests/transforms/test_bounding_rectd.py index 96435036b1..c28ce9d941 100644 --- a/tests/test_bounding_rectd.py +++ b/tests/transforms/test_bounding_rectd.py @@ -18,7 +18,7 @@ import monai from monai.transforms import BoundingRectD -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS TEST_CASE_1 = [(2, 3), [[0, 0], [1, 2]]] @@ -28,7 +28,6 @@ class TestBoundingRectD(unittest.TestCase): - def setUp(self): monai.utils.set_determinism(1) diff --git a/tests/test_cast_to_type.py b/tests/transforms/test_cast_to_type.py similarity index 97% rename from tests/test_cast_to_type.py rename to tests/transforms/test_cast_to_type.py index 035260804e..b4fba0939d 100644 --- a/tests/test_cast_to_type.py +++ b/tests/transforms/test_cast_to_type.py @@ -20,7 +20,7 @@ from monai.transforms import CastToType from monai.utils import optional_import from monai.utils.type_conversion import get_equivalent_dtype -from tests.utils import HAS_CUPY, TEST_NDARRAYS +from tests.test_utils import HAS_CUPY, TEST_NDARRAYS cp, _ = optional_import("cupy") @@ -37,7 +37,6 @@ class TestCastToType(unittest.TestCase): - @parameterized.expand(TESTS) def test_type(self, out_dtype, input_data, expected_type): result = CastToType(dtype=out_dtype)(input_data) diff --git a/tests/test_cast_to_typed.py b/tests/transforms/test_cast_to_typed.py similarity index 98% rename from tests/test_cast_to_typed.py rename to tests/transforms/test_cast_to_typed.py index 81e17117a9..89eed795df 100644 --- a/tests/test_cast_to_typed.py +++ b/tests/transforms/test_cast_to_typed.py @@ -19,7 +19,7 @@ from monai.transforms import CastToTyped from monai.utils import optional_import -from tests.utils import HAS_CUPY +from tests.test_utils import HAS_CUPY cp, _ = optional_import("cupy") @@ -53,7 +53,6 @@ class TestCastToTyped(unittest.TestCase): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2]) def test_type(self, input_param, input_data, expected_type): result = CastToTyped(**input_param)(input_data) diff --git a/tests/test_center_scale_crop.py b/tests/transforms/test_center_scale_crop.py similarity index 100% rename from tests/test_center_scale_crop.py rename to tests/transforms/test_center_scale_crop.py diff --git a/tests/test_center_scale_cropd.py b/tests/transforms/test_center_scale_cropd.py similarity index 100% rename from tests/test_center_scale_cropd.py rename to tests/transforms/test_center_scale_cropd.py diff --git a/tests/test_center_spatial_crop.py b/tests/transforms/test_center_spatial_crop.py similarity index 100% rename from tests/test_center_spatial_crop.py rename to tests/transforms/test_center_spatial_crop.py diff --git a/tests/test_center_spatial_cropd.py b/tests/transforms/test_center_spatial_cropd.py similarity index 100% rename from tests/test_center_spatial_cropd.py rename to tests/transforms/test_center_spatial_cropd.py diff --git a/tests/test_classes_to_indices.py b/tests/transforms/test_classes_to_indices.py similarity index 97% rename from tests/test_classes_to_indices.py rename to tests/transforms/test_classes_to_indices.py index a7377dac16..6a1d5bf8f7 100644 --- a/tests/test_classes_to_indices.py +++ b/tests/transforms/test_classes_to_indices.py @@ -16,7 +16,7 @@ from parameterized import parameterized from monai.transforms import ClassesToIndices -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS_CASES = [] for p in TEST_NDARRAYS: @@ -82,7 +82,6 @@ class TestClassesToIndices(unittest.TestCase): - @parameterized.expand(TESTS_CASES) def test_value(self, input_args, label, image, expected_indices): indices = ClassesToIndices(**input_args)(label, image) diff --git a/tests/test_classes_to_indicesd.py b/tests/transforms/test_classes_to_indicesd.py similarity index 98% rename from tests/test_classes_to_indicesd.py rename to tests/transforms/test_classes_to_indicesd.py index dead1ae753..1dca89ace8 100644 --- a/tests/test_classes_to_indicesd.py +++ b/tests/transforms/test_classes_to_indicesd.py @@ -16,7 +16,7 @@ from parameterized import parameterized from monai.transforms import ClassesToIndicesd -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS_CASES = [] for p in TEST_NDARRAYS: @@ -97,7 +97,6 @@ class TestClassesToIndicesd(unittest.TestCase): - @parameterized.expand(TESTS_CASES) def test_value(self, input_args, input_data, expected_indices): result = ClassesToIndicesd(**input_args)(input_data) diff --git a/tests/test_clip_intensity_percentiles.py b/tests/transforms/test_clip_intensity_percentiles.py similarity index 98% rename from tests/test_clip_intensity_percentiles.py rename to tests/transforms/test_clip_intensity_percentiles.py index 77f811db87..18ed47dbaa 100644 --- a/tests/test_clip_intensity_percentiles.py +++ b/tests/transforms/test_clip_intensity_percentiles.py @@ -19,7 +19,7 @@ from monai.transforms.utils import soft_clip from monai.transforms.utils_pytorch_numpy_unification import clip, percentile from monai.utils.type_conversion import convert_to_tensor -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, NumpyImageTestCase3D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, NumpyImageTestCase3D, assert_allclose def test_hard_clip_func(im, lower, upper): @@ -45,7 +45,6 @@ def test_soft_clip_func(im, lower, upper): class TestClipIntensityPercentiles2D(NumpyImageTestCase2D): - @parameterized.expand([[p] for p in TEST_NDARRAYS]) def test_hard_clipping_two_sided(self, p): hard_clipper = ClipIntensityPercentiles(upper=95, lower=5) @@ -130,7 +129,6 @@ def test_ill_both_none(self): class TestClipIntensityPercentiles3D(NumpyImageTestCase3D): - @parameterized.expand([[p] for p in TEST_NDARRAYS]) def test_hard_clipping_two_sided(self, p): hard_clipper = ClipIntensityPercentiles(upper=95, lower=5) diff --git a/tests/test_clip_intensity_percentilesd.py b/tests/transforms/test_clip_intensity_percentilesd.py similarity index 97% rename from tests/test_clip_intensity_percentilesd.py rename to tests/transforms/test_clip_intensity_percentilesd.py index 3e06b18418..ddf4d1a581 100644 --- a/tests/test_clip_intensity_percentilesd.py +++ b/tests/transforms/test_clip_intensity_percentilesd.py @@ -18,13 +18,11 @@ from monai.transforms import ClipIntensityPercentilesd from monai.transforms.utils_pytorch_numpy_unification import clip, percentile from monai.utils.type_conversion import convert_to_tensor -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, NumpyImageTestCase3D, assert_allclose - -from .test_clip_intensity_percentiles import test_hard_clip_func, test_soft_clip_func +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, NumpyImageTestCase3D, assert_allclose +from tests.transforms.test_clip_intensity_percentiles import test_hard_clip_func, test_soft_clip_func class TestClipIntensityPercentilesd2D(NumpyImageTestCase2D): - @parameterized.expand([[p] for p in TEST_NDARRAYS]) def test_hard_clipping_two_sided(self, p): key = "img" @@ -121,7 +119,6 @@ def test_ill_both_none(self): class TestClipIntensityPercentilesd3D(NumpyImageTestCase3D): - @parameterized.expand([[p] for p in TEST_NDARRAYS]) def test_hard_clipping_two_sided(self, p): key = "img" diff --git a/tests/test_compose_get_number_conversions.py b/tests/transforms/test_compose_get_number_conversions.py similarity index 100% rename from tests/test_compose_get_number_conversions.py rename to tests/transforms/test_compose_get_number_conversions.py diff --git a/tests/test_concat_itemsd.py b/tests/transforms/test_concat_itemsd.py similarity index 98% rename from tests/test_concat_itemsd.py rename to tests/transforms/test_concat_itemsd.py index 564ddf5c1f..823c6283e7 100644 --- a/tests/test_concat_itemsd.py +++ b/tests/transforms/test_concat_itemsd.py @@ -18,11 +18,10 @@ from monai.data import MetaTensor from monai.transforms import ConcatItemsd -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose class TestConcatItemsd(unittest.TestCase): - def test_tensor_values(self): device = torch.device("cuda:0") if torch.cuda.is_available() else torch.device("cpu:0") input_data = { diff --git a/tests/test_convert_to_multi_channel.py b/tests/transforms/test_convert_to_multi_channel.py similarity index 96% rename from tests/test_convert_to_multi_channel.py rename to tests/transforms/test_convert_to_multi_channel.py index 98bbea1ebf..dfa324b6b9 100644 --- a/tests/test_convert_to_multi_channel.py +++ b/tests/transforms/test_convert_to_multi_channel.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import ConvertToMultiChannelBasedOnBratsClasses -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -48,7 +48,6 @@ class TestConvertToMultiChannel(unittest.TestCase): - @parameterized.expand(TESTS) def test_type_shape(self, data, expected_result): result = ConvertToMultiChannelBasedOnBratsClasses()(data) diff --git a/tests/test_convert_to_multi_channeld.py b/tests/transforms/test_convert_to_multi_channeld.py similarity index 100% rename from tests/test_convert_to_multi_channeld.py rename to tests/transforms/test_convert_to_multi_channeld.py diff --git a/tests/test_copy_itemsd.py b/tests/transforms/test_copy_itemsd.py similarity index 98% rename from tests/test_copy_itemsd.py rename to tests/transforms/test_copy_itemsd.py index a78e08897b..584f54b438 100644 --- a/tests/test_copy_itemsd.py +++ b/tests/transforms/test_copy_itemsd.py @@ -20,7 +20,7 @@ from monai.networks import eval_mode from monai.transforms import CopyItemsd from monai.utils import ensure_tuple -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_CASE_1 = ["img", 1, "img_1"] @@ -32,7 +32,6 @@ class TestCopyItemsd(unittest.TestCase): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4]) def test_numpy_values(self, keys, times, names): input_data = {"img": np.array([[0, 1], [1, 2]]), "seg": np.array([[3, 4], [4, 5]])} diff --git a/tests/test_create_grid_and_affine.py b/tests/transforms/test_create_grid_and_affine.py similarity index 99% rename from tests/test_create_grid_and_affine.py rename to tests/transforms/test_create_grid_and_affine.py index 4910a10470..f4793cabe0 100644 --- a/tests/test_create_grid_and_affine.py +++ b/tests/transforms/test_create_grid_and_affine.py @@ -24,11 +24,10 @@ create_shear, create_translate, ) -from tests.utils import assert_allclose, is_tf32_env +from tests.test_utils import assert_allclose, is_tf32_env class TestCreateGrid(unittest.TestCase): - def test_create_grid(self): with self.assertRaisesRegex(TypeError, ""): create_grid(None) @@ -169,7 +168,6 @@ def test_assert(func, params, expected): class TestCreateAffine(unittest.TestCase): - def test_create_rotate(self): with self.assertRaisesRegex(TypeError, ""): create_rotate(2, None) diff --git a/tests/test_crop_foreground.py b/tests/transforms/test_crop_foreground.py similarity index 99% rename from tests/test_crop_foreground.py rename to tests/transforms/test_crop_foreground.py index f63cb3e8b0..c533e46ee4 100644 --- a/tests/test_crop_foreground.py +++ b/tests/transforms/test_crop_foreground.py @@ -20,7 +20,7 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms import CropForeground from monai.transforms.lazy.functional import apply_pending -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose TEST_COORDS, TESTS, TEST_LAZY_ERROR = [], [], [] @@ -99,7 +99,6 @@ class TestCropForeground(unittest.TestCase): - @parameterized.expand(TEST_COORDS + TESTS) def test_value(self, arguments, image, expected_data, _): cropper = CropForeground(**arguments) diff --git a/tests/test_crop_foregroundd.py b/tests/transforms/test_crop_foregroundd.py similarity index 99% rename from tests/test_crop_foregroundd.py rename to tests/transforms/test_crop_foregroundd.py index 92954aa81e..83d7a8e07c 100644 --- a/tests/test_crop_foregroundd.py +++ b/tests/transforms/test_crop_foregroundd.py @@ -19,7 +19,7 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms import CropForegroundd from monai.transforms.lazy.functional import apply_pending -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose TEST_POSITION, TESTS = [], [] for p in TEST_NDARRAYS_ALL: @@ -158,7 +158,6 @@ class TestCropForegroundd(unittest.TestCase): - @parameterized.expand(TEST_POSITION + TESTS) def test_value(self, arguments, input_data, expected_data, _): cropper = CropForegroundd(**arguments) diff --git a/tests/test_cucim_dict_transform.py b/tests/transforms/test_cucim_dict_transform.py similarity index 99% rename from tests/test_cucim_dict_transform.py rename to tests/transforms/test_cucim_dict_transform.py index 3c5703a34c..1febf7d2b4 100644 --- a/tests/test_cucim_dict_transform.py +++ b/tests/transforms/test_cucim_dict_transform.py @@ -18,7 +18,7 @@ from monai.transforms import CuCIMd from monai.utils import optional_import, set_determinism -from tests.utils import HAS_CUPY, skip_if_no_cuda +from tests.test_utils import HAS_CUPY, skip_if_no_cuda _, has_cut = optional_import("cucim.core.operations.expose.transform") cp, _ = optional_import("cupy") @@ -66,7 +66,6 @@ @unittest.skipUnless(HAS_CUPY, "CuPy is required.") @unittest.skipUnless(has_cut, "cuCIM transforms are required.") class TestCuCIMDict(unittest.TestCase): - @parameterized.expand( [ TEST_CASE_COLOR_JITTER_1, diff --git a/tests/test_cucim_transform.py b/tests/transforms/test_cucim_transform.py similarity index 98% rename from tests/test_cucim_transform.py rename to tests/transforms/test_cucim_transform.py index 162e16b52a..97c1e94703 100644 --- a/tests/test_cucim_transform.py +++ b/tests/transforms/test_cucim_transform.py @@ -18,7 +18,7 @@ from monai.transforms import CuCIM from monai.utils import optional_import, set_determinism -from tests.utils import HAS_CUPY, skip_if_no_cuda +from tests.test_utils import HAS_CUPY, skip_if_no_cuda _, has_cut = optional_import("cucim.core.operations.expose.transform") cp, _ = optional_import("cupy") @@ -66,7 +66,6 @@ @unittest.skipUnless(HAS_CUPY, "CuPy is required.") @unittest.skipUnless(has_cut, "cuCIM transforms are required.") class TestCuCIM(unittest.TestCase): - @parameterized.expand( [ TEST_CASE_COLOR_JITTER_1, diff --git a/tests/test_data_stats.py b/tests/transforms/test_data_stats.py similarity index 100% rename from tests/test_data_stats.py rename to tests/transforms/test_data_stats.py diff --git a/tests/test_data_statsd.py b/tests/transforms/test_data_statsd.py similarity index 100% rename from tests/test_data_statsd.py rename to tests/transforms/test_data_statsd.py diff --git a/tests/test_delete_itemsd.py b/tests/transforms/test_delete_itemsd.py similarity index 100% rename from tests/test_delete_itemsd.py rename to tests/transforms/test_delete_itemsd.py diff --git a/tests/test_detect_envelope.py b/tests/transforms/test_detect_envelope.py similarity index 98% rename from tests/test_detect_envelope.py rename to tests/transforms/test_detect_envelope.py index f9c2b5ac53..821c6ad947 100644 --- a/tests/test_detect_envelope.py +++ b/tests/transforms/test_detect_envelope.py @@ -19,7 +19,7 @@ from monai.transforms import DetectEnvelope from monai.utils import OptionalImportError -from tests.utils import TEST_NDARRAYS, SkipIfModule, SkipIfNoModule, assert_allclose +from tests.test_utils import TEST_NDARRAYS, SkipIfModule, SkipIfNoModule, assert_allclose n_samples = 500 hann_windowed_sine = np.sin(2 * np.pi * 10 * np.linspace(0, 1, n_samples)) * np.hanning(n_samples) @@ -116,7 +116,6 @@ @SkipIfNoModule("torch.fft") class TestDetectEnvelope(unittest.TestCase): - @parameterized.expand( [ TEST_CASE_1D_SINE, @@ -152,7 +151,6 @@ def test_value_error(self, arguments, image, method): @SkipIfModule("torch.fft") class TestHilbertTransformNoFFTMod(unittest.TestCase): - def test_no_fft_module_error(self): self.assertRaises(OptionalImportError, DetectEnvelope(), np.random.rand(1, 10)) diff --git a/tests/test_distance_transform_edt.py b/tests/transforms/test_distance_transform_edt.py similarity index 98% rename from tests/test_distance_transform_edt.py rename to tests/transforms/test_distance_transform_edt.py index cf5c253c0c..ad87512ff8 100644 --- a/tests/test_distance_transform_edt.py +++ b/tests/transforms/test_distance_transform_edt.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms import DistanceTransformEDT, DistanceTransformEDTd -from tests.utils import HAS_CUPY, assert_allclose, optional_import, skip_if_no_cuda +from tests.test_utils import HAS_CUPY, assert_allclose, optional_import, skip_if_no_cuda momorphology, has_cucim = optional_import("cucim.core.operations.morphology") ndimage, has_ndimage = optional_import("scipy.ndimage") @@ -146,7 +146,6 @@ class TestDistanceTransformEDT(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_scipy_transform(self, input, expected_output): transform = DistanceTransformEDT() diff --git a/tests/test_divisible_pad.py b/tests/transforms/test_divisible_pad.py similarity index 100% rename from tests/test_divisible_pad.py rename to tests/transforms/test_divisible_pad.py diff --git a/tests/test_divisible_padd.py b/tests/transforms/test_divisible_padd.py similarity index 100% rename from tests/test_divisible_padd.py rename to tests/transforms/test_divisible_padd.py diff --git a/tests/test_ensure_channel_first.py b/tests/transforms/test_ensure_channel_first.py similarity index 100% rename from tests/test_ensure_channel_first.py rename to tests/transforms/test_ensure_channel_first.py diff --git a/tests/test_ensure_channel_firstd.py b/tests/transforms/test_ensure_channel_firstd.py similarity index 100% rename from tests/test_ensure_channel_firstd.py rename to tests/transforms/test_ensure_channel_firstd.py diff --git a/tests/test_ensure_type.py b/tests/transforms/test_ensure_type.py similarity index 99% rename from tests/test_ensure_type.py rename to tests/transforms/test_ensure_type.py index 00b01898b3..9e008f9811 100644 --- a/tests/test_ensure_type.py +++ b/tests/transforms/test_ensure_type.py @@ -18,11 +18,10 @@ from monai.data import MetaTensor from monai.transforms import EnsureType -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose class TestEnsureType(unittest.TestCase): - def test_array_input(self): test_datas = [np.array([[1, 2], [3, 4]]), torch.as_tensor([[1, 2], [3, 4]])] if torch.cuda.is_available(): diff --git a/tests/test_ensure_typed.py b/tests/transforms/test_ensure_typed.py similarity index 99% rename from tests/test_ensure_typed.py rename to tests/transforms/test_ensure_typed.py index fe543347de..0d2a5610ba 100644 --- a/tests/test_ensure_typed.py +++ b/tests/transforms/test_ensure_typed.py @@ -18,11 +18,10 @@ from monai.data import MetaTensor from monai.transforms import EnsureTyped -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose class TestEnsureTyped(unittest.TestCase): - def test_array_input(self): test_datas = [np.array([[1, 2], [3, 4]]), torch.as_tensor([[1, 2], [3, 4]])] if torch.cuda.is_available(): diff --git a/tests/test_fg_bg_to_indices.py b/tests/transforms/test_fg_bg_to_indices.py similarity index 97% rename from tests/test_fg_bg_to_indices.py rename to tests/transforms/test_fg_bg_to_indices.py index a28c491333..3de25905ce 100644 --- a/tests/test_fg_bg_to_indices.py +++ b/tests/transforms/test_fg_bg_to_indices.py @@ -16,7 +16,7 @@ from parameterized import parameterized from monai.transforms import FgBgToIndices -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS_CASES = [] for p in TEST_NDARRAYS: @@ -72,7 +72,6 @@ class TestFgBgToIndices(unittest.TestCase): - @parameterized.expand(TESTS_CASES) def test_type_shape(self, input_data, label, image, expected_fg, expected_bg): fg_indices, bg_indices = FgBgToIndices(**input_data)(label, image) diff --git a/tests/test_fg_bg_to_indicesd.py b/tests/transforms/test_fg_bg_to_indicesd.py similarity index 97% rename from tests/test_fg_bg_to_indicesd.py rename to tests/transforms/test_fg_bg_to_indicesd.py index c6dd2059f4..7a03b386ac 100644 --- a/tests/test_fg_bg_to_indicesd.py +++ b/tests/transforms/test_fg_bg_to_indicesd.py @@ -16,7 +16,7 @@ from parameterized import parameterized from monai.transforms import FgBgToIndicesd -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TEST_CASES = [] for p in TEST_NDARRAYS: @@ -67,7 +67,6 @@ class TestFgBgToIndicesd(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_type_shape(self, input_data, data, expected_fg, expected_bg): result = FgBgToIndicesd(**input_data)(data) diff --git a/tests/test_fill_holes.py b/tests/transforms/test_fill_holes.py similarity index 98% rename from tests/test_fill_holes.py rename to tests/transforms/test_fill_holes.py index 241f7f8254..4a90b0c429 100644 --- a/tests/test_fill_holes.py +++ b/tests/transforms/test_fill_holes.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import FillHoles -from tests.utils import TEST_NDARRAYS, assert_allclose, clone +from tests.test_utils import TEST_NDARRAYS, assert_allclose, clone grid_1_raw = [[1, 1, 1], [1, 0, 1], [1, 1, 1]] @@ -195,7 +195,6 @@ class TestFillHoles(unittest.TestCase): - @parameterized.expand(VALID_CASES) def test_correct_results(self, _, args, input_image, expected): converter = FillHoles(**args) diff --git a/tests/test_fill_holesd.py b/tests/transforms/test_fill_holesd.py similarity index 98% rename from tests/test_fill_holesd.py rename to tests/transforms/test_fill_holesd.py index 28c17b00ac..f4b44d328f 100644 --- a/tests/test_fill_holesd.py +++ b/tests/transforms/test_fill_holesd.py @@ -18,7 +18,7 @@ from monai.transforms import FillHolesd from monai.utils.enums import CommonKeys -from tests.utils import TEST_NDARRAYS, assert_allclose, clone +from tests.test_utils import TEST_NDARRAYS, assert_allclose, clone grid_1_raw = [[1, 1, 1], [1, 0, 1], [1, 1, 1]] @@ -196,7 +196,6 @@ class TestFillHoles(unittest.TestCase): - @parameterized.expand(VALID_CASES) def test_correct_results(self, _, args, input_image, expected): key = CommonKeys.IMAGE diff --git a/tests/test_flatten_sub_keysd.py b/tests/transforms/test_flatten_sub_keysd.py similarity index 100% rename from tests/test_flatten_sub_keysd.py rename to tests/transforms/test_flatten_sub_keysd.py diff --git a/tests/test_flip.py b/tests/transforms/test_flip.py similarity index 95% rename from tests/test_flip.py rename to tests/transforms/test_flip.py index 789ec86920..3d18b7eb89 100644 --- a/tests/test_flip.py +++ b/tests/transforms/test_flip.py @@ -21,7 +21,13 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms import Flip from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_DEVICES, TEST_NDARRAYS_ALL, NumpyImageTestCase2D, assert_allclose, test_local_inversion +from tests.test_utils import ( + TEST_DEVICES, + TEST_NDARRAYS_ALL, + NumpyImageTestCase2D, + assert_allclose, + test_local_inversion, +) INVALID_CASES = [("wrong_axis", ["s", 1], TypeError), ("not_numbers", "s", TypeError)] @@ -34,7 +40,6 @@ class TestFlip(NumpyImageTestCase2D): - @parameterized.expand(INVALID_CASES) def test_invalid_inputs(self, _, spatial_axis, raises): with self.assertRaises(raises): diff --git a/tests/test_flipd.py b/tests/transforms/test_flipd.py similarity index 95% rename from tests/test_flipd.py rename to tests/transforms/test_flipd.py index 1df6d34056..1a2af4b11f 100644 --- a/tests/test_flipd.py +++ b/tests/transforms/test_flipd.py @@ -22,7 +22,13 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms import Flipd from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_DEVICES, TEST_NDARRAYS_ALL, NumpyImageTestCase2D, assert_allclose, test_local_inversion +from tests.test_utils import ( + TEST_DEVICES, + TEST_NDARRAYS_ALL, + NumpyImageTestCase2D, + assert_allclose, + test_local_inversion, +) INVALID_CASES = [("wrong_axis", ["s", 1], TypeError), ("not_numbers", "s", TypeError)] @@ -35,7 +41,6 @@ class TestFlipd(NumpyImageTestCase2D): - @parameterized.expand(INVALID_CASES) def test_invalid_cases(self, _, spatial_axis, raises): with self.assertRaises(raises): diff --git a/tests/test_fourier.py b/tests/transforms/test_fourier.py similarity index 96% rename from tests/test_fourier.py rename to tests/transforms/test_fourier.py index 177fc280f7..f9685030d4 100644 --- a/tests/test_fourier.py +++ b/tests/transforms/test_fourier.py @@ -20,7 +20,7 @@ from monai.data.synthetic import create_test_image_2d, create_test_image_3d from monai.transforms import Fourier from monai.utils.misc import set_determinism -from tests.utils import SkipIfBeforePyTorchVersion, SkipIfNoModule +from tests.test_utils import SkipIfBeforePyTorchVersion, SkipIfNoModule TEST_CASES = [((128, 64),), ((64, 48, 80),)] @@ -28,7 +28,6 @@ @SkipIfBeforePyTorchVersion((1, 8)) @SkipIfNoModule("torch.fft") class TestFourier(unittest.TestCase): - def setUp(self): set_determinism(0) super().setUp() diff --git a/tests/test_gaussian_sharpen.py b/tests/transforms/test_gaussian_sharpen.py similarity index 98% rename from tests/test_gaussian_sharpen.py rename to tests/transforms/test_gaussian_sharpen.py index 392a7b376b..596935d6dc 100644 --- a/tests/test_gaussian_sharpen.py +++ b/tests/transforms/test_gaussian_sharpen.py @@ -16,7 +16,7 @@ from parameterized import parameterized from monai.transforms import GaussianSharpen -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] @@ -82,7 +82,6 @@ class TestGaussianSharpen(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, arguments, image, expected_data): result = GaussianSharpen(**arguments)(image) diff --git a/tests/test_gaussian_sharpend.py b/tests/transforms/test_gaussian_sharpend.py similarity index 98% rename from tests/test_gaussian_sharpend.py rename to tests/transforms/test_gaussian_sharpend.py index 15b219fd2c..625d13addc 100644 --- a/tests/test_gaussian_sharpend.py +++ b/tests/transforms/test_gaussian_sharpend.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import GaussianSharpend -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -82,7 +82,6 @@ class TestGaussianSharpend(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, arguments, image, expected_data): result = GaussianSharpend(**arguments)(image) diff --git a/tests/test_gaussian_smooth.py b/tests/transforms/test_gaussian_smooth.py similarity index 98% rename from tests/test_gaussian_smooth.py rename to tests/transforms/test_gaussian_smooth.py index 9f99ebe0f8..a97124fadd 100644 --- a/tests/test_gaussian_smooth.py +++ b/tests/transforms/test_gaussian_smooth.py @@ -16,7 +16,7 @@ from parameterized import parameterized from monai.transforms import GaussianSmooth -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] @@ -86,7 +86,6 @@ class TestGaussianSmooth(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, arguments, image, expected_data): result = GaussianSmooth(**arguments)(image) diff --git a/tests/test_gaussian_smoothd.py b/tests/transforms/test_gaussian_smoothd.py similarity index 98% rename from tests/test_gaussian_smoothd.py rename to tests/transforms/test_gaussian_smoothd.py index a6de4a159b..eedec62dd2 100644 --- a/tests/test_gaussian_smoothd.py +++ b/tests/transforms/test_gaussian_smoothd.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import GaussianSmoothd -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -86,7 +86,6 @@ class TestGaussianSmoothd(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, arguments, image, expected_data): result = GaussianSmoothd(**arguments)(image) diff --git a/tests/test_generate_label_classes_crop_centers.py b/tests/transforms/test_generate_label_classes_crop_centers.py similarity index 97% rename from tests/test_generate_label_classes_crop_centers.py rename to tests/transforms/test_generate_label_classes_crop_centers.py index 1cbb5f05c3..61b9b40096 100644 --- a/tests/test_generate_label_classes_crop_centers.py +++ b/tests/transforms/test_generate_label_classes_crop_centers.py @@ -18,7 +18,7 @@ from monai.transforms import generate_label_classes_crop_centers from monai.utils.misc import set_determinism -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TEST_CASE_1 = [ { @@ -48,7 +48,6 @@ class TestGenerateLabelClassesCropCenters(unittest.TestCase): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2]) def test_type_shape(self, input_data, expected_type, expected_count, expected_shape): results = [] diff --git a/tests/test_generate_pos_neg_label_crop_centers.py b/tests/transforms/test_generate_pos_neg_label_crop_centers.py similarity index 97% rename from tests/test_generate_pos_neg_label_crop_centers.py rename to tests/transforms/test_generate_pos_neg_label_crop_centers.py index de127b33df..112350072d 100644 --- a/tests/test_generate_pos_neg_label_crop_centers.py +++ b/tests/transforms/test_generate_pos_neg_label_crop_centers.py @@ -18,7 +18,7 @@ from monai.transforms import generate_pos_neg_label_crop_centers from monai.utils.misc import set_determinism -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [ [ @@ -51,7 +51,6 @@ class TestGeneratePosNegLabelCropCenters(unittest.TestCase): - @parameterized.expand(TESTS) def test_type_shape(self, input_data, expected_type, expected_count, expected_shape): results = [] diff --git a/tests/test_generate_spatial_bounding_box.py b/tests/transforms/test_generate_spatial_bounding_box.py similarity index 98% rename from tests/test_generate_spatial_bounding_box.py rename to tests/transforms/test_generate_spatial_bounding_box.py index 6d5b415ec2..1f63b2c1ef 100644 --- a/tests/test_generate_spatial_bounding_box.py +++ b/tests/transforms/test_generate_spatial_bounding_box.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import generate_spatial_bounding_box -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS TESTS = [] for p in TEST_NDARRAYS: @@ -104,7 +104,6 @@ class TestGenerateSpatialBoundingBox(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, input_data, expected_box): result = generate_spatial_bounding_box(**input_data) diff --git a/tests/test_get_extreme_points.py b/tests/transforms/test_get_extreme_points.py similarity index 97% rename from tests/test_get_extreme_points.py rename to tests/transforms/test_get_extreme_points.py index e60715e2fe..370a11f0c7 100644 --- a/tests/test_get_extreme_points.py +++ b/tests/transforms/test_get_extreme_points.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import get_extreme_points -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS TESTS = [] for p in TEST_NDARRAYS: @@ -47,7 +47,6 @@ class TestGetExtremePoints(unittest.TestCase): - @parameterized.expand(TESTS) def test_type_shape(self, input_data, expected): result = get_extreme_points(**input_data) diff --git a/tests/test_gibbs_noise.py b/tests/transforms/test_gibbs_noise.py similarity index 97% rename from tests/test_gibbs_noise.py rename to tests/transforms/test_gibbs_noise.py index bdc66b9495..2aa2a44d10 100644 --- a/tests/test_gibbs_noise.py +++ b/tests/transforms/test_gibbs_noise.py @@ -21,7 +21,7 @@ from monai.transforms import GibbsNoise from monai.utils.misc import set_determinism from monai.utils.module import optional_import -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose _, has_torch_fft = optional_import("torch.fft", name="fftshift") @@ -32,7 +32,6 @@ class TestGibbsNoise(unittest.TestCase): - def setUp(self): set_determinism(0) super().setUp() diff --git a/tests/test_gibbs_noised.py b/tests/transforms/test_gibbs_noised.py similarity index 98% rename from tests/test_gibbs_noised.py rename to tests/transforms/test_gibbs_noised.py index 3b2cae7e84..f951e6dd3b 100644 --- a/tests/test_gibbs_noised.py +++ b/tests/transforms/test_gibbs_noised.py @@ -21,7 +21,7 @@ from monai.transforms import GibbsNoised from monai.utils.misc import set_determinism from monai.utils.module import optional_import -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose _, has_torch_fft = optional_import("torch.fft", name="fftshift") @@ -33,7 +33,6 @@ class TestGibbsNoised(unittest.TestCase): - def setUp(self): set_determinism(0) super().setUp() diff --git a/tests/test_grid_distortion.py b/tests/transforms/test_grid_distortion.py similarity index 98% rename from tests/test_grid_distortion.py rename to tests/transforms/test_grid_distortion.py index 9ec85250e8..5b2d014132 100644 --- a/tests/test_grid_distortion.py +++ b/tests/transforms/test_grid_distortion.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import GridDistortion -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose TESTS = [] for p in TEST_NDARRAYS_ALL: @@ -99,7 +99,6 @@ class TestGridDistortion(unittest.TestCase): - @parameterized.expand(TESTS) def test_grid_distortion(self, input_param, input_data, expected_val): g = GridDistortion(**input_param) diff --git a/tests/test_grid_distortiond.py b/tests/transforms/test_grid_distortiond.py similarity index 98% rename from tests/test_grid_distortiond.py rename to tests/transforms/test_grid_distortiond.py index ce73593dc7..c56450ad3e 100644 --- a/tests/test_grid_distortiond.py +++ b/tests/transforms/test_grid_distortiond.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import GridDistortiond -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose TESTS = [] num_cells = (2, 2) @@ -75,7 +75,6 @@ class TestGridDistortiond(unittest.TestCase): - @parameterized.expand(TESTS) def test_grid_distortiond(self, input_param, input_data, expected_val_img, expected_val_mask): g = GridDistortiond(**input_param) diff --git a/tests/test_grid_split.py b/tests/transforms/test_grid_split.py similarity index 98% rename from tests/test_grid_split.py rename to tests/transforms/test_grid_split.py index 852a4847a6..1e9ac8e5f2 100644 --- a/tests/test_grid_split.py +++ b/tests/transforms/test_grid_split.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import GridSplit -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose A11 = torch.randn(3, 2, 2) A12 = torch.randn(3, 2, 2) @@ -66,7 +66,6 @@ class TestGridSplit(unittest.TestCase): - @parameterized.expand(TEST_SINGLE) def test_split_patch_single_call(self, in_type, input_parameters, image, expected): input_image = in_type(image) diff --git a/tests/test_grid_splitd.py b/tests/transforms/test_grid_splitd.py similarity index 98% rename from tests/test_grid_splitd.py rename to tests/transforms/test_grid_splitd.py index 215076d5a3..b0daf3fece 100644 --- a/tests/test_grid_splitd.py +++ b/tests/transforms/test_grid_splitd.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import GridSplitd -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose A11 = torch.randn(3, 2, 2) A12 = torch.randn(3, 2, 2) @@ -70,7 +70,6 @@ class TestGridSplitd(unittest.TestCase): - @parameterized.expand(TEST_SINGLE) def test_split_patch_single_call(self, in_type, input_parameters, img_dict, expected): input_dict = {} diff --git a/tests/test_histogram_normalize.py b/tests/transforms/test_histogram_normalize.py similarity index 96% rename from tests/test_histogram_normalize.py rename to tests/transforms/test_histogram_normalize.py index 25c0afb64d..7378400c5e 100644 --- a/tests/test_histogram_normalize.py +++ b/tests/transforms/test_histogram_normalize.py @@ -18,7 +18,7 @@ from monai.transforms import HistogramNormalize from monai.utils import get_equivalent_dtype -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -48,7 +48,6 @@ class TestHistogramNormalize(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, arguments, image, expected_data): result = HistogramNormalize(**arguments)(image) diff --git a/tests/test_histogram_normalized.py b/tests/transforms/test_histogram_normalized.py similarity index 97% rename from tests/test_histogram_normalized.py rename to tests/transforms/test_histogram_normalized.py index a390375441..a7b2d8488f 100644 --- a/tests/test_histogram_normalized.py +++ b/tests/transforms/test_histogram_normalized.py @@ -18,7 +18,7 @@ from monai.transforms import HistogramNormalized from monai.utils import get_equivalent_dtype -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -48,7 +48,6 @@ class TestHistogramNormalized(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, arguments, image, expected_data): result = HistogramNormalized(**arguments)(image)["img"] diff --git a/tests/test_image_filter.py b/tests/transforms/test_image_filter.py similarity index 100% rename from tests/test_image_filter.py rename to tests/transforms/test_image_filter.py diff --git a/tests/test_intensity_stats.py b/tests/transforms/test_intensity_stats.py similarity index 98% rename from tests/test_intensity_stats.py rename to tests/transforms/test_intensity_stats.py index e45c2acbad..2338cca805 100644 --- a/tests/test_intensity_stats.py +++ b/tests/transforms/test_intensity_stats.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import IntensityStats -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS TESTS = [] for p in TEST_NDARRAYS: @@ -53,7 +53,6 @@ class TestIntensityStats(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, input_param, img, meta_dict, expected): _, meta_dict = IntensityStats(**input_param)(img, meta_dict) diff --git a/tests/test_intensity_statsd.py b/tests/transforms/test_intensity_statsd.py similarity index 100% rename from tests/test_intensity_statsd.py rename to tests/transforms/test_intensity_statsd.py diff --git a/tests/test_inverse.py b/tests/transforms/test_inverse.py similarity index 99% rename from tests/test_inverse.py rename to tests/transforms/test_inverse.py index 6bd14a19f1..01d32e4baf 100644 --- a/tests/test_inverse.py +++ b/tests/transforms/test_inverse.py @@ -69,7 +69,7 @@ reset_ops_id, ) from monai.utils import first, get_seed, optional_import, set_determinism -from tests.utils import make_nifti_image, make_rand_affine +from tests.test_utils import make_nifti_image, make_rand_affine if TYPE_CHECKING: has_nib = True diff --git a/tests/test_inverse_collation.py b/tests/transforms/test_inverse_collation.py similarity index 99% rename from tests/test_inverse_collation.py rename to tests/transforms/test_inverse_collation.py index bf3972e6bd..e12c00611f 100644 --- a/tests/test_inverse_collation.py +++ b/tests/transforms/test_inverse_collation.py @@ -43,7 +43,7 @@ Rotated, ) from monai.utils import optional_import, set_determinism -from tests.utils import make_nifti_image +from tests.test_utils import make_nifti_image if TYPE_CHECKING: has_nib = True diff --git a/tests/test_invert.py b/tests/transforms/test_invert.py similarity index 98% rename from tests/test_invert.py rename to tests/transforms/test_invert.py index 69d31edfc8..a7391f5fb2 100644 --- a/tests/test_invert.py +++ b/tests/transforms/test_invert.py @@ -37,11 +37,10 @@ Spacing, ) from monai.utils import set_determinism -from tests.utils import assert_allclose, make_nifti_image +from tests.test_utils import assert_allclose, make_nifti_image class TestInvert(unittest.TestCase): - def test_invert(self): set_determinism(seed=0) im_fname = make_nifti_image(create_test_image_3d(101, 100, 107, noise_max=100)[1]) # label image, discrete diff --git a/tests/test_invertd.py b/tests/transforms/test_invertd.py similarity index 98% rename from tests/test_invertd.py rename to tests/transforms/test_invertd.py index f6e8fc40e7..2b5e9da85d 100644 --- a/tests/test_invertd.py +++ b/tests/transforms/test_invertd.py @@ -37,13 +37,12 @@ Spacingd, ) from monai.utils import set_determinism -from tests.utils import assert_allclose, make_nifti_image +from tests.test_utils import assert_allclose, make_nifti_image KEYS = ["image", "label"] class TestInvertd(unittest.TestCase): - def test_invert(self): set_determinism(seed=0) im_fname, seg_fname = (make_nifti_image(i) for i in create_test_image_3d(101, 100, 107, noise_max=100)) diff --git a/tests/test_k_space_spike_noise.py b/tests/transforms/test_k_space_spike_noise.py similarity index 98% rename from tests/test_k_space_spike_noise.py rename to tests/transforms/test_k_space_spike_noise.py index 17acedf319..20ce785517 100644 --- a/tests/test_k_space_spike_noise.py +++ b/tests/transforms/test_k_space_spike_noise.py @@ -22,7 +22,7 @@ from monai.data.synthetic import create_test_image_2d, create_test_image_3d from monai.transforms import KSpaceSpikeNoise from monai.utils.misc import set_determinism -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS TESTS = [] for shape in ((128, 64), (64, 48, 80)): @@ -32,7 +32,6 @@ class TestKSpaceSpikeNoise(unittest.TestCase): - def setUp(self): set_determinism(0) super().setUp() diff --git a/tests/test_k_space_spike_noised.py b/tests/transforms/test_k_space_spike_noised.py similarity index 98% rename from tests/test_k_space_spike_noised.py rename to tests/transforms/test_k_space_spike_noised.py index ce542af0aa..8dbb8c2f49 100644 --- a/tests/test_k_space_spike_noised.py +++ b/tests/transforms/test_k_space_spike_noised.py @@ -22,7 +22,7 @@ from monai.data.synthetic import create_test_image_2d, create_test_image_3d from monai.transforms import KSpaceSpikeNoised from monai.utils.misc import set_determinism -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for shape in ((128, 64), (64, 48, 80)): @@ -33,7 +33,6 @@ class TestKSpaceSpikeNoised(unittest.TestCase): - def setUp(self): set_determinism(0) super().setUp() diff --git a/tests/test_keep_largest_connected_component.py b/tests/transforms/test_keep_largest_connected_component.py similarity index 99% rename from tests/test_keep_largest_connected_component.py rename to tests/transforms/test_keep_largest_connected_component.py index 2dfac1142e..639cdf9936 100644 --- a/tests/test_keep_largest_connected_component.py +++ b/tests/transforms/test_keep_largest_connected_component.py @@ -21,7 +21,7 @@ from monai.transforms import KeepLargestConnectedComponent from monai.transforms.utils_pytorch_numpy_unification import moveaxis from monai.utils.type_conversion import convert_to_dst_type -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose def to_onehot(x): @@ -381,7 +381,6 @@ def to_onehot(x): class TestKeepLargestConnectedComponent(unittest.TestCase): - @parameterized.expand(TESTS) def test_correct_results(self, _, args, input_image, expected): converter = KeepLargestConnectedComponent(**args) diff --git a/tests/test_keep_largest_connected_componentd.py b/tests/transforms/test_keep_largest_connected_componentd.py similarity index 99% rename from tests/test_keep_largest_connected_componentd.py rename to tests/transforms/test_keep_largest_connected_componentd.py index 4d3172741d..3df87e99f1 100644 --- a/tests/test_keep_largest_connected_componentd.py +++ b/tests/transforms/test_keep_largest_connected_componentd.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import KeepLargestConnectedComponentd -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose grid_1 = [[[0, 0, 1, 0, 0], [0, 2, 1, 1, 1], [1, 2, 1, 0, 0], [1, 2, 0, 1, 0], [2, 2, 0, 0, 2]]] grid_2 = [[[0, 0, 0, 0, 1], [0, 0, 1, 1, 1], [1, 0, 1, 1, 2], [1, 0, 1, 2, 2], [0, 0, 0, 0, 1]]] @@ -337,7 +337,6 @@ class TestKeepLargestConnectedComponentd(unittest.TestCase): - @parameterized.expand(VALID_CASES) def test_correct_results(self, _, args, input_dict, expected): converter = KeepLargestConnectedComponentd(**args) diff --git a/tests/test_label_filter.py b/tests/transforms/test_label_filter.py similarity index 97% rename from tests/test_label_filter.py rename to tests/transforms/test_label_filter.py index 93cf95a2a0..414dfc5e7e 100644 --- a/tests/test_label_filter.py +++ b/tests/transforms/test_label_filter.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import LabelFilter -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose grid_1 = torch.tensor([[[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]]) @@ -58,7 +58,6 @@ class TestLabelFilter(unittest.TestCase): - @parameterized.expand(VALID_TESTS) def test_correct_results(self, _, args, input_image, expected): converter = LabelFilter(**args) diff --git a/tests/test_label_to_contour.py b/tests/transforms/test_label_to_contour.py similarity index 99% rename from tests/test_label_to_contour.py rename to tests/transforms/test_label_to_contour.py index d7fbfc9b8d..3ec94e1d13 100644 --- a/tests/test_label_to_contour.py +++ b/tests/transforms/test_label_to_contour.py @@ -17,7 +17,7 @@ import torch from monai.transforms import LabelToContour -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose expected_output_for_cube = [ [ @@ -142,7 +142,6 @@ def gen_fixed_img(array_type): class TestContour(unittest.TestCase): - def test_contour(self): input_param = {"kernel_type": "Laplace"} diff --git a/tests/test_label_to_contourd.py b/tests/transforms/test_label_to_contourd.py similarity index 99% rename from tests/test_label_to_contourd.py rename to tests/transforms/test_label_to_contourd.py index a91a712da6..1d31ec8a38 100644 --- a/tests/test_label_to_contourd.py +++ b/tests/transforms/test_label_to_contourd.py @@ -17,7 +17,7 @@ import torch from monai.transforms import LabelToContourd -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose expected_output_for_cube = [ [ @@ -143,7 +143,6 @@ def gen_fixed_img(array_type): class TestContourd(unittest.TestCase): - def test_contour(self): input_param = {"keys": "img", "kernel_type": "Laplace"} diff --git a/tests/test_label_to_mask.py b/tests/transforms/test_label_to_mask.py similarity index 97% rename from tests/test_label_to_mask.py rename to tests/transforms/test_label_to_mask.py index 47a58cc989..66b3f09294 100644 --- a/tests/test_label_to_mask.py +++ b/tests/transforms/test_label_to_mask.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import LabelToMask -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -59,7 +59,6 @@ class TestLabelToMask(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, arguments, image, expected_data): result = LabelToMask(**arguments)(image) diff --git a/tests/test_label_to_maskd.py b/tests/transforms/test_label_to_maskd.py similarity index 97% rename from tests/test_label_to_maskd.py rename to tests/transforms/test_label_to_maskd.py index 44b537128d..051806e3eb 100644 --- a/tests/test_label_to_maskd.py +++ b/tests/transforms/test_label_to_maskd.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import LabelToMaskd -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -59,7 +59,6 @@ class TestLabelToMaskd(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, arguments, input_data, expected_data): result = LabelToMaskd(**arguments)(input_data) diff --git a/tests/test_load_image.py b/tests/transforms/test_load_image.py similarity index 99% rename from tests/test_load_image.py rename to tests/transforms/test_load_image.py index 07acf7c179..930a18f2ee 100644 --- a/tests/test_load_image.py +++ b/tests/transforms/test_load_image.py @@ -29,7 +29,7 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms import LoadImage from monai.utils import optional_import -from tests.utils import SkipIfNoModule, assert_allclose, skip_if_downloading_fails, testing_data_config +from tests.test_utils import SkipIfNoModule, assert_allclose, skip_if_downloading_fails, testing_data_config itk, has_itk = optional_import("itk", allow_namespace_pkg=True) ITKReader, _ = optional_import("monai.data", name="ITKReader", as_type="decorator") @@ -186,7 +186,6 @@ def get_data(self, _obj): @unittest.skipUnless(has_itk, "itk not installed") class TestLoadImage(unittest.TestCase): - @classmethod def setUpClass(cls): super(__class__, cls).setUpClass() @@ -470,7 +469,6 @@ def test_channel_dim(self, input_param, filename, expected_shape): @unittest.skipUnless(has_itk, "itk not installed") class TestLoadImageMeta(unittest.TestCase): - @classmethod def setUpClass(cls): super(__class__, cls).setUpClass() diff --git a/tests/test_load_imaged.py b/tests/transforms/test_load_imaged.py similarity index 99% rename from tests/test_load_imaged.py rename to tests/transforms/test_load_imaged.py index 914240c705..27ed993022 100644 --- a/tests/test_load_imaged.py +++ b/tests/transforms/test_load_imaged.py @@ -28,7 +28,7 @@ from monai.transforms import Compose, EnsureChannelFirstD, FromMetaTensord, LoadImaged, SaveImageD from monai.transforms.meta_utility.dictionary import ToMetaTensord from monai.utils import optional_import -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose itk, has_itk = optional_import("itk", allow_namespace_pkg=True) @@ -46,7 +46,6 @@ @unittest.skipUnless(has_itk, "itk not installed") class TestLoadImaged(unittest.TestCase): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2]) def test_shape(self, input_param, expected_shape): test_image = nib.Nifti1Image(np.random.rand(128, 128, 128), np.eye(4)) @@ -95,7 +94,6 @@ def test_no_file(self): @unittest.skipUnless(has_itk, "itk not installed") class TestConsistency(unittest.TestCase): - def _cmp(self, filename, ch_shape, reader_1, reader_2, outname, ext): data_dict = {"img": filename} keys = data_dict.keys() @@ -157,7 +155,6 @@ def test_png(self): @unittest.skipUnless(has_itk, "itk not installed") class TestLoadImagedMeta(unittest.TestCase): - @classmethod def setUpClass(cls): super(__class__, cls).setUpClass() diff --git a/tests/test_load_spacing_orientation.py b/tests/transforms/test_load_spacing_orientation.py similarity index 97% rename from tests/test_load_spacing_orientation.py rename to tests/transforms/test_load_spacing_orientation.py index cbc730e1bb..8ba3c09789 100644 --- a/tests/test_load_spacing_orientation.py +++ b/tests/transforms/test_load_spacing_orientation.py @@ -14,6 +14,7 @@ import os import time import unittest +from pathlib import Path import nibabel import numpy as np @@ -23,14 +24,13 @@ from monai.transforms import Compose, EnsureChannelFirstd, LoadImaged, Orientationd, Spacingd +TESTS_PATH = Path(__file__).parents[1] FILES = tuple( - os.path.join(os.path.dirname(__file__), "testing_data", filename) - for filename in ("anatomical.nii", "reoriented_anat_moved.nii") + os.path.join(TESTS_PATH, "testing_data", filename) for filename in ("anatomical.nii", "reoriented_anat_moved.nii") ) class TestLoadSpacingOrientation(unittest.TestCase): - @staticmethod def load_image(filename): data = {"image": filename} diff --git a/tests/test_map_and_generate_sampling_centers.py b/tests/transforms/test_map_and_generate_sampling_centers.py similarity index 97% rename from tests/test_map_and_generate_sampling_centers.py rename to tests/transforms/test_map_and_generate_sampling_centers.py index ff74f974b9..ac16b04be9 100644 --- a/tests/test_map_and_generate_sampling_centers.py +++ b/tests/transforms/test_map_and_generate_sampling_centers.py @@ -19,7 +19,7 @@ from monai.transforms import map_and_generate_sampling_centers from monai.utils.misc import set_determinism -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TEST_CASE_1 = [ # test Argmax data @@ -63,7 +63,6 @@ class TestMapAndGenerateSamplingCenters(unittest.TestCase): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2]) def test_map_and_generate_sampling_centers(self, input_data, expected_type, expected_count, expected_shape): results = [] diff --git a/tests/test_map_binary_to_indices.py b/tests/transforms/test_map_binary_to_indices.py similarity index 97% rename from tests/test_map_binary_to_indices.py rename to tests/transforms/test_map_binary_to_indices.py index 9931d997bb..7ba9883700 100644 --- a/tests/test_map_binary_to_indices.py +++ b/tests/transforms/test_map_binary_to_indices.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import map_binary_to_indices -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -64,7 +64,6 @@ class TestMapBinaryToIndices(unittest.TestCase): - @parameterized.expand(TESTS) def test_type_shape(self, input_data, expected_fg, expected_bg): fg_indices, bg_indices = map_binary_to_indices(**input_data) diff --git a/tests/test_map_classes_to_indices.py b/tests/transforms/test_map_classes_to_indices.py similarity index 98% rename from tests/test_map_classes_to_indices.py rename to tests/transforms/test_map_classes_to_indices.py index 902744ab65..f626705195 100644 --- a/tests/test_map_classes_to_indices.py +++ b/tests/transforms/test_map_classes_to_indices.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import map_classes_to_indices -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -124,7 +124,6 @@ class TestMapClassesToIndices(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, input_data, expected_indices): indices = map_classes_to_indices(**input_data) diff --git a/tests/test_map_label_value.py b/tests/transforms/test_map_label_value.py similarity index 98% rename from tests/test_map_label_value.py rename to tests/transforms/test_map_label_value.py index cd311df6bd..ea22e960c0 100644 --- a/tests/test_map_label_value.py +++ b/tests/transforms/test_map_label_value.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms import MapLabelValue -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -75,7 +75,6 @@ class TestMapLabelValue(unittest.TestCase): - @parameterized.expand(TESTS) def test_shape(self, input_param, input_data, expected_value): result = MapLabelValue(**input_param)(input_data) diff --git a/tests/test_map_label_valued.py b/tests/transforms/test_map_label_valued.py similarity index 98% rename from tests/test_map_label_valued.py rename to tests/transforms/test_map_label_valued.py index 0fb46f2515..521c2a1872 100644 --- a/tests/test_map_label_valued.py +++ b/tests/transforms/test_map_label_valued.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms import MapLabelValued -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_CASE_1 = [ {"keys": "seg", "orig_labels": [3, 2, 1], "target_labels": [0, 1, 2]}, @@ -69,7 +69,6 @@ class TestMapLabelValued(unittest.TestCase): - @parameterized.expand( [TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5, TEST_CASE_5_1, TEST_CASE_6, TEST_CASE_7] ) diff --git a/tests/test_map_transform.py b/tests/transforms/test_map_transform.py similarity index 100% rename from tests/test_map_transform.py rename to tests/transforms/test_map_transform.py diff --git a/tests/test_mask_intensity.py b/tests/transforms/test_mask_intensity.py similarity index 98% rename from tests/test_mask_intensity.py rename to tests/transforms/test_mask_intensity.py index b7ff324946..7ab3994550 100644 --- a/tests/test_mask_intensity.py +++ b/tests/transforms/test_mask_intensity.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms import MaskIntensity -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TEST_CASE_1 = [ {"mask_data": np.array([[[0, 0, 0], [0, 1, 0], [0, 0, 0]]])}, @@ -55,7 +55,6 @@ class TestMaskIntensity(unittest.TestCase): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5]) def test_value(self, arguments, image, expected_data): for p in TEST_NDARRAYS: diff --git a/tests/test_mask_intensityd.py b/tests/transforms/test_mask_intensityd.py similarity index 100% rename from tests/test_mask_intensityd.py rename to tests/transforms/test_mask_intensityd.py diff --git a/tests/test_mean_ensemble.py b/tests/transforms/test_mean_ensemble.py similarity index 97% rename from tests/test_mean_ensemble.py rename to tests/transforms/test_mean_ensemble.py index 6b463f8530..55bd6b1422 100644 --- a/tests/test_mean_ensemble.py +++ b/tests/transforms/test_mean_ensemble.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms import MeanEnsemble -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -58,7 +58,6 @@ class TestMeanEnsemble(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, input_param, img, expected_value): result = MeanEnsemble(**input_param)(img) diff --git a/tests/test_mean_ensembled.py b/tests/transforms/test_mean_ensembled.py similarity index 98% rename from tests/test_mean_ensembled.py rename to tests/transforms/test_mean_ensembled.py index 795ae47368..ed6280e8b9 100644 --- a/tests/test_mean_ensembled.py +++ b/tests/transforms/test_mean_ensembled.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms import MeanEnsembled -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -72,7 +72,6 @@ class TestMeanEnsembled(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, input_param, data, expected_value): result = MeanEnsembled(**input_param)(data) diff --git a/tests/test_median_smooth.py b/tests/transforms/test_median_smooth.py similarity index 95% rename from tests/test_median_smooth.py rename to tests/transforms/test_median_smooth.py index 5930c0c6b6..97618a0b43 100644 --- a/tests/test_median_smooth.py +++ b/tests/transforms/test_median_smooth.py @@ -16,7 +16,7 @@ from parameterized import parameterized from monai.transforms import MedianSmooth -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] @@ -31,7 +31,6 @@ class TestMedianSmooth(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, arguments, image, expected_data): result = MedianSmooth(**arguments)(image) diff --git a/tests/test_median_smoothd.py b/tests/transforms/test_median_smoothd.py similarity index 97% rename from tests/test_median_smoothd.py rename to tests/transforms/test_median_smoothd.py index e0bdb331c8..24e325d107 100644 --- a/tests/test_median_smoothd.py +++ b/tests/transforms/test_median_smoothd.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import MedianSmoothd -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS[0:1]: @@ -55,7 +55,6 @@ class TestMedianSmoothd(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, arguments, image, expected_data): result = MedianSmoothd(**arguments)(image) diff --git a/tests/test_morphological_ops.py b/tests/transforms/test_morphological_ops.py similarity index 98% rename from tests/test_morphological_ops.py rename to tests/transforms/test_morphological_ops.py index 422e8c4b9d..1999bdc99a 100644 --- a/tests/test_morphological_ops.py +++ b/tests/transforms/test_morphological_ops.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms.utils_morphological_ops import dilate, erode, get_morphological_filter_result_t -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS_SHAPE = [] for p in TEST_NDARRAYS: @@ -77,7 +77,6 @@ class TestMorph(unittest.TestCase): - @parameterized.expand(TESTS_SHAPE) def test_shape(self, input_data, expected_result): result1 = erode(input_data["mask"], input_data["filter_size"]) diff --git a/tests/test_nifti_endianness.py b/tests/transforms/test_nifti_endianness.py similarity index 100% rename from tests/test_nifti_endianness.py rename to tests/transforms/test_nifti_endianness.py diff --git a/tests/test_normalize_intensity.py b/tests/transforms/test_normalize_intensity.py similarity index 98% rename from tests/test_normalize_intensity.py rename to tests/transforms/test_normalize_intensity.py index 7efd0d83e5..c58bc587f2 100644 --- a/tests/test_normalize_intensity.py +++ b/tests/transforms/test_normalize_intensity.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms import NormalizeIntensity -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -83,7 +83,6 @@ class TestNormalizeIntensity(NumpyImageTestCase2D): - @parameterized.expand([[p] for p in TEST_NDARRAYS]) def test_default(self, im_type): im = im_type(self.imt.copy()) diff --git a/tests/test_normalize_intensityd.py b/tests/transforms/test_normalize_intensityd.py similarity index 97% rename from tests/test_normalize_intensityd.py rename to tests/transforms/test_normalize_intensityd.py index 229dcd00ff..b8e4c7bca8 100644 --- a/tests/test_normalize_intensityd.py +++ b/tests/transforms/test_normalize_intensityd.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import NormalizeIntensityd -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -51,7 +51,6 @@ class TestNormalizeIntensityd(NumpyImageTestCase2D): - @parameterized.expand([[p] for p in TEST_NDARRAYS]) def test_image_normalize_intensityd(self, im_type): key = "img" diff --git a/tests/test_nvtx_decorator.py b/tests/transforms/test_nvtx_decorator.py similarity index 99% rename from tests/test_nvtx_decorator.py rename to tests/transforms/test_nvtx_decorator.py index efd2906972..74fdd5fa28 100644 --- a/tests/test_nvtx_decorator.py +++ b/tests/transforms/test_nvtx_decorator.py @@ -35,7 +35,7 @@ ToTensord, ) from monai.utils import Range, optional_import -from tests.utils import HAS_CUPY +from tests.test_utils import HAS_CUPY _, has_nvtx = optional_import("torch._C._nvtx", descriptor="NVTX is not installed. Are you sure you have a CUDA build?") _, has_tvt = optional_import("torchvision.transforms") @@ -72,7 +72,6 @@ @unittest.skipUnless(has_nvtx, "Required torch._C._nvtx for NVTX Range!") class TestNVTXRangeDecorator(unittest.TestCase): - @parameterized.expand([TEST_CASE_ARRAY_0, TEST_CASE_ARRAY_1]) def test_tranform_array(self, input): transforms = Compose([Range("random flip")(Flip()), Range()(ToTensor())]) diff --git a/tests/test_nvtx_transform.py b/tests/transforms/test_nvtx_transform.py similarity index 100% rename from tests/test_nvtx_transform.py rename to tests/transforms/test_nvtx_transform.py diff --git a/tests/test_orientation.py b/tests/transforms/test_orientation.py similarity index 99% rename from tests/test_orientation.py rename to tests/transforms/test_orientation.py index 2f3334e622..fee287dd5b 100644 --- a/tests/test_orientation.py +++ b/tests/transforms/test_orientation.py @@ -22,7 +22,7 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms import Orientation, create_rotate, create_translate from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_DEVICES, assert_allclose +from tests.test_utils import TEST_DEVICES, assert_allclose TESTS = [] for device in TEST_DEVICES: @@ -177,7 +177,6 @@ class TestOrientationCase(unittest.TestCase): - @parameterized.expand(TESTS) def test_ornt_meta( self, diff --git a/tests/test_orientationd.py b/tests/transforms/test_orientationd.py similarity index 99% rename from tests/test_orientationd.py rename to tests/transforms/test_orientationd.py index b885266c69..3fe52b0b8a 100644 --- a/tests/test_orientationd.py +++ b/tests/transforms/test_orientationd.py @@ -22,7 +22,7 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms import Orientationd from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_DEVICES +from tests.test_utils import TEST_DEVICES TESTS = [] for device in TEST_DEVICES: @@ -65,7 +65,6 @@ class TestOrientationdCase(unittest.TestCase): - @parameterized.expand(TESTS) def test_orntd( self, init_param, img: torch.Tensor, affine: torch.Tensor | None, expected_shape, expected_code, device diff --git a/tests/test_rand_adjust_contrast.py b/tests/transforms/test_rand_adjust_contrast.py similarity index 94% rename from tests/test_rand_adjust_contrast.py rename to tests/transforms/test_rand_adjust_contrast.py index 72d0df141e..36d0724e83 100644 --- a/tests/test_rand_adjust_contrast.py +++ b/tests/transforms/test_rand_adjust_contrast.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import RandAdjustContrast -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose TEST_CASE_1 = [(0.5, 4.5)] @@ -25,7 +25,6 @@ class TestRandAdjustContrast(NumpyImageTestCase2D): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2]) def test_correct_results(self, gamma): adjuster = RandAdjustContrast(prob=1.0, gamma=gamma) diff --git a/tests/test_rand_adjust_contrastd.py b/tests/transforms/test_rand_adjust_contrastd.py similarity index 94% rename from tests/test_rand_adjust_contrastd.py rename to tests/transforms/test_rand_adjust_contrastd.py index bbd5c22009..ab5ae5ef9b 100644 --- a/tests/test_rand_adjust_contrastd.py +++ b/tests/transforms/test_rand_adjust_contrastd.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import RandAdjustContrastd -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose TEST_CASE_1 = [(0.5, 4.5)] @@ -25,7 +25,6 @@ class TestRandAdjustContrastd(NumpyImageTestCase2D): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2]) def test_correct_results(self, gamma): adjuster = RandAdjustContrastd("img", prob=1.0, gamma=gamma) diff --git a/tests/test_rand_affine.py b/tests/transforms/test_rand_affine.py similarity index 98% rename from tests/test_rand_affine.py rename to tests/transforms/test_rand_affine.py index 2c827b7426..7b07d5f09d 100644 --- a/tests/test_rand_affine.py +++ b/tests/transforms/test_rand_affine.py @@ -20,7 +20,7 @@ from monai.transforms import RandAffine from monai.utils.type_conversion import convert_data_type from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose, is_tf32_env +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose, is_tf32_env _rtol = 1e-3 if is_tf32_env() else 1e-4 @@ -140,7 +140,6 @@ class TestRandAffine(unittest.TestCase): - @parameterized.expand(TESTS) def test_rand_affine(self, input_param, input_data, expected_val): g = RandAffine(**input_param) diff --git a/tests/test_rand_affine_grid.py b/tests/transforms/test_rand_affine_grid.py similarity index 99% rename from tests/test_rand_affine_grid.py rename to tests/transforms/test_rand_affine_grid.py index 91558ebd03..c27b44baa9 100644 --- a/tests/test_rand_affine_grid.py +++ b/tests/transforms/test_rand_affine_grid.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms import RandAffineGrid -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose, is_tf32_env +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose, is_tf32_env _rtol = 1e-1 if is_tf32_env() else 1e-4 @@ -198,7 +198,6 @@ class TestRandAffineGrid(unittest.TestCase): - @parameterized.expand(TESTS) def test_rand_affine_grid(self, input_param, input_data, expected_val): g = RandAffineGrid(**input_param) diff --git a/tests/test_rand_affined.py b/tests/transforms/test_rand_affined.py similarity index 99% rename from tests/test_rand_affined.py rename to tests/transforms/test_rand_affined.py index eb8ebd06c5..1c55a936d8 100644 --- a/tests/test_rand_affined.py +++ b/tests/transforms/test_rand_affined.py @@ -22,7 +22,7 @@ from monai.transforms import RandAffined from monai.utils import GridSampleMode, ensure_tuple_rep from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import assert_allclose, is_tf32_env +from tests.test_utils import assert_allclose, is_tf32_env _rtol = 1e-3 if is_tf32_env() else 1e-4 @@ -216,7 +216,6 @@ class TestRandAffined(unittest.TestCase): - @parameterized.expand(x + [y] for x, y in itertools.product(TESTS, (False, True))) def test_rand_affined(self, input_param, input_data, expected_val, track_meta): set_track_meta(track_meta) diff --git a/tests/test_rand_axis_flip.py b/tests/transforms/test_rand_axis_flip.py similarity index 94% rename from tests/test_rand_axis_flip.py rename to tests/transforms/test_rand_axis_flip.py index 9c465a0bcb..6904f77462 100644 --- a/tests/test_rand_axis_flip.py +++ b/tests/transforms/test_rand_axis_flip.py @@ -19,11 +19,10 @@ from monai.data import MetaTensor, set_track_meta from monai.transforms import RandAxisFlip from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, assert_allclose, test_local_inversion +from tests.test_utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, assert_allclose, test_local_inversion class TestRandAxisFlip(NumpyImageTestCase2D): - def test_correct_results(self): for p in TEST_NDARRAYS_ALL: flip = RandAxisFlip(prob=1.0) diff --git a/tests/test_rand_axis_flipd.py b/tests/transforms/test_rand_axis_flipd.py similarity index 94% rename from tests/test_rand_axis_flipd.py rename to tests/transforms/test_rand_axis_flipd.py index d3abef1be4..59da54c5f1 100644 --- a/tests/test_rand_axis_flipd.py +++ b/tests/transforms/test_rand_axis_flipd.py @@ -19,11 +19,10 @@ from monai.data import MetaTensor, set_track_meta from monai.transforms import RandAxisFlipd from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_NDARRAYS_ALL, NumpyImageTestCase3D, assert_allclose, test_local_inversion +from tests.test_utils import TEST_NDARRAYS_ALL, NumpyImageTestCase3D, assert_allclose, test_local_inversion class TestRandAxisFlip(NumpyImageTestCase3D): - def test_correct_results(self): for p in TEST_NDARRAYS_ALL: flip = RandAxisFlipd(keys="img", prob=1.0) diff --git a/tests/test_rand_bias_field.py b/tests/transforms/test_rand_bias_field.py similarity index 98% rename from tests/test_rand_bias_field.py rename to tests/transforms/test_rand_bias_field.py index 328f46b7ee..2789338cd8 100644 --- a/tests/test_rand_bias_field.py +++ b/tests/transforms/test_rand_bias_field.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms import RandBiasField -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS TEST_CASES_2D = [{"prob": 1.0}, (3, 32, 32)] TEST_CASES_3D = [{"prob": 1.0}, (3, 32, 32, 32)] @@ -30,7 +30,6 @@ class TestRandBiasField(unittest.TestCase): - @parameterized.expand([TEST_CASES_2D, TEST_CASES_3D]) def test_output_shape(self, class_args, img_shape): for p in TEST_NDARRAYS: diff --git a/tests/test_rand_bias_fieldd.py b/tests/transforms/test_rand_bias_fieldd.py similarity index 100% rename from tests/test_rand_bias_fieldd.py rename to tests/transforms/test_rand_bias_fieldd.py diff --git a/tests/test_rand_coarse_dropout.py b/tests/transforms/test_rand_coarse_dropout.py similarity index 98% rename from tests/test_rand_coarse_dropout.py rename to tests/transforms/test_rand_coarse_dropout.py index ac857f9184..5d4173d163 100644 --- a/tests/test_rand_coarse_dropout.py +++ b/tests/transforms/test_rand_coarse_dropout.py @@ -19,7 +19,7 @@ from monai.transforms import RandCoarseDropout from monai.utils import fall_back_tuple -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TEST_CASE_0 = [ {"holes": 2, "spatial_size": [2, 2, 2], "fill_value": 5, "prob": 1.0}, @@ -63,7 +63,6 @@ class TestRandCoarseDropout(unittest.TestCase): - @parameterized.expand( [TEST_CASE_0, TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5, TEST_CASE_6, TEST_CASE_7] ) diff --git a/tests/test_rand_coarse_dropoutd.py b/tests/transforms/test_rand_coarse_dropoutd.py similarity index 100% rename from tests/test_rand_coarse_dropoutd.py rename to tests/transforms/test_rand_coarse_dropoutd.py diff --git a/tests/test_rand_coarse_shuffle.py b/tests/transforms/test_rand_coarse_shuffle.py similarity index 100% rename from tests/test_rand_coarse_shuffle.py rename to tests/transforms/test_rand_coarse_shuffle.py diff --git a/tests/test_rand_coarse_shuffled.py b/tests/transforms/test_rand_coarse_shuffled.py similarity index 100% rename from tests/test_rand_coarse_shuffled.py rename to tests/transforms/test_rand_coarse_shuffled.py diff --git a/tests/test_rand_crop_by_label_classes.py b/tests/transforms/test_rand_crop_by_label_classes.py similarity index 98% rename from tests/test_rand_crop_by_label_classes.py rename to tests/transforms/test_rand_crop_by_label_classes.py index 743b894d75..84c75858e9 100644 --- a/tests/test_rand_crop_by_label_classes.py +++ b/tests/transforms/test_rand_crop_by_label_classes.py @@ -19,7 +19,7 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms import ClassesToIndices, RandCropByLabelClasses from monai.transforms.lazy.functional import apply_pending -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose TESTS_INDICES, TESTS_SHAPE = [], [] for p in TEST_NDARRAYS_ALL: @@ -127,7 +127,6 @@ class TestRandCropByLabelClasses(unittest.TestCase): - @parameterized.expand(TESTS_INDICES + TESTS_SHAPE) def test_type_shape(self, input_param, input_data, expected_type, expected_shape): result = RandCropByLabelClasses(**input_param)(**input_data) diff --git a/tests/test_rand_crop_by_label_classesd.py b/tests/transforms/test_rand_crop_by_label_classesd.py similarity index 98% rename from tests/test_rand_crop_by_label_classesd.py rename to tests/transforms/test_rand_crop_by_label_classesd.py index 8908c456ee..290165fbd4 100644 --- a/tests/test_rand_crop_by_label_classesd.py +++ b/tests/transforms/test_rand_crop_by_label_classesd.py @@ -19,7 +19,7 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms import ClassesToIndicesd, RandCropByLabelClassesd from monai.transforms.lazy.functional import apply_pending -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose TESTS = [] for p in TEST_NDARRAYS_ALL: @@ -120,7 +120,6 @@ class TestRandCropByLabelClassesd(unittest.TestCase): - @parameterized.expand(TESTS) def test_type_shape(self, input_param, input_data, expected_type, expected_shape): result = RandCropByLabelClassesd(**input_param)(input_data) diff --git a/tests/test_rand_crop_by_pos_neg_label.py b/tests/transforms/test_rand_crop_by_pos_neg_label.py similarity index 98% rename from tests/test_rand_crop_by_pos_neg_label.py rename to tests/transforms/test_rand_crop_by_pos_neg_label.py index 66e7a5e849..85b6d0c65e 100644 --- a/tests/test_rand_crop_by_pos_neg_label.py +++ b/tests/transforms/test_rand_crop_by_pos_neg_label.py @@ -20,7 +20,7 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms import RandCropByPosNegLabel from monai.transforms.lazy.functional import apply_pending -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose TESTS = [ [ @@ -96,7 +96,6 @@ class TestRandCropByPosNegLabel(unittest.TestCase): - @staticmethod def convert_data_type(im_type, d, keys=("img", "image", "label")): out = deepcopy(d) diff --git a/tests/test_rand_crop_by_pos_neg_labeld.py b/tests/transforms/test_rand_crop_by_pos_neg_labeld.py similarity index 99% rename from tests/test_rand_crop_by_pos_neg_labeld.py rename to tests/transforms/test_rand_crop_by_pos_neg_labeld.py index 11381e226d..0724397163 100644 --- a/tests/test_rand_crop_by_pos_neg_labeld.py +++ b/tests/transforms/test_rand_crop_by_pos_neg_labeld.py @@ -20,7 +20,7 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms import RandCropByPosNegLabeld from monai.transforms.lazy.functional import apply_pending -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose TESTS = [ [ @@ -107,7 +107,6 @@ class TestRandCropByPosNegLabeld(unittest.TestCase): - @staticmethod def convert_data_type(im_type, d, keys=("img", "image", "label")): out = deepcopy(d) diff --git a/tests/test_rand_cucim_dict_transform.py b/tests/transforms/test_rand_cucim_dict_transform.py similarity index 99% rename from tests/test_rand_cucim_dict_transform.py rename to tests/transforms/test_rand_cucim_dict_transform.py index 3f473897dd..2bb2009c23 100644 --- a/tests/test_rand_cucim_dict_transform.py +++ b/tests/transforms/test_rand_cucim_dict_transform.py @@ -18,7 +18,7 @@ from monai.transforms import RandCuCIMd from monai.utils import optional_import, set_determinism -from tests.utils import HAS_CUPY, skip_if_no_cuda +from tests.test_utils import HAS_CUPY, skip_if_no_cuda _, has_cut = optional_import("cucim.core.operations.expose.transform") cp, _ = optional_import("cupy") @@ -78,7 +78,6 @@ @unittest.skipUnless(HAS_CUPY, "CuPy is required.") @unittest.skipUnless(has_cut, "cuCIM transforms are required.") class TestRandCuCIMDict(unittest.TestCase): - @parameterized.expand( [ TEST_CASE_COLOR_JITTER_1, diff --git a/tests/test_rand_cucim_transform.py b/tests/transforms/test_rand_cucim_transform.py similarity index 99% rename from tests/test_rand_cucim_transform.py rename to tests/transforms/test_rand_cucim_transform.py index ce731a05ae..7406e71e41 100644 --- a/tests/test_rand_cucim_transform.py +++ b/tests/transforms/test_rand_cucim_transform.py @@ -18,7 +18,7 @@ from monai.transforms import RandCuCIM from monai.utils import optional_import, set_determinism -from tests.utils import HAS_CUPY, skip_if_no_cuda +from tests.test_utils import HAS_CUPY, skip_if_no_cuda _, has_cut = optional_import("cucim.core.operations.expose.transform") cp, _ = optional_import("cupy") @@ -78,7 +78,6 @@ @unittest.skipUnless(HAS_CUPY, "CuPy is required.") @unittest.skipUnless(has_cut, "cuCIM transforms are required.") class TestRandCuCIM(unittest.TestCase): - @parameterized.expand( [ TEST_CASE_COLOR_JITTER_1, diff --git a/tests/test_rand_deform_grid.py b/tests/transforms/test_rand_deform_grid.py similarity index 99% rename from tests/test_rand_deform_grid.py rename to tests/transforms/test_rand_deform_grid.py index 88fc1333ec..3e2cc4ee76 100644 --- a/tests/test_rand_deform_grid.py +++ b/tests/transforms/test_rand_deform_grid.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import RandDeformGrid -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_CASES = [ [ @@ -126,7 +126,6 @@ class TestRandDeformGrid(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_rand_deform_grid(self, input_param, input_data, expected_val): g = RandDeformGrid(**input_param) diff --git a/tests/test_rand_elastic_2d.py b/tests/transforms/test_rand_elastic_2d.py similarity index 98% rename from tests/test_rand_elastic_2d.py rename to tests/transforms/test_rand_elastic_2d.py index 1f3d389a93..920bdfab26 100644 --- a/tests/test_rand_elastic_2d.py +++ b/tests/transforms/test_rand_elastic_2d.py @@ -19,7 +19,7 @@ from monai.data import MetaTensor, set_track_meta from monai.transforms import Rand2DElastic -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose, is_tf32_env +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose, is_tf32_env _rtol = 5e-3 if is_tf32_env() else 1e-4 @@ -110,7 +110,6 @@ class TestRand2DElastic(unittest.TestCase): - @parameterized.expand(TESTS) def test_rand_2d_elastic(self, input_param, input_data, expected_val): g = Rand2DElastic(**input_param) diff --git a/tests/test_rand_elastic_3d.py b/tests/transforms/test_rand_elastic_3d.py similarity index 98% rename from tests/test_rand_elastic_3d.py rename to tests/transforms/test_rand_elastic_3d.py index 5bfa8a6e83..b027f431fa 100644 --- a/tests/test_rand_elastic_3d.py +++ b/tests/transforms/test_rand_elastic_3d.py @@ -19,7 +19,7 @@ from monai.data import MetaTensor, set_track_meta from monai.transforms import Rand3DElastic -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose TESTS = [] for p in TEST_NDARRAYS_ALL: @@ -86,7 +86,6 @@ class TestRand3DElastic(unittest.TestCase): - @parameterized.expand(TESTS) def test_rand_3d_elastic(self, input_param, input_data, expected_val): g = Rand3DElastic(**input_param) diff --git a/tests/test_rand_elasticd_2d.py b/tests/transforms/test_rand_elasticd_2d.py similarity index 98% rename from tests/test_rand_elasticd_2d.py rename to tests/transforms/test_rand_elasticd_2d.py index 10aa116192..90f171677a 100644 --- a/tests/test_rand_elasticd_2d.py +++ b/tests/transforms/test_rand_elasticd_2d.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms import Rand2DElasticd -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose, is_tf32_env +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose, is_tf32_env _rtol = 5e-3 if is_tf32_env() else 1e-4 @@ -160,7 +160,6 @@ class TestRand2DElasticd(unittest.TestCase): - @parameterized.expand(TESTS) def test_rand_2d_elasticd(self, input_param, input_data, expected_val): g = Rand2DElasticd(**input_param) diff --git a/tests/test_rand_elasticd_3d.py b/tests/transforms/test_rand_elasticd_3d.py similarity index 98% rename from tests/test_rand_elasticd_3d.py rename to tests/transforms/test_rand_elasticd_3d.py index 3838f43f29..ea47fbe80a 100644 --- a/tests/test_rand_elasticd_3d.py +++ b/tests/transforms/test_rand_elasticd_3d.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms import Rand3DElasticd -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose TESTS = [] for p in TEST_NDARRAYS_ALL: @@ -139,7 +139,6 @@ class TestRand3DElasticd(unittest.TestCase): - @parameterized.expand(TESTS) def test_rand_3d_elasticd(self, input_param, input_data, expected_val): g = Rand3DElasticd(**input_param) diff --git a/tests/test_rand_flip.py b/tests/transforms/test_rand_flip.py similarity index 95% rename from tests/test_rand_flip.py rename to tests/transforms/test_rand_flip.py index faeae94cab..863b9f9704 100644 --- a/tests/test_rand_flip.py +++ b/tests/transforms/test_rand_flip.py @@ -20,7 +20,7 @@ from monai.data import MetaTensor, set_track_meta from monai.transforms import RandFlip from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, assert_allclose, test_local_inversion +from tests.test_utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, assert_allclose, test_local_inversion INVALID_CASES = [("wrong_axis", ["s", 1], TypeError), ("not_numbers", "s", TypeError)] @@ -28,7 +28,6 @@ class TestRandFlip(NumpyImageTestCase2D): - @parameterized.expand(INVALID_CASES) def test_invalid_inputs(self, _, spatial_axis, raises): with self.assertRaises(raises): diff --git a/tests/test_rand_flipd.py b/tests/transforms/test_rand_flipd.py similarity index 94% rename from tests/test_rand_flipd.py rename to tests/transforms/test_rand_flipd.py index a34aa58ed2..3016cd2814 100644 --- a/tests/test_rand_flipd.py +++ b/tests/transforms/test_rand_flipd.py @@ -20,13 +20,12 @@ from monai.data import MetaTensor, set_track_meta from monai.transforms import RandFlipd from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, assert_allclose, test_local_inversion +from tests.test_utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, assert_allclose, test_local_inversion VALID_CASES = [("no_axis", None), ("one_axis", 1), ("many_axis", [0, 1])] class TestRandFlipd(NumpyImageTestCase2D): - @parameterized.expand(VALID_CASES) def test_correct_results(self, _, spatial_axis): for p in TEST_NDARRAYS_ALL: diff --git a/tests/test_rand_gaussian_noise.py b/tests/transforms/test_rand_gaussian_noise.py similarity index 96% rename from tests/test_rand_gaussian_noise.py rename to tests/transforms/test_rand_gaussian_noise.py index 233b4dd1b6..e67abb6f37 100644 --- a/tests/test_rand_gaussian_noise.py +++ b/tests/transforms/test_rand_gaussian_noise.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms import RandGaussianNoise -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D TESTS = [] for p in TEST_NDARRAYS: @@ -28,7 +28,6 @@ class TestRandGaussianNoise(NumpyImageTestCase2D): - @parameterized.expand(TESTS) def test_correct_results(self, _, im_type, mean, std, sample_std): seed = 0 diff --git a/tests/test_rand_gaussian_noised.py b/tests/transforms/test_rand_gaussian_noised.py similarity index 96% rename from tests/test_rand_gaussian_noised.py rename to tests/transforms/test_rand_gaussian_noised.py index e3df196be2..a30d965915 100644 --- a/tests/test_rand_gaussian_noised.py +++ b/tests/transforms/test_rand_gaussian_noised.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms import RandGaussianNoised -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D TESTS = [] for p in TEST_NDARRAYS: @@ -30,7 +30,6 @@ class TestRandGaussianNoised(NumpyImageTestCase2D): - @parameterized.expand(TESTS) def test_correct_results(self, _, im_type, keys, mean, std, sample_std): gaussian_fn = RandGaussianNoised( diff --git a/tests/test_rand_gaussian_sharpen.py b/tests/transforms/test_rand_gaussian_sharpen.py similarity index 98% rename from tests/test_rand_gaussian_sharpen.py rename to tests/transforms/test_rand_gaussian_sharpen.py index ee8604c14b..83c3f9d0de 100644 --- a/tests/test_rand_gaussian_sharpen.py +++ b/tests/transforms/test_rand_gaussian_sharpen.py @@ -16,7 +16,7 @@ from parameterized import parameterized from monai.transforms import RandGaussianSharpen -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] @@ -128,7 +128,6 @@ class TestRandGaussianSharpen(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, arguments, image, expected_data): converter = RandGaussianSharpen(**arguments) diff --git a/tests/test_rand_gaussian_sharpend.py b/tests/transforms/test_rand_gaussian_sharpend.py similarity index 98% rename from tests/test_rand_gaussian_sharpend.py rename to tests/transforms/test_rand_gaussian_sharpend.py index b9bae529db..034047b530 100644 --- a/tests/test_rand_gaussian_sharpend.py +++ b/tests/transforms/test_rand_gaussian_sharpend.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import RandGaussianSharpend -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -131,7 +131,6 @@ class TestRandGaussianSharpend(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, arguments, image, expected_data): converter = RandGaussianSharpend(**arguments) diff --git a/tests/test_rand_gaussian_smooth.py b/tests/transforms/test_rand_gaussian_smooth.py similarity index 98% rename from tests/test_rand_gaussian_smooth.py rename to tests/transforms/test_rand_gaussian_smooth.py index 8bb36ca0fa..82392746a3 100644 --- a/tests/test_rand_gaussian_smooth.py +++ b/tests/transforms/test_rand_gaussian_smooth.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import RandGaussianSmooth -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -86,7 +86,6 @@ class TestRandGaussianSmooth(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, arguments, image, expected_data): converter = RandGaussianSmooth(**arguments) diff --git a/tests/test_rand_gaussian_smoothd.py b/tests/transforms/test_rand_gaussian_smoothd.py similarity index 98% rename from tests/test_rand_gaussian_smoothd.py rename to tests/transforms/test_rand_gaussian_smoothd.py index a93b355184..67bdd6946c 100644 --- a/tests/test_rand_gaussian_smoothd.py +++ b/tests/transforms/test_rand_gaussian_smoothd.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import RandGaussianSmoothd -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -86,7 +86,6 @@ class TestRandGaussianSmoothd(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, arguments, image, expected_data): converter = RandGaussianSmoothd(**arguments) diff --git a/tests/test_rand_gibbs_noise.py b/tests/transforms/test_rand_gibbs_noise.py similarity index 98% rename from tests/test_rand_gibbs_noise.py rename to tests/transforms/test_rand_gibbs_noise.py index 5ef249a1f4..21a17fd688 100644 --- a/tests/test_rand_gibbs_noise.py +++ b/tests/transforms/test_rand_gibbs_noise.py @@ -21,7 +21,7 @@ from monai.transforms import RandGibbsNoise from monai.utils.misc import set_determinism from monai.utils.module import optional_import -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose _, has_torch_fft = optional_import("torch.fft", name="fftshift") @@ -32,7 +32,6 @@ class TestRandGibbsNoise(unittest.TestCase): - def setUp(self): set_determinism(0) super().setUp() diff --git a/tests/test_rand_gibbs_noised.py b/tests/transforms/test_rand_gibbs_noised.py similarity index 98% rename from tests/test_rand_gibbs_noised.py rename to tests/transforms/test_rand_gibbs_noised.py index 382290dd39..9cdd35a171 100644 --- a/tests/test_rand_gibbs_noised.py +++ b/tests/transforms/test_rand_gibbs_noised.py @@ -21,7 +21,7 @@ from monai.transforms import RandGibbsNoised from monai.utils.misc import set_determinism from monai.utils.module import optional_import -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose _, has_torch_fft = optional_import("torch.fft", name="fftshift") @@ -34,7 +34,6 @@ class TestRandGibbsNoised(unittest.TestCase): - def setUp(self): set_determinism(0) super().setUp() diff --git a/tests/test_rand_grid_distortion.py b/tests/transforms/test_rand_grid_distortion.py similarity index 98% rename from tests/test_rand_grid_distortion.py rename to tests/transforms/test_rand_grid_distortion.py index e07c311b25..4e0cda2d19 100644 --- a/tests/test_rand_grid_distortion.py +++ b/tests/transforms/test_rand_grid_distortion.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import RandGridDistortion -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose TESTS = [] for p in TEST_NDARRAYS_ALL: @@ -84,7 +84,6 @@ class TestRandGridDistortion(unittest.TestCase): - @parameterized.expand(TESTS) def test_rand_grid_distortion(self, input_param, seed, input_data, expected_val): g = RandGridDistortion(**input_param) diff --git a/tests/test_rand_grid_distortiond.py b/tests/transforms/test_rand_grid_distortiond.py similarity index 98% rename from tests/test_rand_grid_distortiond.py rename to tests/transforms/test_rand_grid_distortiond.py index f28e0ae86e..8f8de144f6 100644 --- a/tests/test_rand_grid_distortiond.py +++ b/tests/transforms/test_rand_grid_distortiond.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import RandGridDistortiond -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose TESTS = [] num_cells = 2 @@ -77,7 +77,6 @@ class TestRandGridDistortiond(unittest.TestCase): - @parameterized.expand(TESTS) def test_rand_grid_distortiond(self, input_param, seed, input_data, expected_val_img, expected_val_mask): g = RandGridDistortiond(**input_param) diff --git a/tests/test_rand_histogram_shift.py b/tests/transforms/test_rand_histogram_shift.py similarity index 98% rename from tests/test_rand_histogram_shift.py rename to tests/transforms/test_rand_histogram_shift.py index 785e24e53b..e9dba31bbb 100644 --- a/tests/test_rand_histogram_shift.py +++ b/tests/transforms/test_rand_histogram_shift.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms import RandHistogramShift -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -56,7 +56,6 @@ class TestRandHistogramShift(unittest.TestCase): - @parameterized.expand(TESTS) def test_rand_histogram_shift(self, input_param, input_data, expected_val): g = RandHistogramShift(**input_param) diff --git a/tests/test_rand_k_space_spike_noise.py b/tests/transforms/test_rand_k_space_spike_noise.py similarity index 98% rename from tests/test_rand_k_space_spike_noise.py rename to tests/transforms/test_rand_k_space_spike_noise.py index 7a9dd4288d..eb0fa154f4 100644 --- a/tests/test_rand_k_space_spike_noise.py +++ b/tests/transforms/test_rand_k_space_spike_noise.py @@ -19,7 +19,7 @@ from monai.data.synthetic import create_test_image_2d, create_test_image_3d from monai.transforms import KSpaceSpikeNoise, RandKSpaceSpikeNoise from monai.utils.misc import set_determinism -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for shape in ((128, 64), (64, 48, 80)): @@ -29,7 +29,6 @@ class TestRandKSpaceSpikeNoise(unittest.TestCase): - def setUp(self): set_determinism(0) super().setUp() diff --git a/tests/test_rand_k_space_spike_noised.py b/tests/transforms/test_rand_k_space_spike_noised.py similarity index 97% rename from tests/test_rand_k_space_spike_noised.py rename to tests/transforms/test_rand_k_space_spike_noised.py index 86d4256637..41fb1fff01 100644 --- a/tests/test_rand_k_space_spike_noised.py +++ b/tests/transforms/test_rand_k_space_spike_noised.py @@ -19,7 +19,7 @@ from monai.data.synthetic import create_test_image_2d, create_test_image_3d from monai.transforms import RandKSpaceSpikeNoised from monai.utils.misc import set_determinism -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for shape in ((128, 64), (64, 48, 80)): @@ -30,7 +30,6 @@ class TestKSpaceSpikeNoised(unittest.TestCase): - def setUp(self): set_determinism(0) super().setUp() diff --git a/tests/test_rand_rician_noise.py b/tests/transforms/test_rand_rician_noise.py similarity index 96% rename from tests/test_rand_rician_noise.py rename to tests/transforms/test_rand_rician_noise.py index 8dd1c48e29..6f461230e8 100644 --- a/tests/test_rand_rician_noise.py +++ b/tests/transforms/test_rand_rician_noise.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms import RandRicianNoise -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D TESTS = [] for p in TEST_NDARRAYS: @@ -27,7 +27,6 @@ class TestRandRicianNoise(NumpyImageTestCase2D): - @parameterized.expand(TESTS) def test_correct_results(self, _, in_type, mean, std): seed = 0 diff --git a/tests/test_rand_rician_noised.py b/tests/transforms/test_rand_rician_noised.py similarity index 96% rename from tests/test_rand_rician_noised.py rename to tests/transforms/test_rand_rician_noised.py index a190ba866d..beff228f21 100644 --- a/tests/test_rand_rician_noised.py +++ b/tests/transforms/test_rand_rician_noised.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms import RandRicianNoised -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D TESTS = [] for p in TEST_NDARRAYS: @@ -29,7 +29,6 @@ class TestRandRicianNoisedNumpy(NumpyImageTestCase2D): - @parameterized.expand(TESTS) def test_correct_results(self, _, in_type, keys, mean, std): rician_fn = RandRicianNoised(keys=keys, prob=1.0, mean=mean, std=std, dtype=np.float64) diff --git a/tests/test_rand_rotate.py b/tests/transforms/test_rand_rotate.py similarity index 99% rename from tests/test_rand_rotate.py rename to tests/transforms/test_rand_rotate.py index c54229dcfe..d1240e6c6a 100644 --- a/tests/test_rand_rotate.py +++ b/tests/transforms/test_rand_rotate.py @@ -22,7 +22,7 @@ from monai.data import MetaTensor, set_track_meta from monai.transforms import RandRotate from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import ( +from tests.test_utils import ( TEST_NDARRAYS_ALL, NumpyImageTestCase2D, NumpyImageTestCase3D, @@ -73,7 +73,6 @@ class TestRandRotate2D(NumpyImageTestCase2D): - @parameterized.expand(TEST_CASES_2D) def test_correct_results(self, im_type, degrees, keep_size, mode, padding_mode, align_corners): init_param = { @@ -113,7 +112,6 @@ def test_correct_results(self, im_type, degrees, keep_size, mode, padding_mode, @unittest.skipIf(USE_COMPILED, "unit tests not for compiled version.") class TestRandRotate3D(NumpyImageTestCase3D): - @parameterized.expand(TEST_CASES_3D) def test_correct_results(self, im_type, x, y, z, keep_size, mode, padding_mode, align_corners, expected): init_param = { @@ -148,7 +146,6 @@ def test_correct_results(self, im_type, x, y, z, keep_size, mode, padding_mode, class TestRandRotateDtype(NumpyImageTestCase2D): - @parameterized.expand(TEST_CASES_2D) def test_correct_results(self, im_type, degrees, keep_size, mode, padding_mode, align_corners): rotate_fn = RandRotate( diff --git a/tests/test_rand_rotate90.py b/tests/transforms/test_rand_rotate90.py similarity index 97% rename from tests/test_rand_rotate90.py rename to tests/transforms/test_rand_rotate90.py index be2e658b78..b5e36f2dde 100644 --- a/tests/test_rand_rotate90.py +++ b/tests/transforms/test_rand_rotate90.py @@ -19,11 +19,10 @@ from monai.data import MetaTensor, set_track_meta from monai.transforms import RandRotate90 from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, assert_allclose, test_local_inversion +from tests.test_utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, assert_allclose, test_local_inversion class TestRandRotate90(NumpyImageTestCase2D): - def test_default(self): rotate = RandRotate90() for p in TEST_NDARRAYS_ALL: diff --git a/tests/test_rand_rotate90d.py b/tests/transforms/test_rand_rotate90d.py similarity index 97% rename from tests/test_rand_rotate90d.py rename to tests/transforms/test_rand_rotate90d.py index 02836b5dd8..0434f0b554 100644 --- a/tests/test_rand_rotate90d.py +++ b/tests/transforms/test_rand_rotate90d.py @@ -19,11 +19,10 @@ from monai.data import MetaTensor, set_track_meta from monai.transforms import RandRotate90d from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, assert_allclose, test_local_inversion +from tests.test_utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, assert_allclose, test_local_inversion class TestRandRotate90d(NumpyImageTestCase2D): - def test_default(self): key = "test" rotate = RandRotate90d(keys=key) diff --git a/tests/test_rand_rotated.py b/tests/transforms/test_rand_rotated.py similarity index 98% rename from tests/test_rand_rotated.py rename to tests/transforms/test_rand_rotated.py index 71d0f67b63..46026b6fde 100644 --- a/tests/test_rand_rotated.py +++ b/tests/transforms/test_rand_rotated.py @@ -22,7 +22,7 @@ from monai.transforms import RandRotated from monai.utils import GridSampleMode, GridSamplePadMode from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, NumpyImageTestCase3D, test_local_inversion +from tests.test_utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, NumpyImageTestCase3D, test_local_inversion TEST_CASES_2D: list[tuple] = [] for p in TEST_NDARRAYS_ALL: @@ -109,7 +109,6 @@ class TestRandRotated2D(NumpyImageTestCase2D): - @parameterized.expand(TEST_CASES_2D) def test_correct_results(self, im_type, degrees, keep_size, mode, padding_mode, align_corners): init_param = { @@ -154,7 +153,6 @@ def test_correct_results(self, im_type, degrees, keep_size, mode, padding_mode, @unittest.skipIf(USE_COMPILED, "unit tests not for compiled version.") class TestRandRotated3D(NumpyImageTestCase3D): - @parameterized.expand(TEST_CASES_3D) def test_correct_shapes(self, im_type, x, y, z, keep_size, mode, padding_mode, align_corners, expected): init_param = { diff --git a/tests/test_rand_scale_crop.py b/tests/transforms/test_rand_scale_crop.py similarity index 97% rename from tests/test_rand_scale_crop.py rename to tests/transforms/test_rand_scale_crop.py index bf43273fcf..464ab4438d 100644 --- a/tests/test_rand_scale_crop.py +++ b/tests/transforms/test_rand_scale_crop.py @@ -18,7 +18,7 @@ from monai.transforms import RandScaleCrop from tests.croppers import CropTest -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose TEST_SHAPES = [ [{"roi_scale": [1.0, 1.0, -1.0], "random_center": True}, (3, 3, 3, 4), (3, 3, 3, 4)], diff --git a/tests/test_rand_scale_cropd.py b/tests/transforms/test_rand_scale_cropd.py similarity index 98% rename from tests/test_rand_scale_cropd.py rename to tests/transforms/test_rand_scale_cropd.py index 15a48a55d7..27d3e5a44f 100644 --- a/tests/test_rand_scale_cropd.py +++ b/tests/transforms/test_rand_scale_cropd.py @@ -18,7 +18,7 @@ from monai.transforms import RandScaleCropd from tests.croppers import CropTest -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose TEST_SHAPES = [ [{"keys": "img", "roi_scale": [1.0, 1.0, -1.0], "random_center": True}, (3, 3, 3, 4), (3, 3, 3, 4)], diff --git a/tests/test_rand_scale_intensity.py b/tests/transforms/test_rand_scale_intensity.py similarity index 96% rename from tests/test_rand_scale_intensity.py rename to tests/transforms/test_rand_scale_intensity.py index 7e999c00b3..1b6ec56fdb 100644 --- a/tests/test_rand_scale_intensity.py +++ b/tests/transforms/test_rand_scale_intensity.py @@ -17,11 +17,10 @@ from parameterized import parameterized from monai.transforms import RandScaleIntensity -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class TestRandScaleIntensity(NumpyImageTestCase2D): - @parameterized.expand([[p] for p in TEST_NDARRAYS]) def test_value(self, p): scaler = RandScaleIntensity(factors=0.5, prob=1.0) diff --git a/tests/test_rand_scale_intensity_fixed_mean.py b/tests/transforms/test_rand_scale_intensity_fixed_mean.py similarity index 94% rename from tests/test_rand_scale_intensity_fixed_mean.py rename to tests/transforms/test_rand_scale_intensity_fixed_mean.py index 9324c711fa..ac45a9d463 100644 --- a/tests/test_rand_scale_intensity_fixed_mean.py +++ b/tests/transforms/test_rand_scale_intensity_fixed_mean.py @@ -17,11 +17,10 @@ from parameterized import parameterized from monai.transforms import RandScaleIntensityFixedMean -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class TestRandScaleIntensity(NumpyImageTestCase2D): - @parameterized.expand([[p] for p in TEST_NDARRAYS]) def test_value(self, p): scaler = RandScaleIntensityFixedMean(prob=1.0, factors=0.5) diff --git a/tests/test_rand_scale_intensity_fixed_meand.py b/tests/transforms/test_rand_scale_intensity_fixed_meand.py similarity index 94% rename from tests/test_rand_scale_intensity_fixed_meand.py rename to tests/transforms/test_rand_scale_intensity_fixed_meand.py index 8c127ac130..55111a4c2e 100644 --- a/tests/test_rand_scale_intensity_fixed_meand.py +++ b/tests/transforms/test_rand_scale_intensity_fixed_meand.py @@ -16,11 +16,10 @@ import numpy as np from monai.transforms import RandScaleIntensityFixedMeand -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class TestRandScaleIntensityFixedMeand(NumpyImageTestCase2D): - def test_value(self): key = "img" for p in TEST_NDARRAYS: diff --git a/tests/test_rand_scale_intensityd.py b/tests/transforms/test_rand_scale_intensityd.py similarity index 96% rename from tests/test_rand_scale_intensityd.py rename to tests/transforms/test_rand_scale_intensityd.py index 32c96f0313..3a44ab60bb 100644 --- a/tests/test_rand_scale_intensityd.py +++ b/tests/transforms/test_rand_scale_intensityd.py @@ -16,11 +16,10 @@ import numpy as np from monai.transforms import RandScaleIntensityd -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class TestRandScaleIntensityd(NumpyImageTestCase2D): - def test_value(self): key = "img" for p in TEST_NDARRAYS: diff --git a/tests/test_rand_shift_intensity.py b/tests/transforms/test_rand_shift_intensity.py similarity index 96% rename from tests/test_rand_shift_intensity.py rename to tests/transforms/test_rand_shift_intensity.py index 907773ccf5..32021a6bb6 100644 --- a/tests/test_rand_shift_intensity.py +++ b/tests/transforms/test_rand_shift_intensity.py @@ -17,11 +17,10 @@ from parameterized import parameterized from monai.transforms import RandShiftIntensity -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class TestRandShiftIntensity(NumpyImageTestCase2D): - @parameterized.expand([[p] for p in TEST_NDARRAYS]) def test_value(self, p): shifter = RandShiftIntensity(offsets=1.0, prob=1.0) diff --git a/tests/test_rand_shift_intensityd.py b/tests/transforms/test_rand_shift_intensityd.py similarity index 97% rename from tests/test_rand_shift_intensityd.py rename to tests/transforms/test_rand_shift_intensityd.py index 51675e324c..2faeb9288b 100644 --- a/tests/test_rand_shift_intensityd.py +++ b/tests/transforms/test_rand_shift_intensityd.py @@ -17,11 +17,10 @@ from monai.transforms import IntensityStatsd, RandShiftIntensityd from monai.utils.enums import PostFix -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class TestRandShiftIntensityd(NumpyImageTestCase2D): - def test_value(self): key = "img" for p in TEST_NDARRAYS: diff --git a/tests/test_rand_simulate_low_resolution.py b/tests/transforms/test_rand_simulate_low_resolution.py similarity index 98% rename from tests/test_rand_simulate_low_resolution.py rename to tests/transforms/test_rand_simulate_low_resolution.py index 6aa586fb0b..3a8032d152 100644 --- a/tests/test_rand_simulate_low_resolution.py +++ b/tests/transforms/test_rand_simulate_low_resolution.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import RandSimulateLowResolution -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -71,7 +71,6 @@ class TestRandGaussianSmooth(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, arguments, image, expected_data): randsimlowres = RandSimulateLowResolution(**arguments) diff --git a/tests/test_rand_simulate_low_resolutiond.py b/tests/transforms/test_rand_simulate_low_resolutiond.py similarity index 97% rename from tests/test_rand_simulate_low_resolutiond.py rename to tests/transforms/test_rand_simulate_low_resolutiond.py index 5ec84eba1d..2a042aa92b 100644 --- a/tests/test_rand_simulate_low_resolutiond.py +++ b/tests/transforms/test_rand_simulate_low_resolutiond.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import RandSimulateLowResolutiond -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -60,7 +60,6 @@ class TestRandGaussianSmoothd(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, arguments, image, expected_data): converter = RandSimulateLowResolutiond(**arguments) diff --git a/tests/test_rand_spatial_crop.py b/tests/transforms/test_rand_spatial_crop.py similarity index 98% rename from tests/test_rand_spatial_crop.py rename to tests/transforms/test_rand_spatial_crop.py index df121e2220..03d56daf61 100644 --- a/tests/test_rand_spatial_crop.py +++ b/tests/transforms/test_rand_spatial_crop.py @@ -20,7 +20,7 @@ from monai.transforms import RandScaleCrop, RandSpatialCrop from monai.transforms.lazy.functional import apply_pending from tests.croppers import CropTest -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose TEST_SHAPES = [ [{"roi_size": [3, 3, -1], "random_center": True}, (3, 3, 3, 4), (3, 3, 3, 4)], diff --git a/tests/test_rand_spatial_crop_samples.py b/tests/transforms/test_rand_spatial_crop_samples.py similarity index 98% rename from tests/test_rand_spatial_crop_samples.py rename to tests/transforms/test_rand_spatial_crop_samples.py index 92f0f9d9be..4a1d8697d4 100644 --- a/tests/test_rand_spatial_crop_samples.py +++ b/tests/transforms/test_rand_spatial_crop_samples.py @@ -20,7 +20,7 @@ from monai.transforms import RandSpatialCropSamples from monai.transforms.lazy.functional import apply_pending from tests.croppers import CropTest -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose TEST_CASE_1 = [ {"roi_size": [3, 3, 3], "num_samples": 4, "random_center": True, "random_size": False}, diff --git a/tests/test_rand_spatial_crop_samplesd.py b/tests/transforms/test_rand_spatial_crop_samplesd.py similarity index 98% rename from tests/test_rand_spatial_crop_samplesd.py rename to tests/transforms/test_rand_spatial_crop_samplesd.py index cb53e94b7d..27cd845e52 100644 --- a/tests/test_rand_spatial_crop_samplesd.py +++ b/tests/transforms/test_rand_spatial_crop_samplesd.py @@ -19,7 +19,7 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms import Compose, DivisiblePadd, RandSpatialCropSamplesd from monai.transforms.lazy.functional import apply_pending -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose TEST_CASE_1 = [ {"keys": ["img", "seg"], "num_samples": 4, "roi_size": [2, 2, 2], "random_center": True, "random_size": True}, @@ -90,7 +90,6 @@ class TestRandSpatialCropSamplesd(unittest.TestCase): - @parameterized.expand([TEST_CASE_1, *TEST_CASE_2]) def test_shape(self, input_param, input_data, expected_shape, expected_last): xform = RandSpatialCropSamplesd(**input_param) diff --git a/tests/test_rand_spatial_cropd.py b/tests/transforms/test_rand_spatial_cropd.py similarity index 98% rename from tests/test_rand_spatial_cropd.py rename to tests/transforms/test_rand_spatial_cropd.py index 123459235f..a3aec5e525 100644 --- a/tests/test_rand_spatial_cropd.py +++ b/tests/transforms/test_rand_spatial_cropd.py @@ -20,7 +20,7 @@ from monai.transforms import RandScaleCropd, RandSpatialCropd from monai.transforms.lazy.functional import apply_pending from tests.croppers import CropTest -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose TEST_SHAPES = [ [{"keys": "img", "roi_size": [3, 3, -1], "random_center": True}, (3, 3, 3, 5), (3, 3, 3, 5)], diff --git a/tests/test_rand_std_shift_intensity.py b/tests/transforms/test_rand_std_shift_intensity.py similarity index 94% rename from tests/test_rand_std_shift_intensity.py rename to tests/transforms/test_rand_std_shift_intensity.py index 0ac5e9482e..300f630430 100644 --- a/tests/test_rand_std_shift_intensity.py +++ b/tests/transforms/test_rand_std_shift_intensity.py @@ -18,11 +18,10 @@ from parameterized import parameterized from monai.transforms import RandStdShiftIntensity -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class TestRandStdShiftIntensity(NumpyImageTestCase2D): - @parameterized.expand([[p] for p in TEST_NDARRAYS]) def test_value(self, p): np.random.seed(0) diff --git a/tests/test_rand_std_shift_intensityd.py b/tests/transforms/test_rand_std_shift_intensityd.py similarity index 94% rename from tests/test_rand_std_shift_intensityd.py rename to tests/transforms/test_rand_std_shift_intensityd.py index 1fd0c5d2a8..a2d984b9ac 100644 --- a/tests/test_rand_std_shift_intensityd.py +++ b/tests/transforms/test_rand_std_shift_intensityd.py @@ -16,11 +16,10 @@ import numpy as np from monai.transforms import RandStdShiftIntensityd -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class TestRandStdShiftIntensityd(NumpyImageTestCase2D): - def test_value(self): for p in TEST_NDARRAYS: key = "img" diff --git a/tests/test_rand_zoom.py b/tests/transforms/test_rand_zoom.py similarity index 97% rename from tests/test_rand_zoom.py rename to tests/transforms/test_rand_zoom.py index 2da04fd652..2824b197b6 100644 --- a/tests/test_rand_zoom.py +++ b/tests/transforms/test_rand_zoom.py @@ -22,7 +22,7 @@ from monai.transforms import RandZoom from monai.utils import InterpolateMode from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, assert_allclose, test_local_inversion +from tests.test_utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, assert_allclose, test_local_inversion VALID_CASES = [ (0.8, 1.2, "nearest", False), @@ -33,7 +33,6 @@ class TestRandZoom(NumpyImageTestCase2D): - @parameterized.expand(VALID_CASES) def test_correct_results(self, min_zoom, max_zoom, mode, keep_size, align_corners=None): for p in TEST_NDARRAYS_ALL: diff --git a/tests/test_rand_zoomd.py b/tests/transforms/test_rand_zoomd.py similarity index 97% rename from tests/test_rand_zoomd.py rename to tests/transforms/test_rand_zoomd.py index bcbf188310..1ad7bedbaf 100644 --- a/tests/test_rand_zoomd.py +++ b/tests/transforms/test_rand_zoomd.py @@ -21,7 +21,7 @@ from monai.config import USE_COMPILED from monai.transforms import RandZoomd from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, assert_allclose, test_local_inversion +from tests.test_utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, assert_allclose, test_local_inversion VALID_CASES = [ (0.8, 1.2, "nearest", None, False), @@ -31,7 +31,6 @@ class TestRandZoomd(NumpyImageTestCase2D): - @parameterized.expand(VALID_CASES) def test_correct_results(self, min_zoom, max_zoom, mode, align_corners, keep_size): key = "img" diff --git a/tests/test_randidentity.py b/tests/transforms/test_randidentity.py similarity index 95% rename from tests/test_randidentity.py rename to tests/transforms/test_randidentity.py index 3a8936f2d2..3344690b69 100644 --- a/tests/test_randidentity.py +++ b/tests/transforms/test_randidentity.py @@ -15,17 +15,15 @@ import monai.transforms as mt from monai.data import CacheDataset -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class T(mt.Transform): - def __call__(self, x): return x * 2 class TestIdentity(NumpyImageTestCase2D): - def test_identity(self): for p in TEST_NDARRAYS: img = p(self.imt) diff --git a/tests/test_random_order.py b/tests/transforms/test_random_order.py similarity index 98% rename from tests/test_random_order.py rename to tests/transforms/test_random_order.py index b38d2398fb..c7f8fe2742 100644 --- a/tests/test_random_order.py +++ b/tests/transforms/test_random_order.py @@ -26,11 +26,10 @@ from monai.transforms.compose import Compose from monai.utils import set_determinism from monai.utils.enums import TraceKeys -from tests.test_one_of import A, B, C, Inv, NonInv, X, Y +from tests.integration.test_one_of import A, B, C, Inv, NonInv, X, Y class InvC(Inv): - def __init__(self, keys): super().__init__(keys) self.fwd_fn = lambda x: x + 1 @@ -38,7 +37,6 @@ def __init__(self, keys): class InvD(Inv): - def __init__(self, keys): super().__init__(keys) self.fwd_fn = lambda x: x * 100 @@ -57,7 +55,6 @@ def __init__(self, keys): class TestRandomOrder(unittest.TestCase): - def test_empty_compose(self): c = RandomOrder() i = 1 @@ -116,7 +113,6 @@ def test_inverse(self, transform, invertible, use_metatensor): class TestRandomOrderAPITests(unittest.TestCase): - @staticmethod def data_from_keys(keys): if keys is None: diff --git a/tests/test_randtorchvisiond.py b/tests/transforms/test_randtorchvisiond.py similarity index 98% rename from tests/test_randtorchvisiond.py rename to tests/transforms/test_randtorchvisiond.py index 7ad06dfd2a..e2324c4499 100644 --- a/tests/test_randtorchvisiond.py +++ b/tests/transforms/test_randtorchvisiond.py @@ -18,7 +18,7 @@ from monai.transforms import RandomizableTrait, RandTorchVisiond from monai.utils import set_determinism -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_CASE_1 = [ {"keys": "img", "name": "ColorJitter"}, @@ -52,7 +52,6 @@ class TestRandTorchVisiond(unittest.TestCase): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3]) def test_value(self, input_param, input_data, expected_value): set_determinism(seed=0) diff --git a/tests/test_regularization.py b/tests/transforms/test_regularization.py similarity index 99% rename from tests/test_regularization.py rename to tests/transforms/test_regularization.py index 12d64637d5..48768a8d25 100644 --- a/tests/test_regularization.py +++ b/tests/transforms/test_regularization.py @@ -17,11 +17,10 @@ import torch from monai.transforms import CutMix, CutMixd, CutOut, CutOutd, MixUp, MixUpd -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose class TestMixup(unittest.TestCase): - def test_mixup(self): for dims in [2, 3]: shape = (6, 3) + (32,) * dims @@ -74,7 +73,6 @@ def test_mixupd(self): class TestCutMix(unittest.TestCase): - def test_cutmix(self): for dims in [2, 3]: shape = (6, 3) + (32,) * dims @@ -99,7 +97,6 @@ def test_cutmixd(self): class TestCutOut(unittest.TestCase): - def test_cutout(self): for dims in [2, 3]: shape = (6, 3) + (32,) * dims diff --git a/tests/test_remove_repeated_channel.py b/tests/transforms/test_remove_repeated_channel.py similarity index 96% rename from tests/test_remove_repeated_channel.py rename to tests/transforms/test_remove_repeated_channel.py index 7da00ee75d..122e68bcc1 100644 --- a/tests/test_remove_repeated_channel.py +++ b/tests/transforms/test_remove_repeated_channel.py @@ -16,7 +16,7 @@ from parameterized import parameterized from monai.transforms import RemoveRepeatedChannel -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS TEST_CASES = [] for q in TEST_NDARRAYS: @@ -24,7 +24,6 @@ class TestRemoveRepeatedChannel(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_shape(self, input_param, input_data, expected_shape): result = RemoveRepeatedChannel(**input_param)(input_data) diff --git a/tests/test_remove_repeated_channeld.py b/tests/transforms/test_remove_repeated_channeld.py similarity index 96% rename from tests/test_remove_repeated_channeld.py rename to tests/transforms/test_remove_repeated_channeld.py index 08ec7fb44c..bd983cf185 100644 --- a/tests/test_remove_repeated_channeld.py +++ b/tests/transforms/test_remove_repeated_channeld.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import RemoveRepeatedChanneld -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS TESTS = [] for p in TEST_NDARRAYS: @@ -34,7 +34,6 @@ class TestRemoveRepeatedChanneld(unittest.TestCase): - @parameterized.expand(TESTS) def test_shape(self, input_param, input_data, expected_shape): result = RemoveRepeatedChanneld(**input_param)(input_data) diff --git a/tests/test_repeat_channel.py b/tests/transforms/test_repeat_channel.py similarity index 96% rename from tests/test_repeat_channel.py rename to tests/transforms/test_repeat_channel.py index 82d1d92bd2..1859420479 100644 --- a/tests/test_repeat_channel.py +++ b/tests/transforms/test_repeat_channel.py @@ -16,7 +16,7 @@ from parameterized import parameterized from monai.transforms import RepeatChannel -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS TESTS = [] for p in TEST_NDARRAYS: @@ -24,7 +24,6 @@ class TestRepeatChannel(unittest.TestCase): - @parameterized.expand(TESTS) def test_shape(self, input_param, input_data, expected_shape): result = RepeatChannel(**input_param)(input_data) diff --git a/tests/test_repeat_channeld.py b/tests/transforms/test_repeat_channeld.py similarity index 96% rename from tests/test_repeat_channeld.py rename to tests/transforms/test_repeat_channeld.py index 2be13a08d1..be1e298573 100644 --- a/tests/test_repeat_channeld.py +++ b/tests/transforms/test_repeat_channeld.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import RepeatChanneld -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS TESTS = [] for p in TEST_NDARRAYS: @@ -31,7 +31,6 @@ class TestRepeatChanneld(unittest.TestCase): - @parameterized.expand(TESTS) def test_shape(self, input_param, input_data, expected_shape): result = RepeatChanneld(**input_param)(input_data) diff --git a/tests/test_resample_backends.py b/tests/transforms/test_resample_backends.py similarity index 97% rename from tests/test_resample_backends.py rename to tests/transforms/test_resample_backends.py index 7ddd9c7ec2..e4ca3edc19 100644 --- a/tests/test_resample_backends.py +++ b/tests/transforms/test_resample_backends.py @@ -22,7 +22,7 @@ from monai.transforms import Resample from monai.transforms.utils import create_grid from monai.utils import GridSampleMode, GridSamplePadMode, NdimageMode, SplineMode, convert_to_numpy -from tests.utils import SkipIfBeforePyTorchVersion, assert_allclose, is_tf32_env +from tests.test_utils import SkipIfBeforePyTorchVersion, assert_allclose, is_tf32_env _rtol = 1e-3 if is_tf32_env() else 1e-4 @@ -44,7 +44,6 @@ @SkipIfBeforePyTorchVersion((1, 9, 1)) class TestResampleBackends(unittest.TestCase): - @parameterized.expand(TEST_IDENTITY) def test_resample_identity(self, input_param, im_type, interp, padding, input_shape): """test resampling of an identity grid with padding 2, im_type, interp, padding, input_shape""" diff --git a/tests/test_resample_to_match.py b/tests/transforms/test_resample_to_match.py similarity index 97% rename from tests/test_resample_to_match.py rename to tests/transforms/test_resample_to_match.py index f0d34547a7..4b0f10898c 100644 --- a/tests/test_resample_to_match.py +++ b/tests/transforms/test_resample_to_match.py @@ -30,7 +30,7 @@ from monai.transforms import Compose, EnsureChannelFirstd, LoadImaged, ResampleToMatch, SaveImage, SaveImaged from monai.utils import optional_import from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import assert_allclose, download_url_or_skip_test, testing_data_config +from tests.test_utils import assert_allclose, download_url_or_skip_test, testing_data_config _, has_itk = optional_import("itk", allow_namespace_pkg=True) @@ -46,7 +46,6 @@ def get_rand_fname(len=10, suffix=".nii.gz"): @unittest.skipUnless(has_itk, "itk not installed") class TestResampleToMatch(unittest.TestCase): - @classmethod def setUpClass(cls): super(__class__, cls).setUpClass() diff --git a/tests/test_resample_to_matchd.py b/tests/transforms/test_resample_to_matchd.py similarity index 97% rename from tests/test_resample_to_matchd.py rename to tests/transforms/test_resample_to_matchd.py index 9d104bf392..936d336a1f 100644 --- a/tests/test_resample_to_matchd.py +++ b/tests/transforms/test_resample_to_matchd.py @@ -27,7 +27,7 @@ SaveImaged, ) from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import assert_allclose, download_url_or_skip_test, testing_data_config +from tests.test_utils import assert_allclose, download_url_or_skip_test, testing_data_config def update_fname(d): @@ -36,7 +36,6 @@ def update_fname(d): class TestResampleToMatchd(unittest.TestCase): - @classmethod def setUpClass(cls): super(__class__, cls).setUpClass() diff --git a/tests/test_resampler.py b/tests/transforms/test_resampler.py similarity index 99% rename from tests/test_resampler.py rename to tests/transforms/test_resampler.py index af0db657aa..0a0983c18e 100644 --- a/tests/test_resampler.py +++ b/tests/transforms/test_resampler.py @@ -19,7 +19,7 @@ from monai.transforms import Resample from monai.transforms.utils import create_grid -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose TESTS = [] for p in TEST_NDARRAYS_ALL: @@ -152,7 +152,6 @@ class TestResample(unittest.TestCase): - @parameterized.expand(TESTS) def test_resample(self, input_param, input_data, expected_val): g = Resample(**input_param) diff --git a/tests/test_resize.py b/tests/transforms/test_resize.py similarity index 99% rename from tests/test_resize.py rename to tests/transforms/test_resize.py index d4c57e2742..0e11035cf7 100644 --- a/tests/test_resize.py +++ b/tests/transforms/test_resize.py @@ -21,7 +21,7 @@ from monai.data import MetaTensor, set_track_meta from monai.transforms import Resize from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import ( +from tests.test_utils import ( TEST_NDARRAYS_ALL, NumpyImageTestCase2D, SkipIfAtLeastPyTorchVersion, @@ -46,7 +46,6 @@ class TestResize(NumpyImageTestCase2D): - def test_invalid_inputs(self): with self.assertRaises(ValueError): resize = Resize(spatial_size=(128, 128, 3), mode="order") diff --git a/tests/test_resize_with_pad_or_crop.py b/tests/transforms/test_resize_with_pad_or_crop.py similarity index 98% rename from tests/test_resize_with_pad_or_crop.py rename to tests/transforms/test_resize_with_pad_or_crop.py index daf257f89f..bcda36adeb 100644 --- a/tests/test_resize_with_pad_or_crop.py +++ b/tests/transforms/test_resize_with_pad_or_crop.py @@ -20,7 +20,7 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms import ResizeWithPadOrCrop from monai.transforms.lazy.functional import apply_pending -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose, pytorch_after +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose, pytorch_after TEST_CASES = [ [{"spatial_size": [15, 8, 8], "mode": "constant"}, (3, 8, 8, 4), (3, 15, 8, 8), True], @@ -48,7 +48,6 @@ class TestResizeWithPadOrCrop(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_pad_shape(self, input_param, input_shape, expected_shape, _): for p in TEST_NDARRAYS_ALL: diff --git a/tests/test_resize_with_pad_or_cropd.py b/tests/transforms/test_resize_with_pad_or_cropd.py similarity index 96% rename from tests/test_resize_with_pad_or_cropd.py rename to tests/transforms/test_resize_with_pad_or_cropd.py index 391e0feb22..2e162d3f69 100644 --- a/tests/test_resize_with_pad_or_cropd.py +++ b/tests/transforms/test_resize_with_pad_or_cropd.py @@ -21,8 +21,8 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms import ResizeWithPadOrCropd from monai.transforms.lazy.functional import apply_pending -from tests.test_resize_with_pad_or_crop import TESTS_PENDING_MODE -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose, pytorch_after +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose, pytorch_after +from tests.transforms.test_resize_with_pad_or_crop import TESTS_PENDING_MODE TEST_CASES = [ [{"keys": "img", "spatial_size": [15, 8, 8], "mode": "constant"}, {"img": np.zeros((3, 8, 8, 4))}, (3, 15, 8, 8)], @@ -46,7 +46,6 @@ class TestResizeWithPadOrCropd(unittest.TestCase): - @parameterized.expand(TEST_CASES) def test_pad_shape(self, input_param, input_data, expected_val): for p in TEST_NDARRAYS_ALL: diff --git a/tests/test_resized.py b/tests/transforms/test_resized.py similarity index 99% rename from tests/test_resized.py rename to tests/transforms/test_resized.py index 243a4e6622..926e0fa58a 100644 --- a/tests/test_resized.py +++ b/tests/transforms/test_resized.py @@ -21,7 +21,7 @@ from monai.data import MetaTensor, set_track_meta from monai.transforms import Invertd, Resize, Resized from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import ( +from tests.test_utils import ( TEST_NDARRAYS_ALL, NumpyImageTestCase2D, SkipIfAtLeastPyTorchVersion, @@ -66,7 +66,6 @@ @SkipIfAtLeastPyTorchVersion((2, 2, 0)) # https://github.com/Project-MONAI/MONAI/issues/7445 class TestResized(NumpyImageTestCase2D): - def test_invalid_inputs(self): with self.assertRaises(ValueError): resize = Resized(keys="img", spatial_size=(128, 128, 3), mode="order") diff --git a/tests/test_rotate.py b/tests/transforms/test_rotate.py similarity index 97% rename from tests/test_rotate.py rename to tests/transforms/test_rotate.py index 19fbd1409f..709a3bd6f4 100644 --- a/tests/test_rotate.py +++ b/tests/transforms/test_rotate.py @@ -22,7 +22,13 @@ from monai.data import MetaTensor, set_track_meta from monai.transforms import Rotate from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import HAS_CUPY, TEST_NDARRAYS_ALL, NumpyImageTestCase2D, NumpyImageTestCase3D, test_local_inversion +from tests.test_utils import ( + HAS_CUPY, + TEST_NDARRAYS_ALL, + NumpyImageTestCase2D, + NumpyImageTestCase3D, + test_local_inversion, +) TEST_CASES_2D: list[tuple] = [] for p in TEST_NDARRAYS_ALL: @@ -52,7 +58,6 @@ class TestRotate2D(NumpyImageTestCase2D): - @parameterized.expand(TEST_CASES_2D) def test_correct_results(self, im_type, angle, keep_size, mode, padding_mode, align_corners): init_param = { @@ -91,7 +96,6 @@ def test_correct_results(self, im_type, angle, keep_size, mode, padding_mode, al class TestRotate3D(NumpyImageTestCase3D): - @parameterized.expand(TEST_CASES_3D) def test_correct_results(self, im_type, angle, keep_size, mode, padding_mode, align_corners): init_param = { diff --git a/tests/test_rotate90.py b/tests/transforms/test_rotate90.py similarity index 99% rename from tests/test_rotate90.py rename to tests/transforms/test_rotate90.py index ebc3fba7e0..9c71004c65 100644 --- a/tests/test_rotate90.py +++ b/tests/transforms/test_rotate90.py @@ -21,7 +21,7 @@ from monai.transforms.lazy.functional import apply_pending from monai.utils import optional_import from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import ( +from tests.test_utils import ( TEST_NDARRAYS_ALL, NumpyImageTestCase2D, NumpyImageTestCase3D, @@ -31,7 +31,6 @@ class TestRotate90(NumpyImageTestCase2D): - def test_rotate90_default(self): rotate = Rotate90() for p in TEST_NDARRAYS_ALL: @@ -103,7 +102,6 @@ def test_prob_k_spatial_axes(self): class TestRotate903d(NumpyImageTestCase3D): - def test_rotate90_default(self): rotate = Rotate90() for p in TEST_NDARRAYS_ALL: @@ -171,7 +169,6 @@ def test_prob_k_spatial_axes(self): @unittest.skipUnless(optional_import("scipy")[1], "Requires scipy library.") class TestRot90Consistency(unittest.TestCase): - @parameterized.expand([[2], [3], [4]]) def test_affine_rot90(self, s): """s""" diff --git a/tests/test_rotate90d.py b/tests/transforms/test_rotate90d.py similarity index 97% rename from tests/test_rotate90d.py rename to tests/transforms/test_rotate90d.py index ffe920992a..d9f8aeea8a 100644 --- a/tests/test_rotate90d.py +++ b/tests/transforms/test_rotate90d.py @@ -18,11 +18,10 @@ from monai.data import MetaTensor, set_track_meta from monai.transforms import Rotate90d from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, assert_allclose, test_local_inversion +from tests.test_utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, assert_allclose, test_local_inversion class TestRotate90d(NumpyImageTestCase2D): - def test_rotate90_default(self): key = "test" rotate = Rotate90d(keys=key) diff --git a/tests/test_rotated.py b/tests/transforms/test_rotated.py similarity index 98% rename from tests/test_rotated.py rename to tests/transforms/test_rotated.py index 28ca755661..09c2304c6b 100644 --- a/tests/test_rotated.py +++ b/tests/transforms/test_rotated.py @@ -22,7 +22,7 @@ from monai.data import MetaTensor from monai.transforms import Rotated from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, NumpyImageTestCase3D, test_local_inversion +from tests.test_utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, NumpyImageTestCase3D, test_local_inversion TEST_CASES_2D: list[tuple] = [] for p in TEST_NDARRAYS_ALL: @@ -43,7 +43,6 @@ @unittest.skipIf(USE_COMPILED, "unittests are not designed for both USE_COMPILED=True/False") class TestRotated2D(NumpyImageTestCase2D): - @parameterized.expand(TEST_CASES_2D) def test_correct_results(self, im_type, angle, keep_size, mode, padding_mode, align_corners): init_param = { @@ -95,7 +94,6 @@ def test_correct_results(self, im_type, angle, keep_size, mode, padding_mode, al @unittest.skipIf(USE_COMPILED, "unittests are not designed for both USE_COMPILED=True/False") class TestRotated3D(NumpyImageTestCase3D): - @parameterized.expand(TEST_CASES_3D) def test_correct_results(self, im_type, angle, keep_size, mode, padding_mode, align_corners): init_param = { @@ -145,7 +143,6 @@ def test_correct_results(self, im_type, angle, keep_size, mode, padding_mode, al @unittest.skipIf(USE_COMPILED, "unittests are not designed for both USE_COMPILED=True/False") class TestRotated3DXY(NumpyImageTestCase3D): - @parameterized.expand(TEST_CASES_3D) def test_correct_results(self, im_type, angle, keep_size, mode, padding_mode, align_corners): rotate_fn = Rotated( diff --git a/tests/test_save_classificationd.py b/tests/transforms/test_save_classificationd.py similarity index 100% rename from tests/test_save_classificationd.py rename to tests/transforms/test_save_classificationd.py diff --git a/tests/test_save_image.py b/tests/transforms/test_save_image.py similarity index 100% rename from tests/test_save_image.py rename to tests/transforms/test_save_image.py diff --git a/tests/test_save_imaged.py b/tests/transforms/test_save_imaged.py similarity index 100% rename from tests/test_save_imaged.py rename to tests/transforms/test_save_imaged.py diff --git a/tests/test_savitzky_golay_smooth.py b/tests/transforms/test_savitzky_golay_smooth.py similarity index 97% rename from tests/test_savitzky_golay_smooth.py rename to tests/transforms/test_savitzky_golay_smooth.py index 14e403e238..cf92fdb7b4 100644 --- a/tests/test_savitzky_golay_smooth.py +++ b/tests/transforms/test_savitzky_golay_smooth.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import SavitzkyGolaySmooth -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose # Zero-padding trivial tests @@ -60,7 +60,6 @@ class TestSavitzkyGolaySmooth(unittest.TestCase): - @parameterized.expand( [TEST_CASE_SINGLE_VALUE, TEST_CASE_2D_AXIS_2, TEST_CASE_SINE_SMOOTH, TEST_CASE_SINGLE_VALUE_REP] ) diff --git a/tests/test_savitzky_golay_smoothd.py b/tests/transforms/test_savitzky_golay_smoothd.py similarity index 98% rename from tests/test_savitzky_golay_smoothd.py rename to tests/transforms/test_savitzky_golay_smoothd.py index 3bb4056046..ff981de097 100644 --- a/tests/test_savitzky_golay_smoothd.py +++ b/tests/transforms/test_savitzky_golay_smoothd.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import SavitzkyGolaySmoothd -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose # Zero-padding trivial tests @@ -60,7 +60,6 @@ class TestSavitzkyGolaySmoothd(unittest.TestCase): - @parameterized.expand( [TEST_CASE_SINGLE_VALUE, TEST_CASE_2D_AXIS_2, TEST_CASE_SINE_SMOOTH, TEST_CASE_SINGLE_VALUE_REP] ) diff --git a/tests/test_scale_intensity.py b/tests/transforms/test_scale_intensity.py similarity index 97% rename from tests/test_scale_intensity.py rename to tests/transforms/test_scale_intensity.py index 17dfe305b2..7047ddef1a 100644 --- a/tests/test_scale_intensity.py +++ b/tests/transforms/test_scale_intensity.py @@ -18,11 +18,10 @@ from monai.transforms import ScaleIntensity from monai.transforms.utils import rescale_array -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class TestScaleIntensity(NumpyImageTestCase2D): - @parameterized.expand([[p] for p in TEST_NDARRAYS]) def test_range_scale(self, p): scaler = ScaleIntensity(minv=1.0, maxv=2.0) diff --git a/tests/test_scale_intensity_fixed_mean.py b/tests/transforms/test_scale_intensity_fixed_mean.py similarity index 97% rename from tests/test_scale_intensity_fixed_mean.py rename to tests/transforms/test_scale_intensity_fixed_mean.py index 35d38ef0b1..7ea09ce3bc 100644 --- a/tests/test_scale_intensity_fixed_mean.py +++ b/tests/transforms/test_scale_intensity_fixed_mean.py @@ -17,11 +17,10 @@ from parameterized import parameterized from monai.transforms import ScaleIntensityFixedMean -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class TestScaleIntensityFixedMean(NumpyImageTestCase2D): - def test_factor_scale(self): for p in TEST_NDARRAYS: scaler = ScaleIntensityFixedMean(factor=0.1, fixed_mean=False) diff --git a/tests/test_scale_intensity_range.py b/tests/transforms/test_scale_intensity_range.py similarity index 95% rename from tests/test_scale_intensity_range.py rename to tests/transforms/test_scale_intensity_range.py index 6013a237db..b39ce6dd37 100644 --- a/tests/test_scale_intensity_range.py +++ b/tests/transforms/test_scale_intensity_range.py @@ -16,11 +16,10 @@ import numpy as np from monai.transforms import ScaleIntensityRange -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class IntensityScaleIntensityRange(NumpyImageTestCase2D): - def test_image_scale_intensity_range(self): scaler = ScaleIntensityRange(a_min=20, a_max=108, b_min=50, b_max=80, dtype=np.uint8) for p in TEST_NDARRAYS: diff --git a/tests/test_scale_intensity_ranged.py b/tests/transforms/test_scale_intensity_ranged.py similarity index 94% rename from tests/test_scale_intensity_ranged.py rename to tests/transforms/test_scale_intensity_ranged.py index cc3f1220e7..a2015dd2fa 100644 --- a/tests/test_scale_intensity_ranged.py +++ b/tests/transforms/test_scale_intensity_ranged.py @@ -14,11 +14,10 @@ import unittest from monai.transforms import ScaleIntensityRanged -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class IntensityScaleIntensityRanged(NumpyImageTestCase2D): - def test_image_scale_intensity_ranged(self): key = "img" scaler = ScaleIntensityRanged(keys=key, a_min=20, a_max=108, b_min=50, b_max=80) diff --git a/tests/test_scale_intensityd.py b/tests/transforms/test_scale_intensityd.py similarity index 96% rename from tests/test_scale_intensityd.py rename to tests/transforms/test_scale_intensityd.py index 88beece894..29c2a937dd 100644 --- a/tests/test_scale_intensityd.py +++ b/tests/transforms/test_scale_intensityd.py @@ -16,11 +16,10 @@ import numpy as np from monai.transforms import ScaleIntensityd -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class TestScaleIntensityd(NumpyImageTestCase2D): - def test_range_scale(self): key = "img" for p in TEST_NDARRAYS: diff --git a/tests/test_select_itemsd.py b/tests/transforms/test_select_itemsd.py similarity index 100% rename from tests/test_select_itemsd.py rename to tests/transforms/test_select_itemsd.py diff --git a/tests/test_shift_intensity.py b/tests/transforms/test_shift_intensity.py similarity index 95% rename from tests/test_shift_intensity.py rename to tests/transforms/test_shift_intensity.py index 90aa0f9271..70a6c7bf79 100644 --- a/tests/test_shift_intensity.py +++ b/tests/transforms/test_shift_intensity.py @@ -16,11 +16,10 @@ import numpy as np from monai.transforms import ShiftIntensity -from tests.utils import NumpyImageTestCase2D +from tests.test_utils import NumpyImageTestCase2D class TestShiftIntensity(NumpyImageTestCase2D): - def test_value(self): shifter = ShiftIntensity(offset=1.0) result = shifter(self.imt) diff --git a/tests/test_shift_intensityd.py b/tests/transforms/test_shift_intensityd.py similarity index 95% rename from tests/test_shift_intensityd.py rename to tests/transforms/test_shift_intensityd.py index 22336b4415..063202db0f 100644 --- a/tests/test_shift_intensityd.py +++ b/tests/transforms/test_shift_intensityd.py @@ -17,11 +17,10 @@ from monai.transforms import IntensityStatsd, ShiftIntensityd from monai.utils.enums import PostFix -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class TestShiftIntensityd(NumpyImageTestCase2D): - def test_value(self): key = "img" for p in TEST_NDARRAYS: diff --git a/tests/test_signal_continuouswavelet.py b/tests/transforms/test_signal_continuouswavelet.py similarity index 91% rename from tests/test_signal_continuouswavelet.py rename to tests/transforms/test_signal_continuouswavelet.py index 7e6ee8b105..992ef91b38 100644 --- a/tests/test_signal_continuouswavelet.py +++ b/tests/transforms/test_signal_continuouswavelet.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path from unittest import skipUnless import numpy as np @@ -22,14 +23,14 @@ from monai.utils import optional_import _, has_pywt = optional_import("pywt") -TEST_SIGNAL = os.path.join(os.path.dirname(__file__), "testing_data", "signal.npy") +TESTS_PATH = Path(__file__).parents[1] +TEST_SIGNAL = os.path.join(TESTS_PATH, "testing_data", "signal.npy") VALID_CASES = [("mexh", 150, 500)] EXPECTED_RESULTS = [(6, 150, 2000)] @skipUnless(has_pywt, "pywt required") class TestSignalContinousWavelet(unittest.TestCase): - @parameterized.expand(VALID_CASES) def test_correct_parameters_multi_channels(self, type, length, frequency): self.assertIsInstance(SignalContinuousWavelet(type, length, frequency), SignalContinuousWavelet) diff --git a/tests/test_signal_fillempty.py b/tests/transforms/test_signal_fillempty.py similarity index 90% rename from tests/test_signal_fillempty.py rename to tests/transforms/test_signal_fillempty.py index 2be4bd8600..d9166db986 100644 --- a/tests/test_signal_fillempty.py +++ b/tests/transforms/test_signal_fillempty.py @@ -13,20 +13,21 @@ import os import unittest +from pathlib import Path import numpy as np import torch from monai.transforms import SignalFillEmpty from monai.utils.type_conversion import convert_to_tensor -from tests.utils import SkipIfBeforePyTorchVersion +from tests.test_utils import SkipIfBeforePyTorchVersion -TEST_SIGNAL = os.path.join(os.path.dirname(__file__), "testing_data", "signal.npy") +TESTS_PATH = Path(__file__).parents[1] +TEST_SIGNAL = os.path.join(TESTS_PATH, "testing_data", "signal.npy") @SkipIfBeforePyTorchVersion((1, 9)) class TestSignalFillEmptyNumpy(unittest.TestCase): - def test_correct_parameters_multi_channels(self): self.assertIsInstance(SignalFillEmpty(replacement=0.0), SignalFillEmpty) sig = np.load(TEST_SIGNAL) @@ -38,7 +39,6 @@ def test_correct_parameters_multi_channels(self): @SkipIfBeforePyTorchVersion((1, 9)) class TestSignalFillEmptyTorch(unittest.TestCase): - def test_correct_parameters_multi_channels(self): self.assertIsInstance(SignalFillEmpty(replacement=0.0), SignalFillEmpty) sig = convert_to_tensor(np.load(TEST_SIGNAL)) diff --git a/tests/test_signal_fillemptyd.py b/tests/transforms/test_signal_fillemptyd.py similarity index 91% rename from tests/test_signal_fillemptyd.py rename to tests/transforms/test_signal_fillemptyd.py index 7710279495..01ab135eb0 100644 --- a/tests/test_signal_fillemptyd.py +++ b/tests/transforms/test_signal_fillemptyd.py @@ -13,20 +13,21 @@ import os import unittest +from pathlib import Path import numpy as np import torch from monai.transforms import SignalFillEmptyd from monai.utils.type_conversion import convert_to_tensor -from tests.utils import SkipIfBeforePyTorchVersion +from tests.test_utils import SkipIfBeforePyTorchVersion -TEST_SIGNAL = os.path.join(os.path.dirname(__file__), "testing_data", "signal.npy") +TESTS_PATH = Path(__file__).parents[1] +TEST_SIGNAL = os.path.join(TESTS_PATH, "testing_data", "signal.npy") @SkipIfBeforePyTorchVersion((1, 9)) class TestSignalFillEmptyNumpy(unittest.TestCase): - def test_correct_parameters_multi_channels(self): self.assertIsInstance(SignalFillEmptyd(replacement=0.0), SignalFillEmptyd) sig = np.load(TEST_SIGNAL) @@ -42,7 +43,6 @@ def test_correct_parameters_multi_channels(self): @SkipIfBeforePyTorchVersion((1, 9)) class TestSignalFillEmptyTorch(unittest.TestCase): - def test_correct_parameters_multi_channels(self): self.assertIsInstance(SignalFillEmptyd(replacement=0.0), SignalFillEmptyd) sig = convert_to_tensor(np.load(TEST_SIGNAL)) diff --git a/tests/test_signal_rand_add_gaussiannoise.py b/tests/transforms/test_signal_rand_add_gaussiannoise.py similarity index 93% rename from tests/test_signal_rand_add_gaussiannoise.py rename to tests/transforms/test_signal_rand_add_gaussiannoise.py index e5c9eba8a2..a2713ad893 100644 --- a/tests/test_signal_rand_add_gaussiannoise.py +++ b/tests/transforms/test_signal_rand_add_gaussiannoise.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path import numpy as np from parameterized import parameterized @@ -20,12 +21,12 @@ from monai.transforms import SignalRandAddGaussianNoise from monai.utils.type_conversion import convert_to_tensor -TEST_SIGNAL = os.path.join(os.path.dirname(__file__), "testing_data", "signal.npy") +TESTS_PATH = Path(__file__).parents[1] +TEST_SIGNAL = os.path.join(TESTS_PATH, "testing_data", "signal.npy") VALID_CASES = [([0.0, 0.02],)] class TestSignalRandAddGaussianNoiseNumpy(unittest.TestCase): - @parameterized.expand(VALID_CASES) def test_correct_parameters_multi_channels(self, boundaries): self.assertIsInstance(SignalRandAddGaussianNoise(boundaries), SignalRandAddGaussianNoise) @@ -36,7 +37,6 @@ def test_correct_parameters_multi_channels(self, boundaries): class TestSignalRandAddGaussianNoiseTorch(unittest.TestCase): - @parameterized.expand(VALID_CASES) def test_correct_parameters_multi_channels(self, boundaries): self.assertIsInstance(SignalRandAddGaussianNoise(boundaries), SignalRandAddGaussianNoise) diff --git a/tests/test_signal_rand_add_sine.py b/tests/transforms/test_signal_rand_add_sine.py similarity index 93% rename from tests/test_signal_rand_add_sine.py rename to tests/transforms/test_signal_rand_add_sine.py index 4ba91247dd..8f37806796 100644 --- a/tests/test_signal_rand_add_sine.py +++ b/tests/transforms/test_signal_rand_add_sine.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path import numpy as np from parameterized import parameterized @@ -20,7 +21,8 @@ from monai.transforms import SignalRandAddSine from monai.utils.type_conversion import convert_to_tensor -TEST_SIGNAL = os.path.join(os.path.dirname(__file__), "testing_data", "signal.npy") +TESTS_PATH = Path(__file__).parents[1] +TEST_SIGNAL = os.path.join(TESTS_PATH, "testing_data", "signal.npy") VALID_CASES = [([0.0, 1.0], [0.0, 0.5]), ([0.0, 1.0], [0.01, 0.1])] diff --git a/tests/test_signal_rand_add_sine_partial.py b/tests/transforms/test_signal_rand_add_sine_partial.py similarity index 93% rename from tests/test_signal_rand_add_sine_partial.py rename to tests/transforms/test_signal_rand_add_sine_partial.py index 71b67747a2..61fcd9c40e 100644 --- a/tests/test_signal_rand_add_sine_partial.py +++ b/tests/transforms/test_signal_rand_add_sine_partial.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path import numpy as np from parameterized import parameterized @@ -20,12 +21,12 @@ from monai.transforms import SignalRandAddSinePartial from monai.utils.type_conversion import convert_to_tensor -TEST_SIGNAL = os.path.join(os.path.dirname(__file__), "testing_data", "signal.npy") +TESTS_PATH = Path(__file__).parents[1] +TEST_SIGNAL = os.path.join(TESTS_PATH, "testing_data", "signal.npy") VALID_CASES = [([0.0, 1.0], [0.1, 0.6], [0.0, 0.4])] class TestSignalRandAddSinePartialNumpy(unittest.TestCase): - @parameterized.expand(VALID_CASES) def test_correct_parameters_multi_channels(self, boundaries, frequencies, fraction): self.assertIsInstance(SignalRandAddSinePartial(boundaries, frequencies, fraction), SignalRandAddSinePartial) @@ -36,7 +37,6 @@ def test_correct_parameters_multi_channels(self, boundaries, frequencies, fracti class TestSignalRandAddSinePartialTorch(unittest.TestCase): - @parameterized.expand(VALID_CASES) def test_correct_parameters_multi_channels(self, boundaries, frequencies, fraction): self.assertIsInstance(SignalRandAddSinePartial(boundaries, frequencies, fraction), SignalRandAddSinePartial) diff --git a/tests/test_signal_rand_add_squarepulse.py b/tests/transforms/test_signal_rand_add_squarepulse.py similarity index 92% rename from tests/test_signal_rand_add_squarepulse.py rename to tests/transforms/test_signal_rand_add_squarepulse.py index e1432029ea..da3fe44a75 100644 --- a/tests/test_signal_rand_add_squarepulse.py +++ b/tests/transforms/test_signal_rand_add_squarepulse.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path from unittest import skipUnless import numpy as np @@ -21,17 +22,17 @@ from monai.transforms import SignalRandAddSquarePulse from monai.utils import optional_import from monai.utils.type_conversion import convert_to_tensor -from tests.utils import SkipIfBeforePyTorchVersion +from tests.test_utils import SkipIfBeforePyTorchVersion _, has_scipy = optional_import("scipy") -TEST_SIGNAL = os.path.join(os.path.dirname(__file__), "testing_data", "signal.npy") +TESTS_PATH = Path(__file__).parents[1] +TEST_SIGNAL = os.path.join(TESTS_PATH, "testing_data", "signal.npy") VALID_CASES = [([0.0, 1.0], [0.001, 0.2])] @skipUnless(has_scipy, "scipy required") @SkipIfBeforePyTorchVersion((1, 10, 1)) class TestSignalRandAddSquarePulseNumpy(unittest.TestCase): - @parameterized.expand(VALID_CASES) def test_correct_parameters_multi_channels(self, boundaries, frequencies): self.assertIsInstance(SignalRandAddSquarePulse(boundaries, frequencies), SignalRandAddSquarePulse) @@ -44,7 +45,6 @@ def test_correct_parameters_multi_channels(self, boundaries, frequencies): @skipUnless(has_scipy, "scipy required") @SkipIfBeforePyTorchVersion((1, 10, 1)) class TestSignalRandAddSquarePulseTorch(unittest.TestCase): - @parameterized.expand(VALID_CASES) def test_correct_parameters_multi_channels(self, boundaries, frequencies): self.assertIsInstance(SignalRandAddSquarePulse(boundaries, frequencies), SignalRandAddSquarePulse) diff --git a/tests/test_signal_rand_add_squarepulse_partial.py b/tests/transforms/test_signal_rand_add_squarepulse_partial.py similarity index 92% rename from tests/test_signal_rand_add_squarepulse_partial.py rename to tests/transforms/test_signal_rand_add_squarepulse_partial.py index 7e1c2bb9d8..c5c53b602f 100644 --- a/tests/test_signal_rand_add_squarepulse_partial.py +++ b/tests/transforms/test_signal_rand_add_squarepulse_partial.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path from unittest import skipUnless import numpy as np @@ -21,17 +22,17 @@ from monai.transforms import SignalRandAddSquarePulsePartial from monai.utils import optional_import from monai.utils.type_conversion import convert_to_tensor -from tests.utils import SkipIfBeforePyTorchVersion +from tests.test_utils import SkipIfBeforePyTorchVersion _, has_scipy = optional_import("scipy") -TEST_SIGNAL = os.path.join(os.path.dirname(__file__), "testing_data", "signal.npy") +TESTS_PATH = Path(__file__).parents[1] +TEST_SIGNAL = os.path.join(TESTS_PATH, "testing_data", "signal.npy") VALID_CASES = [([0.0, 1.0], [0.001, 0.2], [0.0, 0.4])] @skipUnless(has_scipy, "scipy required") @SkipIfBeforePyTorchVersion((1, 10, 1)) class TestSignalRandAddSquarePulsePartialNumpy(unittest.TestCase): - @parameterized.expand(VALID_CASES) def test_correct_parameters_multi_channels(self, boundaries, frequencies, fraction): self.assertIsInstance( @@ -46,7 +47,6 @@ def test_correct_parameters_multi_channels(self, boundaries, frequencies, fracti @skipUnless(has_scipy, "scipy required") @SkipIfBeforePyTorchVersion((1, 10, 1)) class TestSignalRandAddSquarePulsePartialTorch(unittest.TestCase): - @parameterized.expand(VALID_CASES) def test_correct_parameters_multi_channels(self, boundaries, frequencies, fraction): self.assertIsInstance( diff --git a/tests/test_signal_rand_drop.py b/tests/transforms/test_signal_rand_drop.py similarity index 92% rename from tests/test_signal_rand_drop.py rename to tests/transforms/test_signal_rand_drop.py index bf2db75a6a..faba528720 100644 --- a/tests/test_signal_rand_drop.py +++ b/tests/transforms/test_signal_rand_drop.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path import numpy as np from parameterized import parameterized @@ -20,12 +21,12 @@ from monai.transforms import SignalRandDrop from monai.utils.type_conversion import convert_to_tensor -TEST_SIGNAL = os.path.join(os.path.dirname(__file__), "testing_data", "signal.npy") +TESTS_PATH = Path(__file__).parents[1] +TEST_SIGNAL = os.path.join(TESTS_PATH, "testing_data", "signal.npy") VALID_CASES = [([0.0, 1.0],), ([0.01, 0.1],)] class TestSignalRandDropNumpy(unittest.TestCase): - @parameterized.expand(VALID_CASES) def test_correct_parameters_multi_channels(self, boundaries): self.assertIsInstance(SignalRandDrop(boundaries), SignalRandDrop) @@ -36,7 +37,6 @@ def test_correct_parameters_multi_channels(self, boundaries): class TestSignalRandDropTorch(unittest.TestCase): - @parameterized.expand(VALID_CASES) def test_correct_parameters_multi_channels(self, boundaries): self.assertIsInstance(SignalRandDrop(boundaries), SignalRandDrop) diff --git a/tests/test_signal_rand_scale.py b/tests/transforms/test_signal_rand_scale.py similarity index 92% rename from tests/test_signal_rand_scale.py rename to tests/transforms/test_signal_rand_scale.py index c040c59a1f..fe0782a4a9 100644 --- a/tests/test_signal_rand_scale.py +++ b/tests/transforms/test_signal_rand_scale.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path import numpy as np from parameterized import parameterized @@ -20,7 +21,8 @@ from monai.transforms import SignalRandScale from monai.utils.type_conversion import convert_to_tensor -TEST_SIGNAL = os.path.join(os.path.dirname(__file__), "testing_data", "signal.npy") +TESTS_PATH = Path(__file__).parents[1] +TEST_SIGNAL = os.path.join(TESTS_PATH, "testing_data", "signal.npy") VALID_CASES = [([-1.0, 1.0],), ([0.01, 0.1],)] diff --git a/tests/test_signal_rand_shift.py b/tests/transforms/test_signal_rand_shift.py similarity index 93% rename from tests/test_signal_rand_shift.py rename to tests/transforms/test_signal_rand_shift.py index 96809e7446..1bc779e879 100644 --- a/tests/test_signal_rand_shift.py +++ b/tests/transforms/test_signal_rand_shift.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path from unittest import skipUnless import numpy as np @@ -23,13 +24,13 @@ from monai.utils.type_conversion import convert_to_tensor _, has_scipy = optional_import("scipy") -TEST_SIGNAL = os.path.join(os.path.dirname(__file__), "testing_data", "signal.npy") +TESTS_PATH = Path(__file__).parents[1] +TEST_SIGNAL = os.path.join(TESTS_PATH, "testing_data", "signal.npy") VALID_CASES = [("wrap", 0.0, [-1.0, 1.0])] @skipUnless(has_scipy, "scipy required") class TestSignalRandShiftNumpy(unittest.TestCase): - @parameterized.expand(VALID_CASES) def test_correct_parameters_multi_channels(self, mode, filling, boundaries): self.assertIsInstance(SignalRandShift(mode, filling, boundaries), SignalRandShift) @@ -41,7 +42,6 @@ def test_correct_parameters_multi_channels(self, mode, filling, boundaries): @skipUnless(has_scipy, "scipy required") class TestSignalRandShiftTorch(unittest.TestCase): - @parameterized.expand(VALID_CASES) def test_correct_parameters_multi_channels(self, mode, filling, boundaries): self.assertIsInstance(SignalRandShift(mode, filling, boundaries), SignalRandShift) diff --git a/tests/test_signal_remove_frequency.py b/tests/transforms/test_signal_remove_frequency.py similarity index 95% rename from tests/test_signal_remove_frequency.py rename to tests/transforms/test_signal_remove_frequency.py index 9f795ce68b..16c3e22f59 100644 --- a/tests/test_signal_remove_frequency.py +++ b/tests/transforms/test_signal_remove_frequency.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path from unittest import skipUnless import numpy as np @@ -25,13 +26,13 @@ _, has_scipy = optional_import("scipy") _, has_torchaudio = optional_import("torchaudio") -TEST_SIGNAL = os.path.join(os.path.dirname(__file__), "testing_data", "signal.npy") +TESTS_PATH = Path(__file__).parents[1] +TEST_SIGNAL = os.path.join(TESTS_PATH, "testing_data", "signal.npy") VALID_CASES = [(60, 1, 500)] @skipUnless(has_scipy and has_torchaudio, "scipy and torchaudio are required") class TestSignalRemoveFrequencyNumpy(unittest.TestCase): - @parameterized.expand(VALID_CASES) def test_correct_parameters_multi_channels(self, frequency, quality_factor, sampling_freq): self.assertIsInstance(SignalRemoveFrequency(frequency, quality_factor, sampling_freq), SignalRemoveFrequency) @@ -50,7 +51,6 @@ def test_correct_parameters_multi_channels(self, frequency, quality_factor, samp @skipUnless(has_scipy and has_torchaudio, "scipy and torchaudio are required") class TestSignalRemoveFrequencyTorch(unittest.TestCase): - @parameterized.expand(VALID_CASES) def test_correct_parameters_multi_channels(self, frequency, quality_factor, sampling_freq): self.assertIsInstance(SignalRemoveFrequency(frequency, quality_factor, sampling_freq), SignalRemoveFrequency) diff --git a/tests/test_smooth_field.py b/tests/transforms/test_smooth_field.py similarity index 98% rename from tests/test_smooth_field.py rename to tests/transforms/test_smooth_field.py index ca010641c4..a92b98582f 100644 --- a/tests/test_smooth_field.py +++ b/tests/transforms/test_smooth_field.py @@ -20,7 +20,7 @@ from monai.networks.utils import meshgrid_xy from monai.transforms import RandSmoothDeformd, RandSmoothFieldAdjustContrastd, RandSmoothFieldAdjustIntensityd -from tests.utils import TEST_NDARRAYS, assert_allclose, is_tf32_env +from tests.test_utils import TEST_NDARRAYS, assert_allclose, is_tf32_env _rtol = 5e-3 if is_tf32_env() else 1e-4 @@ -88,7 +88,6 @@ class TestSmoothField(unittest.TestCase): - @parameterized.expand(TESTS_CONTRAST) def test_rand_smooth_field_adjust_contrastd(self, input_param, input_data, expected_val): g = RandSmoothFieldAdjustContrastd(**input_param) diff --git a/tests/test_sobel_gradient.py b/tests/transforms/test_sobel_gradient.py similarity index 99% rename from tests/test_sobel_gradient.py rename to tests/transforms/test_sobel_gradient.py index a0d7cf5a8b..29db34df01 100644 --- a/tests/test_sobel_gradient.py +++ b/tests/transforms/test_sobel_gradient.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import SobelGradients -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose IMAGE = torch.zeros(1, 16, 16, dtype=torch.float32) IMAGE[0, 8, :] = 1 diff --git a/tests/test_sobel_gradientd.py b/tests/transforms/test_sobel_gradientd.py similarity index 99% rename from tests/test_sobel_gradientd.py rename to tests/transforms/test_sobel_gradientd.py index 03524823a5..aa8af3be89 100644 --- a/tests/test_sobel_gradientd.py +++ b/tests/transforms/test_sobel_gradientd.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import SobelGradientsd -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose IMAGE = torch.zeros(1, 16, 16, dtype=torch.float32) IMAGE[0, 8, :] = 1 diff --git a/tests/test_spacing.py b/tests/transforms/test_spacing.py similarity index 99% rename from tests/test_spacing.py rename to tests/transforms/test_spacing.py index c9a6291c78..f3ef25d1d2 100644 --- a/tests/test_spacing.py +++ b/tests/transforms/test_spacing.py @@ -24,7 +24,7 @@ from monai.transforms import Spacing from monai.utils import fall_back_tuple from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_DEVICES, TEST_NDARRAYS_ALL, assert_allclose, skip_if_quick +from tests.test_utils import TEST_DEVICES, TEST_NDARRAYS_ALL, assert_allclose, skip_if_quick TESTS: list[list] = [] for device in TEST_DEVICES: @@ -271,7 +271,6 @@ @skip_if_quick class TestSpacingCase(unittest.TestCase): - @parameterized.expand(TESTS) def test_spacing( self, diff --git a/tests/test_spacingd.py b/tests/transforms/test_spacingd.py similarity index 98% rename from tests/test_spacingd.py rename to tests/transforms/test_spacingd.py index 1cecaabced..a3dcaf5c67 100644 --- a/tests/test_spacingd.py +++ b/tests/transforms/test_spacingd.py @@ -23,7 +23,7 @@ from monai.transforms import Spacingd from monai.utils import ensure_tuple_rep from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_DEVICES, assert_allclose, skip_if_quick +from tests.test_utils import TEST_DEVICES, assert_allclose, skip_if_quick TESTS: list[tuple] = [] for device in TEST_DEVICES: @@ -105,7 +105,6 @@ class TestSpacingDCase(unittest.TestCase): - @parameterized.expand(TESTS) def test_spacingd(self, _, data, kw_args, expected_shape, expected_affine, device): data = {k: v.to(device) for k, v in data.items()} diff --git a/tests/test_spatial_crop.py b/tests/transforms/test_spatial_crop.py similarity index 100% rename from tests/test_spatial_crop.py rename to tests/transforms/test_spatial_crop.py diff --git a/tests/test_spatial_cropd.py b/tests/transforms/test_spatial_cropd.py similarity index 100% rename from tests/test_spatial_cropd.py rename to tests/transforms/test_spatial_cropd.py diff --git a/tests/test_spatial_pad.py b/tests/transforms/test_spatial_pad.py similarity index 100% rename from tests/test_spatial_pad.py rename to tests/transforms/test_spatial_pad.py diff --git a/tests/test_spatial_padd.py b/tests/transforms/test_spatial_padd.py similarity index 100% rename from tests/test_spatial_padd.py rename to tests/transforms/test_spatial_padd.py diff --git a/tests/test_spatial_resample.py b/tests/transforms/test_spatial_resample.py similarity index 99% rename from tests/test_spatial_resample.py rename to tests/transforms/test_spatial_resample.py index e64b242128..7962c77f1c 100644 --- a/tests/test_spatial_resample.py +++ b/tests/transforms/test_spatial_resample.py @@ -24,7 +24,7 @@ from monai.transforms import SpatialResample from monai.utils import optional_import from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_DEVICES, TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_DEVICES, TEST_NDARRAYS_ALL, assert_allclose TESTS = [] @@ -133,7 +133,6 @@ class TestSpatialResample(unittest.TestCase): - @parameterized.expand(TESTS) def test_flips(self, img, device, data_param, expected_output): for p in TEST_NDARRAYS_ALL: diff --git a/tests/test_squeezedim.py b/tests/transforms/test_squeezedim.py similarity index 97% rename from tests/test_squeezedim.py rename to tests/transforms/test_squeezedim.py index a295d20ef5..5fd333d821 100644 --- a/tests/test_squeezedim.py +++ b/tests/transforms/test_squeezedim.py @@ -18,7 +18,7 @@ from monai.data import MetaTensor from monai.transforms import SqueezeDim -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS, TESTS_FAIL = [], [] for p in TEST_NDARRAYS: @@ -32,7 +32,6 @@ class TestSqueezeDim(unittest.TestCase): - @parameterized.expand(TESTS) def test_shape(self, input_param, test_data, expected_shape): result = SqueezeDim(**input_param)(test_data) diff --git a/tests/test_squeezedimd.py b/tests/transforms/test_squeezedimd.py similarity index 98% rename from tests/test_squeezedimd.py rename to tests/transforms/test_squeezedimd.py index 934479563d..134dba6a26 100644 --- a/tests/test_squeezedimd.py +++ b/tests/transforms/test_squeezedimd.py @@ -18,7 +18,7 @@ from monai.data import MetaTensor from monai.transforms import SqueezeDimd -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS, TESTS_FAIL = [], [] for p in TEST_NDARRAYS: @@ -80,7 +80,6 @@ class TestSqueezeDim(unittest.TestCase): - @parameterized.expand(TESTS) def test_shape(self, input_param, test_data, expected_shape): result = SqueezeDimd(**input_param)(test_data) diff --git a/tests/test_std_shift_intensity.py b/tests/transforms/test_std_shift_intensity.py similarity index 97% rename from tests/test_std_shift_intensity.py rename to tests/transforms/test_std_shift_intensity.py index b4dc1db568..9f5f6ac54b 100644 --- a/tests/test_std_shift_intensity.py +++ b/tests/transforms/test_std_shift_intensity.py @@ -17,11 +17,10 @@ from monai.transforms import ShiftIntensity, StdShiftIntensity from monai.utils import dtype_numpy_to_torch -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class TestStdShiftIntensity(NumpyImageTestCase2D): - def test_value(self): for p in TEST_NDARRAYS: imt = p(self.imt) diff --git a/tests/test_std_shift_intensityd.py b/tests/transforms/test_std_shift_intensityd.py similarity index 98% rename from tests/test_std_shift_intensityd.py rename to tests/transforms/test_std_shift_intensityd.py index 73617ef4a3..d90febca32 100644 --- a/tests/test_std_shift_intensityd.py +++ b/tests/transforms/test_std_shift_intensityd.py @@ -17,11 +17,10 @@ from monai.transforms import ShiftIntensityd, StdShiftIntensityd from monai.utils import dtype_numpy_to_torch -from tests.utils import NumpyImageTestCase2D +from tests.test_utils import NumpyImageTestCase2D class TestStdShiftIntensityd(NumpyImageTestCase2D): - def test_value(self): key = "img" factor = np.random.rand() diff --git a/tests/test_threshold_intensity.py b/tests/transforms/test_threshold_intensity.py similarity index 96% rename from tests/test_threshold_intensity.py rename to tests/transforms/test_threshold_intensity.py index 97c80eebcd..8803987fd9 100644 --- a/tests/test_threshold_intensity.py +++ b/tests/transforms/test_threshold_intensity.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import ThresholdIntensity -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -27,7 +27,6 @@ class TestThresholdIntensity(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, in_type, input_param, expected_value): test_data = in_type(np.arange(10)) diff --git a/tests/test_threshold_intensityd.py b/tests/transforms/test_threshold_intensityd.py similarity index 97% rename from tests/test_threshold_intensityd.py rename to tests/transforms/test_threshold_intensityd.py index 867ebfe952..e825340658 100644 --- a/tests/test_threshold_intensityd.py +++ b/tests/transforms/test_threshold_intensityd.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import ThresholdIntensityd -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -45,7 +45,6 @@ class TestThresholdIntensityd(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, in_type, input_param, expected_value): test_data = {"image": in_type(np.arange(10)), "label": in_type(np.arange(10)), "extra": in_type(np.arange(10))} diff --git a/tests/test_to_contiguous.py b/tests/transforms/test_to_contiguous.py similarity index 97% rename from tests/test_to_contiguous.py rename to tests/transforms/test_to_contiguous.py index 73a9ca27f6..2b4fe7a4e9 100644 --- a/tests/test_to_contiguous.py +++ b/tests/transforms/test_to_contiguous.py @@ -17,11 +17,10 @@ import torch from monai.transforms import convert_to_contiguous -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose class TestToContiguous(unittest.TestCase): - def test_contiguous_dict(self): tochange = np.moveaxis(np.zeros((2, 3, 4)), 0, -1) test_dict = {"test_key": [[1]], 0: np.array(0), 1: np.array([0]), "nested": {"nested": [tochange]}} diff --git a/tests/test_to_cupy.py b/tests/transforms/test_to_cupy.py similarity index 98% rename from tests/test_to_cupy.py rename to tests/transforms/test_to_cupy.py index 38400f0d3f..a9f95ba1b0 100644 --- a/tests/test_to_cupy.py +++ b/tests/transforms/test_to_cupy.py @@ -19,14 +19,13 @@ from monai.transforms import ToCupy from monai.utils import optional_import -from tests.utils import HAS_CUPY, skip_if_no_cuda +from tests.test_utils import HAS_CUPY, skip_if_no_cuda cp, _ = optional_import("cupy") @skipUnless(HAS_CUPY, "CuPy is required.") class TestToCupy(unittest.TestCase): - def test_cupy_input(self): test_data = cp.array([[1, 2], [3, 4]], dtype=cp.float32) test_data = cp.rot90(test_data) diff --git a/tests/test_to_cupyd.py b/tests/transforms/test_to_cupyd.py similarity index 98% rename from tests/test_to_cupyd.py rename to tests/transforms/test_to_cupyd.py index a07ab671e1..9e26b4d1a5 100644 --- a/tests/test_to_cupyd.py +++ b/tests/transforms/test_to_cupyd.py @@ -19,14 +19,13 @@ from monai.transforms import ToCupyd from monai.utils import optional_import -from tests.utils import HAS_CUPY, skip_if_no_cuda +from tests.test_utils import HAS_CUPY, skip_if_no_cuda cp, _ = optional_import("cupy") @skipUnless(HAS_CUPY, "CuPy is required.") class TestToCupyd(unittest.TestCase): - def test_cupy_input(self): test_data = cp.array([[1, 2], [3, 4]]) test_data = cp.rot90(test_data) diff --git a/tests/test_to_device.py b/tests/transforms/test_to_device.py similarity index 95% rename from tests/test_to_device.py rename to tests/transforms/test_to_device.py index 6a13ffca99..1bfa199c96 100644 --- a/tests/test_to_device.py +++ b/tests/transforms/test_to_device.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import ToDevice -from tests.utils import assert_allclose, skip_if_no_cuda +from tests.test_utils import assert_allclose, skip_if_no_cuda TEST_CASE_1 = ["cuda:0"] @@ -30,7 +30,6 @@ @skip_if_no_cuda class TestToDevice(unittest.TestCase): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4]) def test_value(self, device): converter = ToDevice(device=device, non_blocking=True) diff --git a/tests/test_to_deviced.py b/tests/transforms/test_to_deviced.py similarity index 95% rename from tests/test_to_deviced.py rename to tests/transforms/test_to_deviced.py index 19c2d0761f..d86634fb3f 100644 --- a/tests/test_to_deviced.py +++ b/tests/transforms/test_to_deviced.py @@ -17,12 +17,11 @@ from monai.data import CacheDataset, ThreadDataLoader from monai.transforms import ToDeviced -from tests.utils import assert_allclose, skip_if_no_cuda +from tests.test_utils import assert_allclose, skip_if_no_cuda @skip_if_no_cuda class TestToDeviced(unittest.TestCase): - def test_value(self): device = "cuda:0" data = [{"img": torch.tensor(i)} for i in range(4)] diff --git a/tests/test_to_numpy.py b/tests/transforms/test_to_numpy.py similarity index 97% rename from tests/test_to_numpy.py rename to tests/transforms/test_to_numpy.py index f4e5f80a29..6e69fbf90e 100644 --- a/tests/test_to_numpy.py +++ b/tests/transforms/test_to_numpy.py @@ -19,13 +19,12 @@ from monai.transforms import ToNumpy from monai.utils import optional_import -from tests.utils import HAS_CUPY, assert_allclose, skip_if_no_cuda +from tests.test_utils import HAS_CUPY, assert_allclose, skip_if_no_cuda cp, _ = optional_import("cupy") class TestToNumpy(unittest.TestCase): - @skipUnless(HAS_CUPY, "CuPy is required.") def test_cupy_input(self): test_data = cp.array([[1, 2], [3, 4]]) diff --git a/tests/test_to_numpyd.py b/tests/transforms/test_to_numpyd.py similarity index 97% rename from tests/test_to_numpyd.py rename to tests/transforms/test_to_numpyd.py index ae9b4c84b3..532cb7d332 100644 --- a/tests/test_to_numpyd.py +++ b/tests/transforms/test_to_numpyd.py @@ -19,13 +19,12 @@ from monai.transforms import ToNumpyd from monai.utils import optional_import -from tests.utils import HAS_CUPY, assert_allclose, skip_if_no_cuda +from tests.test_utils import HAS_CUPY, assert_allclose, skip_if_no_cuda cp, _ = optional_import("cupy") class TestToNumpyd(unittest.TestCase): - @skipUnless(HAS_CUPY, "CuPy is required.") def test_cupy_input(self): test_data = cp.array([[1, 2], [3, 4]]) diff --git a/tests/test_to_pil.py b/tests/transforms/test_to_pil.py similarity index 96% rename from tests/test_to_pil.py rename to tests/transforms/test_to_pil.py index 352e10bcc1..f318bb9e79 100644 --- a/tests/test_to_pil.py +++ b/tests/transforms/test_to_pil.py @@ -20,7 +20,7 @@ from monai.transforms import ToPIL from monai.utils import optional_import -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose if TYPE_CHECKING: from PIL.Image import Image as PILImageImage @@ -40,7 +40,6 @@ class TestToPIL(unittest.TestCase): - @parameterized.expand(TESTS) @skipUnless(has_pil, "Requires `pillow` package.") def test_value(self, test_data): diff --git a/tests/test_to_pild.py b/tests/transforms/test_to_pild.py similarity index 96% rename from tests/test_to_pild.py rename to tests/transforms/test_to_pild.py index 1a0232e134..baee3e0c97 100644 --- a/tests/test_to_pild.py +++ b/tests/transforms/test_to_pild.py @@ -20,7 +20,7 @@ from monai.transforms import ToPILd from monai.utils import optional_import -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose if TYPE_CHECKING: from PIL.Image import Image as PILImageImage @@ -38,7 +38,6 @@ class TestToPIL(unittest.TestCase): - @parameterized.expand(TESTS) @skipUnless(has_pil, "Requires `pillow` package.") def test_values(self, input_param, test_data): diff --git a/tests/test_to_tensor.py b/tests/transforms/test_to_tensor.py similarity index 95% rename from tests/test_to_tensor.py rename to tests/transforms/test_to_tensor.py index 50df80128b..790556a9bc 100644 --- a/tests/test_to_tensor.py +++ b/tests/transforms/test_to_tensor.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import ToTensor -from tests.utils import HAS_CUPY, TEST_NDARRAYS, assert_allclose, optional_import +from tests.test_utils import HAS_CUPY, TEST_NDARRAYS, assert_allclose, optional_import cp, _ = optional_import("cupy") @@ -33,7 +33,6 @@ class TestToTensor(unittest.TestCase): - @parameterized.expand(TESTS) def test_array_input(self, test_data, expected_shape): result = ToTensor(dtype=torch.float32, device="cpu", wrap_sequence=True)(test_data) diff --git a/tests/test_to_tensord.py b/tests/transforms/test_to_tensord.py similarity index 96% rename from tests/test_to_tensord.py rename to tests/transforms/test_to_tensord.py index 1eab7b9485..b7735f5ea3 100644 --- a/tests/test_to_tensord.py +++ b/tests/transforms/test_to_tensord.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms import ToTensord -from tests.utils import HAS_CUPY, TEST_NDARRAYS, assert_allclose, optional_import +from tests.test_utils import HAS_CUPY, TEST_NDARRAYS, assert_allclose, optional_import cp, _ = optional_import("cupy") @@ -34,7 +34,6 @@ class TestToTensord(unittest.TestCase): - @parameterized.expand(TESTS) def test_array_input(self, test_data, expected_shape): test_data = {"img": test_data} diff --git a/tests/test_torchvision.py b/tests/transforms/test_torchvision.py similarity index 97% rename from tests/test_torchvision.py rename to tests/transforms/test_torchvision.py index 2931b0c1a8..b15fd88dc5 100644 --- a/tests/test_torchvision.py +++ b/tests/transforms/test_torchvision.py @@ -17,7 +17,7 @@ from monai.transforms import TorchVision from monai.utils import set_determinism -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -55,7 +55,6 @@ class TestTorchVision(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, input_param, input_data, expected_value): set_determinism(seed=0) diff --git a/tests/test_torchvisiond.py b/tests/transforms/test_torchvisiond.py similarity index 98% rename from tests/test_torchvisiond.py rename to tests/transforms/test_torchvisiond.py index ec09692df9..2e5003cbac 100644 --- a/tests/test_torchvisiond.py +++ b/tests/transforms/test_torchvisiond.py @@ -18,7 +18,7 @@ from monai.transforms import TorchVisiond from monai.utils import set_determinism -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TEST_CASE_1 = [ {"keys": "img", "name": "ColorJitter"}, @@ -52,7 +52,6 @@ class TestTorchVisiond(unittest.TestCase): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3]) def test_value(self, input_param, input_data, expected_value): set_determinism(seed=0) diff --git a/tests/test_transform.py b/tests/transforms/test_transform.py similarity index 100% rename from tests/test_transform.py rename to tests/transforms/test_transform.py diff --git a/tests/test_transpose.py b/tests/transforms/test_transpose.py similarity index 95% rename from tests/test_transpose.py rename to tests/transforms/test_transpose.py index 2f5ccd1235..b6ff5ea589 100644 --- a/tests/test_transpose.py +++ b/tests/transforms/test_transpose.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.transforms import Transpose -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -27,7 +27,6 @@ class TestTranspose(unittest.TestCase): - @parameterized.expand(TESTS) def test_transpose(self, im, indices): tr = Transpose(indices) diff --git a/tests/test_transposed.py b/tests/transforms/test_transposed.py similarity index 96% rename from tests/test_transposed.py rename to tests/transforms/test_transposed.py index e7c6ecbe8a..b47762843a 100644 --- a/tests/test_transposed.py +++ b/tests/transforms/test_transposed.py @@ -19,7 +19,7 @@ from parameterized import parameterized from monai.transforms import Transposed -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -30,7 +30,6 @@ class TestTranspose(unittest.TestCase): - @parameterized.expand(TESTS) def test_transpose(self, im, indices): data = {"i": deepcopy(im), "j": deepcopy(im)} diff --git a/tests/test_ultrasound_confidence_map_transform.py b/tests/transforms/test_ultrasound_confidence_map_transform.py similarity index 97% rename from tests/test_ultrasound_confidence_map_transform.py rename to tests/transforms/test_ultrasound_confidence_map_transform.py index 1c6b8f7635..331c46ee00 100644 --- a/tests/test_ultrasound_confidence_map_transform.py +++ b/tests/transforms/test_ultrasound_confidence_map_transform.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path import numpy as np import torch @@ -21,10 +22,12 @@ from monai.transforms import UltrasoundConfidenceMapTransform from monai.utils import optional_import -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose _, has_scipy = optional_import("scipy") +TESTS_PATH = Path(__file__).parents[1] + TEST_INPUT = np.array( [ [1, 2, 3, 23, 13, 22, 5, 1, 2, 3], @@ -487,7 +490,6 @@ @unittest.skipUnless(has_scipy, "Requires scipy") class TestUltrasoundConfidenceMapTransform(unittest.TestCase): - def setUp(self): self.input_img_np = np.expand_dims(TEST_INPUT, axis=0) # mock image (numpy array) self.input_mask_np = np.expand_dims(TEST_MASK, axis=0) # mock mask (numpy array) @@ -496,13 +498,13 @@ def setUp(self): self.input_mask_torch = torch.from_numpy(TEST_MASK).unsqueeze(0) # mock mask (torch tensor) self.real_input_img_paths = [ - os.path.join(os.path.dirname(__file__), "testing_data", "ultrasound_confidence_map", "neck_input.png"), - os.path.join(os.path.dirname(__file__), "testing_data", "ultrasound_confidence_map", "femur_input.png"), + os.path.join(TESTS_PATH, "testing_data", "ultrasound_confidence_map", "neck_input.png"), + os.path.join(TESTS_PATH, "testing_data", "ultrasound_confidence_map", "femur_input.png"), ] self.real_result_npy_paths = [ - os.path.join(os.path.dirname(__file__), "testing_data", "ultrasound_confidence_map", "neck_result.npy"), - os.path.join(os.path.dirname(__file__), "testing_data", "ultrasound_confidence_map", "femur_result.npy"), + os.path.join(TESTS_PATH, "testing_data", "ultrasound_confidence_map", "neck_result.npy"), + os.path.join(TESTS_PATH, "testing_data", "ultrasound_confidence_map", "femur_result.npy"), ] self.real_input_paramaters = [ diff --git a/tests/test_utils_pytorch_numpy_unification.py b/tests/transforms/test_utils_pytorch_numpy_unification.py similarity index 97% rename from tests/test_utils_pytorch_numpy_unification.py rename to tests/transforms/test_utils_pytorch_numpy_unification.py index 90c0401e46..a78fcab0d1 100644 --- a/tests/test_utils_pytorch_numpy_unification.py +++ b/tests/transforms/test_utils_pytorch_numpy_unification.py @@ -19,7 +19,7 @@ from monai.transforms.utils_pytorch_numpy_unification import max, min, mode, percentile from monai.utils import set_determinism -from tests.utils import TEST_NDARRAYS, assert_allclose, skip_if_quick +from tests.test_utils import TEST_NDARRAYS, assert_allclose, skip_if_quick TEST_MODE = [] for p in TEST_NDARRAYS: @@ -36,7 +36,6 @@ class TestPytorchNumpyUnification(unittest.TestCase): - def setUp(self) -> None: set_determinism(0) diff --git a/tests/test_vote_ensemble.py b/tests/transforms/test_vote_ensemble.py similarity index 97% rename from tests/test_vote_ensemble.py rename to tests/transforms/test_vote_ensemble.py index 4abdd0b050..3a93600ec4 100644 --- a/tests/test_vote_ensemble.py +++ b/tests/transforms/test_vote_ensemble.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import VoteEnsemble -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -71,7 +71,6 @@ class TestVoteEnsemble(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, input_param, img, expected_value): result = VoteEnsemble(**input_param)(img) diff --git a/tests/test_vote_ensembled.py b/tests/transforms/test_vote_ensembled.py similarity index 98% rename from tests/test_vote_ensembled.py rename to tests/transforms/test_vote_ensembled.py index 957133d7fc..e43271357e 100644 --- a/tests/test_vote_ensembled.py +++ b/tests/transforms/test_vote_ensembled.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms import VoteEnsembled -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose TESTS = [] for p in TEST_NDARRAYS: @@ -86,7 +86,6 @@ class TestVoteEnsembled(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, input_param, img, expected_value): result = VoteEnsembled(**input_param)(img) diff --git a/tests/test_with_allow_missing_keys.py b/tests/transforms/test_with_allow_missing_keys.py similarity index 100% rename from tests/test_with_allow_missing_keys.py rename to tests/transforms/test_with_allow_missing_keys.py diff --git a/tests/test_zoom.py b/tests/transforms/test_zoom.py similarity index 99% rename from tests/test_zoom.py rename to tests/transforms/test_zoom.py index 2db2df4486..93225420c5 100644 --- a/tests/test_zoom.py +++ b/tests/transforms/test_zoom.py @@ -21,7 +21,7 @@ from monai.data import MetaTensor, set_track_meta from monai.transforms import Zoom from monai.transforms.lazy.functional import apply_pending -from tests.utils import ( +from tests.test_utils import ( DEFAULT_TEST_AFFINE, TEST_NDARRAYS_ALL, NumpyImageTestCase2D, @@ -43,7 +43,6 @@ class TestZoom(NumpyImageTestCase2D): - @parameterized.expand(VALID_CASES) def test_pending_ops(self, zoom, mode, align_corners=False, keep_size=False): im = MetaTensor(self.imt[0], meta={"a": "b", "affine": DEFAULT_TEST_AFFINE}) diff --git a/tests/test_zoomd.py b/tests/transforms/test_zoomd.py similarity index 96% rename from tests/test_zoomd.py rename to tests/transforms/test_zoomd.py index ad91f398ff..65b82a3fbf 100644 --- a/tests/test_zoomd.py +++ b/tests/transforms/test_zoomd.py @@ -21,7 +21,7 @@ from monai.config import USE_COMPILED from monai.transforms import Zoomd from tests.lazy_transforms_utils import test_resampler_lazy -from tests.utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, assert_allclose, test_local_inversion +from tests.test_utils import TEST_NDARRAYS_ALL, NumpyImageTestCase2D, assert_allclose, test_local_inversion VALID_CASES = [ (1.5, "nearest", False), @@ -34,7 +34,6 @@ class TestZoomd(NumpyImageTestCase2D): - @parameterized.expand(VALID_CASES) def test_correct_results(self, zoom, mode, keep_size, align_corners=None): key = "img" diff --git a/tests/transforms/transform/__init__.py b/tests/transforms/transform/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/transforms/transform/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_randomizable.py b/tests/transforms/transform/test_randomizable.py similarity index 100% rename from tests/test_randomizable.py rename to tests/transforms/transform/test_randomizable.py diff --git a/tests/test_randomizable_transform_type.py b/tests/transforms/transform/test_randomizable_transform_type.py similarity index 100% rename from tests/test_randomizable_transform_type.py rename to tests/transforms/transform/test_randomizable_transform_type.py diff --git a/tests/transforms/utility/__init__.py b/tests/transforms/utility/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/transforms/utility/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_apply_transform_to_points.py b/tests/transforms/utility/test_apply_transform_to_points.py similarity index 100% rename from tests/test_apply_transform_to_points.py rename to tests/transforms/utility/test_apply_transform_to_points.py diff --git a/tests/test_apply_transform_to_pointsd.py b/tests/transforms/utility/test_apply_transform_to_pointsd.py similarity index 100% rename from tests/test_apply_transform_to_pointsd.py rename to tests/transforms/utility/test_apply_transform_to_pointsd.py diff --git a/tests/test_identity.py b/tests/transforms/utility/test_identity.py similarity index 92% rename from tests/test_identity.py rename to tests/transforms/utility/test_identity.py index 4243a7f19a..b873854e0a 100644 --- a/tests/test_identity.py +++ b/tests/transforms/utility/test_identity.py @@ -14,11 +14,10 @@ import unittest from monai.transforms.utility.array import Identity -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class TestIdentity(NumpyImageTestCase2D): - def test_identity(self): for p in TEST_NDARRAYS: img = p(self.imt) diff --git a/tests/test_identityd.py b/tests/transforms/utility/test_identityd.py similarity index 92% rename from tests/test_identityd.py rename to tests/transforms/utility/test_identityd.py index 6b81ad9f16..770eb14620 100644 --- a/tests/test_identityd.py +++ b/tests/transforms/utility/test_identityd.py @@ -14,11 +14,10 @@ import unittest from monai.transforms.utility.dictionary import Identityd -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class TestIdentityd(NumpyImageTestCase2D): - def test_identityd(self): for p in TEST_NDARRAYS: img = p(self.imt) diff --git a/tests/test_lambda.py b/tests/transforms/utility/test_lambda.py similarity index 96% rename from tests/test_lambda.py rename to tests/transforms/utility/test_lambda.py index e0a5cf84db..1aa3567d23 100644 --- a/tests/test_lambda.py +++ b/tests/transforms/utility/test_lambda.py @@ -19,11 +19,10 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms.utility.array import Lambda from monai.utils.type_conversion import convert_to_numpy, convert_to_tensor -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class TestLambda(NumpyImageTestCase2D): - def test_lambda_identity(self): for p in TEST_NDARRAYS: img = p(self.imt) diff --git a/tests/test_lambdad.py b/tests/transforms/utility/test_lambdad.py similarity index 97% rename from tests/test_lambdad.py rename to tests/transforms/utility/test_lambdad.py index fad5ebeee4..2c996b23db 100644 --- a/tests/test_lambdad.py +++ b/tests/transforms/utility/test_lambdad.py @@ -19,11 +19,10 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms.utility.dictionary import Lambdad from monai.utils.type_conversion import convert_to_numpy, convert_to_tensor -from tests.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose +from tests.test_utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class TestLambdad(NumpyImageTestCase2D): - def test_lambdad_identity(self): for p in TEST_NDARRAYS: img = p(self.imt) diff --git a/tests/test_rand_lambda.py b/tests/transforms/utility/test_rand_lambda.py similarity index 97% rename from tests/test_rand_lambda.py rename to tests/transforms/utility/test_rand_lambda.py index 98a324aec5..74627c3d3b 100644 --- a/tests/test_rand_lambda.py +++ b/tests/transforms/utility/test_rand_lambda.py @@ -20,7 +20,7 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms.transform import Randomizable from monai.transforms.utility.array import RandLambda -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose class RandTest(Randomizable): @@ -37,7 +37,6 @@ def __call__(self, data): class TestRandLambda(unittest.TestCase): - def check(self, tr: RandLambda, img, img_orig_type, out, expected=None): # input shouldn't change self.assertIsInstance(img, img_orig_type) diff --git a/tests/test_rand_lambdad.py b/tests/transforms/utility/test_rand_lambdad.py similarity index 97% rename from tests/test_rand_lambdad.py rename to tests/transforms/utility/test_rand_lambdad.py index 5247d79843..7eb8ddf7ba 100644 --- a/tests/test_rand_lambdad.py +++ b/tests/transforms/utility/test_rand_lambdad.py @@ -20,7 +20,7 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms.transform import Randomizable from monai.transforms.utility.dictionary import RandLambdad -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose class RandTest(Randomizable): @@ -37,7 +37,6 @@ def __call__(self, data): class TestRandLambdad(unittest.TestCase): - def check(self, tr: RandLambdad, input: dict, out: dict, expected: dict): if isinstance(input["img"], MetaTensor): self.assertEqual(len(input["img"].applied_operations), 0) diff --git a/tests/test_simulatedelay.py b/tests/transforms/utility/test_simulatedelay.py similarity index 96% rename from tests/test_simulatedelay.py rename to tests/transforms/utility/test_simulatedelay.py index 0a4f23450a..743150ab0d 100644 --- a/tests/test_simulatedelay.py +++ b/tests/transforms/utility/test_simulatedelay.py @@ -18,11 +18,10 @@ from parameterized import parameterized from monai.transforms.utility.array import SimulateDelay -from tests.utils import NumpyImageTestCase2D +from tests.test_utils import NumpyImageTestCase2D class TestSimulateDelay(NumpyImageTestCase2D): - @parameterized.expand([(0.45,), (1,)]) def test_value(self, delay_test_time: float): resize = SimulateDelay(delay_time=delay_test_time) diff --git a/tests/test_simulatedelayd.py b/tests/transforms/utility/test_simulatedelayd.py similarity index 96% rename from tests/test_simulatedelayd.py rename to tests/transforms/utility/test_simulatedelayd.py index 419e21f24d..1d473a86a9 100644 --- a/tests/test_simulatedelayd.py +++ b/tests/transforms/utility/test_simulatedelayd.py @@ -18,11 +18,10 @@ from parameterized import parameterized from monai.transforms.utility.dictionary import SimulateDelayd -from tests.utils import NumpyImageTestCase2D +from tests.test_utils import NumpyImageTestCase2D class TestSimulateDelay(NumpyImageTestCase2D): - @parameterized.expand([(0.45,), (1,)]) def test_value(self, delay_test_time: float): resize = SimulateDelayd(keys="imgd", delay_time=delay_test_time) diff --git a/tests/test_splitdim.py b/tests/transforms/utility/test_splitdim.py similarity index 97% rename from tests/test_splitdim.py rename to tests/transforms/utility/test_splitdim.py index f557f44142..31d9983a2b 100644 --- a/tests/test_splitdim.py +++ b/tests/transforms/utility/test_splitdim.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.transforms.utility.array import SplitDim -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS TESTS = [] for p in TEST_NDARRAYS: @@ -26,7 +26,6 @@ class TestSplitDim(unittest.TestCase): - @parameterized.expand(TESTS) def test_correct_shape(self, shape, keepdim, im_type): arr = im_type(np.random.rand(*shape)) diff --git a/tests/test_splitdimd.py b/tests/transforms/utility/test_splitdimd.py similarity index 97% rename from tests/test_splitdimd.py rename to tests/transforms/utility/test_splitdimd.py index b01913269d..6e221d3d52 100644 --- a/tests/test_splitdimd.py +++ b/tests/transforms/utility/test_splitdimd.py @@ -21,7 +21,7 @@ from monai.data.meta_tensor import MetaTensor from monai.transforms import LoadImaged from monai.transforms.utility.dictionary import SplitDimd -from tests.utils import TEST_NDARRAYS, assert_allclose, make_nifti_image, make_rand_affine +from tests.test_utils import TEST_NDARRAYS, assert_allclose, make_nifti_image, make_rand_affine TESTS = [] for p in TEST_NDARRAYS: diff --git a/tests/transforms/utils/__init__.py b/tests/transforms/utils/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/transforms/utils/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_correct_crop_centers.py b/tests/transforms/utils/test_correct_crop_centers.py similarity index 96% rename from tests/test_correct_crop_centers.py rename to tests/transforms/utils/test_correct_crop_centers.py index 82b0b93b53..3b483c8e69 100644 --- a/tests/test_correct_crop_centers.py +++ b/tests/transforms/utils/test_correct_crop_centers.py @@ -17,13 +17,12 @@ from parameterized import parameterized from monai.transforms.utils import correct_crop_centers -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TESTS = [[[1, 5, 0], [2, 2, 2], [10, 10, 10]], [[4, 4, 4], [2, 2, 1], [10, 10, 10]]] class TestCorrectCropCenters(unittest.TestCase): - @parameterized.expand(TESTS) def test_torch(self, spatial_size, centers, label_spatial_shape): result1 = correct_crop_centers(centers, spatial_size, label_spatial_shape) diff --git a/tests/test_get_unique_labels.py b/tests/transforms/utils/test_get_unique_labels.py similarity index 97% rename from tests/test_get_unique_labels.py rename to tests/transforms/utils/test_get_unique_labels.py index 0a88145489..13e034b9f8 100644 --- a/tests/test_get_unique_labels.py +++ b/tests/transforms/utils/test_get_unique_labels.py @@ -19,7 +19,7 @@ from monai.transforms.utils import get_unique_labels from monai.transforms.utils_pytorch_numpy_unification import moveaxis -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS grid_raw = [[0, 0, 0], [0, 0, 1], [2, 2, 3], [5, 5, 6], [3, 6, 2], [5, 6, 6]] grid = torch.Tensor(grid_raw).unsqueeze(0).to(torch.int64) @@ -35,7 +35,6 @@ class TestGetUniqueLabels(unittest.TestCase): - @parameterized.expand(TESTS) def test_correct_results(self, args, expected): result = get_unique_labels(**args) diff --git a/tests/test_print_transform_backends.py b/tests/transforms/utils/test_print_transform_backends.py similarity index 100% rename from tests/test_print_transform_backends.py rename to tests/transforms/utils/test_print_transform_backends.py diff --git a/tests/test_soft_clip.py b/tests/transforms/utils/test_soft_clip.py similarity index 100% rename from tests/test_soft_clip.py rename to tests/transforms/utils/test_soft_clip.py diff --git a/tests/utils/__init__.py b/tests/utils/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/utils/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/utils/enums/__init__.py b/tests/utils/enums/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/utils/enums/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_hovernet_loss.py b/tests/utils/enums/test_hovernet_loss.py similarity index 100% rename from tests/test_hovernet_loss.py rename to tests/utils/enums/test_hovernet_loss.py diff --git a/tests/test_ordering.py b/tests/utils/enums/test_ordering.py similarity index 100% rename from tests/test_ordering.py rename to tests/utils/enums/test_ordering.py diff --git a/tests/test_wsireader.py b/tests/utils/enums/test_wsireader.py similarity index 97% rename from tests/test_wsireader.py rename to tests/utils/enums/test_wsireader.py index 99a86c5ac8..3b84af7345 100644 --- a/tests/test_wsireader.py +++ b/tests/utils/enums/test_wsireader.py @@ -13,6 +13,7 @@ import os import unittest +from pathlib import Path from typing import Any from unittest import skipUnless @@ -26,7 +27,7 @@ from monai.transforms import Compose, LoadImaged, ToTensord from monai.utils import first, optional_import from monai.utils.enums import PostFix, WSIPatchKeys -from tests.utils import assert_allclose, download_url_or_skip_test, skip_if_no_cuda, testing_data_config +from tests.test_utils import assert_allclose, download_url_or_skip_test, skip_if_no_cuda, testing_data_config cucim, has_cucim = optional_import("cucim") has_cucim = has_cucim and hasattr(cucim, "CuImage") @@ -35,11 +36,12 @@ _, has_codec = optional_import("imagecodecs") has_tiff = has_tiff and has_codec +TESTS_PATH = Path(__file__).parents[2] WSI_GENERIC_TIFF_KEY = "wsi_generic_tiff" -WSI_GENERIC_TIFF_PATH = os.path.join(os.path.dirname(__file__), "testing_data", f"temp_{WSI_GENERIC_TIFF_KEY}.tiff") +WSI_GENERIC_TIFF_PATH = os.path.join(TESTS_PATH, "testing_data", f"temp_{WSI_GENERIC_TIFF_KEY}.tiff") WSI_APERIO_SVS_KEY = "wsi_aperio_svs" -WSI_APERIO_SVS_PATH = os.path.join(os.path.dirname(__file__), "testing_data", f"temp_{WSI_APERIO_SVS_KEY}.svs") +WSI_APERIO_SVS_PATH = os.path.join(TESTS_PATH, "testing_data", f"temp_{WSI_APERIO_SVS_KEY}.svs") WSI_GENERIC_TIFF_HEIGHT = 32914 WSI_GENERIC_TIFF_WIDTH = 46000 @@ -402,7 +404,6 @@ def setUpModule(): class WSIReaderTests: - class Tests(unittest.TestCase): backend = None @@ -497,9 +498,7 @@ def test_read_rgba(self, img_expected): reader = WSIReader(self.backend) for mode in ["RGB", "RGBA"]: file_path = save_rgba_tiff( - img_expected, - os.path.join(os.path.dirname(__file__), "testing_data", f"temp_tiff_image_{mode}.tiff"), - mode=mode, + img_expected, os.path.join(TESTS_PATH, "testing_data", f"temp_tiff_image_{mode}.tiff"), mode=mode ) with reader.read(file_path) as img_obj: image[mode], _ = reader.get_data(img_obj) @@ -514,7 +513,7 @@ def test_read_malformats(self, img_expected): # Until cuCIM addresses https://github.com/rapidsai/cucim/issues/230 return reader = WSIReader(self.backend) - file_path = os.path.join(os.path.dirname(__file__), "testing_data", "temp_tiff_image_gray.tiff") + file_path = os.path.join(TESTS_PATH, "testing_data", "temp_tiff_image_gray.tiff") imwrite(file_path, img_expected, shape=img_expected.shape) with self.assertRaises((RuntimeError, ValueError, openslide.OpenSlideError if has_osl else ValueError)): with reader.read(file_path) as img_obj: @@ -641,7 +640,6 @@ def test_errors(self, file_path, reader_kwargs, patch_info, exception): @skipUnless(has_cucim, "Requires cucim") class TestCuCIM(WSIReaderTests.Tests): - @classmethod def setUpClass(cls): cls.backend = "cucim" @@ -649,7 +647,6 @@ def setUpClass(cls): @skipUnless(has_osl, "Requires openslide") class TestOpenSlide(WSIReaderTests.Tests): - @classmethod def setUpClass(cls): cls.backend = "openslide" @@ -657,7 +654,6 @@ def setUpClass(cls): @skipUnless(has_tiff, "Requires tifffile") class TestTiffFile(WSIReaderTests.Tests): - @classmethod def setUpClass(cls): cls.backend = "tifffile" diff --git a/tests/utils/misc/__init__.py b/tests/utils/misc/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/utils/misc/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_ensure_tuple.py b/tests/utils/misc/test_ensure_tuple.py similarity index 97% rename from tests/test_ensure_tuple.py rename to tests/utils/misc/test_ensure_tuple.py index ec8c92785a..c947c12f69 100644 --- a/tests/test_ensure_tuple.py +++ b/tests/utils/misc/test_ensure_tuple.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.utils.misc import ensure_tuple -from tests.utils import assert_allclose +from tests.test_utils import assert_allclose TESTS = [ ["test", ("test",)], @@ -37,7 +37,6 @@ class TestEnsureTuple(unittest.TestCase): - @parameterized.expand(TESTS) def test_value(self, input, expected_value, wrap_array=False): result = ensure_tuple(input, wrap_array) diff --git a/tests/test_monai_env_vars.py b/tests/utils/misc/test_monai_env_vars.py similarity index 100% rename from tests/test_monai_env_vars.py rename to tests/utils/misc/test_monai_env_vars.py diff --git a/tests/test_monai_utils_misc.py b/tests/utils/misc/test_monai_utils_misc.py similarity index 100% rename from tests/test_monai_utils_misc.py rename to tests/utils/misc/test_monai_utils_misc.py diff --git a/tests/test_str2bool.py b/tests/utils/misc/test_str2bool.py similarity index 100% rename from tests/test_str2bool.py rename to tests/utils/misc/test_str2bool.py diff --git a/tests/test_str2list.py b/tests/utils/misc/test_str2list.py similarity index 100% rename from tests/test_str2list.py rename to tests/utils/misc/test_str2list.py diff --git a/tests/test_alias.py b/tests/utils/test_alias.py similarity index 92% rename from tests/test_alias.py rename to tests/utils/test_alias.py index e2dd8bcf26..e7abff3d89 100644 --- a/tests/test_alias.py +++ b/tests/utils/test_alias.py @@ -15,15 +15,18 @@ import inspect import os import unittest +from pathlib import Path from monai.utils import optional_import +TESTS_PATH = Path(__file__).parents[1] + class TestModuleAlias(unittest.TestCase): """check that 'import monai.xx.file_name' returns a module""" def test_files(self): - src_dir = os.path.dirname(os.path.dirname(__file__)) + src_dir = os.path.dirname(TESTS_PATH) monai_dir = os.path.join(src_dir, "monai") py_files = glob.glob(os.path.join(monai_dir, "**", "*.py"), recursive=True) for x in py_files: diff --git a/tests/test_component_store.py b/tests/utils/test_component_store.py similarity index 100% rename from tests/test_component_store.py rename to tests/utils/test_component_store.py diff --git a/tests/test_deprecated.py b/tests/utils/test_deprecated.py similarity index 100% rename from tests/test_deprecated.py rename to tests/utils/test_deprecated.py diff --git a/tests/test_enum_bound_interp.py b/tests/utils/test_enum_bound_interp.py similarity index 98% rename from tests/test_enum_bound_interp.py rename to tests/utils/test_enum_bound_interp.py index cd3119f91c..6f8ffa2481 100644 --- a/tests/test_enum_bound_interp.py +++ b/tests/utils/test_enum_bound_interp.py @@ -14,7 +14,7 @@ import unittest from monai.utils import optional_import -from tests.utils import skip_if_no_cpp_extension +from tests.test_utils import skip_if_no_cpp_extension b, _ = optional_import("monai._C", name="BoundType") p, _ = optional_import("monai._C", name="InterpolationType") @@ -22,7 +22,6 @@ @skip_if_no_cpp_extension class TestEnumBoundInterp(unittest.TestCase): - def test_bound(self): self.assertEqual(str(b.replicate), "BoundType.replicate") self.assertEqual(str(b.nearest), "BoundType.replicate") diff --git a/tests/test_evenly_divisible_all_gather_dist.py b/tests/utils/test_evenly_divisible_all_gather_dist.py similarity index 96% rename from tests/test_evenly_divisible_all_gather_dist.py rename to tests/utils/test_evenly_divisible_all_gather_dist.py index f1d45ba48f..cea8921544 100644 --- a/tests/test_evenly_divisible_all_gather_dist.py +++ b/tests/utils/test_evenly_divisible_all_gather_dist.py @@ -17,11 +17,10 @@ import torch.distributed as dist from monai.utils import evenly_divisible_all_gather -from tests.utils import DistCall, DistTestCase, assert_allclose +from tests.test_utils import DistCall, DistTestCase, assert_allclose class DistributedEvenlyDivisibleAllGather(DistTestCase): - @DistCall(nnodes=1, nproc_per_node=2) def test_data(self): self._run() diff --git a/tests/test_get_package_version.py b/tests/utils/test_get_package_version.py similarity index 100% rename from tests/test_get_package_version.py rename to tests/utils/test_get_package_version.py diff --git a/tests/test_handler_logfile.py b/tests/utils/test_handler_logfile.py similarity index 98% rename from tests/test_handler_logfile.py rename to tests/utils/test_handler_logfile.py index 457aca2ebc..344ede7874 100644 --- a/tests/test_handler_logfile.py +++ b/tests/utils/test_handler_logfile.py @@ -18,7 +18,7 @@ import torch from monai.utils import optional_import -from tests.utils import SkipIfNoModule +from tests.test_utils import SkipIfNoModule try: _, has_ignite = optional_import("ignite") @@ -30,7 +30,6 @@ class TestHandlerLogfile(unittest.TestCase): - def setUp(self): if has_ignite: # set up engine diff --git a/tests/test_handler_metric_logger.py b/tests/utils/test_handler_metric_logger.py similarity index 97% rename from tests/test_handler_metric_logger.py rename to tests/utils/test_handler_metric_logger.py index 06d50e97ff..cf67fc3843 100644 --- a/tests/test_handler_metric_logger.py +++ b/tests/utils/test_handler_metric_logger.py @@ -16,7 +16,7 @@ import torch from monai.utils import optional_import -from tests.utils import SkipIfNoModule +from tests.test_utils import SkipIfNoModule try: _, has_ignite = optional_import("ignite") @@ -28,7 +28,6 @@ class TestHandlerMetricLogger(unittest.TestCase): - @SkipIfNoModule("ignite") def test_metric_logging(self): dummy_name = "dummy" diff --git a/tests/test_list_to_dict.py b/tests/utils/test_list_to_dict.py similarity index 100% rename from tests/test_list_to_dict.py rename to tests/utils/test_list_to_dict.py diff --git a/tests/test_look_up_option.py b/tests/utils/test_look_up_option.py similarity index 100% rename from tests/test_look_up_option.py rename to tests/utils/test_look_up_option.py diff --git a/tests/test_optional_import.py b/tests/utils/test_optional_import.py similarity index 100% rename from tests/test_optional_import.py rename to tests/utils/test_optional_import.py diff --git a/tests/test_pad_mode.py b/tests/utils/test_pad_mode.py similarity index 96% rename from tests/test_pad_mode.py rename to tests/utils/test_pad_mode.py index 54ee2c6d75..a4a4012fc5 100644 --- a/tests/test_pad_mode.py +++ b/tests/utils/test_pad_mode.py @@ -18,12 +18,11 @@ from monai.transforms import CastToType, Pad from monai.utils import NumpyPadMode, PytorchPadMode -from tests.utils import SkipIfBeforePyTorchVersion +from tests.test_utils import SkipIfBeforePyTorchVersion @SkipIfBeforePyTorchVersion((1, 10, 1)) class TestPadMode(unittest.TestCase): - def test_pad(self): expected_shapes = {3: (1, 15, 10), 4: (1, 10, 6, 7)} for t in (float, int, np.uint8, np.int16, np.float32, bool): diff --git a/tests/test_profiling.py b/tests/utils/test_profiling.py similarity index 99% rename from tests/test_profiling.py rename to tests/utils/test_profiling.py index 649d980ebf..da41a8ef69 100644 --- a/tests/test_profiling.py +++ b/tests/utils/test_profiling.py @@ -23,13 +23,12 @@ from monai.utils import first, optional_import from monai.utils.enums import CommonKeys from monai.utils.profiling import ProfileHandler, ProfileResult, WorkflowProfiler -from tests.utils import SkipIfNoModule +from tests.test_utils import SkipIfNoModule pd, _ = optional_import("pandas") class TestWorkflowProfiler(unittest.TestCase): - def setUp(self): super().setUp() diff --git a/tests/test_rankfilter_dist.py b/tests/utils/test_rankfilter_dist.py similarity index 97% rename from tests/test_rankfilter_dist.py rename to tests/utils/test_rankfilter_dist.py index fd02e3bdc9..caeaf2e10d 100644 --- a/tests/test_rankfilter_dist.py +++ b/tests/utils/test_rankfilter_dist.py @@ -19,11 +19,10 @@ import torch.distributed as dist from monai.utils import RankFilter -from tests.utils import DistCall, DistTestCase +from tests.test_utils import DistCall, DistTestCase class DistributedRankFilterTest(DistTestCase): - def setUp(self): self.log_dir = tempfile.TemporaryDirectory() @@ -51,7 +50,6 @@ def tearDown(self) -> None: class SingleRankFilterTest(unittest.TestCase): - def tearDown(self) -> None: self.log_dir.cleanup() diff --git a/tests/test_require_pkg.py b/tests/utils/test_require_pkg.py similarity index 100% rename from tests/test_require_pkg.py rename to tests/utils/test_require_pkg.py diff --git a/tests/test_sample_slices.py b/tests/utils/test_sample_slices.py similarity index 96% rename from tests/test_sample_slices.py rename to tests/utils/test_sample_slices.py index a183689970..7080fb1b88 100644 --- a/tests/test_sample_slices.py +++ b/tests/utils/test_sample_slices.py @@ -17,7 +17,7 @@ from parameterized import parameterized from monai.utils import sample_slices -from tests.utils import TEST_NDARRAYS, assert_allclose +from tests.test_utils import TEST_NDARRAYS, assert_allclose # test data[:, [1, ], ...] TEST_CASE_1 = [torch.tensor([[[0, 2], [1, 0]]]), 1, True, (1,), torch.tensor([[[1, 0]]])] @@ -32,7 +32,6 @@ class TestSampleSlices(unittest.TestCase): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5]) def test_shape(self, input_data, dim, as_indices, vals, expected_result): for p in TEST_NDARRAYS: diff --git a/tests/test_set_determinism.py b/tests/utils/test_set_determinism.py similarity index 97% rename from tests/test_set_determinism.py rename to tests/utils/test_set_determinism.py index 7d64aed244..2507741eb4 100644 --- a/tests/test_set_determinism.py +++ b/tests/utils/test_set_determinism.py @@ -17,11 +17,10 @@ import torch from monai.utils import get_seed, set_determinism -from tests.utils import SkipIfBeforePyTorchVersion, skip_if_no_cuda +from tests.test_utils import SkipIfBeforePyTorchVersion, skip_if_no_cuda class TestSetDeterminism(unittest.TestCase): - def test_values(self): # check system default flags set_determinism(None) @@ -56,7 +55,6 @@ def test_values(self): class TestSetFlag(unittest.TestCase): - def setUp(self): set_determinism(1, use_deterministic_algorithms=True) diff --git a/tests/test_squeeze_unsqueeze.py b/tests/utils/test_squeeze_unsqueeze.py similarity index 100% rename from tests/test_squeeze_unsqueeze.py rename to tests/utils/test_squeeze_unsqueeze.py diff --git a/tests/test_state_cacher.py b/tests/utils/test_state_cacher.py similarity index 100% rename from tests/test_state_cacher.py rename to tests/utils/test_state_cacher.py diff --git a/tests/test_torchscript_utils.py b/tests/utils/test_torchscript_utils.py similarity index 100% rename from tests/test_torchscript_utils.py rename to tests/utils/test_torchscript_utils.py diff --git a/tests/test_version.py b/tests/utils/test_version.py similarity index 100% rename from tests/test_version.py rename to tests/utils/test_version.py diff --git a/tests/test_version_after.py b/tests/utils/test_version_after.py similarity index 100% rename from tests/test_version_after.py rename to tests/utils/test_version_after.py diff --git a/tests/utils/type_conversion/__init__.py b/tests/utils/type_conversion/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/utils/type_conversion/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_convert_data_type.py b/tests/utils/type_conversion/test_convert_data_type.py similarity index 98% rename from tests/test_convert_data_type.py rename to tests/utils/type_conversion/test_convert_data_type.py index a27a05cf28..4c1905b188 100644 --- a/tests/test_convert_data_type.py +++ b/tests/utils/type_conversion/test_convert_data_type.py @@ -19,7 +19,7 @@ from monai.data import MetaTensor from monai.utils.type_conversion import convert_data_type, convert_to_dst_type, get_equivalent_dtype -from tests.utils import TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import TEST_NDARRAYS_ALL, assert_allclose TESTS: list[tuple] = [] for in_type in TEST_NDARRAYS_ALL + (int, float): @@ -78,7 +78,6 @@ class TestTensor(torch.Tensor): class TestConvertDataType(unittest.TestCase): - @parameterized.expand(TESTS) def test_convert_data_type(self, in_image, im_out, out_dtype, safe): converted_im, orig_type, orig_device = convert_data_type(in_image, type(im_out), dtype=out_dtype, safe=safe) diff --git a/tests/test_get_equivalent_dtype.py b/tests/utils/type_conversion/test_get_equivalent_dtype.py similarity index 98% rename from tests/test_get_equivalent_dtype.py rename to tests/utils/type_conversion/test_get_equivalent_dtype.py index 2b4de1bc2a..7e733d9ef6 100644 --- a/tests/test_get_equivalent_dtype.py +++ b/tests/utils/type_conversion/test_get_equivalent_dtype.py @@ -18,7 +18,7 @@ from parameterized import parameterized from monai.utils.type_conversion import get_equivalent_dtype, get_numpy_dtype_from_string, get_torch_dtype_from_string -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS DTYPES = [torch.float32, np.float32, np.dtype(np.float32)] @@ -29,7 +29,6 @@ class TestGetEquivalentDtype(unittest.TestCase): - @parameterized.expand(TESTS) def test_get_equivalent_dtype(self, im, input_dtype): out_dtype = get_equivalent_dtype(input_dtype, type(im)) diff --git a/tests/test_safe_dtype_range.py b/tests/utils/type_conversion/test_safe_dtype_range.py similarity index 98% rename from tests/test_safe_dtype_range.py rename to tests/utils/type_conversion/test_safe_dtype_range.py index 61b55635ae..a096233886 100644 --- a/tests/test_safe_dtype_range.py +++ b/tests/utils/type_conversion/test_safe_dtype_range.py @@ -19,7 +19,7 @@ from monai.utils import optional_import from monai.utils.type_conversion import get_equivalent_dtype, safe_dtype_range -from tests.utils import HAS_CUPY, TEST_NDARRAYS_ALL, assert_allclose +from tests.test_utils import HAS_CUPY, TEST_NDARRAYS_ALL, assert_allclose cp, _ = optional_import("cupy") @@ -54,7 +54,6 @@ class TesSafeDtypeRange(unittest.TestCase): - @parameterized.expand(TESTS) def test_safe_dtype_range(self, in_image, im_out, out_dtype): result = safe_dtype_range(in_image, out_dtype) diff --git a/tests/visualize/__init__.py b/tests/visualize/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/visualize/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_img2tensorboard.py b/tests/visualize/test_img2tensorboard.py similarity index 100% rename from tests/test_img2tensorboard.py rename to tests/visualize/test_img2tensorboard.py diff --git a/tests/test_occlusion_sensitivity.py b/tests/visualize/test_occlusion_sensitivity.py similarity index 100% rename from tests/test_occlusion_sensitivity.py rename to tests/visualize/test_occlusion_sensitivity.py diff --git a/tests/test_plot_2d_or_3d_image.py b/tests/visualize/test_plot_2d_or_3d_image.py similarity index 97% rename from tests/test_plot_2d_or_3d_image.py rename to tests/visualize/test_plot_2d_or_3d_image.py index 16241853b3..b9ced3953c 100644 --- a/tests/test_plot_2d_or_3d_image.py +++ b/tests/visualize/test_plot_2d_or_3d_image.py @@ -20,7 +20,7 @@ from monai.utils import optional_import from monai.visualize import plot_2d_or_3d_image -from tests.utils import SkipIfBeforePyTorchVersion, SkipIfNoModule +from tests.test_utils import SkipIfBeforePyTorchVersion, SkipIfNoModule SummaryWriter, has_tb = optional_import("torch.utils.tensorboard", name="SummaryWriter") @@ -40,7 +40,6 @@ @unittest.skipUnless(has_tb, "Requires SummaryWriter installation") @SkipIfBeforePyTorchVersion((1, 13)) # issue 6683 class TestPlot2dOr3dImage(unittest.TestCase): - @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5]) def test_tb_image(self, shape): with tempfile.TemporaryDirectory() as tempdir: diff --git a/tests/test_vis_cam.py b/tests/visualize/test_vis_cam.py similarity index 100% rename from tests/test_vis_cam.py rename to tests/visualize/test_vis_cam.py diff --git a/tests/test_vis_gradcam.py b/tests/visualize/test_vis_gradcam.py similarity index 99% rename from tests/test_vis_gradcam.py rename to tests/visualize/test_vis_gradcam.py index f77d916a5b..274510ba30 100644 --- a/tests/test_vis_gradcam.py +++ b/tests/visualize/test_vis_gradcam.py @@ -20,11 +20,10 @@ from monai.networks.nets import DenseNet, DenseNet121, SEResNet50 from monai.visualize import GradCAM, GradCAMpp -from tests.utils import assert_allclose, skip_if_quick +from tests.test_utils import assert_allclose, skip_if_quick class DenseNetAdjoint(DenseNet121): - def __call__(self, x, adjoint_info): if adjoint_info != 42: raise ValueError @@ -150,7 +149,6 @@ def __call__(self, x, adjoint_info): @skip_if_quick class TestGradientClassActivationMap(unittest.TestCase): - @parameterized.expand(TESTS) def test_shape(self, cam_class, input_data, expected_shape): model = None diff --git a/tests/visualize/utils/__init__.py b/tests/visualize/utils/__init__.py new file mode 100644 index 0000000000..1e97f89407 --- /dev/null +++ b/tests/visualize/utils/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/test_blend_images.py b/tests/visualize/utils/test_blend_images.py similarity index 98% rename from tests/test_blend_images.py rename to tests/visualize/utils/test_blend_images.py index 700ae1fe58..4ec9635e9b 100644 --- a/tests/test_blend_images.py +++ b/tests/visualize/utils/test_blend_images.py @@ -22,7 +22,7 @@ from monai.transforms.utils_pytorch_numpy_unification import moveaxis from monai.utils.module import optional_import from monai.visualize.utils import blend_images -from tests.utils import TEST_NDARRAYS +from tests.test_utils import TEST_NDARRAYS plt, has_matplotlib = optional_import("matplotlib.pyplot") @@ -44,7 +44,6 @@ def get_alpha(img): @skipUnless(has_matplotlib, "Matplotlib required") class TestBlendImages(unittest.TestCase): - @parameterized.expand(TESTS) def test_blend(self, image, label, alpha): blended = blend_images(image, label, alpha) diff --git a/tests/test_matshow3d.py b/tests/visualize/utils/test_matshow3d.py similarity index 91% rename from tests/test_matshow3d.py rename to tests/visualize/utils/test_matshow3d.py index 2eba310f4e..f10f1ea79d 100644 --- a/tests/test_matshow3d.py +++ b/tests/visualize/utils/test_matshow3d.py @@ -14,6 +14,7 @@ import os import tempfile import unittest +from pathlib import Path import numpy as np @@ -27,7 +28,7 @@ ) from monai.utils import optional_import from monai.visualize.utils import matshow3d -from tests.utils import SkipIfNoModule +from tests.test_utils import SkipIfNoModule compare_images, _ = optional_import("matplotlib.testing.compare", name="compare_images") pyplot, has_pyplot = optional_import("matplotlib", name="pyplot") @@ -35,9 +36,10 @@ @SkipIfNoModule("matplotlib") class TestMatshow3d(unittest.TestCase): - def test_3d(self): - testing_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "testing_data") + test_root = Path(__file__).parents[2] + testing_dir = os.path.join(test_root, "testing_data") + print("test_root: ", testing_dir) keys = "image" xforms = Compose( [ @@ -62,7 +64,8 @@ def test_3d(self): matshow3d(ims[keys], fig=axes, figsize=(2, 2), frames_per_row=5, every_n=2, frame_dim=-1, show=False) def test_samples(self): - testing_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "testing_data") + test_root = Path(__file__).parents[2] + testing_dir = os.path.join(test_root, "testing_data") keys = "image" xforms = Compose( [ @@ -91,7 +94,8 @@ def test_samples(self): self.assertIsNone(comp, f"value of comp={comp}") # None indicates test passed def test_3d_rgb(self): - testing_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "testing_data") + test_dir = Path(__file__).parents[2].as_posix() + testing_dir = os.path.join(test_dir, "testing_data") keys = "image" xforms = Compose( [