diff --git a/.gitignore b/.gitignore index 76c6ab0d12..c1c4568810 100644 --- a/.gitignore +++ b/.gitignore @@ -130,6 +130,7 @@ temp/ .DS_Store # temporary testing data MedNIST +tests/integration/testing_data/MedNIST* tests/testing_data/MedNIST* tests/testing_data/*Hippocampus* tests/testing_data/*.tiff diff --git a/runtests.sh b/runtests.sh index 65e3a2bb6b..5a84f94949 100755 --- a/runtests.sh +++ b/runtests.sh @@ -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/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/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/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/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/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..fe9afaa8d4 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.utils.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..a6ad00aabb 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.utils.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..21a8ba2675 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.utils.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/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..9b9c43033c 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.utils.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..88ae5c8205 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.utils.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..5173c9cf1e 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.utils.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 97% rename from tests/test_detector_boxselector.py rename to tests/apps/detection/utils/test_detector_boxselector.py index 326ecd5773..dd4002301b 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.utils.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..419598539d 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.utils.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..9466e28c56 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.utils.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/test_autoencoderkl_maisi.py b/tests/apps/generation/maisi/networks/test_autoencoderkl_maisi.py similarity index 99% rename from tests/test_autoencoderkl_maisi.py rename to tests/apps/generation/maisi/networks/test_autoencoderkl_maisi.py index 0e9f427fb6..9755f00726 100644 --- a/tests/test_autoencoderkl_maisi.py +++ b/tests/apps/generation/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.utils.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/generation/maisi/networks/test_controlnet_maisi.py similarity index 99% rename from tests/test_controlnet_maisi.py rename to tests/apps/generation/maisi/networks/test_controlnet_maisi.py index bfdf25ec6e..66004890ed 100644 --- a/tests/test_controlnet_maisi.py +++ b/tests/apps/generation/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.utils.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/generation/maisi/networks/test_diffusion_model_unet_maisi.py similarity index 100% rename from tests/test_diffusion_model_unet_maisi.py rename to tests/apps/generation/maisi/networks/test_diffusion_model_unet_maisi.py 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/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..8c075d06e5 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.utils.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..34e4a6b82c 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.utils.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/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..45baa51b64 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.utils.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..e33dd54c53 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.utils.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..8e61116e6b 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.utils.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..77e56f459d 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.utils.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..9d4a3b5f41 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.utils.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..d36bbd5b0f 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.utils.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..1bd3eac47b 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.utils.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..2729f246d6 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.utils.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..10eef42edb 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.utils.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..63288a9cf1 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.utils.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..552ccc9d62 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.utils.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..5103c622f2 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.utils.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..405f707431 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.utils.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..ca15c5cd5a 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.utils.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..298b98e10b 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.utils.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..44bdec463d 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.utils.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..7b37352222 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.utils.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..c89ce4910f 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.utils.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..791e4b714d 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.utils.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/test_recon_net_utils.py b/tests/apps/reconstruction/networks/nets/test_recon_net_utils.py similarity index 95% rename from tests/test_recon_net_utils.py rename to tests/apps/reconstruction/networks/nets/test_recon_net_utils.py index 48d3b59a17..a39fb5b0c7 100644 --- a/tests/test_recon_net_utils.py +++ b/tests/apps/reconstruction/networks/nets/test_recon_net_utils.py @@ -27,7 +27,7 @@ sensitivity_map_expand, sensitivity_map_reduce, ) -from tests.utils import assert_allclose +from tests.utils.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..df437838fe 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.utils.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..fbdd8b92ad 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.utils.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..7fe579027c 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.utils.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/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..c5cc1bbbbc 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.utils.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..0845c7aef6 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.utils.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..b4d3c2bf62 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.utils.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..8d69cba4cb 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.utils.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..0ad3bc5320 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.utils.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 96% rename from tests/test_download_and_extract.py rename to tests/apps/test_download_and_extract.py index 555f7dc250..3ad7d1980a 100644 --- a/tests/test_download_and_extract.py +++ b/tests/apps/test_download_and_extract.py @@ -20,11 +20,10 @@ from parameterized import parameterized from monai.apps import download_and_extract, download_url, extractall -from tests.utils import skip_if_downloading_fails, skip_if_quick, testing_data_config +from tests.utils.utils import skip_if_downloading_fails, skip_if_quick, testing_data_config 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") 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 97% rename from tests/test_mednistdataset.py rename to tests/apps/test_mednistdataset.py index c1b21e9373..8c244ea095 100644 --- a/tests/test_mednistdataset.py +++ b/tests/apps/test_mednistdataset.py @@ -19,13 +19,12 @@ 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.utils.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") 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..01ad456457 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.utils.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 98% rename from tests/test_tciadataset.py rename to tests/apps/test_tciadataset.py index 5a16bb4816..2d5ef26d22 100644 --- a/tests/test_tciadataset.py +++ b/tests/apps/test_tciadataset.py @@ -19,11 +19,10 @@ 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.utils.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") 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..f82708185a 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.utils.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/test_bundle_ckpt_export.py b/tests/bundle/test_bundle_ckpt_export.py new file mode 100644 index 0000000000..9a784abb97 --- /dev/null +++ b/tests/bundle/test_bundle_ckpt_export.py @@ -0,0 +1,102 @@ +# 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. + +from __future__ import annotations + +import json +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.utils import command_line_tests, skip_if_windows + +TEST_CASE_1 = ["", ""] +TEST_CASE_2 = ["model", ""] +TEST_CASE_3 = ["model", "True"] + + +@skip_if_windows +class TestCKPTExport(unittest.TestCase): + def setUp(self): + self.device = os.environ.get("CUDA_VISIBLE_DEVICES") + if not self.device: + os.environ["CUDA_VISIBLE_DEVICES"] = "0" # default + module_path = Path(__file__).resolve().parents[1].as_posix() + self.meta_file = os.path.join(module_path, "testing_data", "metadata.json") + self.config_file = os.path.join(module_path, "testing_data", "inference.json") + self.tempdir_obj = tempfile.TemporaryDirectory() + tempdir = self.tempdir_obj.name + self.def_args = {"meta_file": "will be replaced by `meta_file` arg"} + self.def_args_file = os.path.join(tempdir, "def_args.yaml") + + self.ckpt_file = os.path.join(tempdir, "model.pt") + self.ts_file = os.path.join(tempdir, "model.ts") + + self.parser = ConfigParser() + self.parser.export_config_file(config=self.def_args, filepath=self.def_args_file) + self.parser.read_config(self.config_file) + self.net = self.parser.get_parsed_content("network_def") + self.cmd = ["coverage", "run", "-m", "monai.bundle", "ckpt_export", "network_def", "--filepath", self.ts_file] + self.cmd += [ + "--meta_file", + self.meta_file, + "--config_file", + f"['{self.config_file}','{self.def_args_file}']", + "--ckpt_file", + ] + + def tearDown(self): + if self.device is not None: + os.environ["CUDA_VISIBLE_DEVICES"] = self.device + else: + del os.environ["CUDA_VISIBLE_DEVICES"] # previously unset + self.tempdir_obj.cleanup() + + @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3]) + def test_export(self, key_in_ckpt, use_trace): + save_state(src=self.net if key_in_ckpt == "" else {key_in_ckpt: self.net}, path=self.ckpt_file) + full_cmd = self.cmd + [self.ckpt_file, "--key_in_ckpt", key_in_ckpt, "--args_file", self.def_args_file] + if use_trace == "True": + full_cmd += ["--use_trace", use_trace, "--input_shape", "[1, 1, 96, 96, 96]"] + command_line_tests(full_cmd) + self.assertTrue(os.path.exists(self.ts_file)) + + _, metadata, extra_files = load_net_with_metadata( + self.ts_file, more_extra_files=["inference.json", "def_args.json"] + ) + self.assertIn("schema", metadata) + self.assertIn("meta_file", json.loads(extra_files["def_args.json"])) + self.assertIn("network_def", json.loads(extra_files["inference.json"])) + + @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3]) + def test_default_value(self, key_in_ckpt, use_trace): + ckpt_file = os.path.join(self.tempdir_obj.name, "models/model.pt") + ts_file = os.path.join(self.tempdir_obj.name, "models/model.ts") + + save_state(src=self.net if key_in_ckpt == "" else {key_in_ckpt: self.net}, path=ckpt_file) + + # check with default value + cmd = ["coverage", "run", "-m", "monai.bundle", "ckpt_export", "--key_in_ckpt", key_in_ckpt] + cmd += ["--config_file", self.config_file, "--bundle_root", self.tempdir_obj.name] + if use_trace == "True": + cmd += ["--use_trace", use_trace, "--input_shape", "[1, 1, 96, 96, 96]"] + command_line_tests(cmd) + self.assertTrue(os.path.exists(ts_file)) + + +if __name__ == "__main__": + unittest.main() 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..c6296bb5ed 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.utils.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..1c22a472aa 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.utils.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..3a6dff57df 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.utils.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..10e49ccf01 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.utils.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..6fb049c987 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.utils.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..d5319c5b1e 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.utils.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..595cb6892a 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.utils.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..5f62e59adb 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.utils.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/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..355ff683ff 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.utils.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..c9e937c104 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.utils.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..e5d937b251 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.utils.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..5714fa6a08 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.utils.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..2928d6d9f8 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.utils.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..8fe808d4f1 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.utils.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..43903b5583 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.utils.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..591723f502 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.utils.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..0b69449490 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.utils.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..9568f571ad 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.utils.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_init_reader.py b/tests/data/test_init_reader.py similarity index 97% rename from tests/test_init_reader.py rename to tests/data/test_init_reader.py index cb45cb5146..2b1e1cde1c 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.utils.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 99% rename from tests/test_itk_torch_bridge.py rename to tests/data/test_itk_torch_bridge.py index 22ae019271..baeddcc194 100644 --- a/tests/test_itk_torch_bridge.py +++ b/tests/data/test_itk_torch_bridge.py @@ -35,7 +35,7 @@ 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.utils.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,7 +49,6 @@ @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") @@ -494,7 +493,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..32601613a8 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.utils.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..c963b1dda2 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.utils.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..c7442cd696 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.utils.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..53981aa7d3 100644 --- a/tests/test_masked_patch_wsi_dataset.py +++ b/tests/data/test_masked_patch_wsi_dataset.py @@ -21,7 +21,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.utils.utils import download_url_or_skip_test, testing_data_config set_determinism(0) @@ -34,7 +34,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 = os.path.dirname(os.path.realpath(__file__)) +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 +75,6 @@ def setUpModule(): class MaskedPatchWSIDatasetTests: - class Tests(unittest.TestCase): backend = None @@ -101,7 +101,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 +108,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..10e196f3a6 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.utils.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..51f1f1287a 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.utils.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..3ed8007c8b 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.utils.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..2a1288db64 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.utils.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 97% rename from tests/test_sampler_dist.py rename to tests/data/test_sampler_dist.py index b8bd1c7a9f..130cfc1b8e 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.utils.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..1fd0c11db1 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.utils.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..fa1ec720c7 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.utils.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..a490b28b3e 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.utils.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..ad1e2b016e 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.utils.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..748dcb4eda 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.utils.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..f4493dd2c2 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.utils.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..55dfdd2591 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.utils.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..1bb09fb942 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.utils.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..2ef9fd9db0 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.utils.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/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..6459612a07 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.utils.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..f2efd10b6d 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.utils.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..81c00732a5 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.utils.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..8061509c2a 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.utils.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/test_fl_monai_algo.py b/tests/fl/client/monai_algo/test_fl_monai_algo.py similarity index 98% rename from tests/test_fl_monai_algo.py rename to tests/fl/client/monai_algo/test_fl_monai_algo.py index c8cb3451fc..af9e05a93d 100644 --- a/tests/test_fl_monai_algo.py +++ b/tests/fl/client/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.utils.utils import SkipIfNoModule -_root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__))) +_root_dir = Path(__file__).resolve().parents[3] _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/client/monai_algo/test_fl_monai_algo_dist.py similarity index 93% rename from tests/test_fl_monai_algo_dist.py rename to tests/fl/client/monai_algo/test_fl_monai_algo_dist.py index d8dbfa5339..a57b6e9f18 100644 --- a/tests/test_fl_monai_algo_dist.py +++ b/tests/fl/client/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.utils.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[3].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..2f3b8efb41 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.utils.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/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..0fddf6c917 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.utils.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/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..a0c65e5380 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.utils.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..df715e4199 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.utils.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..a1c39d6ff4 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.utils.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..d9dd93d2c1 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.utils.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..a57d8d4e68 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.utils.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..afe8156d55 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.utils.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..3867363090 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.utils.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..a2c69ba988 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.utils.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..8883b4af4f 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.utils.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..2c77941063 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.utils.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..625bb105a4 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.utils.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..c922faaf8c 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.utils.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..e4fe9fe509 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.utils.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..c1e0f8f23a 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.utils.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..e1be85ba95 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.utils.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..04128f81b1 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.utils.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..7d02bb4b7f 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.utils.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..02230e3082 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.utils.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..324efd0645 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.utils.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..0e63008bb9 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.utils.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..66552fb667 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.utils.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..8129906702 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.utils.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/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..bd6bda0966 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.utils.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..01a676171f 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.utils.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..941eb94ca3 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.utils.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..3b0285d6ad 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.utils.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..b707ae3cab 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.utils.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 de7fad48da..afac260592 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 optional_import -from tests.utils import assert_allclose +from tests.utils.utils import assert_allclose np.seterr(divide="ignore", invalid="ignore") zarr, has_zarr = optional_import("zarr") @@ -256,7 +256,6 @@ @unittest.skipUnless(has_zarr and has_numcodecs, "Requires zarr (and numcodecs) packages.)") class ZarrAvgMergerTests(unittest.TestCase): - @parameterized.expand( [ TEST_CASE_0_DEFAULT_DTYPE, 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..c424d1a849 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.utils.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..1b5953d932 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.utils.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..00ecd7d41c 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.utils.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_image_rw.py b/tests/integration/test_image_rw.py similarity index 99% rename from tests/test_image_rw.py rename to tests/integration/test_image_rw.py index 7e1c1deecc..cfa0cadf09 100644 --- a/tests/test_image_rw.py +++ b/tests/integration/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.utils.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_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..29c1e1429d 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.utils.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 96% rename from tests/test_integration_bundle_run.py rename to tests/integration/test_integration_bundle_run.py index 60aaef05bf..8d3733f4d0 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.utils.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() @@ -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..141e2e562d 100644 --- a/tests/test_integration_classification_2d.py +++ b/tests/integration/test_integration_classification_2d.py @@ -39,13 +39,12 @@ ) from monai.utils import set_determinism 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 +from tests.utils.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") @@ -214,7 +212,7 @@ def setUp(self): image_classes.extend([i] * len(image_files[i])) # split train, val, test - valid_frac, test_frac = 0.1, 0.1 + valid_frac, test_frac = 0.01, 0.01 self.train_x, self.train_y = [], [] self.val_x, self.val_y = [], [] self.test_x, self.test_y = [], [] @@ -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..02047a2179 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.utils.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..a03617e235 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.utils.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..1d572ef756 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.utils.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..33ba8744da 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.utils.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..23b6f740f6 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.utils.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..dcabc1b163 100644 --- a/tests/test_integration_segmentation_3d.py +++ b/tests/integration/test_integration_segmentation_3d.py @@ -42,7 +42,7 @@ from monai.utils import optional_import, set_determinism from monai.visualize import plot_2d_or_3d_image from tests.testing_data.integration_answers import test_integration_value -from tests.utils import DistTestCase, TimedCall, skip_if_quick +from tests.utils.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..7b94ec68a4 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.utils.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..af5708a614 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.utils.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..a92f341933 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.utils.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..c3351bb345 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.utils.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..e514ba20b9 100644 --- a/tests/test_integration_workflows.py +++ b/tests/integration/test_integration_workflows.py @@ -54,7 +54,7 @@ ) from monai.utils import optional_import, set_determinism from tests.testing_data.integration_answers import test_integration_value -from tests.utils import DistTestCase, TimedCall, assert_allclose, pytorch_after, skip_if_quick +from tests.utils.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..c71778ad43 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.utils.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..3e2dcd71a3 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.utils.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..32ae5b8fba 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.utils.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..8f07fa12b2 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.utils.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..0fc0f9d89c 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.utils.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..a3d85de7c1 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.utils.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..5e9ebefb39 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.utils.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..b2c67b8963 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.utils.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..f0a680510a 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.utils.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/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/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..77a43a5ee5 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.utils.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[1] +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..553aecd9dd 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.utils.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..fc1a177838 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.utils.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..50995f2520 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.utils.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..db404f4edc 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.utils.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..5cf78c2af9 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.utils.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..6b5d31acd3 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.utils.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..6627ea086f 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.utils.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..a20df309cd 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.utils.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..e1fed59673 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.utils.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..a7f7de5f82 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.utils.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..971f102d79 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.utils.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..4db2c9da07 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.utils.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/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..0300b4a6e5 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.utils.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..249dec2a84 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.utils.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..3b6e27f823 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.utils.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..20a8eca718 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.utils.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..8cbbb4e28b 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.utils.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..15e40c4e35 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.utils.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/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..2a2e0cb477 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.utils.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..336dcdd19f 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.utils.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..a95272a68a 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.utils.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..020d5c921b 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.utils.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..46c3696955 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.utils.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..e2f4b0d859 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.utils.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..4be046ab44 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.utils.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..77b13cae9a 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.utils.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..31d550ac9e 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.utils.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..f172399abd 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.utils.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..80578d2215 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.utils.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..13f12fb2bb 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.utils.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..274b2d654b 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.utils.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..e11276e22a 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.utils.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..a227ba9f4b 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.utils.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/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..c299d729cb 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.utils.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[1] +FILE_PATH = os.path.join(TESTS_PATH, "testing_data", "temp_" + "mri.nii") def load_img_and_sample_ddf(): 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..5f80a6f7b2 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.utils.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..9645ca63db 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.utils.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..04e38895c1 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.utils.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..8dd627f122 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.utils.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..840736abbf 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.utils.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..ffcc48162f 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.utils.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..3122b2cd33 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.utils.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..6e84245b62 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.utils.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..35515c0323 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.utils.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..8ec8fbdc87 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.utils.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..751074395c 100644 --- a/tests/test_grid_pull.py +++ b/tests/networks/layers/test_grid_pull.py @@ -21,7 +21,7 @@ from monai.networks.utils import meshgrid_ij from monai.utils import optional_import 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 +from tests.utils.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..64ed4bd3fa 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.utils.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..ec89582d7f 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.utils.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..f1b90f461e 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.utils.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/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..8826c55b79 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.utils.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/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..3663814b01 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.utils.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..efd58a7e79 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.utils.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..01b228cfd3 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.utils.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..09e8092f73 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.utils.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..b29fa8cab7 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.utils.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..5b117408de 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.utils.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..f0cf40d1a3 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.utils.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..650cbed00c 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.utils.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..dda8b31fbc 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.utils.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..16c51774d6 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.utils.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 97% rename from tests/test_daf3d.py rename to tests/networks/nets/test_daf3d.py index d20cb3cfd1..e7d73b6889 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.utils.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 97% rename from tests/test_densenet.py rename to tests/networks/nets/test_densenet.py index ee4be9003b..a4ccc22f16 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.utils.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..c795c71c2f 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.utils.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..89d473dd1c 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.utils.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..552829ace1 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.utils.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..1e9d5bb1e7 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.utils.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..de09fd6904 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.utils.utils import skip_if_downloading_fails, skip_if_quick, test_pretrained_networks, test_script_save + +TESTS_PATH = Path(__file__).parents[1] 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..41a23d997e 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.utils.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..96078ebef4 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.utils.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..f72119b37d 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.utils.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..44accb25bd 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.utils.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..19fb424840 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.utils.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..20c435f8bd 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.utils.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..32f92ca98c 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.utils.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..b2983d2fdd 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.utils.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..196a5edd80 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.utils.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..a75f733fd0 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.utils.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..21d512f32f 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.utils.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..e78a8a3ba5 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.utils.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..ebd270aa5b 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.utils.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 98% rename from tests/test_senet.py rename to tests/networks/nets/test_senet.py index 6809d4562b..4dcdc237cc 100644 --- a/tests/test_senet.py +++ b/tests/networks/nets/test_senet.py @@ -23,7 +23,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.utils.utils import test_is_quick, test_pretrained_networks, test_script_save, testing_data_config if TYPE_CHECKING: import pretrainedmodels @@ -58,7 +58,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 +75,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() 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..b752f31eee 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.utils.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..9f59b1be2f 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.utils.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..989cfc3529 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.utils.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..1b696a71c1 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.utils.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..316937e1ff 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.utils.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..f8cb55df06 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.utils.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..50337e27c5 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.utils.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..b52810540a 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.utils.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..31d2a65769 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.utils.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..0f545141d0 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.utils.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..58aee99359 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.utils.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..0353358c0c 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.utils.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..c733879467 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.utils.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/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..4cd672afbc 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.utils.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 98% rename from tests/test_scheduler_ddpm.py rename to tests/networks/schedulers/test_scheduler_ddpm.py index f0447aded2..42232e7fb4 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.utils.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..a23f2c0709 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.utils.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..855685c335 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.utils.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..7ff2c7abbc 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.utils.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..55e12ea69c 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.utils.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..fd7fe584f8 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.utils.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/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..986ee272db 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.utils.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..d99a5ca85b 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.utils.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/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..79329095ad 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.utils.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 83% rename from tests/test_lr_finder.py rename to tests/optimizers/test_lr_finder.py index d26cb23a90..3672d0f5f3 100644 --- a/tests/test_lr_finder.py +++ b/tests/optimizers/test_lr_finder.py @@ -11,7 +11,7 @@ from __future__ import annotations -import os +from pathlib import Path import pickle import random import sys @@ -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.utils.utils import skip_if_downloading_fails if TYPE_CHECKING: import matplotlib.pyplot as plt @@ -48,20 +48,17 @@ @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.transforms = Compose( - [ - LoadImaged(keys="image"), - EnsureChannelFirstd(keys="image", channel_dim="no_channel"), - ScaleIntensityd(keys="image"), - ToTensord(keys="image"), - ] - ) + self.root_dir = Path(__file__).parents[1] / "testing_data" + + self.transforms = Compose([ + LoadImaged(keys="image"), + EnsureChannelFirstd(keys="image", channel_dim="no_channel"), + ScaleIntensityd(keys="image"), + ToTensord(keys="image"), + ]) def test_lr_finder(self): # 0.001 gives 54 examples @@ -77,9 +74,7 @@ def test_lr_finder(self): train_loader = DataLoader(train_ds, batch_size=300, shuffle=True, num_workers=2) num_classes = train_ds.get_num_classes() - model = DenseNet( - spatial_dims=2, in_channels=1, out_channels=num_classes, init_features=2, growth_rate=2, block_config=(2,) - ) + model = DenseNet(spatial_dims=2, in_channels=1, out_channels=num_classes, init_features=2, growth_rate=2, block_config=(2,)) loss_function = torch.nn.CrossEntropyLoss() learning_rate = 1e-5 optimizer = torch.optim.Adam(model.parameters(), learning_rate) 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..fdfd502688 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.utils.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/test_auto3dseg.py b/tests/test_auto3dseg.py index 5273f0663a..04e75b3fe0 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.utils.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_bundle_ckpt_export.py b/tests/test_bundle_ckpt_export.py deleted file mode 100644 index cfcadcfc4c..0000000000 --- a/tests/test_bundle_ckpt_export.py +++ /dev/null @@ -1,104 +0,0 @@ -# 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. - -from __future__ import annotations - -import json -import os -import tempfile -import unittest - -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 - -TEST_CASE_1 = ["", ""] - -TEST_CASE_2 = ["model", ""] - -TEST_CASE_3 = ["model", "True"] - - -@skip_if_windows -class TestCKPTExport(unittest.TestCase): - - def setUp(self): - self.device = os.environ.get("CUDA_VISIBLE_DEVICES") - if not self.device: - os.environ["CUDA_VISIBLE_DEVICES"] = "0" # default - - def tearDown(self): - if self.device is not None: - os.environ["CUDA_VISIBLE_DEVICES"] = self.device - else: - del os.environ["CUDA_VISIBLE_DEVICES"] # previously unset - - @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") - 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") - - ckpt_file = os.path.join(tempdir, "model.pt") - ts_file = os.path.join(tempdir, "model.ts") - - parser = ConfigParser() - parser.export_config_file(config=def_args, filepath=def_args_file) - parser.read_config(config_file) - net = parser.get_parsed_content("network_def") - save_state(src=net if key_in_ckpt == "" else {key_in_ckpt: net}, path=ckpt_file) - - cmd = ["coverage", "run", "-m", "monai.bundle", "ckpt_export", "network_def", "--filepath", ts_file] - cmd += ["--meta_file", meta_file, "--config_file", f"['{config_file}','{def_args_file}']", "--ckpt_file"] - cmd += [ckpt_file, "--key_in_ckpt", key_in_ckpt, "--args_file", def_args_file] - if use_trace == "True": - cmd += ["--use_trace", use_trace, "--input_shape", "[1, 1, 96, 96, 96]"] - command_line_tests(cmd) - self.assertTrue(os.path.exists(ts_file)) - - _, metadata, extra_files = load_net_with_metadata( - ts_file, more_extra_files=["inference.json", "def_args.json"] - ) - self.assertIn("schema", metadata) - self.assertIn("meta_file", json.loads(extra_files["def_args.json"])) - self.assertIn("network_def", json.loads(extra_files["inference.json"])) - - @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") - 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") - ckpt_file = os.path.join(tempdir, "models/model.pt") - ts_file = os.path.join(tempdir, "models/model.ts") - - parser = ConfigParser() - parser.export_config_file(config=def_args, filepath=def_args_file) - parser.read_config(config_file) - net = parser.get_parsed_content("network_def") - save_state(src=net if key_in_ckpt == "" else {key_in_ckpt: net}, path=ckpt_file) - - # check with default value - cmd = ["coverage", "run", "-m", "monai.bundle", "ckpt_export", "--key_in_ckpt", key_in_ckpt] - cmd += ["--config_file", config_file, "--bundle_root", tempdir] - if use_trace == "True": - cmd += ["--use_trace", use_trace, "--input_shape", "[1, 1, 96, 96, 96]"] - command_line_tests(cmd) - self.assertTrue(os.path.exists(ts_file)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_call_dist.py b/tests/test_call_dist.py index 503cb5e792..add778bf8b 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.utils.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..3ad4188b8b 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.utils.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..d563327887 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.utils.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..545c613442 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.utils.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..0dfa1ec354 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.utils.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..12d7d2a330 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.utils.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..4cbc2c01ac 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.utils.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/testing_data/1D_BP_bwd.txt b/tests/testing_data/1D_BP_bwd.txt deleted file mode 100644 index de43270e94..0000000000 --- a/tests/testing_data/1D_BP_bwd.txt +++ /dev/null @@ -1,224 +0,0 @@ -0., 1., 1., 1., 1., 1., 1., 1., 1.,12., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., # InterpolationType.nearest BoundType.replicate -0., 1., 1., 1., 1., 1., 1., 1., 1.,12., # InterpolationType.nearest BoundType.replicate -0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0., # InterpolationType.nearest BoundType.replicate -0., # InterpolationType.nearest BoundType.replicate -0.5, 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. ,11.5, 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , # InterpolationType.linear BoundType.replicate -0.5, 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. ,11.5, # InterpolationType.linear BoundType.replicate -1.,1.,1.,1.,1.,1.,1.,1.,1.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0., # InterpolationType.linear BoundType.replicate -0., # InterpolationType.linear BoundType.replicate -0.5, 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. ,11.5, 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , # InterpolationType.quadratic BoundType.replicate -0.5, 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. ,11.5, # InterpolationType.quadratic BoundType.replicate -1.,1.,1.,1.,1.,1.,1.,1.,1.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0., # InterpolationType.quadratic BoundType.replicate -0., # InterpolationType.quadratic BoundType.replicate -0.5208333 , 0.9791666 , 0.99999994, 0.99999994, 0.99999994, 0.99999994, 0.99999994, 0.99999994, 0.99999994,11.5 , 0.875 , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 0.875 , 0.125 , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , # InterpolationType.cubic BoundType.replicate -0.5208333 , 0.9791666 , 0.99999994, 0.99999994, 0.99999994, 0.99999994, 0.99999994, 0.99999994, 0.99999994,11.5 , # InterpolationType.cubic BoundType.replicate -0.875,1. ,1. ,1. ,1. ,1. ,1. ,1. ,0.875,0.125,0. ,0. ,0. ,0. ,0. ,0. ,0. ,0. ,0. ,0. , # InterpolationType.cubic BoundType.replicate -0., # InterpolationType.cubic BoundType.replicate -0.5416667 , 0.9583334 , 1. , 1. , 1. , 1. , 1. , 1. , 1. ,11.5 , 0.8333334 , 1. , 1. , 1. , 1. , 1. , 0.9999999 , 1. , 0.833333 , 0.16666651, 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , # InterpolationType.fourth BoundType.replicate -0.5416667, 0.9583334, 1. , 1. , 1. , 1. , 1. , 1. , 1. ,11.5 , # InterpolationType.fourth BoundType.replicate -0.8333334 ,1. ,1. ,1. ,1. ,1. ,0.9999999 ,1. ,0.833333 ,0.16666651,0. ,0. ,0. ,0. ,0. ,0. ,0. ,0. ,0. ,0. , # InterpolationType.fourth BoundType.replicate -0., # InterpolationType.fourth BoundType.replicate -5.6223959e-01,9.3802083e-01,9.9973959e-01,1.0000000e+00,1.0000000e+00,1.0000000e+00,1.0000000e+00,1.0000000e+00,1.0000000e+00,1.1499999e+01,7.9947913e-01,9.9739581e-01,1.0000000e+00,1.0000000e+00,9.9999994e-01,1.0000001e+00,9.9999976e-01,9.9739575e-01,7.9947948e-01,2.0052099e-01,2.6040077e-03,0.,0.,0.,0.,0.,0.,0.,0.,0., # InterpolationType.fifth BoundType.replicate -0.5622396, 0.9380208, 0.9997396, 1. , 1. , 1. , 1. , 1. , 1. ,11.499999 , # InterpolationType.fifth BoundType.replicate -0.7994791 ,0.9973958 ,1. ,1. ,0.99999994,1.0000001 ,0.99999976,0.99739575,0.7994795 ,0.20052099,0.00260401,0. ,0. ,0. ,0. ,0. ,0. ,0. ,0. ,0. , # InterpolationType.fifth BoundType.replicate -0., # InterpolationType.fifth BoundType.replicate -5.8194447e-01,9.1944444e-01,9.9861109e-01,1.0000000e+00,1.0000000e+00,1.0000000e+00,1.0000000e+00,1.0000000e+00,1.0000000e+00,1.1499997e+01,7.7499998e-01,9.9166673e-01,1.0000000e+00,1.0000000e+00,1.0000000e+00,9.9999982e-01,1.0000004e+00,9.9166673e-01,7.7499980e-01,2.2500010e-01,8.3333999e-03,1.9371510e-07,1.9371510e-07,1.9371510e-07,1.9371510e-07,1.9371510e-07,1.9371510e-07,1.9371510e-07,1.9371510e-07,1.9371510e-07, # InterpolationType.sixth BoundType.replicate -0.58194447, 0.91944444, 0.9986111 , 1. , 1. , 1. , 1. , 1. , 1. ,11.499997 , # InterpolationType.sixth BoundType.replicate -7.7499998e-01,9.9166673e-01,1.0000000e+00,1.0000000e+00,1.0000000e+00,9.9999982e-01,1.0000004e+00,9.9166673e-01,7.7499980e-01,2.2500010e-01,8.3333999e-03,1.9371510e-07,1.9371510e-07,1.9371510e-07,1.9371510e-07,1.9371510e-07,1.9371510e-07,1.9371510e-07,1.9371510e-07,1.9371510e-07, # InterpolationType.sixth BoundType.replicate -0., # InterpolationType.sixth BoundType.replicate -6.0078436e-01,9.0259641e-01,9.9662077e-01,9.9999845e-01,1.0000000e+00,1.0000000e+00,1.0000000e+00,1.0000000e+00,1.0000000e+00,1.1500004e+01,7.5551212e-01,9.8430985e-01,9.9997836e-01,9.9999994e-01,1.0000000e+00,1.0000001e+00,9.9997842e-01,9.8431003e-01,7.5551212e-01,2.4448761e-01,1.5690181e-02,2.1788481e-05,3.3080869e-07,3.3080869e-07,3.3080869e-07,3.3080869e-07,3.3080869e-07,3.3080869e-07,3.3080869e-07,3.3080869e-07, # InterpolationType.seventh BoundType.replicate -0.60078436, 0.9025964 , 0.9966208 , 0.99999845, 1. , 1. , 1. , 1. , 1. ,11.500004 , # InterpolationType.seventh BoundType.replicate -7.5551212e-01,9.8430985e-01,9.9997836e-01,9.9999994e-01,1.0000000e+00,1.0000001e+00,9.9997842e-01,9.8431003e-01,7.5551212e-01,2.4448761e-01,1.5690181e-02,2.1788481e-05,3.3080869e-07,3.3080869e-07,3.3080869e-07,3.3080869e-07,3.3080869e-07,3.3080869e-07,3.3080869e-07,3.3080869e-07, # InterpolationType.seventh BoundType.replicate -0., # InterpolationType.seventh BoundType.replicate -1.,3.,3.,2.,2.,2.,2.,2.,2.,1.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0., # InterpolationType.nearest BoundType.dct1 -1.,3.,3.,2.,2.,2.,2.,2.,2.,1., # InterpolationType.nearest BoundType.dct1 -0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0., # InterpolationType.nearest BoundType.dct1 -0., # InterpolationType.nearest BoundType.dct1 -1.5, 3. , 2.5, 2. , 2. , 2. , 2. , 2. , 2. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. ,-1. ,-1. ,-1. ,-1. ,-1. ,-1. ,-1. ,-1. ,-1. , 1. , 1. , # InterpolationType.linear BoundType.dct1 -1.5,3. ,2.5,2. ,2. ,2. ,2. ,2. ,2. ,1. , # InterpolationType.linear BoundType.dct1 -1., 1., 1., 1., 1., 1., 1., 1., 1.,-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1., 1., 1., # InterpolationType.linear BoundType.dct1 -0., # InterpolationType.linear BoundType.dct1 -1.5, 3. , 2.5, 2. , 2. , 2. , 2. , 2. , 2. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. ,-1. ,-1. ,-1. ,-1. ,-1. ,-1. ,-1. ,-1. ,-1. , 1. , 1. , # InterpolationType.quadratic BoundType.dct1 -1.5,3. ,2.5,2. ,2. ,2. ,2. ,2. ,2. ,1. , # InterpolationType.quadratic BoundType.dct1 -1., 1., 1., 1., 1., 1., 1., 1., 1.,-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1., 1., 1., # InterpolationType.quadratic BoundType.dct1 -0., # InterpolationType.quadratic BoundType.dct1 -1.5 , 2.9791667 , 2.5 , 2.0208333 , 1.9999999 , 1.9999999 , 1.9999999 , 1.9999999 , 1.9999999 , 0.99999994, 0.75 , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 0.75 ,-0.75 ,-1. ,-1. ,-1. ,-1. ,-1. ,-1. ,-1. ,-0.75 , 0.75 , 1. , # InterpolationType.cubic BoundType.dct1 -1.5 ,2.9791667 ,2.5 ,2.0208333 ,1.9999999 ,1.9999999 ,1.9999999 ,1.9999999 ,1.9999999 ,0.99999994, # InterpolationType.cubic BoundType.dct1 -0.75, 1. , 1. , 1. , 1. , 1. , 1. , 1. , 0.75,-0.75,-1. ,-1. ,-1. ,-1. ,-1. ,-1. ,-1. ,-0.75, 0.75, 1. , # InterpolationType.cubic BoundType.dct1 -0., # InterpolationType.cubic BoundType.dct1 -1.5 , 2.9583333 , 2.5 , 2.0416667 , 2. , 2. , 2. , 2. , 2. , 1. , 0.6666666 , 1. , 1. , 1. , 1. , 1. , 0.9999999 , 1. , 0.6666664 ,-0.66666675,-1. ,-1.0000001 ,-1.0000002 ,-1. ,-1.0000001 ,-1.0000001 ,-1. ,-0.6666667 , 0.6666666 , 1. , # InterpolationType.fourth BoundType.dct1 -1.5 ,2.9583333,2.5 ,2.0416667,2. ,2. ,2. ,2. ,2. ,1. , # InterpolationType.fourth BoundType.dct1 -0.6666666 , 1. , 1. , 1. , 1. , 1. , 0.9999999 , 1. , 0.6666664 ,-0.66666675,-1. ,-1.0000001 ,-1.0000002 ,-1. ,-1.0000001 ,-1.0000001 ,-1. ,-0.6666667 , 0.6666666 , 1. , # InterpolationType.fourth BoundType.dct1 -0., # InterpolationType.fourth BoundType.dct1 -1.4997395 , 2.9380207 , 2.5 , 2.061979 , 2.0002604 , 2. , 2. , 2. , 2. , 1. , 0.5989583 , 0.9947917 , 1. , 1. , 0.99999994, 1.0000001 , 0.99999976, 0.99479157, 0.5989587 ,-0.59895825,-0.9947917 ,-0.9999998 ,-1.0000002 ,-1. ,-0.9999998 ,-1. ,-0.9947917 ,-0.5989583 , 0.5989583 , 0.9947917 , # InterpolationType.fifth BoundType.dct1 -1.4997395,2.9380207,2.5 ,2.061979 ,2.0002604,2. ,2. ,2. ,2. ,1. , # InterpolationType.fifth BoundType.dct1 -0.5989583 , 0.9947917 , 1. , 1. , 0.99999994, 1.0000001 , 0.99999976, 0.99479157, 0.5989587 ,-0.59895825,-0.9947917 ,-0.9999998 ,-1.0000002 ,-1. ,-0.9999998 ,-1. ,-0.9947917 ,-0.5989583 , 0.5989583 , 0.9947917 , # InterpolationType.fifth BoundType.dct1 -0., # InterpolationType.fifth BoundType.dct1 -1.498611 , 2.919444 , 2.5 , 2.0805554 , 2.0013888 , 2. , 2. , 2. , 2. , 1. , 0.54999995, 0.9833334 , 1. , 1. , 1. , 0.9999998 , 1.0000004 , 0.9833334 , 0.5499998 ,-0.5499999 ,-0.9833334 ,-1.0000004 ,-1.0000001 ,-1.0000001 ,-1. ,-0.99999994,-0.98333335,-0.55 , 0.54999995, 0.9833334 , # InterpolationType.sixth BoundType.dct1 -1.498611 ,2.919444 ,2.5 ,2.0805554,2.0013888,2. ,2. ,2. ,2. ,1. , # InterpolationType.sixth BoundType.dct1 -0.54999995, 0.9833334 , 1. , 1. , 1. , 0.9999998 , 1.0000004 , 0.9833334 , 0.5499998 ,-0.5499999 ,-0.9833334 ,-1.0000004 ,-1.0000001 ,-1.0000001 ,-1. ,-0.99999994,-0.98333335,-0.55 , 0.54999995, 0.9833334 , # InterpolationType.sixth BoundType.dct1 -0., # InterpolationType.sixth BoundType.dct1 -1.4966209 , 2.9025953 , 2.5000002 , 2.097404 , 2.0033796 , 2.000002 , 2.0000002 , 2.0000002 , 2.0000002 , 1. , 0.5110243 , 0.9686197 , 0.99995667, 0.99999994, 1. , 1.0000001 , 0.9999567 , 0.96861994, 0.51102436,-0.5110245 ,-0.9686197 ,-0.99995685,-1. ,-1. ,-1.0000001 ,-0.99995655,-0.9686198 ,-0.5110243 , 0.5110243 , 0.9686197 , # InterpolationType.seventh BoundType.dct1 -1.4966209,2.9025953,2.5000002,2.097404 ,2.0033796,2.000002 ,2.0000002,2.0000002,2.0000002,1. , # InterpolationType.seventh BoundType.dct1 -0.5110243 , 0.9686197 , 0.99995667, 0.99999994, 1. , 1.0000001 , 0.9999567 , 0.96861994, 0.51102436,-0.5110245 ,-0.9686197 ,-0.99995685,-1. ,-1. ,-1.0000001 ,-0.99995655,-0.9686198 ,-0.5110243 , 0.5110243 , 0.9686197 , # InterpolationType.seventh BoundType.dct1 -0., # InterpolationType.seventh BoundType.dct1 -2.,2.,2.,2.,2.,2.,2.,2.,2.,2.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0., # InterpolationType.nearest BoundType.dct2 -2.,2.,2.,2.,2.,2.,2.,2.,2.,2., # InterpolationType.nearest BoundType.dct2 -0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0., # InterpolationType.nearest BoundType.dct2 -0., # InterpolationType.nearest BoundType.dct2 -2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0.,-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1., 0., # InterpolationType.linear BoundType.dct2 -2.,2.,2.,2.,2.,2.,2.,2.,2.,2., # InterpolationType.linear BoundType.dct2 -1., 1., 1., 1., 1., 1., 1., 1., 1., 0.,-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1., 0., # InterpolationType.linear BoundType.dct2 -0., # InterpolationType.linear BoundType.dct2 -2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0.,-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1., 0., # InterpolationType.quadratic BoundType.dct2 -2.,2.,2.,2.,2.,2.,2.,2.,2.,2., # InterpolationType.quadratic BoundType.dct2 -1., 1., 1., 1., 1., 1., 1., 1., 1., 0.,-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1., 0., # InterpolationType.quadratic BoundType.dct2 -0., # InterpolationType.quadratic BoundType.dct2 -1.9999999, 2. , 1.9999999, 1.9999999, 1.9999999, 1.9999999, 1.9999999, 1.9999999, 1.9999999, 2. , 0.875 , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 0.875 , 0. ,-0.875 ,-1. ,-1. ,-1. ,-1. ,-1. ,-1. ,-1. ,-0.875 , 0. , # InterpolationType.cubic BoundType.dct2 -1.9999999,2. ,1.9999999,1.9999999,1.9999999,1.9999999,1.9999999,1.9999999,1.9999999,2. , # InterpolationType.cubic BoundType.dct2 -0.875, 1. , 1. , 1. , 1. , 1. , 1. , 1. , 0.875, 0. ,-0.875,-1. ,-1. ,-1. ,-1. ,-1. ,-1. ,-1. ,-0.875, 0. , # InterpolationType.cubic BoundType.dct2 -0., # InterpolationType.cubic BoundType.dct2 -2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 8.3333337e-01, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 9.9999988e-01, 1.0000000e+00, 8.3333302e-01,-1.1920929e-07,-8.3333325e-01,-1.0000000e+00,-1.0000001e+00,-1.0000002e+00,-1.0000000e+00,-1.0000001e+00,-1.0000001e+00,-1.0000000e+00,-8.3333337e-01, 0., # InterpolationType.fourth BoundType.dct2 -2.,2.,2.,2.,2.,2.,2.,2.,2.,2., # InterpolationType.fourth BoundType.dct2 -8.3333337e-01, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 9.9999988e-01, 1.0000000e+00, 8.3333302e-01,-1.1920929e-07,-8.3333325e-01,-1.0000000e+00,-1.0000001e+00,-1.0000002e+00,-1.0000000e+00,-1.0000001e+00,-1.0000001e+00,-1.0000000e+00,-8.3333337e-01, 0., # InterpolationType.fourth BoundType.dct2 -0., # InterpolationType.fourth BoundType.dct2 -2.0000000e+00, 1.9999999e+00, 2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 7.9687500e-01, 9.9739581e-01, 1.0000000e+00, 1.0000000e+00, 9.9999994e-01, 1.0000001e+00, 9.9999976e-01, 9.9739575e-01, 7.9687530e-01, 1.6018748e-07,-7.9687524e-01,-9.9739569e-01,-9.9999982e-01,-1.0000002e+00,-1.0000000e+00,-9.9999982e-01,-1.0000000e+00,-9.9739587e-01,-7.9687494e-01, 5.1222742e-09, # InterpolationType.fifth BoundType.dct2 -2. ,1.9999999,2. ,2. ,2. ,2. ,2. ,2. ,2. ,2. , # InterpolationType.fifth BoundType.dct2 -7.9687500e-01, 9.9739581e-01, 1.0000000e+00, 1.0000000e+00, 9.9999994e-01, 1.0000001e+00, 9.9999976e-01, 9.9739575e-01, 7.9687530e-01, 1.6018748e-07,-7.9687524e-01,-9.9739569e-01,-9.9999982e-01,-1.0000002e+00,-1.0000000e+00,-9.9999982e-01,-1.0000000e+00,-9.9739587e-01,-7.9687494e-01, 5.1222742e-09, # InterpolationType.fifth BoundType.dct2 -0., # InterpolationType.fifth BoundType.dct2 -2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 2.0000000e+00, 7.6666665e-01, 9.9166673e-01, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 9.9999982e-01, 1.0000004e+00, 9.9166673e-01, 7.6666647e-01, 5.9604645e-08,-7.6666659e-01,-9.9166662e-01,-1.0000004e+00,-1.0000001e+00,-1.0000001e+00,-1.0000000e+00,-9.9999994e-01,-9.9166667e-01,-7.6666665e-01, 1.8626451e-09, # InterpolationType.sixth BoundType.dct2 -2.,2.,2.,2.,2.,2.,2.,2.,2.,2., # InterpolationType.sixth BoundType.dct2 -7.6666665e-01, 9.9166673e-01, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 9.9999982e-01, 1.0000004e+00, 9.9166673e-01, 7.6666647e-01, 5.9604645e-08,-7.6666659e-01,-9.9166662e-01,-1.0000004e+00,-1.0000001e+00,-1.0000001e+00,-1.0000000e+00,-9.9999994e-01,-9.9166667e-01,-7.6666665e-01, 1.8626451e-09, # InterpolationType.sixth BoundType.dct2 -0., # InterpolationType.sixth BoundType.dct2 -2.0000002e+00, 2.0000000e+00, 2.0000000e+00, 2.0000002e+00, 2.0000002e+00, 2.0000002e+00, 2.0000002e+00, 2.0000002e+00, 2.0000002e+00, 2.0000002e+00, 7.3982203e-01, 9.8428816e-01, 9.9997836e-01, 9.9999994e-01, 1.0000000e+00, 1.0000001e+00, 9.9997842e-01, 9.8428833e-01, 7.3982203e-01,-1.6936974e-07,-7.3982191e-01,-9.8428810e-01,-9.9997830e-01,-1.0000000e+00,-1.0000000e+00,-1.0000001e+00,-9.9997824e-01,-9.8428822e-01,-7.3982203e-01,-2.7284841e-09, # InterpolationType.seventh BoundType.dct2 -2.0000002,2. ,2. ,2.0000002,2.0000002,2.0000002,2.0000002,2.0000002,2.0000002,2.0000002, # InterpolationType.seventh BoundType.dct2 -7.3982203e-01, 9.8428816e-01, 9.9997836e-01, 9.9999994e-01, 1.0000000e+00, 1.0000001e+00, 9.9997842e-01, 9.8428833e-01, 7.3982203e-01,-1.6936974e-07,-7.3982191e-01,-9.8428810e-01,-9.9997830e-01,-1.0000000e+00,-1.0000000e+00,-1.0000001e+00,-9.9997824e-01,-9.8428822e-01,-7.3982203e-01,-2.7284841e-09, # InterpolationType.seventh BoundType.dct2 -0., # InterpolationType.seventh BoundType.dct2 --1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., # InterpolationType.nearest BoundType.dst1 --1., 0., 0., 0., 0., 0., 0., 0., 0., 0., # InterpolationType.nearest BoundType.dst1 -0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0., # InterpolationType.nearest BoundType.dst1 -0., # InterpolationType.nearest BoundType.dst1 -0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 1., 1.,-9.,-9., 1., 1., 1., 1., 1., 1., 1., 1., 1., # InterpolationType.linear BoundType.dst1 -0.,0.,0.,0.,0.,0.,0.,0.,0.,0., # InterpolationType.linear BoundType.dst1 -1., 1., 1., 1., 1., 1., 1., 1., 1.,-9.,-9., 1., 1., 1., 1., 1., 1., 1., 1., 1., # InterpolationType.linear BoundType.dst1 -0., # InterpolationType.linear BoundType.dst1 -0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 1., 1.,-9.,-9., 1., 1., 1., 1., 1., 1., 1., 1., 1., # InterpolationType.quadratic BoundType.dst1 -0.,0.,0.,0.,0.,0.,0.,0.,0.,0., # InterpolationType.quadratic BoundType.dst1 -1., 1., 1., 1., 1., 1., 1., 1., 1.,-9.,-9., 1., 1., 1., 1., 1., 1., 1., 1., 1., # InterpolationType.quadratic BoundType.dst1 -0., # InterpolationType.quadratic BoundType.dst1 -0., 0.,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08, 8.7500000e-01, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00,-2.5000000e-01,-7.7500000e+00,-7.7500000e+00,-2.5000000e-01, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 8.7500000e-01, # InterpolationType.cubic BoundType.dst1 -0., 0.,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08, # InterpolationType.cubic BoundType.dst1 -0.875, 1. , 1. , 1. , 1. , 1. , 1. , 1. ,-0.25 ,-7.75 ,-7.75 ,-0.25 , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 0.875, # InterpolationType.cubic BoundType.dst1 -0., # InterpolationType.cubic BoundType.dst1 -0., 0.,-4.0978193e-08,-4.0978193e-08,-4.0978193e-08,-4.0978193e-08,-4.0978193e-08,-4.0978193e-08,-4.0978193e-08,-1.1175871e-08, 8.3333337e-01, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 9.9999988e-01, 1.0000000e+00,-6.6666698e-01,-7.3333335e+00,-7.3333335e+00,-6.6666675e-01, 1.0000000e+00, 1.0000001e+00, 1.0000002e+00, 1.0000000e+00, 1.0000001e+00, 1.0000001e+00, 1.0000000e+00, 8.3333337e-01, # InterpolationType.fourth BoundType.dst1 -0., 0.,-4.0978193e-08,-4.0978193e-08,-4.0978193e-08,-4.0978193e-08,-4.0978193e-08,-4.0978193e-08,-4.0978193e-08,-1.1175871e-08, # InterpolationType.fourth BoundType.dst1 -0.8333334 , 1. , 1. , 1. , 1. , 1. , 0.9999999 , 1. ,-0.666667 ,-7.3333335 ,-7.3333335 ,-0.66666675, 1. , 1.0000001 , 1.0000002 , 1. , 1.0000001 , 1.0000001 , 1. , 0.8333334 , # InterpolationType.fourth BoundType.dst1 -0., # InterpolationType.fourth BoundType.dst1 -3.9872248e-09, 0., 1.1175871e-08, 7.1886461e-09, 7.1886461e-09, 7.1886461e-09, 7.1886461e-09, 7.1886461e-09, 7.1886461e-09, 7.1886461e-09, 7.9947913e-01, 9.9739581e-01, 1.0000000e+00, 1.0000000e+00, 9.9999994e-01, 1.0000001e+00, 9.9999976e-01, 9.7395825e-01,-1.0052080e+00,-6.9687500e+00,-6.9687500e+00,-1.0052083e+00, 9.7395819e-01, 9.9999982e-01, 1.0000002e+00, 1.0000000e+00, 9.9999982e-01, 1.0000000e+00, 9.9739587e-01, 7.9947913e-01, # InterpolationType.fifth BoundType.dst1 -3.9872248e-09,0.,1.1175871e-08,7.1886461e-09,7.1886461e-09,7.1886461e-09,7.1886461e-09,7.1886461e-09,7.1886461e-09,7.1886461e-09, # InterpolationType.fifth BoundType.dst1 -0.7994791 , 0.9973958 , 1. , 1. , 0.99999994, 1.0000001 , 0.99999976, 0.97395825,-1.005208 ,-6.96875 ,-6.96875 ,-1.0052083 , 0.9739582 , 0.9999998 , 1.0000002 , 1. , 0.9999998 , 1. , 0.9973959 , 0.7994791 , # InterpolationType.fifth BoundType.dst1 -0., # InterpolationType.fifth BoundType.dst1 -4.1094609e-08, 0.,-1.4901161e-08, 3.6088750e-09, 3.6088750e-09, 3.6088750e-09, 3.6088750e-09, 3.6088750e-09, 3.6088750e-09,-2.6193447e-08, 7.7499998e-01, 9.9166673e-01, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 9.9999982e-01, 1.0000004e+00, 9.1666675e-01,-1.2500002e+00,-6.6666665e+00,-6.6666665e+00,-1.2500000e+00, 9.1666681e-01, 1.0000004e+00, 1.0000001e+00, 1.0000001e+00, 1.0000000e+00, 9.9999994e-01, 9.9166667e-01, 7.7499998e-01, # InterpolationType.sixth BoundType.dst1 -4.1094609e-08, 0.,-1.4901161e-08, 3.6088750e-09, 3.6088750e-09, 3.6088750e-09, 3.6088750e-09, 3.6088750e-09, 3.6088750e-09,-2.6193447e-08, # InterpolationType.sixth BoundType.dst1 -0.775 , 0.99166673, 1. , 1. , 1. , 0.9999998 , 1.0000004 , 0.91666675,-1.2500002 ,-6.6666665 ,-6.6666665 ,-1.25 , 0.9166668 , 1.0000004 , 1.0000001 , 1.0000001 , 1. , 0.99999994, 0.9916667 , 0.775 , # InterpolationType.sixth BoundType.dst1 -0., # InterpolationType.sixth BoundType.dst1 --9.7788870e-09, 3.7846348e-10,-7.4505806e-09, 2.3283064e-09, 1.9498430e-09, 1.9498430e-09, 1.9498430e-09, 1.9498430e-09, 1.9498430e-09, 1.9498430e-09, 7.5553381e-01, 9.8430985e-01, 9.9997836e-01, 9.9999994e-01, 1.0000000e+00, 1.0000001e+00, 9.9978310e-01, 8.4309906e-01,-1.4446614e+00,-6.3982205e+00,-6.3982205e+00,-1.4446614e+00, 8.4309900e-01, 9.9978304e-01, 1.0000000e+00, 1.0000000e+00, 1.0000001e+00, 9.9997824e-01, 9.8430991e-01, 7.5553381e-01, # InterpolationType.seventh BoundType.dst1 --9.7788870e-09, 3.7846348e-10,-7.4505806e-09, 2.3283064e-09, 1.9498430e-09, 1.9498430e-09, 1.9498430e-09, 1.9498430e-09, 1.9498430e-09, 1.9498430e-09, # InterpolationType.seventh BoundType.dst1 -0.7555338 , 0.98430985, 0.99997836, 0.99999994, 1. , 1.0000001 , 0.9997831 , 0.84309906,-1.4446614 ,-6.3982205 ,-6.3982205 ,-1.4446614 , 0.843099 , 0.99978304, 1. , 1. , 1.0000001 , 0.99997824, 0.9843099 , 0.7555338 , # InterpolationType.seventh BoundType.dst1 -0., # InterpolationType.seventh BoundType.dst1 -0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0., # InterpolationType.nearest BoundType.dst2 -0.,0.,0.,0.,0.,0.,0.,0.,0.,0., # InterpolationType.nearest BoundType.dst2 -0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0., # InterpolationType.nearest BoundType.dst2 -0., # InterpolationType.nearest BoundType.dst2 - 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 1., 1.,-18., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0., # InterpolationType.linear BoundType.dst2 -0.,0.,0.,0.,0.,0.,0.,0.,0.,0., # InterpolationType.linear BoundType.dst2 - 1., 1., 1., 1., 1., 1., 1., 1., 1.,-18., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0., # InterpolationType.linear BoundType.dst2 -0., # InterpolationType.linear BoundType.dst2 - 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 1., 1.,-18., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0., # InterpolationType.quadratic BoundType.dst2 -0.,0.,0.,0.,0.,0.,0.,0.,0.,0., # InterpolationType.quadratic BoundType.dst2 - 1., 1., 1., 1., 1., 1., 1., 1., 1.,-18., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0., # InterpolationType.quadratic BoundType.dst2 -0., # InterpolationType.quadratic BoundType.dst2 -0., 0.,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08, 9.3132257e-09, 8.7500000e-01, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00,-1.3750000e+00,-1.3250000e+01,-1.3750000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 8.7500000e-01, 2.5000000e-01, # InterpolationType.cubic BoundType.dst2 -0., 0.,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08,-2.0489097e-08, 9.3132257e-09, # InterpolationType.cubic BoundType.dst2 - 0.875, 1. , 1. , 1. , 1. , 1. , 1. , 1. , -1.375,-13.25 , -1.375, 1. , 1. , 1. , 1. , 1. , 1. , 1. , 0.875, 0.25 , # InterpolationType.cubic BoundType.dst2 -0., # InterpolationType.cubic BoundType.dst2 -0., 0.,-4.0978193e-08,-4.0978193e-08,-4.0978193e-08,-4.0978193e-08,-4.0978193e-08,-4.0978193e-08,-4.0978193e-08,-1.1175871e-08, 8.3333337e-01, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 9.9999988e-01, 1.0000000e+00,-2.1666670e+00,-1.1666667e+01,-2.1666667e+00, 1.0000000e+00, 1.0000001e+00, 1.0000002e+00, 1.0000000e+00, 1.0000001e+00, 1.0000001e+00, 1.0000000e+00, 8.3333337e-01, 3.3333334e-01, # InterpolationType.fourth BoundType.dst2 -0., 0.,-4.0978193e-08,-4.0978193e-08,-4.0978193e-08,-4.0978193e-08,-4.0978193e-08,-4.0978193e-08,-4.0978193e-08,-1.1175871e-08, # InterpolationType.fourth BoundType.dst2 - 0.8333334 , 1. , 1. , 1. , 1. , 1. , 0.9999999 , 1. , -2.166667 ,-11.666667 , -2.1666667 , 1. , 1.0000001 , 1.0000002 , 1. , 1.0000001 , 1.0000001 , 1. , 0.8333334 , 0.33333334, # InterpolationType.fourth BoundType.dst2 -0., # InterpolationType.fourth BoundType.dst2 -0., 3.7252903e-09, 1.1175871e-08, 7.1886461e-09, 7.1886461e-09, 7.1886461e-09, 7.1886461e-09, 7.1886461e-09, 7.1886461e-09, 1.0913936e-08, 8.0208331e-01, 9.9739581e-01, 1.0000000e+00, 1.0000000e+00, 9.9999994e-01, 1.0000001e+00, 9.9999976e-01, 9.5052075e-01,-2.7604163e+00,-1.0380208e+01,-2.7604165e+00, 9.5052069e-01, 9.9999982e-01, 1.0000002e+00, 1.0000000e+00, 9.9999982e-01, 1.0000000e+00, 9.9739587e-01, 8.0208331e-01, 4.0104166e-01, # InterpolationType.fifth BoundType.dst2 -0.,3.7252903e-09,1.1175871e-08,7.1886461e-09,7.1886461e-09,7.1886461e-09,7.1886461e-09,7.1886461e-09,7.1886461e-09,1.0913936e-08, # InterpolationType.fifth BoundType.dst2 - 0.8020833 , 0.9973958 , 1. , 1. , 0.99999994, 1.0000001 , 0.99999976, 0.95052075, -2.7604163 ,-10.380208 , -2.7604165 , 0.9505207 , 0.9999998 , 1.0000002 , 1. , 0.9999998 , 1. , 0.9973959 , 0.8020833 , 0.40104166, # InterpolationType.fifth BoundType.dst2 -0., # InterpolationType.fifth BoundType.dst2 -5.9604645e-08,-1.4901161e-08,-1.4901161e-08, 3.6088750e-09, 3.6088750e-09, 3.6088750e-09, 3.6088750e-09, 3.6088750e-09, 3.6088750e-09,-1.1292286e-08, 7.8333330e-01, 9.9166673e-01, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 9.9999982e-01, 1.0000004e+00, 8.4166676e-01,-3.1166668e+00,-9.4499998e+00,-3.1166666e+00, 8.4166652e-01, 1.0000004e+00, 1.0000001e+00, 1.0000001e+00, 1.0000000e+00, 9.9999994e-01, 9.9166667e-01, 7.8333330e-01, 4.5000002e-01, # InterpolationType.sixth BoundType.dst2 -5.9604645e-08,-1.4901161e-08,-1.4901161e-08, 3.6088750e-09, 3.6088750e-09, 3.6088750e-09, 3.6088750e-09, 3.6088750e-09, 3.6088750e-09,-1.1292286e-08, # InterpolationType.sixth BoundType.dst2 -0.7833333 , 0.99166673, 1. , 1. , 1. , 0.9999998 , 1.0000004 , 0.84166676,-3.1166668 ,-9.45 ,-3.1166666 , 0.8416665 , 1.0000004 , 1.0000001 , 1.0000001 , 1. , 0.99999994, 0.9916667 , 0.7833333 , 0.45000002, # InterpolationType.sixth BoundType.dst2 -0., # InterpolationType.sixth BoundType.dst2 -0.,-7.4505806e-09,-6.9849193e-09, 2.3283064e-09, 1.9498430e-09, 1.9498430e-09, 1.9498430e-09, 1.9498430e-09, 1.9498430e-09,-5.0350764e-09, 7.7120221e-01, 9.8433155e-01, 9.9997836e-01, 9.9999994e-01, 1.0000000e+00, 1.0000001e+00, 9.9958777e-01, 7.0230043e-01,-3.3471570e+00,-8.7094622e+00,-3.3471570e+00, 7.0230043e-01, 9.9958777e-01, 1.0000000e+00, 1.0000000e+00, 1.0000001e+00, 9.9997824e-01, 9.8433161e-01, 7.7120221e-01, 4.8897570e-01, # InterpolationType.seventh BoundType.dst2 -0.,-7.4505806e-09,-6.9849193e-09, 2.3283064e-09, 1.9498430e-09, 1.9498430e-09, 1.9498430e-09, 1.9498430e-09, 1.9498430e-09,-5.0350764e-09, # InterpolationType.seventh BoundType.dst2 -0.7712022 , 0.98433155, 0.99997836, 0.99999994, 1. , 1.0000001 , 0.9995878 , 0.7023004 ,-3.347157 ,-8.709462 ,-3.347157 , 0.7023004 , 0.9995878 , 1. , 1. , 1.0000001 , 0.99997824, 0.9843316 , 0.7712022 , 0.4889757 , # InterpolationType.seventh BoundType.dst2 -0., # InterpolationType.seventh BoundType.dst2 -2.,2.,2.,2.,2.,2.,2.,2.,2.,2.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0., # InterpolationType.nearest BoundType.dft -2.,2.,2.,2.,2.,2.,2.,2.,2.,2., # InterpolationType.nearest BoundType.dft -0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0., # InterpolationType.nearest BoundType.dft -0., # InterpolationType.nearest BoundType.dft -2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1.,-9., 1., 1., 1., 1., 1., 1., 1., 1., 1.,-9., # InterpolationType.linear BoundType.dft -2.,2.,2.,2.,2.,2.,2.,2.,2.,2., # InterpolationType.linear BoundType.dft -1., 1., 1., 1., 1., 1., 1., 1., 1.,-9., 1., 1., 1., 1., 1., 1., 1., 1., 1.,-9., # InterpolationType.linear BoundType.dft -0., # InterpolationType.linear BoundType.dft -2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1.,-9., 1., 1., 1., 1., 1., 1., 1., 1., 1.,-9., # InterpolationType.quadratic BoundType.dft -2.,2.,2.,2.,2.,2.,2.,2.,2.,2., # InterpolationType.quadratic BoundType.dft -1., 1., 1., 1., 1., 1., 1., 1., 1.,-9., 1., 1., 1., 1., 1., 1., 1., 1., 1.,-9., # InterpolationType.quadratic BoundType.dft -0., # InterpolationType.quadratic BoundType.dft -2. , 2. , 1.9999999, 1.9999999, 1.9999999, 1.9999999, 1.9999999, 1.9999999, 1.9999999, 2. ,-0.25 , 1. , 1. , 1. , 1. , 1. , 1. , 1. ,-0.25 ,-6.5 ,-0.25 , 1. , 1. , 1. , 1. , 1. , 1. , 1. ,-0.25 ,-6.5 , # InterpolationType.cubic BoundType.dft -2. ,2. ,1.9999999,1.9999999,1.9999999,1.9999999,1.9999999,1.9999999,1.9999999,2. , # InterpolationType.cubic BoundType.dft --0.25, 1. , 1. , 1. , 1. , 1. , 1. , 1. ,-0.25,-6.5 ,-0.25, 1. , 1. , 1. , 1. , 1. , 1. , 1. ,-0.25,-6.5 , # InterpolationType.cubic BoundType.dft -0., # InterpolationType.cubic BoundType.dft -2. , 2. , 2. , 2. , 2. , 2. , 2. , 2. , 2. , 2. ,-0.6666666, 1. , 1. , 1. , 1. , 1. , 0.9999999, 1. ,-0.666667 ,-5.666667 ,-0.6666666, 1. , 1. , 1. , 1. , 1. , 0.9999999, 1. ,-0.666667 ,-5.666667 , # InterpolationType.fourth BoundType.dft -2.,2.,2.,2.,2.,2.,2.,2.,2.,2., # InterpolationType.fourth BoundType.dft --0.6666666, 1. , 1. , 1. , 1. , 1. , 0.9999999, 1. ,-0.666667 ,-5.666667 ,-0.6666666, 1. , 1. , 1. , 1. , 1. , 0.9999999, 1. ,-0.666667 ,-5.666667 , # InterpolationType.fourth BoundType.dft -0., # InterpolationType.fourth BoundType.dft -2. , 2. , 2. , 2. , 2. , 2. , 2. , 2. , 2. , 2. ,-0.97916675, 0.9739583 , 1. , 1. , 0.99999994, 1.0000001 , 0.99999976, 0.97395825,-0.9791663 ,-4.989583 ,-0.97916675, 0.9739583 , 1. , 1. , 0.99999994, 1.0000001 , 0.99999976, 0.97395825,-0.9791663 ,-4.989583 , # InterpolationType.fifth BoundType.dft -2.,2.,2.,2.,2.,2.,2.,2.,2.,2., # InterpolationType.fifth BoundType.dft --0.97916675, 0.9739583 , 1. , 1. , 0.99999994, 1.0000001 , 0.99999976, 0.97395825,-0.9791663 ,-4.989583 ,-0.97916675, 0.9739583 , 1. , 1. , 0.99999994, 1.0000001 , 0.99999976, 0.97395825,-0.9791663 ,-4.989583 , # InterpolationType.fifth BoundType.dft -0., # InterpolationType.fifth BoundType.dft -1.9999999 , 2. , 2. , 2. , 2. , 2. , 2. , 2. , 2. , 2. ,-1.1666667 , 0.9166667 , 1. , 1. , 1. , 0.9999998 , 1.0000004 , 0.91666675,-1.1666669 ,-4.4999995 ,-1.1666667 , 0.9166667 , 1. , 1. , 1. , 0.9999998 , 1.0000004 , 0.91666675,-1.1666669 ,-4.4999995 , # InterpolationType.sixth BoundType.dft -1.9999999,2. ,2. ,2. ,2. ,2. ,2. ,2. ,2. ,2. , # InterpolationType.sixth BoundType.dft --1.1666667 , 0.9166667 , 1. , 1. , 1. , 0.9999998 , 1.0000004 , 0.91666675,-1.1666669 ,-4.4999995 ,-1.1666667 , 0.9166667 , 1. , 1. , 1. , 0.9999998 , 1.0000004 , 0.91666675,-1.1666669 ,-4.4999995 , # InterpolationType.sixth BoundType.dft -0., # InterpolationType.sixth BoundType.dft -2.0000002 , 2.0000002 , 2.0000002 , 2.0000002 , 2.0000002 , 2.0000002 , 2.0000002 , 2.0000002 , 2.0000002 , 2.0000002 ,-1.2879773 , 0.84331596, 0.999783 , 0.99999994, 1. , 1.0000001 , 0.9997831 , 0.8433161 ,-1.2879775 ,-4.110243 ,-1.2879773 , 0.84331596, 0.999783 , 0.99999994, 1. , 1.0000001 , 0.9997831 , 0.8433161 ,-1.2879775 ,-4.110243 , # InterpolationType.seventh BoundType.dft -2.0000002,2.0000002,2.0000002,2.0000002,2.0000002,2.0000002,2.0000002,2.0000002,2.0000002,2.0000002, # InterpolationType.seventh BoundType.dft --1.2879773 , 0.84331596, 0.999783 , 0.99999994, 1. , 1.0000001 , 0.9997831 , 0.8433161 ,-1.2879775 ,-4.110243 ,-1.2879773 , 0.84331596, 0.999783 , 0.99999994, 1. , 1.0000001 , 0.9997831 , 0.8433161 ,-1.2879775 ,-4.110243 , # InterpolationType.seventh BoundType.dft -0., # InterpolationType.seventh BoundType.dft -0.,1.,1.,1.,1.,1.,1.,1.,1.,1.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0., # InterpolationType.nearest BoundType.zero -0.,1.,1.,1.,1.,1.,1.,1.,1.,1., # InterpolationType.nearest BoundType.zero -0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0., # InterpolationType.nearest BoundType.zero -0., # InterpolationType.nearest BoundType.zero -0.5, 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. ,-9. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , # InterpolationType.linear BoundType.zero -0.5,1. ,1. ,1. ,1. ,1. ,1. ,1. ,1. ,1. , # InterpolationType.linear BoundType.zero -1., 1., 1., 1., 1., 1., 1., 1., 1.,-9., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., # InterpolationType.linear BoundType.zero -0., # InterpolationType.linear BoundType.zero -0.5, 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. ,-9. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , # InterpolationType.quadratic BoundType.zero -0.5,1. ,1. ,1. ,1. ,1. ,1. ,1. ,1. ,1. , # InterpolationType.quadratic BoundType.zero -1., 1., 1., 1., 1., 1., 1., 1., 1.,-9., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., # InterpolationType.quadratic BoundType.zero -0., # InterpolationType.quadratic BoundType.zero -0.5 , 0.9791666 , 0.99999994, 0.99999994, 0.99999994, 0.99999994, 0.99999994, 0.99999994, 0.99999994, 0.99999994, 0.875 , 1. , 1. , 1. , 1. , 1. , 1. , 1. ,-0.25 ,-6.625 ,-1.125 , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , # InterpolationType.cubic BoundType.zero -0.5 ,0.9791666 ,0.99999994,0.99999994,0.99999994,0.99999994,0.99999994,0.99999994,0.99999994,0.99999994, # InterpolationType.cubic BoundType.zero -0.875, 1. , 1. , 1. , 1. , 1. , 1. , 1. ,-0.25 ,-6.625,-1.125, 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , # InterpolationType.cubic BoundType.zero -0., # InterpolationType.cubic BoundType.zero -0.5 , 0.9583334, 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 0.8333334, 1. , 1. , 1. , 1. , 1. , 0.9999999, 1. ,-0.666667 ,-5.8333335,-1.5 , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , # InterpolationType.fourth BoundType.zero -0.5 ,0.9583334,1. ,1. ,1. ,1. ,1. ,1. ,1. ,1. , # InterpolationType.fourth BoundType.zero -0.8333334, 1. , 1. , 1. , 1. , 1. , 0.9999999, 1. ,-0.666667 ,-5.8333335,-1.5 , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , # InterpolationType.fourth BoundType.zero -0., # InterpolationType.fourth BoundType.zero -0.5 , 0.9380208 , 0.9997396 , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 0.7994791 , 0.9973958 , 1. , 1. , 0.99999994, 1.0000001 , 0.99999976, 0.97395825,-0.9817705 ,-5.190104 ,-1.7786459 ,-0.0234375 , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , # InterpolationType.fifth BoundType.zero -0.5 ,0.9380208,0.9997396,1. ,1. ,1. ,1. ,1. ,1. ,1. , # InterpolationType.fifth BoundType.zero -0.7994791 , 0.9973958 , 1. , 1. , 0.99999994, 1.0000001 , 0.99999976, 0.97395825,-0.9817705 ,-5.190104 ,-1.7786459 ,-0.0234375 , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , # InterpolationType.fifth BoundType.zero -0., # InterpolationType.fifth BoundType.zero -0.49999997, 0.91944444, 0.9986111 , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 0.775 , 0.99166673, 1. , 1. , 1. , 0.9999998 , 1.0000004 , 0.91666675,-1.1750002 ,-4.725 ,-1.9416667 ,-0.075 , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , # InterpolationType.sixth BoundType.zero -0.49999997,0.91944444,0.9986111 ,1. ,1. ,1. ,1. ,1. ,1. ,1. , # InterpolationType.sixth BoundType.zero -0.775 , 0.99166673, 1. , 1. , 1. , 0.9999998 , 1.0000004 , 0.91666675,-1.1750002 ,-4.725 ,-1.9416667 ,-0.075 , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , # InterpolationType.sixth BoundType.zero -0., # InterpolationType.sixth BoundType.zero -5.0000000e-01, 9.0259641e-01, 9.9662077e-01, 9.9999845e-01, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 7.5551212e-01, 9.8430985e-01, 9.9997836e-01, 9.9999994e-01, 1.0000000e+00, 1.0000001e+00, 9.9978310e-01, 8.4329438e-01,-1.3036675e+00,-4.3547311e+00,-2.0434895e+00,-1.4099392e-01,-1.9531250e-04, 0., 0., 0., 0., 0., 0., 0., # InterpolationType.seventh BoundType.zero -0.5 ,0.9025964 ,0.9966208 ,0.99999845,1. ,1. ,1. ,1. ,1. ,1. , # InterpolationType.seventh BoundType.zero -7.5551212e-01, 9.8430985e-01, 9.9997836e-01, 9.9999994e-01, 1.0000000e+00, 1.0000001e+00, 9.9978310e-01, 8.4329438e-01,-1.3036675e+00,-4.3547311e+00,-2.0434895e+00,-1.4099392e-01,-1.9531250e-04, 0., 0., 0., 0., 0., 0., 0., # InterpolationType.seventh BoundType.zero -0., # InterpolationType.seventh BoundType.zero diff --git a/tests/testing_data/1D_BP_fwd.txt b/tests/testing_data/1D_BP_fwd.txt deleted file mode 100644 index a620d59dff..0000000000 --- a/tests/testing_data/1D_BP_fwd.txt +++ /dev/null @@ -1,56 +0,0 @@ -1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, # InterpolationType.nearest BoundType.replicate -0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, # InterpolationType.linear BoundType.replicate -0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, # InterpolationType.quadratic BoundType.replicate -0.5208, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.4792, 8.9792, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, # InterpolationType.cubic BoundType.replicate -0.5417, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.4583, 8.9583, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, # InterpolationType.fourth BoundType.replicate -0.5622, 1.5003, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4997, 8.4378, 8.9378, 8.9997, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, # InterpolationType.fifth BoundType.replicate -0.5819, 1.5014, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4986, 8.4181, 8.9181, 8.9986, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, # InterpolationType.sixth BoundType.replicate -0.6008, 1.5034, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4966, 8.3992, 8.8992, 8.9966, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0, # InterpolationType.seventh BoundType.replicate -1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0, 1.0, 2.0, # InterpolationType.nearest BoundType.dct1 -0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 8.5, 7.5, 6.5, 5.5, 4.5, 3.5, 2.5, 1.5, 0.5, 0.5, 1.5, # InterpolationType.linear BoundType.dct1 -0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 8.5, 7.5, 6.5, 5.5, 4.5, 3.5, 2.5, 1.5, 0.5, 0.5, 1.5, # InterpolationType.quadratic BoundType.dct1 -0.5417, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.4583, 8.4583, 7.5, 6.5, 5.5, 4.5, 3.5, 2.5, 1.5, 0.5417, 0.5417, 1.5, # InterpolationType.cubic BoundType.dct1 -0.5833, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.4167, 8.4167, 7.5, 6.5, 5.5, 4.5, 3.5, 2.5, 1.5, 0.5833, 0.5833, 1.5, # InterpolationType.fourth BoundType.dct1 -0.6245, 1.5005, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4995, 8.3755, 8.3755, 7.4995, 6.5, 5.5, 4.5, 3.5, 2.5, 1.5005, 0.6245, 0.6245, 1.5005, # InterpolationType.fifth BoundType.dct1 -0.6639, 1.5028, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4972, 8.3361, 8.3361, 7.4972, 6.5, 5.5, 4.5, 3.5, 2.5, 1.5028, 0.6639, 0.6639, 1.5028, # InterpolationType.sixth BoundType.dct1 -0.7016, 1.5068, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4932, 8.2984, 8.2984, 7.4932, 6.5, 5.5, 4.5, 3.5, 2.5, 1.5068, 0.7016, 0.7016, 1.5068, # InterpolationType.seventh BoundType.dct1 -1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0, 0.0, # InterpolationType.nearest BoundType.dct2 -0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.0, 8.5, 7.5, 6.5, 5.5, 4.5, 3.5, 2.5, 1.5, 0.5, 0.0, # InterpolationType.linear BoundType.dct2 -0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.0, 8.5, 7.5, 6.5, 5.5, 4.5, 3.5, 2.5, 1.5, 0.5, 0.0, # InterpolationType.quadratic BoundType.dct2 -0.5208, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.4792, 8.9583, 8.4792, 7.5, 6.5, 5.5, 4.5, 3.5, 2.5, 1.5, 0.5208, 0.0417, # InterpolationType.cubic BoundType.dct2 -0.5417, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.4583, 8.9167, 8.4583, 7.5, 6.5, 5.5, 4.5, 3.5, 2.5, 1.5, 0.5417, 0.0833, # InterpolationType.fourth BoundType.dct2 -0.5625, 1.5003, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4997, 8.4375, 8.8755, 8.4375, 7.4997, 6.5, 5.5, 4.5, 3.5, 2.5, 1.5003, 0.5625, 0.1245, # InterpolationType.fifth BoundType.dct2 -0.5833, 1.5014, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4986, 8.4167, 8.8361, 8.4167, 7.4986, 6.5, 5.5, 4.5, 3.5, 2.5, 1.5014, 0.5833, 0.1639, # InterpolationType.sixth BoundType.dct2 -0.6042, 1.5034, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4966, 8.3958, 8.7984, 8.3958, 7.4966, 6.5, 5.5, 4.5, 3.5, 2.5, 1.5034, 0.6042, 0.2016, # InterpolationType.seventh BoundType.dct2 -1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.0, -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, -3.0, -2.0, -1.0, -0.0, # InterpolationType.nearest BoundType.dst1 -0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 4.5, -4.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, # InterpolationType.linear BoundType.dst1 -0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 4.5, -4.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, # InterpolationType.quadratic BoundType.dst1 -0.5208, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.2917, 4.2917, -4.2917, -8.2917, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5208, # InterpolationType.cubic BoundType.dst1 -0.5417, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.0833, 4.0833, -4.0833, -8.0833, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5417, # InterpolationType.fourth BoundType.dst1 -0.5622, 1.5003, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4974, 7.8776, 3.8802, -3.8802, -7.8776, -7.4974, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5003, -0.5622, # InterpolationType.fifth BoundType.dst1 -0.5819, 1.5014, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4861, 7.6806, 3.6944, -3.6944, -7.6806, -7.4861, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5014, -0.5819, # InterpolationType.sixth BoundType.dst1 -0.6008, 1.5034, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4662, 7.4922, 3.5260, -3.5260, -7.4922, -7.4662, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5034, -0.6008, # InterpolationType.seventh BoundType.dst1 -1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, -3.0, -2.0, -1.0, -0.0, 0.0, # InterpolationType.nearest BoundType.dst2 -0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 0.0, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.0, # InterpolationType.linear BoundType.dst2 -0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 0.0, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.0, # InterpolationType.quadratic BoundType.dst2 -5.2083e-01, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.1042, -1.6391e-07, -8.1042, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -5.2083e-01, 0.0, # InterpolationType.cubic BoundType.dst2 -5.4167e-01, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 7.7083, 1.4901e-07, -7.7083, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -5.4167e-01, 0.0, # InterpolationType.fourth BoundType.dst2 -5.6198e-01, 1.5003, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4951, 7.3224, 1.2107e-07, -7.3224, -7.4951, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5003, -5.6198e-01, 5.2387e-10, # InterpolationType.fifth BoundType.dst2 -5.8056e-01, 1.5014, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4736, 6.9694, -1.0896e-07, -6.9694, -7.4736, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5014, -5.8056e-01, 2.3283e-10, # InterpolationType.sixth BoundType.dst2 -0.59740, 1.5034, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4358, 6.6493, 0.0, -6.6493, -7.4358, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5034, -0.59740, 0.0, # InterpolationType.seventh BoundType.dst2 -1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.0, # InterpolationType.nearest BoundType.dft -0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 4.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 4.5, # InterpolationType.linear BoundType.dft -0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 4.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 4.5, # InterpolationType.quadratic BoundType.dft -0.7083, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.2917, 4.5, 0.7083, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.2917, 4.5, # InterpolationType.cubic BoundType.dft -0.9167, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.0833, 4.5, 0.9167, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.0833, 4.5, # InterpolationType.fourth BoundType.dft -1.1198, 1.5026, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4974, 7.8802, 4.5, 1.1198, 1.5026, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4974, 7.8802, 4.5, # InterpolationType.fifth BoundType.dft -1.3056, 1.5139, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4861, 7.6944, 4.5, 1.3056, 1.5139, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4861, 7.6944, 4.5, # InterpolationType.sixth BoundType.dft -1.4740, 1.5338, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4662, 7.5260, 4.5, 1.4740, 1.5338, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4662, 7.5260, 4.5, # InterpolationType.seventh BoundType.dft -1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, # InterpolationType.nearest BoundType.zero -0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 4.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, # InterpolationType.linear BoundType.zero -0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 4.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, # InterpolationType.quadratic BoundType.zero -0.5208, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.2917, 4.4792, 0.1875, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, # InterpolationType.cubic BoundType.zero -0.5417, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.0833, 4.4583, 0.3750, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, # InterpolationType.fourth BoundType.zero -5.6224e-01, 1.5003, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4974, 7.8799, 4.4378, 5.5755e-01, 2.3438e-03, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, # InterpolationType.fifth BoundType.zero -0.5819, 1.5014, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4861, 7.6931, 4.4181, 0.7236, 0.0125, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, # InterpolationType.sixth BoundType.zero -6.0078e-01, 1.5034, 2.5, 3.5, 4.5, 5.5, 6.5, 7.4662, 7.5226, 4.3992, 8.7325e-01, 3.0411e-02, 1.3951e-05, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, # InterpolationType.seventh BoundType.zero diff --git a/tests/testing_data/CT_DICOM/7106 b/tests/testing_data/CT_DICOM/7106 deleted file mode 100644 index 727bea124b..0000000000 Binary files a/tests/testing_data/CT_DICOM/7106 and /dev/null differ diff --git a/tests/testing_data/CT_DICOM/7136 b/tests/testing_data/CT_DICOM/7136 deleted file mode 100644 index ed1222f80d..0000000000 Binary files a/tests/testing_data/CT_DICOM/7136 and /dev/null differ diff --git a/tests/testing_data/CT_DICOM/7166 b/tests/testing_data/CT_DICOM/7166 deleted file mode 100644 index edadf552b2..0000000000 Binary files a/tests/testing_data/CT_DICOM/7166 and /dev/null differ diff --git a/tests/testing_data/CT_DICOM/7196 b/tests/testing_data/CT_DICOM/7196 deleted file mode 100644 index d4c0f0795e..0000000000 Binary files a/tests/testing_data/CT_DICOM/7196 and /dev/null differ diff --git a/tests/testing_data/anatomical.nii b/tests/testing_data/anatomical.nii deleted file mode 100644 index 2d48e4770d..0000000000 Binary files a/tests/testing_data/anatomical.nii and /dev/null differ 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/bundle_test_network.py b/tests/testing_data/bundle_test_network.py deleted file mode 100644 index 5c91e7e78f..0000000000 --- a/tests/testing_data/bundle_test_network.py +++ /dev/null @@ -1,29 +0,0 @@ -# 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. - -from __future__ import annotations - -import torch - -from monai.networks.nets import UNet - - -class TestMultiInputUNet(UNet): - """ - This class is used for "tests/test_bundle_verify_net.py" to show that the monai.bundle.verify_net_in_out - function supports to verify networks that have multiple args as the input in the forward function. - """ - - def forward(self, x: torch.Tensor, extra_arg1: int, extra_arg2: int) -> torch.Tensor: # type: ignore - x = self.model(x) - x += extra_arg1 - x += extra_arg2 - return x diff --git a/tests/testing_data/config_fl_evaluate.json b/tests/testing_data/config_fl_evaluate.json deleted file mode 100644 index 917e762736..0000000000 --- a/tests/testing_data/config_fl_evaluate.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "validate#handlers": [ - { - "_target_": "CheckpointLoader", - "load_path": "$@bundle_root + '/models/model.pt'", - "load_dict": { - "model": "@network" - } - }, - { - "_target_": "StatsHandler", - "iteration_log": false - } - ], - "run": [ - "$@validate#evaluator.run()" - ] -} diff --git a/tests/testing_data/config_fl_filters.json b/tests/testing_data/config_fl_filters.json deleted file mode 100644 index 5ccafa334c..0000000000 --- a/tests/testing_data/config_fl_filters.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "pre_filters": [ - { - "_target_": "monai.fl.utils.filters.SummaryFilter" - } - ], - "post_weight_filters": [ - { - "_target_": "monai.fl.utils.filters.SummaryFilter" - } - ], - "post_evaluate_filters": [] -} diff --git a/tests/testing_data/config_fl_stats_1.json b/tests/testing_data/config_fl_stats_1.json deleted file mode 100644 index 80773139c2..0000000000 --- a/tests/testing_data/config_fl_stats_1.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "imports": [ - "$import os" - ], - "bundle_root": "", - "dataset_dir": "@bundle_root", - "train": { - "dataset": { - "_target_": "Dataset", - "data": [ - { - "image": "$os.path.join(@dataset_dir, 'anatomical.nii')", - "label": "$os.path.join(@dataset_dir, 'anatomical_label.nii.gz')" - }, - { - "image": "$os.path.join(@dataset_dir, 'reoriented_anat_moved.nii')", - "label": "$os.path.join(@dataset_dir, 'reoriented_anat_moved_label.nii.gz')" - } - ], - "transform": "@train#preprocessing" - } - } -} diff --git a/tests/testing_data/config_fl_stats_2.json b/tests/testing_data/config_fl_stats_2.json deleted file mode 100644 index 8d24bc6a8b..0000000000 --- a/tests/testing_data/config_fl_stats_2.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "imports": [ - "$import os" - ], - "bundle_root": "", - "dataset_dir": "@bundle_root", - "train": { - "dataset": { - "_target_": "Dataset", - "data": [ - { - "image": "$os.path.join(@dataset_dir, 'anatomical.nii')", - "label": "$os.path.join(@dataset_dir, 'anatomical_label.nii.gz')" - }, - { - "image": "$os.path.join(@dataset_dir, 'reoriented_anat_moved.nii')", - "label": "$os.path.join(@dataset_dir, 'reoriented_anat_moved_label.nii.gz')" - } - ], - "transform": "@train#preprocessing" - } - }, - "validate": { - "dataset": { - "_target_": "Dataset", - "data": [ - { - "image": "$os.path.join(@dataset_dir, 'anatomical.nii')", - "label": "$os.path.join(@dataset_dir, 'anatomical_label.nii.gz')" - }, - { - "image": "$os.path.join(@dataset_dir, 'reoriented_anat_moved.nii')", - "label": "$os.path.join(@dataset_dir, 'reoriented_anat_moved_label.nii.gz')" - } - ], - "transform": "@train#preprocessing" - } - } -} diff --git a/tests/testing_data/config_fl_train.json b/tests/testing_data/config_fl_train.json deleted file mode 100644 index 5b7fb6608e..0000000000 --- a/tests/testing_data/config_fl_train.json +++ /dev/null @@ -1,216 +0,0 @@ -{ - "bundle_root": "tests/testing_data", - "dataset_dir": "@bundle_root", - "val_interval": 1, - "imports": [ - "$import os" - ], - "device": "$torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')", - "network_def": { - "_target_": "DenseNet121", - "spatial_dims": 2, - "in_channels": 1, - "out_channels": 6 - }, - "network": "$@network_def.to(@device)", - "loss": { - "_target_": "torch.nn.CrossEntropyLoss" - }, - "optimizer": { - "_target_": "torch.optim.Adam", - "params": "$@network.parameters()", - "lr": 0.0001 - }, - "train": { - "training_transforms": [ - { - "_target_": "LoadImaged", - "keys": [ - "image" - ], - "image_only": true - }, - { - "_target_": "EnsureChannelFirstD", - "keys": [ - "image" - ] - }, - { - "_target_": "ScaleIntensityd", - "keys": [ - "image" - ] - }, - { - "_target_": "RandRotated", - "keys": [ - "image" - ], - "range_x": 15, - "prob": 0.5, - "keep_size": true - }, - { - "_target_": "RandFlipd", - "keys": [ - "image" - ], - "spatial_axis": 0, - "prob": 0.5 - }, - { - "_target_": "RandZoomd", - "keys": [ - "image" - ], - "min_zoom": 0.9, - "max_zoom": 1.1, - "prob": 0.5 - } - ], - "preprocessing": { - "_target_": "Compose", - "transforms": "$@train#training_transforms" - }, - "dataset": { - "_target_": "Dataset", - "data": [ - { - "image": "$os.path.join(@dataset_dir, 'image0.jpeg')", - "label": 0 - }, - { - "image": "$os.path.join(@dataset_dir, 'image1.jpeg')", - "label": 1 - } - ], - "transform": "@train#preprocessing" - }, - "dataloader": { - "_target_": "DataLoader", - "dataset": "@train#dataset", - "batch_size": 3, - "shuffle": true, - "num_workers": 2 - }, - "inferer": { - "_target_": "SimpleInferer" - }, - "handlers": [ - { - "_target_": "ValidationHandler", - "validator": "@validate#evaluator", - "epoch_level": true, - "interval": "@val_interval" - }, - { - "_target_": "StatsHandler", - "tag_name": "train_loss", - "output_transform": "$monai.handlers.from_engine(['loss'], first=True)" - } - ], - "trainer": { - "_target_": "SupervisedTrainer", - "max_epochs": 2, - "device": "@device", - "train_data_loader": "@train#dataloader", - "network": "@network", - "loss_function": "@loss", - "optimizer": "@optimizer", - "inferer": "@train#inferer", - "train_handlers": "@train#handlers" - } - }, - "validate": { - "preprocessing": { - "_target_": "Compose", - "transforms": [ - { - "_target_": "LoadImaged", - "keys": [ - "image" - ], - "image_only": true - }, - { - "_target_": "EnsureChannelFirstD", - "keys": [ - "image" - ] - }, - { - "_target_": "ScaleIntensityd", - "keys": [ - "image" - ] - } - ] - }, - "dataset": { - "_target_": "Dataset", - "data": [ - { - "image": "$os.path.join(@dataset_dir, 'image0.jpeg')", - "label": 0 - }, - { - "image": "$os.path.join(@dataset_dir, 'image1.jpeg')", - "label": 1 - } - ], - "transform": "@validate#preprocessing" - }, - "dataloader": { - "_target_": "DataLoader", - "dataset": "@validate#dataset", - "batch_size": 1, - "shuffle": false, - "num_workers": 2 - }, - "inferer": { - "_target_": "SimpleInferer" - }, - "postprocessing": { - "_target_": "Compose", - "transforms": [ - { - "_target_": "Activationsd", - "keys": "pred", - "softmax": true - } - ] - }, - "key_metric": { - "accuracy": { - "_target_": "ignite.metrics.Accuracy", - "output_transform": "$monai.handlers.from_engine(['pred', 'label'])" - } - }, - "handlers": [ - { - "_target_": "StatsHandler", - "iteration_log": false - } - ], - "evaluator": { - "_target_": "SupervisedEvaluator", - "device": "@device", - "val_data_loader": "@validate#dataloader", - "network": "@network", - "inferer": "@validate#inferer", - "val_handlers": "@validate#handlers", - "postprocessing": "@validate#postprocessing", - "key_val_metric": "@validate#key_metric" - } - }, - "initialize": [ - "$monai.utils.set_determinism(seed=123)" - ], - "run": [ - "$@train#trainer.run()" - ], - "finalize": [ - "$monai.utils.set_determinism(seed=None)" - ] -} diff --git a/tests/testing_data/cpp_resample_answers.py b/tests/testing_data/cpp_resample_answers.py deleted file mode 100644 index 266c45a508..0000000000 --- a/tests/testing_data/cpp_resample_answers.py +++ /dev/null @@ -1,42 +0,0 @@ -# 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. - -from __future__ import annotations - -import csv -import os -import warnings - - -def _read_testing_data_answers(fname: str | None = None, delimiter=",") -> list: - answers: list = [] - if not fname: - return answers - # read answers from directory of the current file - pwd = os.path.dirname(os.path.abspath(__file__)) - filename = os.path.join(pwd, fname) - if not os.path.isfile(filename): - warnings.warn(f"test data {filename} not found.") - return answers - with open(filename) as f: - res_reader = csv.reader(f, delimiter=delimiter) - for r in res_reader: - res_row = [] - for item in r: - if item.strip().startswith("#"): - continue # allow for some simple comments in the file - res_row.append(float(item)) - answers.append(res_row) - return answers - - -Expected_1D_GP_fwd: list = _read_testing_data_answers(fname="1D_BP_fwd.txt") -Expected_1D_GP_bwd: list = _read_testing_data_answers(fname="1D_BP_bwd.txt") diff --git a/tests/testing_data/data_config.json b/tests/testing_data/data_config.json deleted file mode 100644 index 79033dd0d6..0000000000 --- a/tests/testing_data/data_config.json +++ /dev/null @@ -1,170 +0,0 @@ -{ - "images": { - "wsi_generic_tiff": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/CMU-1.tiff", - "hash_type": "sha256", - "hash_val": "73a7e89bc15576587c3d68e55d9bf92f09690280166240b48ff4b48230b13bcd" - }, - "wsi_aperio_svs": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/Aperio-CMU-1.svs", - "hash_type": "sha256", - "hash_val": "00a3d54482cd707abf254fe69dccc8d06b8ff757a1663f1290c23418c480eb30" - }, - "favicon": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/favicon.ico.zip", - "hash_type": "sha256", - "hash_val": "3a3635c8d8adb81feebc5926b4106e8eb643a24a4be2a69a9d35f9a578acadb5" - }, - "icon": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/icon.tar.gz", - "hash_type": "sha256", - "hash_val": "90f24cd8f20f3932624da95190ce384302261acf0ea15b358f7832e3b6becac0" - }, - "mednist": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/MedNIST.tar.gz", - "hash_type": "sha256", - "hash_val": "f2f4881ff8799a170b10a403495f0ce0ad7486491901cde67a647e6627e7f916" - }, - "Prostate_T2W_AX_1": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/Prostate_T2W_AX_1.nii", - "hash_type": "sha256", - "hash_val": "a14231f539c0f365a5f83f2a046969a9b9870e56ffd126fd8e7242364d25938a" - }, - "0000_t2_tse_tra_4": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/ProstateX-0000_t2_tse_tra_4.nii.gz", - "hash_type": "md5", - "hash_val": "adb3f1c4db66a6481c3e4a2a3033c7d5" - }, - "0000_ep2d_diff_tra_7": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/ProstateX-0000_ep2d_diff_tra_7.nii.gz", - "hash_type": "md5", - "hash_val": "f12a11ad0ebb0b1876e9e010564745d2" - }, - "ref_avg152T1_LR": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/avg152T1_LR_nifti.nii.gz", - "hash_type": "sha256", - "hash_val": "c01a50caa7a563158ecda43d93a1466bfc8aa939bc16b06452ac1089c54661c8" - }, - "ref_avg152T1_RL": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/avg152T1_RL_nifti.nii.gz", - "hash_type": "sha256", - "hash_val": "8a731128dac4de46ccb2cc60d972b98f75a52f21fb63ddb040ca96f0aed8b51a" - }, - "MNI152_T1_2mm": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/MNI152_T1_2mm.nii.gz", - "hash_type": "sha256", - "hash_val": "0585cd056bf5ccfb8bf97a5f6a66082d4e7caad525718fc11e40d80a827fcb92" - }, - "MNI152_T1_2mm_strucseg": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/MNI152_T1_2mm_strucseg.nii.gz", - "hash_type": "sha256", - "hash_val": "eb4f1e596ca85aadaefc359d409fb9a3e27d733e6def04b996953b7c54bc26d4" - }, - "copd1_highres_INSP_STD_COPD_img": { - "url": "https://data.kitware.com/api/v1/file/62a0f067bddec9d0c4175c5a/download", - "hash_type": "sha512", - "hash_val": "60193cd6ef0cf055c623046446b74f969a2be838444801bd32ad5bedc8a7eeecb343e8a1208769c9c7a711e101c806a3133eccdda7790c551a69a64b9b3701e9" - }, - "copd1_highres_EXP_STD_COPD_img": { - "url": "https://data.kitware.com/api/v1/item/62a0f045bddec9d0c4175c44/download", - "hash_type": "sha512", - "hash_val": "841ef303958541474e66c2d1ccdc8b7ed17ba2f2681101307766b979a07979f2ec818ddf13791c3f1ac5a8ec3258d6ea45b692b4b4a838de9188602618972b6d" - }, - "CT_2D_head_fixed": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/CT_2D_head_fixed.mha", - "hash_type": "sha256", - "hash_val": "06f2ce6fbf6a59f0874c735555fcf71717f631156b1b0697c1752442f7fc1cc5" - }, - "CT_2D_head_moving": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/CT_2D_head_moving.mha", - "hash_type": "sha256", - "hash_val": "a37c5fe388c38b3f4ac564f456277d09d3982eda58c4da05ead8ee2332360f47" - }, - "DICOM_single": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/CT_DICOM_SINGLE.zip", - "hash_type": "sha256", - "hash_val": "a41f6e93d2e3d68956144f9a847273041d36441da12377d6a1d5ae610e0a7023" - }, - "nrrd_example": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/CT_IMAGE_cropped.nrrd", - "hash_type": "sha256", - "hash_val": "66971ad17f0bac50e6082ed6a4dc1ae7093c30517137e53327b15a752327a1c0" - } - }, - "videos": { - "endovis": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/d1_im.mp4", - "hash_type": "md5", - "hash_val": "9b103c07326439b0ea376018d7189384" - }, - "ultrasound": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/example_data_Ultrasound_Q000_04_tu_segmented_ultrasound_256.avi", - "hash_type": "md5", - "hash_val": "f0755960cc4a08a958561cda9a79a157" - } - }, - "models": { - "senet154-c7b49a05": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/senet154-c7b49a05.pth", - "hash_type": "sha256", - "hash_val": "c7b49a056b98b0bed65b0237c27acdead655e599669215573d357ad337460413" - }, - "se_resnet101-7e38fcc6": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/se_resnet101-7e38fcc6.pth", - "hash_type": "sha256", - "hash_val": "7e38fcc64eff3225a3ea4e6081efeb6087e8d5a61c204d94edc2ed1aab0b9d70" - }, - "se_resnet152-d17c99b7": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/se_resnet152-d17c99b7.pth", - "hash_type": "sha256", - "hash_val": "d17c99b703dcca2d2507ddfb68f72625a2f7e23ee64396eb992f1b2cf7e6bdc1" - }, - "se_resnet50-ce0d4300": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/se_resnet50-ce0d4300.pth", - "hash_type": "sha256", - "hash_val": "ce0d430017d3f4aa6b5658c72209f3bfffb060207fd26a2ef0b203ce592eba01" - }, - "se_resnext101_32x4d-3b2fe3d8": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/se_resnext101_32x4d-3b2fe3d8.pth", - "hash_type": "sha256", - "hash_val": "3b2fe3d8acb8de7d5976c4baf518f24a0237509272a69366e816682d3e57b989" - }, - "se_resnext50_32x4d-a260b3a4": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/se_resnext50_32x4d-a260b3a4.pth", - "hash_type": "sha256", - "hash_val": "a260b3a40f82dfe37c58d26a612bcf7bef0d27c6fed096226b0e4e9fb364168e" - }, - "ssl_pretrained_weights": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/ssl_pretrained_weights.pth", - "hash_type": "sha256", - "hash_val": "c3564f40a6a051d3753a6d8fae5cc8eaf21ce8d82a9a3baf80748d15664055e8" - }, - "decoder_only_transformer_monai_generative_weights": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/decoder_only_transformer.pth", - "hash_type": "sha256", - "hash_val": "f93de37d64d77cf91f3bde95cdf93d161aee800074c89a92aff9d5699120ec0d" - }, - "diffusion_model_unet_monai_generative_weights": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/diffusion_model_unet.pth", - "hash_type": "sha256", - "hash_val": "0d2171b386902f5b4fd3e967b4024f63e353694ca45091b114970019d045beee" - }, - "autoencoderkl_monai_generative_weights": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/autoencoderkl.pth", - "hash_type": "sha256", - "hash_val": "6e02c9540c51b16b9ba98b5c0c75d6b84b430afe9a3237df1d67a520f8d34184" - }, - "controlnet_monai_generative_weights": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/controlnet.pth", - "hash_type": "sha256", - "hash_val": "cd100d0c69f47569ae5b4b7df653a1cb19f5e02eff1630db3210e2646fb1ab2e" - } - }, - "configs": { - "test_meta_file": { - "url": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/meta_schema_20240725.json", - "hash_type": "md5", - "hash_val": "06954cad2cc5d3784e72077ac76f0fc8" - } - } -} diff --git a/tests/testing_data/fl_infer_properties.json b/tests/testing_data/fl_infer_properties.json deleted file mode 100644 index 6b40edd2ab..0000000000 --- a/tests/testing_data/fl_infer_properties.json +++ /dev/null @@ -1,76 +0,0 @@ -{ - "infer": { - "bundle_root": { - "description": "root path of the bundle.", - "required": true, - "id": "bundle_root" - }, - "device": { - "description": "target device to execute the bundle workflow.", - "required": true, - "id": "device" - }, - "dataset_dir": { - "description": "directory path of the dataset.", - "required": true, - "id": "dataset_dir" - }, - "dataset": { - "description": "PyTorch dataset object for the inference / evaluation logic.", - "required": true, - "id": "dataset" - }, - "evaluator": { - "description": "inference / evaluation workflow engine.", - "required": true, - "id": "evaluator" - }, - "network_def": { - "description": "network module for the inference.", - "required": true, - "id": "network_def" - }, - "inferer": { - "description": "MONAI Inferer object to execute the model computation in inference.", - "required": true, - "id": "inferer" - }, - "dataset_data": { - "description": "data source for the inference / evaluation dataset.", - "required": false, - "id": "dataset::data", - "refer_id": null - }, - "handlers": { - "description": "event-handlers for the inference / evaluation logic.", - "required": false, - "id": "handlers", - "refer_id": "evaluator::val_handlers" - }, - "preprocessing": { - "description": "preprocessing for the input data.", - "required": false, - "id": "preprocessing", - "refer_id": "dataset::transform" - }, - "postprocessing": { - "description": "postprocessing for the model output data.", - "required": false, - "id": "postprocessing", - "refer_id": "evaluator::postprocessing" - }, - "key_metric": { - "description": "the key metric during evaluation.", - "required": false, - "id": "key_metric", - "refer_id": "evaluator::key_val_metric" - } - }, - "meta": { - "version": { - "description": "version of the inference configuration.", - "required": true, - "id": "_meta_::version" - } - } -} diff --git a/tests/testing_data/image0.jpeg b/tests/testing_data/image0.jpeg deleted file mode 100644 index 5025e5f992..0000000000 Binary files a/tests/testing_data/image0.jpeg and /dev/null differ diff --git a/tests/testing_data/image1.jpeg b/tests/testing_data/image1.jpeg deleted file mode 100644 index 462db4bbc2..0000000000 Binary files a/tests/testing_data/image1.jpeg and /dev/null differ diff --git a/tests/testing_data/inference.json b/tests/testing_data/inference.json deleted file mode 100644 index 7b1f9c20cf..0000000000 --- a/tests/testing_data/inference.json +++ /dev/null @@ -1,122 +0,0 @@ -{ - "dataset_dir": "/workspace/data/Task09_Spleen", - "bundle_root": "will override", - "output_dir": "need override", - "prediction_shape": "prediction shape:", - "import_glob": "$import glob", - "device": "$torch.device('cpu')", - "print_test_name": "$print('json_test')", - "print_glob_file": "$print(glob.__file__)", - "network_def": { - "_target_": "UNet", - "spatial_dims": 3, - "in_channels": 1, - "out_channels": 2, - "channels": [ - 2, - 2, - 4, - 8, - 4 - ], - "strides": [ - 2, - 2, - 2, - 2 - ], - "num_res_units": 2, - "norm": "batch" - }, - "network": "need override", - "preprocessing": { - "_target_": "Compose", - "transforms": [ - { - "_target_": "LoadImaged", - "keys": "image" - }, - { - "_target_": "EnsureChannelFirstd", - "keys": "image" - }, - { - "_target_": "ScaleIntensityd", - "keys": "image" - }, - { - "_target_": "RandRotated", - "_disabled_": true, - "keys": "image" - } - ] - }, - "dataset": { - "_target_": "need override", - "data": "@_meta_#datalist", - "transform": "@preprocessing" - }, - "dataloader": { - "_target_": "DataLoader", - "dataset": "@dataset", - "batch_size": 1, - "shuffle": false, - "num_workers": 4 - }, - "inferer": { - "_target_": "SlidingWindowInferer", - "roi_size": [ - 64, - 64, - 32 - ], - "sw_batch_size": 4, - "overlap": 0.25 - }, - "postprocessing": { - "_target_": "Compose", - "transforms": [ - { - "_target_": "Activationsd", - "keys": "pred", - "softmax": true - }, - { - "_target_": "AsDiscreted", - "keys": "pred", - "argmax": true - }, - { - "_target_": "SaveImaged", - "keys": "pred", - "output_dir": "@output_dir" - }, - { - "_target_": "Lambdad", - "keys": "pred", - "func": "$lambda x: print(@prediction_shape + str(x.shape))", - "overwrite": false - } - ] - }, - "evaluator": { - "_target_": "SupervisedEvaluator", - "_requires_": [ - "@print_test_name", - "@print_glob_file", - "$print('test_in_line_json')" - ], - "device": "@device", - "val_data_loader": "@dataloader", - "network": "@network", - "inferer": "@inferer", - "postprocessing": "@postprocessing", - "amp": false - }, - "initialize": [ - "$monai.utils.set_determinism(0)" - ], - "run": [ - "$@evaluator.run()" - ] -} diff --git a/tests/testing_data/inference.yaml b/tests/testing_data/inference.yaml deleted file mode 100644 index 0343ea0bae..0000000000 --- a/tests/testing_data/inference.yaml +++ /dev/null @@ -1,89 +0,0 @@ ---- -dataset_dir: "/workspace/data/Task09_Spleen" -bundle_root: "will override" -output_dir: "need override" -prediction_shape: "prediction shape:" -device: "$torch.device('cpu')" -print_test_name: "$print('yaml_test')" -network_def: - _target_: UNet - spatial_dims: 3 - in_channels: 1 - out_channels: 2 - channels: - - 2 - - 2 - - 4 - - 8 - - 4 - strides: - - 2 - - 2 - - 2 - - 2 - num_res_units: 2 - norm: batch -network: need override -preprocessing: - _target_: Compose - transforms: - - _target_: LoadImaged - keys: image - - _target_: EnsureChannelFirstd - keys: image - - _target_: ScaleIntensityd - keys: image - - _target_: RandRotated - _disabled_: true - keys: image -dataset: - _target_: need override - data: "@_meta_#datalist" - transform: "@preprocessing" -dataloader: - _target_: DataLoader - dataset: "@dataset" - batch_size: 1 - shuffle: false - num_workers: 4 -inferer: - _target_: SlidingWindowInferer - roi_size: - - 64 - - 64 - - 32 - sw_batch_size: 4 - overlap: 0.25 -postprocessing: - _target_: Compose - transforms: - - _target_: Activationsd - keys: pred - softmax: true - - _target_: AsDiscreted - keys: pred - argmax: true - - _target_: SaveImaged - keys: pred - output_dir: "@output_dir" - - _target_: Lambdad - keys: pred - func: "$lambda x: print(@prediction_shape + str(x.shape))" - overwrite: false -evaluator: - _target_: SupervisedEvaluator - _requires_: - - "$print('test_in_line_yaml')" - - "@print_test_name" - device: "@device" - val_data_loader: "@dataloader" - network: "@network" - inferer: "@inferer" - postprocessing: "@postprocessing" - amp: false -initialize: - - "$monai.utils.set_determinism(0)" -run: - - "$@evaluator.run()" -finalize: - - "$print('test finalize section.')" diff --git a/tests/testing_data/integration_answers.py b/tests/testing_data/integration_answers.py deleted file mode 100644 index e02b9ae995..0000000000 --- a/tests/testing_data/integration_answers.py +++ /dev/null @@ -1,672 +0,0 @@ -# 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. - -from __future__ import annotations - -import numpy as np - -EXPECTED_ANSWERS = [ - { # test answers for PyTorch 2.0 - "integration_segmentation_3d": { - "losses": [ - 0.5430086106061935, - 0.47010003924369814, - 0.4453376233577728, - 0.451901963353157, - 0.4398456811904907, - 0.43450237810611725, - ], - "best_metric": 0.9329540133476257, - "infer_metric": 0.9330471754074097, - "output_sums": [ - 0.14212507078546172, - 0.15199039602949577, - 0.15133471939291526, - 0.13967984811021827, - 0.18831614355832332, - 0.1694076821827231, - 0.14663931509271658, - 0.16788710637623733, - 0.1569452710008219, - 0.17907130698392254, - 0.16244092698688475, - 0.1679350345855819, - 0.14437674754879065, - 0.11355098478396568, - 0.161660275855964, - 0.20082478187698194, - 0.17575491677668853, - 0.0974593860605401, - 0.19366775441539907, - 0.20293016863409002, - 0.19610441127101647, - 0.20812173772459808, - 0.16184212006067655, - 0.13185211452732482, - 0.14824716961304257, - 0.14229818359602905, - 0.23141282114085215, - 0.1609268635938338, - 0.14825300029123678, - 0.10286266811772046, - 0.11873484714087054, - 0.1296615212510262, - 0.11386621034856693, - 0.15203351148564773, - 0.16300823766585265, - 0.1936726544485426, - 0.2227251185536394, - 0.18067789917505797, - 0.19005874127683337, - 0.07462121515702229, - ], - } - }, - { # test answers for PyTorch 1.12.1 - "integration_classification_2d": { - "losses": [0.776835828070428, 0.1615355300011149, 0.07492854832938523, 0.04591309238865877], - "best_metric": 0.9999184380485994, - "infer_prop": [1029, 896, 980, 1033, 961, 1046], - }, - "integration_segmentation_3d": { - "losses": [ - 0.5428894340991974, - 0.47331981360912323, - 0.4482289582490921, - 0.4452722787857056, - 0.4289989799261093, - 0.4359133839607239, - ], - "best_metric": 0.933259129524231, - "infer_metric": 0.9332860708236694, - "output_sums": [ - 0.142167581604417, - 0.15195543400875847, - 0.1512754523215521, - 0.13962938779108452, - 0.18835719348918614, - 0.16943498693483486, - 0.1465709827477569, - 0.16806483607477135, - 0.1568844609697224, - 0.17911090857818554, - 0.16252098157181355, - 0.16806016936625395, - 0.14430124467305516, - 0.11316135548315168, - 0.16183771025615476, - 0.2009426314066978, - 0.1760258010156966, - 0.09700864497950844, - 0.1938495370314683, - 0.20319147575335647, - 0.19629641404249798, - 0.20852344793102826, - 0.16185073630020633, - 0.13184196857669161, - 0.1480959525354053, - 0.14232924377085415, - 0.23177739882790951, - 0.16094610375534632, - 0.14832771888168225, - 0.10259365443625812, - 0.11850632233099603, - 0.1294100326098242, - 0.11364228279017609, - 0.15181947897584674, - 0.16319358155815072, - 0.1940284526521386, - 0.22306137879066443, - 0.18083137638759522, - 0.1903135237574692, - 0.07402317520619131, - ], - }, - "integration_workflows": { - "best_metric": 0.9219646483659745, - "infer_metric": 0.921751058101654, - "output_sums": [ - 0.14183664321899414, - 0.1513957977294922, - 0.13804054260253906, - 0.13356828689575195, - 0.18456125259399414, - 0.16363763809204102, - 0.14090299606323242, - 0.16649389266967773, - 0.15651893615722656, - 0.17655134201049805, - 0.16116666793823242, - 0.1644763946533203, - 0.14383649826049805, - 0.11055326461791992, - 0.16080379486083984, - 0.19629907608032227, - 0.17441415786743164, - 0.053577423095703125, - 0.19043779373168945, - 0.19904804229736328, - 0.19526052474975586, - 0.20304107666015625, - 0.16030025482177734, - 0.13170623779296875, - 0.15118932723999023, - 0.13686418533325195, - 0.22668886184692383, - 0.1611471176147461, - 0.1472463607788086, - 0.10427379608154297, - 0.11962461471557617, - 0.1305704116821289, - 0.11204910278320312, - 0.15171337127685547, - 0.15962505340576172, - 0.18976259231567383, - 0.21649456024169922, - 0.17761802673339844, - 0.18516874313354492, - 0.03636503219604492, - ], - "best_metric_2": 0.9219559609889985, - "infer_metric_2": 0.9217371672391892, - "output_sums_2": [ - 0.14187288284301758, - 0.15140819549560547, - 0.13802719116210938, - 0.1335887908935547, - 0.18454980850219727, - 0.1636652946472168, - 0.14091157913208008, - 0.16653108596801758, - 0.15651702880859375, - 0.17658615112304688, - 0.1611957550048828, - 0.16448307037353516, - 0.14385128021240234, - 0.1105203628540039, - 0.16085100173950195, - 0.19626951217651367, - 0.17442035675048828, - 0.053586483001708984, - 0.19042730331420898, - 0.1990523338317871, - 0.1952815055847168, - 0.20303773880004883, - 0.16034317016601562, - 0.13172531127929688, - 0.15118741989135742, - 0.1368694305419922, - 0.22667837142944336, - 0.16119050979614258, - 0.14726591110229492, - 0.10426473617553711, - 0.11961841583251953, - 0.13054800033569336, - 0.11203193664550781, - 0.15172529220581055, - 0.15963029861450195, - 0.18975019454956055, - 0.21646499633789062, - 0.17763566970825195, - 0.18517112731933594, - 0.03638744354248047, - ], - }, - }, - { # test answers for cuda 10.x - "integration_classification_2d": { - "losses": [0.777176220515731, 0.16019743723664315, 0.07480076164197011, 0.045643698364780966], - "best_metric": 0.9999418774120775, - "infer_prop": [1030, 897, 980, 1033, 960, 1048], - }, - "integration_segmentation_3d": { - "losses": [ - 0.5326887160539627, - 0.4685510128736496, - 0.46245276033878324, - 0.4411882758140564, - 0.4198471873998642, - 0.43021280467510226, - ], - "best_metric": 0.931993305683136, - "infer_metric": 0.9326668977737427, - "output_sums": [ - 0.1418775228871769, - 0.15188869120317386, - 0.15140863737688195, - 0.1396146850007127, - 0.18784343811575696, - 0.16909487431163164, - 0.14649608249452073, - 0.1677767130878611, - 0.1568122289811143, - 0.17874181729735056, - 0.16213703658980205, - 0.16754335171970686, - 0.14444824920997243, - 0.11432402622850306, - 0.16143210936221247, - 0.20055289634107482, - 0.17543571757219317, - 0.09920729163334538, - 0.19297325815057875, - 0.2023200127892273, - 0.1956677579845722, - 0.20774045016425718, - 0.16193278944159428, - 0.13174198906539808, - 0.14830508550670007, - 0.14241105864278342, - 0.23090631643085724, - 0.16056153813499532, - 0.1480353269419819, - 0.10318719171632634, - 0.11867462580989198, - 0.12997011485830187, - 0.11401220332210203, - 0.15242746700662088, - 0.1628489107974574, - 0.19327235354175412, - 0.22184902863377548, - 0.18028049625972334, - 0.18958059106892552, - 0.07884601267057013, - ], - }, - "integration_workflows": { - "best_metric": 0.9217087924480438, - "infer_metric": 0.9214379042387009, - "output_sums": [ - 0.14209461212158203, - 0.15126705169677734, - 0.13800382614135742, - 0.1338181495666504, - 0.1850571632385254, - 0.16372442245483398, - 0.14059066772460938, - 0.16674423217773438, - 0.15653657913208008, - 0.17690563201904297, - 0.16154909133911133, - 0.16521310806274414, - 0.14388608932495117, - 0.1103353500366211, - 0.1609959602355957, - 0.1967010498046875, - 0.1746964454650879, - 0.05329275131225586, - 0.19098854064941406, - 0.19976520538330078, - 0.19576644897460938, - 0.20346736907958984, - 0.1601848602294922, - 0.1316051483154297, - 0.1511220932006836, - 0.13670969009399414, - 0.2276287078857422, - 0.1611800193786621, - 0.14751672744750977, - 0.10413789749145508, - 0.11944007873535156, - 0.1305546760559082, - 0.11204719543457031, - 0.15145111083984375, - 0.16007614135742188, - 0.1904129981994629, - 0.21741962432861328, - 0.17812013626098633, - 0.18587207794189453, - 0.03605222702026367, - ], - "best_metric_2": 0.9210659921169281, - "infer_metric_2": 0.9208109736442566, - "output_sums_2": [ - 0.14227628707885742, - 0.1515035629272461, - 0.13819408416748047, - 0.13402271270751953, - 0.18525266647338867, - 0.16388607025146484, - 0.14076614379882812, - 0.16694307327270508, - 0.15677356719970703, - 0.1771831512451172, - 0.16172313690185547, - 0.1653728485107422, - 0.14413118362426758, - 0.11057281494140625, - 0.16121912002563477, - 0.19680166244506836, - 0.1748638153076172, - 0.053426265716552734, - 0.19117307662963867, - 0.19996356964111328, - 0.1959366798400879, - 0.20363712310791016, - 0.16037797927856445, - 0.13180780410766602, - 0.1513657569885254, - 0.13686084747314453, - 0.2277364730834961, - 0.16137409210205078, - 0.1476879119873047, - 0.10438394546508789, - 0.11967992782592773, - 0.13080739974975586, - 0.11226606369018555, - 0.15168476104736328, - 0.1602616310119629, - 0.190582275390625, - 0.21756458282470703, - 0.17825984954833984, - 0.18604803085327148, - 0.036206722259521484, - ], - }, - }, - { # test answers for PyTorch 1.9 - "integration_workflows": { - "output_sums_2": [ - 0.14213180541992188, - 0.15153264999389648, - 0.13801145553588867, - 0.1338348388671875, - 0.18515968322753906, - 0.16404008865356445, - 0.14110612869262695, - 0.16686391830444336, - 0.15673542022705078, - 0.1772594451904297, - 0.16174745559692383, - 0.16518878936767578, - 0.1440296173095703, - 0.11033201217651367, - 0.1611781120300293, - 0.19660568237304688, - 0.17468547821044922, - 0.053053855895996094, - 0.1909656524658203, - 0.19952869415283203, - 0.1957845687866211, - 0.2034916877746582, - 0.16042661666870117, - 0.13193607330322266, - 0.15104389190673828, - 0.13695430755615234, - 0.22720861434936523, - 0.16157913208007812, - 0.14759159088134766, - 0.10379791259765625, - 0.11937189102172852, - 0.1306462287902832, - 0.11205482482910156, - 0.15182113647460938, - 0.16006708145141602, - 0.19011592864990234, - 0.21713829040527344, - 0.17794132232666016, - 0.18584394454956055, - 0.03577899932861328, - ] - }, - "integration_segmentation_3d": { # for the mixed readers - "losses": [ - 0.5645154356956482, - 0.4984356611967087, - 0.472334086894989, - 0.47419720590114595, - 0.45881829261779783, - 0.43097741305828097, - ], - "best_metric": 0.9325698614120483, - "infer_metric": 0.9326590299606323, - }, - }, - { # test answers for PyTorch 1.13 - "integration_workflows": { - "output_sums_2": [ - 0.14264830205979873, - 0.15264129328718357, - 0.1519652511118344, - 0.14003114557361543, - 0.18870416611118465, - 0.1699260498246968, - 0.14727475398203582, - 0.16870874483246967, - 0.15757932277023196, - 0.1797779694564011, - 0.16310501082450635, - 0.16850569170136015, - 0.14472958359864832, - 0.11402527744419455, - 0.16217657428257873, - 0.20135486560244975, - 0.17627557567092866, - 0.09802074024435596, - 0.19418729084978026, - 0.20339278025379662, - 0.1966174446916041, - 0.20872528599049203, - 0.16246183433492764, - 0.1323750751202327, - 0.14830347036335728, - 0.14300732028781024, - 0.23163101813922762, - 0.1612925258625139, - 0.1489573676973957, - 0.10299491921717041, - 0.11921404797064328, - 0.1300212751422368, - 0.11437829790254125, - 0.1524755276727056, - 0.16350584736767904, - 0.19424317961257148, - 0.2229762916892286, - 0.18121074825540173, - 0.19064286213535897, - 0.0747544243069024, - ] - }, - "integration_segmentation_3d": { # for the mixed readers - "losses": [ - 0.5451162219047546, - 0.4709601759910583, - 0.45201429128646853, - 0.4443251401185989, - 0.4341257899999619, - 0.4350819975137711, - ], - "best_metric": 0.9316844940185547, - "infer_metric": 0.9316383600234985, - }, - }, - { # test answers for cuda 12 - "integration_segmentation_3d": { - "losses": [ - 0.5362162500619888, - 0.4704935997724533, - 0.4335438072681427, - 0.4507470965385437, - 0.45187077224254607, - 0.4363303750753403, - ], - "best_metric": 0.9334161877632141, - "infer_metric": 0.9335371851921082, - "output_sums": [ - 0.14210400101844414, - 0.1521489829835625, - 0.15127096315211278, - 0.13992817339153868, - 0.1884040828001848, - 0.16929503899789516, - 0.14662516818085808, - 0.16803982264111883, - 0.1570018930834878, - 0.17916684191571494, - 0.1626376090146162, - 0.1680113549677271, - 0.1446708736188978, - 0.1140289628362559, - 0.16191495673888556, - 0.20066696225510708, - 0.17581812459936835, - 0.09836918048666465, - 0.19355007524499268, - 0.20291004237066343, - 0.19606797329772976, - 0.2082113232291515, - 0.16189564397603906, - 0.13203990336741953, - 0.14849477534402156, - 0.14250633066863938, - 0.23139529505006795, - 0.16079877619802546, - 0.14821067071610583, - 0.10302449386782145, - 0.11876349315302756, - 0.13006925219380802, - 0.11431448379763984, - 0.15254606148569302, - 0.16317147221367873, - 0.19376668030880526, - 0.22260597124465822, - 0.18085088544070227, - 0.19010916899493174, - 0.07748195410499427, - ], - } - }, - { # test answers for 23.02 - "integration_segmentation_3d": { - "losses": [ - 0.5401686698198318, - 0.4789864182472229, - 0.4417317628860474, - 0.44183324575424193, - 0.4418945342302322, - 0.44213996827602386, - ], - "best_metric": 0.9316274523735046, - "infer_metric": 0.9321609735488892, - "output_sums": [ - 0.14212507078546172, - 0.15199039602949577, - 0.15133471939291526, - 0.13967984811021827, - 0.18831614355832332, - 0.1694076821827231, - 0.14663931509271658, - 0.16788710637623733, - 0.1569452710008219, - 0.17907130698392254, - 0.16244092698688475, - 0.1679350345855819, - 0.14437674754879065, - 0.11355098478396568, - 0.161660275855964, - 0.20082478187698194, - 0.17575491677668853, - 0.0974593860605401, - 0.19366775441539907, - 0.20293016863409002, - 0.19610441127101647, - 0.20812173772459808, - 0.16184212006067655, - 0.13185211452732482, - 0.14824716961304257, - 0.14229818359602905, - 0.23141282114085215, - 0.1609268635938338, - 0.14825300029123678, - 0.10286266811772046, - 0.11873484714087054, - 0.1296615212510262, - 0.11386621034856693, - 0.15203351148564773, - 0.16300823766585265, - 0.1936726544485426, - 0.2227251185536394, - 0.18067789917505797, - 0.19005874127683337, - 0.07462121515702229, - ], - } - }, - { # test answers for 24.03 - "integration_segmentation_3d": { - "losses": [ - 0.5442982316017151, - 0.4741817444562912, - 0.4535954713821411, - 0.44163046181201937, - 0.4307525992393494, - 0.428487154841423, - ], - "best_metric": 0.9314384460449219, - "infer_metric": 0.9315622448921204, - "output_sums": [ - 0.14268704426414708, - 0.1528672845845743, - 0.1521782248125706, - 0.14028769128068194, - 0.1889830671664784, - 0.16999075690664475, - 0.14736282992708227, - 0.16877952654821815, - 0.15779597155181269, - 0.17987829927082263, - 0.16320253928314676, - 0.16854299322173155, - 0.14497470986956967, - 0.11437140546369519, - 0.1624117412960871, - 0.20156009294443875, - 0.1764654154256958, - 0.0982348259217418, - 0.1942436068604293, - 0.20359421536407518, - 0.19661953116976483, - 0.2088326101468625, - 0.16273043545239807, - 0.1326107887439663, - 0.1489245275752285, - 0.143107476635514, - 0.23189027677929547, - 0.1613818424566088, - 0.14889532196775188, - 0.10332622984492143, - 0.11940054688302351, - 0.13040496302762658, - 0.11472123087193181, - 0.15307044007394474, - 0.16371989575844717, - 0.1942898223272055, - 0.2230120930471398, - 0.1814679187634795, - 0.19069496508164732, - 0.07537197031940022, - ], - } - }, -] - - -def test_integration_value(test_name, key, data, rtol=1e-2): - for idx, expected in enumerate(EXPECTED_ANSWERS): - if test_name not in expected: - continue - if key not in expected[test_name]: - continue - value = expected[test_name][key] - if np.allclose(data, value, rtol=rtol): - print(f"matched {idx} result of {test_name}, {key}, {rtol}.") - return True - raise ValueError(f"no matched results for {test_name}, {key}. {data}.") diff --git a/tests/testing_data/kitty_test.jpg b/tests/testing_data/kitty_test.jpg deleted file mode 100644 index f103760de5..0000000000 Binary files a/tests/testing_data/kitty_test.jpg and /dev/null differ diff --git a/tests/testing_data/logging.conf b/tests/testing_data/logging.conf deleted file mode 100644 index 2e3404e0ab..0000000000 --- a/tests/testing_data/logging.conf +++ /dev/null @@ -1,27 +0,0 @@ -[loggers] -keys=root,ignite.engine.SupervisedEvaluator - -[handlers] -keys=consoleHandler - -[formatters] -keys=fullFormatter - -[logger_root] -level=INFO -handlers=consoleHandler - -[logger_ignite.engine.SupervisedEvaluator] -level=INFO -handlers=consoleHandler -qualname=ignite.engine.SupervisedEvaluator -propagate=0 - -[handler_consoleHandler] -class=StreamHandler -level=INFO -formatter=fullFormatter -args=(sys.stdout,) - -[formatter_fullFormatter] -format=%(asctime)s - %(name)s - %(levelname)s - %(message)s diff --git a/tests/testing_data/matshow3d_patch_test.png b/tests/testing_data/matshow3d_patch_test.png deleted file mode 100644 index 0a4632a763..0000000000 Binary files a/tests/testing_data/matshow3d_patch_test.png and /dev/null differ diff --git a/tests/testing_data/matshow3d_rgb_test.png b/tests/testing_data/matshow3d_rgb_test.png deleted file mode 100644 index 7c8e224c0e..0000000000 Binary files a/tests/testing_data/matshow3d_rgb_test.png and /dev/null differ diff --git a/tests/testing_data/matshow3d_test.png b/tests/testing_data/matshow3d_test.png deleted file mode 100644 index d720a0c407..0000000000 Binary files a/tests/testing_data/matshow3d_test.png and /dev/null differ diff --git a/tests/testing_data/metadata.json b/tests/testing_data/metadata.json deleted file mode 100644 index 29737e3a9d..0000000000 --- a/tests/testing_data/metadata.json +++ /dev/null @@ -1,76 +0,0 @@ -{ - "schema": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/meta_schema_20240725.json", - "version": "0.1.0", - "changelog": { - "0.1.0": "complete the model package", - "0.0.1": "initialize the model package structure" - }, - "monai_version": "0.9.0", - "pytorch_version": "1.10.0", - "numpy_version": "1.21.2", - "required_packages_version": { - "nibabel": "3.2.1" - }, - "task": "Decathlon spleen segmentation", - "description": "A pre-trained model for volumetric (3D) segmentation of the spleen from CT image", - "authors": "MONAI team", - "copyright": "Copyright (c) MONAI Consortium", - "data_source": "Task09_Spleen.tar from http://medicaldecathlon.com/", - "data_type": "dicom", - "image_classes": "single channel data, intensity scaled to [0, 1]", - "label_classes": "single channel data, 1 is spleen, 0 is everything else", - "pred_classes": "2 channels OneHot data, channel 1 is spleen, channel 0 is background", - "eval_metrics": { - "mean_dice": 0.96 - }, - "intended_use": "This is an example, not to be used for diagnostic purposes", - "references": [ - "Xia, Yingda, et al. '3D Semi-Supervised Learning with Uncertainty-Aware Multi-View Co-Training. arXiv preprint arXiv:1811.12506 (2018). https://arxiv.org/abs/1811.12506.", - "Kerfoot E., Clough J., Oksuz I., Lee J., King A.P., Schnabel J.A. (2019) Left-Ventricle Quantification Using Residual U-Net. In: Pop M. et al. (eds) Statistical Atlases and Computational Models of the Heart. Atrial Segmentation and LV Quantification Challenges. STACOM 2018. Lecture Notes in Computer Science, vol 11395. Springer, Cham. https://doi.org/10.1007/978-3-030-12029-0_40" - ], - "network_data_format": { - "inputs": { - "image": { - "type": "image", - "format": "magnitude", - "num_channels": 1, - "spatial_shape": [ - 160, - 160, - 160 - ], - "dtype": "float32", - "value_range": [ - 0, - 1 - ], - "is_patch_data": false, - "channel_def": { - "0": "image" - } - } - }, - "outputs": { - "pred": { - "type": "image", - "format": "segmentation", - "num_channels": 2, - "spatial_shape": [ - 160, - 160, - 160 - ], - "dtype": "float32", - "value_range": [ - 0, - 1 - ], - "is_patch_data": false, - "channel_def": { - "0": "background", - "1": "spleen" - } - } - } - } -} diff --git a/tests/testing_data/multi_gpu_evaluate.json b/tests/testing_data/multi_gpu_evaluate.json deleted file mode 100644 index 37286cfb7a..0000000000 --- a/tests/testing_data/multi_gpu_evaluate.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "device": "$torch.device(f'cuda:{dist.get_rank()}')", - "network": { - "_target_": "torch.nn.parallel.DistributedDataParallel", - "module": "$@network_def.to(@device)", - "device_ids": [ - "@device" - ] - }, - "validate#sampler": { - "_target_": "DistributedSampler", - "dataset": "@validate#dataset", - "even_divisible": false, - "shuffle": false - }, - "validate#dataloader#sampler": "@validate#sampler", - "initialize": [ - "$import torch.distributed as dist", - "$dist.is_initialized() or dist.init_process_group(backend='nccl')", - "$torch.cuda.set_device(@device)", - "$setattr(torch.backends.cudnn, 'benchmark', True)", - "$import logging", - "$@validate#evaluator.logger.setLevel(logging.WARNING if dist.get_rank() > 0 else logging.INFO)" - ], - "run": [ - "$@validate#evaluator.run()" - ], - "finalize": [ - "$dist.destroy_process_group()" - ] -} diff --git a/tests/testing_data/multi_gpu_train.json b/tests/testing_data/multi_gpu_train.json deleted file mode 100644 index a617e53dfd..0000000000 --- a/tests/testing_data/multi_gpu_train.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "device": "$torch.device(f'cuda:{dist.get_rank()}')", - "network": { - "_target_": "torch.nn.parallel.DistributedDataParallel", - "module": "$@network_def.to(@device)", - "device_ids": [ - "@device" - ] - }, - "train#sampler": { - "_target_": "DistributedSampler", - "dataset": "@train#dataset", - "even_divisible": true, - "shuffle": true - }, - "train#dataloader#sampler": "@train#sampler", - "train#dataloader#shuffle": false, - "initialize": [ - "$import torch.distributed as dist", - "$dist.is_initialized() or dist.init_process_group(backend='nccl')", - "$torch.cuda.set_device(@device)", - "$monai.utils.set_determinism(seed=123)", - "$setattr(torch.backends.cudnn, 'benchmark', True)", - "$import logging", - "$@train#trainer.logger.setLevel(logging.WARNING if dist.get_rank() > 0 else logging.INFO)", - "$@validate#evaluator.logger.setLevel(logging.WARNING if dist.get_rank() > 0 else logging.INFO)" - ], - "run": [ - "$@train#trainer.run()" - ], - "finalize": [ - "$dist.destroy_process_group()" - ] -} diff --git a/tests/testing_data/python_workflow_properties.json b/tests/testing_data/python_workflow_properties.json deleted file mode 100644 index cd4295839a..0000000000 --- a/tests/testing_data/python_workflow_properties.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "infer": { - "bundle_root": { - "description": "root path of the bundle.", - "required": true, - "id": "bundle_root" - }, - "device": { - "description": "target device to execute the bundle workflow.", - "required": true, - "id": "device" - }, - "inferer": { - "description": "MONAI Inferer object to execute the model computation in inference.", - "required": true, - "id": "inferer" - } - }, - "meta": { - "version": { - "description": "version of the inference configuration.", - "required": true, - "id": "_meta_::version" - } - } -} diff --git a/tests/testing_data/reoriented_anat_moved.nii b/tests/testing_data/reoriented_anat_moved.nii deleted file mode 100644 index 2f2411d115..0000000000 Binary files a/tests/testing_data/reoriented_anat_moved.nii 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/testing_data/responsive_inference.json b/tests/testing_data/responsive_inference.json deleted file mode 100644 index 16d953d38e..0000000000 --- a/tests/testing_data/responsive_inference.json +++ /dev/null @@ -1,101 +0,0 @@ -{ - "imports": [ - "$from collections import defaultdict" - ], - "bundle_root": "will override", - "device": "$torch.device('cpu')", - "network_def": { - "_target_": "UNet", - "spatial_dims": 3, - "in_channels": 1, - "out_channels": 2, - "channels": [ - 2, - 2, - 4, - 8, - 4 - ], - "strides": [ - 2, - 2, - 2, - 2 - ], - "num_res_units": 2, - "norm": "batch" - }, - "network": "$@network_def.to(@device)", - "dataflow": "$defaultdict()", - "preprocessing": { - "_target_": "Compose", - "transforms": [ - { - "_target_": "EnsureChannelFirstd", - "keys": "image" - }, - { - "_target_": "ScaleIntensityd", - "keys": "image" - }, - { - "_target_": "RandRotated", - "_disabled_": true, - "keys": "image" - } - ] - }, - "dataset": { - "_target_": "Dataset", - "data": [ - "@dataflow" - ], - "transform": "@preprocessing" - }, - "dataloader": { - "_target_": "DataLoader", - "dataset": "@dataset", - "batch_size": 1, - "shuffle": false, - "num_workers": 0 - }, - "inferer": { - "_target_": "SlidingWindowInferer", - "roi_size": [ - 64, - 64, - 32 - ], - "sw_batch_size": 4, - "overlap": 0.25 - }, - "postprocessing": { - "_target_": "Compose", - "transforms": [ - { - "_target_": "Activationsd", - "keys": "pred", - "softmax": true - }, - { - "_target_": "AsDiscreted", - "keys": "pred", - "argmax": true - } - ] - }, - "evaluator": { - "_target_": "SupervisedEvaluator", - "device": "@device", - "val_data_loader": "@dataloader", - "network": "@network", - "inferer": "@inferer", - "postprocessing": "@postprocessing", - "amp": false, - "epoch_length": 1 - }, - "run": [ - "$@evaluator.run()", - "$@dataflow.update(@evaluator.state.output[0])" - ] -} diff --git a/tests/testing_data/signal.npy b/tests/testing_data/signal.npy deleted file mode 100755 index 7803f0d371..0000000000 Binary files a/tests/testing_data/signal.npy and /dev/null differ diff --git a/tests/testing_data/threadcontainer_plot_test.png b/tests/testing_data/threadcontainer_plot_test.png deleted file mode 100644 index af742a8812..0000000000 Binary files a/tests/testing_data/threadcontainer_plot_test.png and /dev/null differ diff --git a/tests/testing_data/transform_metatensor_cases.yaml b/tests/testing_data/transform_metatensor_cases.yaml deleted file mode 100644 index 1c79d4e4ce..0000000000 --- a/tests/testing_data/transform_metatensor_cases.yaml +++ /dev/null @@ -1,199 +0,0 @@ ---- -input_keys: [image, segs] -test_device: "$torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')" -init_affine: "$np.array([[-2, 0, 0, 90], [0, 2, 0, -126], [0, 0, 2, -72], [0, 0, 0, 1]], dtype=np.float64)" -init_shape: [1, 91, 109, 91] -TEST_CASE_1: - _target_: Compose - transforms: - - _target_: LoadImageD - keys: "@input_keys" - ensure_channel_first: True - image_only: True - - _target_: ToDeviced - keys: "@input_keys" - device: "@test_device" - - _target_: CenterScaleCropD - keys: "@input_keys" - roi_scale: 0.98 - - _target_: CropForegroundD - keys: "@input_keys" - source_key: seg - start_coord_key: null - end_coord_key: null - k_divisible: 5 - - _target_: RandSpatialCropD - keys: "@input_keys" - roi_size: [76, 87, 73] - random_size: True - - _target_: RandScaleCropD - keys: "@input_keys" - roi_scale: 0.9 - random_size: True - - _target_: ResizeWithPadOrCropD - keys: "@input_keys" - spatial_size: [32, 43, 54] - - _target_: DivisiblePadD - keys: "@input_keys" - k: 3 - -TEST_CASE_2: - _target_: Compose - transforms: - - _target_: LoadImaged - keys: "@input_keys" - ensure_channel_first: False - image_only: True - - _target_: ToDeviced - keys: "@input_keys" - device: "@test_device" - - _target_: EnsureChannelFirstd - keys: "@input_keys" - - _target_: ScaleIntensityRangePercentilesd - keys: "$@input_keys[0]" - lower: 4 - upper: 95 - b_min: 1 - b_max: 10 - - _target_: RandScaleIntensityd - keys: "$@input_keys[0]" - prob: 1.0 - factors: [5, 10] - - _target_: RandGaussianNoised - keys: "$@input_keys[0]" - prob: 1.0 - mean: 10.0 - std: 2.0 - - _target_: RandCoarseShuffled - keys: "$@input_keys[0]" - prob: 1.0 - holes: 2 - spatial_size: [10, 13, 18] - max_spatial_size: [14, 30, 57] - - _target_: DataStatsd - keys: "$@input_keys[0]" - - _target_: RandBiasFieldd - keys: "$@input_keys[0]" - prob: 1.0 - - _target_: RandGaussianSmoothd - keys: "$@input_keys[0]" - prob: 1.0 - - _target_: RandGaussianSharpend - keys: "$@input_keys[0]" - prob: 1.0 - - _target_: RandHistogramShiftd - keys: "$@input_keys[0]" - prob: 1.0 - - _target_: RandAdjustContrastd - keys: "$@input_keys[0]" - prob: 1.0 - - _target_: RandCoarseDropoutd - keys: "$@input_keys[0]" - prob: 1.0 - holes: 3 - spatial_size: [10, 13, 18] - max_spatial_size: [14, 30, 57] - - _target_: RandRicianNoised - keys: "$@input_keys[0]" - prob: 1.0 - -TEST_CASE_3: - _target_: Compose - transforms: - - _target_: LoadImageD - keys: "@input_keys" - ensure_channel_first: True - image_only: True - - _target_: CenterScaleCropD - keys: "@input_keys" - roi_scale: 0.98 - - _target_: CropForegroundD - keys: "@input_keys" - source_key: seg - start_coord_key: null - end_coord_key: null - k_divisible: 5 - - _target_: ToDeviced - keys: "@input_keys" - device: "@test_device" - - _target_: RandRotate90d - keys: "@input_keys" - prob: 1.0 - spatial_axes: [2, 1] - - _target_: Spacingd - keys: "@input_keys" - pixdim: [1.8, 2.1, 2.3] - - _target_: RandFlipd - keys: "@input_keys" - prob: 1.0 - spatial_axis: 2 - - _target_: RandAffined - keys: "@input_keys" - prob: 1.0 - spatial_size: [80, 91, 92] - rotate_range: 1.0 - scale_range: 0.1 - - _target_: Flipd - keys: "@input_keys" - spatial_axis: 2 - - _target_: Orientationd - keys: "@input_keys" - axcodes: "RPI" - - _target_: Affined - keys: "@input_keys" - shear_params: [0, 0.5, 0] - - _target_: Rotate90d - keys: "@input_keys" - spatial_axes: [1, 2] - - _target_: Zoomd - keys: "@input_keys" - zoom: 1.3 - - _target_: ScaleIntensityd - keys: "@input_keys" - minv: 0 - maxv: 10 - - _target_: RandAxisFlipD - keys: "@input_keys" - prob: 1.0 - - _target_: RandRotated - keys: "@input_keys" - prob: 1.0 - range_y: "$np.pi/3" - - _target_: RandZoomD - keys: "@input_keys" - prob: 1.0 - max_zoom: 1.2 - keep_size: True - - _target_: RandGaussianNoised - keys: "@input_keys" - prob: 1.0 - - _target_: ResizeWithPadOrCropD - keys: "@input_keys" - spatial_size: [71, 56, 80] - - _target_: Rand3DElasticd - keys: "@input_keys" - spatial_size: [71, 56, 80] - sigma_range: [5, 7] - magnitude_range: [50, 150] - prob: 1.0 - - _target_: Resized - keys: "@input_keys" - spatial_size: [72, 57, 82] - -TEST_CASE_1_answer: - load_shape: [1, 1, 33, 45, 54] - affine: "$np.array([[-2, 0, 0, 30], [0, 2, 0, -62], [0, 0, 2, -48], [0, 0, 0, 1]], dtype=np.float64)" - inv_affine: "@init_affine" - inv_shape: "@init_shape" - -TEST_CASE_2_answer: - load_shape: [1, 1, 91, 109, 91] - affine: "$np.array([[-2, 0, 0, 90], [0, 2, 0, -126], [0, 0, 2, -72], [0, 0, 0, 1]], dtype=np.float64)" - inv_affine: "@init_affine" - inv_shape: "@init_shape" - -TEST_CASE_3_answer: - load_shape: [1, 1, 72, 57, 82] - affine: "$np.array([[1.300558, -0.700765, -0.511861, -3.739605], [0.479723, -1.171149, 1.193079, -50.087933], [0.395736, 1.183532, 0.984201, -80.496605], [0, 0, 0, 1]], dtype=np.float64)" - inv_affine: "@init_affine" - inv_shape: "@init_shape" diff --git a/tests/testing_data/ultrasound_confidence_map/femur_input.png b/tests/testing_data/ultrasound_confidence_map/femur_input.png deleted file mode 100644 index 0343e58720..0000000000 Binary files a/tests/testing_data/ultrasound_confidence_map/femur_input.png and /dev/null differ diff --git a/tests/testing_data/ultrasound_confidence_map/femur_result.npy b/tests/testing_data/ultrasound_confidence_map/femur_result.npy deleted file mode 100644 index a3f322b113..0000000000 Binary files a/tests/testing_data/ultrasound_confidence_map/femur_result.npy and /dev/null differ diff --git a/tests/testing_data/ultrasound_confidence_map/neck_input.png b/tests/testing_data/ultrasound_confidence_map/neck_input.png deleted file mode 100644 index 74a64a9d90..0000000000 Binary files a/tests/testing_data/ultrasound_confidence_map/neck_input.png and /dev/null differ diff --git a/tests/testing_data/ultrasound_confidence_map/neck_result.npy b/tests/testing_data/ultrasound_confidence_map/neck_result.npy deleted file mode 100644 index 8bf760182c..0000000000 Binary files a/tests/testing_data/ultrasound_confidence_map/neck_result.npy and /dev/null differ 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/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..53f4053242 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.utils.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..00c144acb6 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.utils.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/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..f43d53865f 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.utils.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..453e8cf972 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.utils.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..675fbe2e40 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.utils.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..b3a93efd8e 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.utils.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..360e9139a7 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.utils.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..9a383b83a3 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.utils.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..133eb7ea63 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.utils.utils import TEST_NDARRAYS, NumpyImageTestCase2D, assert_allclose class TestScaleIntensityRangePercentilesd(NumpyImageTestCase2D): - def test_scaling(self): img = self.imt lower = 10 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..34fa4c6bb2 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.utils.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/test_apply.py b/tests/transforms/lazy/functional/test_apply.py similarity index 98% rename from tests/test_apply.py rename to tests/transforms/lazy/functional/test_apply.py index ca37e945ba..164de96dff 100644 --- a/tests/test_apply.py +++ b/tests/transforms/lazy/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.utils.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/lazy/functional/test_resample.py similarity index 96% rename from tests/test_resample.py rename to tests/transforms/lazy/functional/test_resample.py index 68b08b8b87..ad826aaeac 100644 --- a/tests/test_resample.py +++ b/tests/transforms/lazy/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.utils.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/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..18fa2904ca 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.utils.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..5fb38ee45f 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.utils.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..2dcdcd11a7 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.utils.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..fbd9443345 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.utils.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/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..cb34bb0726 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.utils.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..a20e1a6a09 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.utils.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..13860607e6 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.utils.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..baa7e19360 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.utils.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..7928b0fb2c 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.utils.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..89a273bc2d 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.utils.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..6928485067 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.utils.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..5e8af644aa 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.utils.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..f40f25a2fd 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.utils.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..301a037172 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.utils.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..2bb568ceba 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.utils.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..8b71a0e051 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.utils.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..edf7166a0f 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.utils.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..24f9a1c725 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.utils.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..049d64b84a 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.utils.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..4f89411c91 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.utils.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..ef5db64f53 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.utils.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..93ee7481f0 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.utils.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..8b93019ecc 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.utils.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..28d0d2166a 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.utils.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..5f8e553736 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.utils.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..ca7ec1637f 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.utils.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..a8c434ffc4 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.utils.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..4e5f1b97d6 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.utils.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..50e5b1daa6 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.utils.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..98ee951308 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.utils.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..3db07e787e 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.utils.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..12f64069cf 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.utils.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..793e5093dc 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.transforms.test_clip_intensity_percentiles import test_hard_clip_func, test_soft_clip_func +from tests.utils.utils import TEST_NDARRAYS, NumpyImageTestCase2D, NumpyImageTestCase3D, assert_allclose 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..49bfb8bb5e 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.utils.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..56aa60ce12 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.utils.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..d379d030ad 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.utils.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..d74fdd9c63 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.utils.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..0e61cc50c3 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.utils.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..1cc44054ed 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.utils.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..c82947544b 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.utils.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..8a35032c6a 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.utils.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..3067e68f9e 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.utils.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..6714bb4b08 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.utils.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 98% rename from tests/test_ensure_type.py rename to tests/transforms/test_ensure_type.py index 00b01898b3..9616d331e2 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.utils.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..9ac021c2fe 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.utils.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..6d518a904d 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.utils.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..9a2ac32cdd 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.utils.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..f2aefba4fb 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.utils.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..542f03b2d1 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.utils.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 96% rename from tests/test_flip.py rename to tests/transforms/test_flip.py index 789ec86920..20e849a03a 100644 --- a/tests/test_flip.py +++ b/tests/transforms/test_flip.py @@ -21,7 +21,7 @@ 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.utils.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 +34,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 96% rename from tests/test_flipd.py rename to tests/transforms/test_flipd.py index 1df6d34056..255e248131 100644 --- a/tests/test_flipd.py +++ b/tests/transforms/test_flipd.py @@ -22,7 +22,7 @@ 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.utils.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 +35,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..8f7408fe90 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.utils.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..7d22c74f49 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.utils.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..fa768d37e8 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.utils.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..6f66cf26d9 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.utils.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..de0563acfc 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.utils.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..2ac7eca46c 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.utils.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..802e92390f 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.utils.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..5fbd6d15b2 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.utils.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..cdb42838c9 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.utils.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..e36f45ed49 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.utils.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..387c1e3e58 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.utils.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..5f3995928f 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.utils.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..f064cd03b7 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.utils.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..674979f283 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.utils.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..d0d19d319f 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.utils.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..91a156c8be 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.utils.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..88588dfc1b 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.utils.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..c5a9be7224 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.utils.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..84e8373011 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.utils.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..5c7b032ec4 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.utils.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..fe9d717455 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.utils.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..effc47f436 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.utils.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..eaa9d4c501 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.utils.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..55e8dd9155 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.utils.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..6ebb62432c 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.utils.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..fca0d77ab3 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.utils.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..8fe9e9b980 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.utils.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..f9f852bf1f 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.utils.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..7747bb4130 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.utils.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..341a6afe91 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.utils.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..e3867d4524 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.utils.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 0207079d7d..0a557d96b4 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 assert_allclose, skip_if_downloading_fails, testing_data_config +from tests.utils.utils import 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") @@ -160,7 +160,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() @@ -380,7 +379,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..15f9ebf207 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.utils.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..a56d6c4e70 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.utils.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..807df7d2cd 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.utils.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..1a7663f0ac 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.utils.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..3362668be7 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.utils.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..a646d18a55 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.utils.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..3ef505c442 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.utils.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..6787299f95 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.utils.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..4c4c18a01a 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.utils.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..ff17e78515 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.utils.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..1585d43f54 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.utils.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..9b8993c8b9 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.utils.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 72ebf579e1..33a0f559da 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.utils.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..d2a805fc0c 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.utils.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..00c60de398 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.utils.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..2e6f39379c 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.utils.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 98% rename from tests/test_orientationd.py rename to tests/transforms/test_orientationd.py index b885266c69..66540fc80a 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.utils.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..e361394508 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.utils.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..9d50160b0a 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.utils.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..864ca6909e 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.utils.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..d4596ff46d 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.utils.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..1ac70592b8 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.utils.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..73ddc85ead 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.utils.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..9de8817cda 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.utils.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..fb7fbe5b5e 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.utils.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..c5fbb32dac 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.utils.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..2564bf2aab 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.utils.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..8340596c1d 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.utils.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..cfef3dd517 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.utils.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..a38655294f 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.utils.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..f3e28b56b8 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.utils.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..ac2763c1da 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.utils.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..d0d29c226e 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.utils.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..b93687e982 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.utils.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..70a71b1826 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.utils.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..0d9bc46415 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.utils.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..cea7246c50 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.utils.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..e0c26349c4 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.utils.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..42986fb9b4 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.utils.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..8281294308 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.utils.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..2aa2e73dd0 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.utils.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..cbf08dec81 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.utils.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..74a84cac7f 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.utils.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..3ce5e19ea8 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.utils.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..8daa853e9b 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.utils.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..c036d40eb3 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.utils.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..50bf9faae1 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.utils.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..6412afb284 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.utils.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..75f70d5fea 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.utils.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..e2a113a269 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.utils.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..8fbae69e18 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.utils.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..72ca029f7f 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.utils.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..4cbad3818f 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.utils.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..9731b898fb 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.utils.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..490ab99500 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.utils.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..f68b0cbbb9 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.utils.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..4f67406b0e 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.utils.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..584661c53d 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.utils.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..68274c188b 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.utils.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..6eb23f2787 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.utils.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..267afd1a4d 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.utils.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..1967e3d466 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.utils.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..1217b54063 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.utils.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..b89698540f 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.utils.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..1850cc7c51 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.utils.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..348181304b 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.utils.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..71f0c01705 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.utils.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..4ca1b015bf 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.utils.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..ba244c0fc7 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.utils.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..31bc481cce 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.utils.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..af0e8020ba 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.utils.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..57eaf7b218 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.utils.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..6780f79d87 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.utils.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..5822dfe4b6 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.utils.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..f3fae3adf4 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.utils.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..c54de27afc 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.utils.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..daf09c5dda 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.utils.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..136e607b11 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.utils.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..b93e3158ed 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.utils.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..3793b6c673 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.utils.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..ed59e164ab 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.utils.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..d7f5f490a0 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.utils.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..a1d816a30c 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.utils.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..b6116c66fe 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.utils.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..e18b46f751 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.utils.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..62b4765fe0 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.utils.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..bca4c57bf2 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.utils.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..620d742f3b 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.utils.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..4828518eee 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.utils.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..8900e5917b 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.transforms.test_resize_with_pad_or_crop import TESTS_PENDING_MODE +from tests.utils.utils import TEST_NDARRAYS_ALL, assert_allclose, pytorch_after 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..42741b3b20 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.utils.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 98% rename from tests/test_rotate.py rename to tests/transforms/test_rotate.py index 19fbd1409f..f07090bec9 100644 --- a/tests/test_rotate.py +++ b/tests/transforms/test_rotate.py @@ -22,7 +22,7 @@ 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.utils.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 +52,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 +90,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..016827cef5 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.utils.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..082c11a75d 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.utils.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..2b24282c33 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.utils.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..a01dd56129 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.utils.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 97% rename from tests/test_savitzky_golay_smoothd.py rename to tests/transforms/test_savitzky_golay_smoothd.py index 3bb4056046..dff3830aa0 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.utils.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..50f6e67d0f 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.utils.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..8f4926bd48 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.utils.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..b03a46ef63 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.utils.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..fe152bf048 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.utils.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..761d4b9f7d 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.utils.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..41071c4aaf 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.utils.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 94% rename from tests/test_shift_intensityd.py rename to tests/transforms/test_shift_intensityd.py index 22336b4415..a752eacc4a 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.utils.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..97648dca14 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.utils.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..6994338f5c 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.utils.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 91% rename from tests/test_signal_rand_add_squarepulse.py rename to tests/transforms/test_signal_rand_add_squarepulse.py index e1432029ea..bf103d1663 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.utils.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..6c1b631ee5 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.utils.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..a880261524 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.utils.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..2c795e7e18 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.utils.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..521aa25a91 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.utils.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..4059da9a7a 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.utils.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..da68b06225 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.utils.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..21e14626bc 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.utils.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..37f9fc2b6f 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.utils.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..6f3f5d6c65 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.utils.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..d98f17e923 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.utils.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..bfd23e0298 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.utils.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 95% rename from tests/test_threshold_intensity.py rename to tests/transforms/test_threshold_intensity.py index 97c80eebcd..20d7704bf2 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.utils.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..1c5cd04d6b 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.utils.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..c01912e398 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.utils.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..f1d28f902e 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.utils.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..61efbff33c 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.utils.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..e18f085939 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.utils.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..9c6a3ef967 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.utils.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..8822f5f8c5 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.utils.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..1f7212f8ca 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.utils.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..43f01e7945 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.utils.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..be029bfc6f 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.utils.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..c0066d6921 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.utils.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..1d762d2a82 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.utils.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..a31dd22c98 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.utils.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..77e12ed77b 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.utils.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..d489586683 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.utils.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..976c04bf15 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.utils.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..9adf7793f5 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.utils.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..19f1a25040 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.utils.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..ff5dd4fe92 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.utils.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..039e684cb7 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.utils.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..6fde1e7094 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.utils.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..9b7e9efd15 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.utils.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/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/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 91% rename from tests/test_identity.py rename to tests/transforms/utility/test_identity.py index 4243a7f19a..d47ad0d63e 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.utils.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..1cd32cf63c 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.utils.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..16a6d8cf07 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.utils.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..300fd7a90a 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.utils.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..47900ce5a1 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.utils.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..bc209413b8 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.utils.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..d726a32f64 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.utils.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..b2a5458ada 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.utils.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..5f3835d80b 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.utils.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..040ce2907a 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.utils.utils import TEST_NDARRAYS, assert_allclose, make_nifti_image, make_rand_affine TESTS = [] for p in TEST_NDARRAYS: 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..c6a3947b6e 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.utils.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..9d3321a976 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.utils.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/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..a137c5a58a 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.utils.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[1] 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/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..9a3e925b7e 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.utils.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..4a3f775793 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.utils.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..9d3bbf8b92 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.utils.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..c9e8b212b2 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.utils.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..ddc665e7a6 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.utils.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..fa4dd89724 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.utils.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..f0227ec30e 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.utils.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..962999d0fb 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.utils.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..0d46bda5fb 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.utils.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..22e785b094 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.utils.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/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..870456e226 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.utils.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..099860e252 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.utils.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..0e66646b97 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.utils.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/utils/utils.py b/tests/utils/utils.py new file mode 100644 index 0000000000..2a00af50e9 --- /dev/null +++ b/tests/utils/utils.py @@ -0,0 +1,867 @@ +# 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. + +from __future__ import annotations + +import argparse +import copy +import datetime +import functools +import importlib +import json +import operator +import os +import queue +import ssl +import subprocess +import sys +import tempfile +import time +import traceback +import unittest +import warnings +from contextlib import contextmanager +from functools import partial, reduce +from subprocess import PIPE, Popen +from typing import Callable +from urllib.error import ContentTooShortError, HTTPError + +import numpy as np +import torch +import torch.distributed as dist + +from monai.apps.utils import download_url +from monai.config import NdarrayTensor +from monai.config.deviceconfig import USE_COMPILED +from monai.config.type_definitions import NdarrayOrTensor +from monai.data import create_test_image_2d, create_test_image_3d +from monai.data.meta_tensor import MetaTensor, get_track_meta +from monai.networks import convert_to_onnx, convert_to_torchscript +from monai.utils import optional_import +from monai.utils.misc import MONAIEnvVars +from monai.utils.module import compute_capabilities_after, pytorch_after +from monai.utils.tf32 import detect_default_tf32 +from monai.utils.type_conversion import convert_data_type + +nib, _ = optional_import("nibabel") +http_error, has_req = optional_import("requests", name="HTTPError") + +quick_test_var = "QUICKTEST" +_tf32_enabled = None +_test_data_config: dict = {} + + +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: + _config = json.load(c) + for k, v in _config.items(): + _test_data_config[k] = v + return reduce(operator.getitem, keys, _test_data_config) + + +def get_testing_algo_template_path(): + """ + a local folder to the testing algorithm template or a url to the compressed template file. + Default to None, which effectively uses bundle_gen's ``default_algo_zip`` path. + + https://github.com/Project-MONAI/MONAI/blob/1.1.0/monai/apps/auto3dseg/bundle_gen.py#L380-L381 + """ + return MONAIEnvVars.testing_algo_template() + + +def clone(data: NdarrayTensor) -> NdarrayTensor: + """ + Clone data independent of type. + + Args: + data (NdarrayTensor): This can be a Pytorch Tensor or numpy array. + + Returns: + Any: Cloned data object + """ + return copy.deepcopy(data) + + +def assert_allclose( + actual: NdarrayOrTensor, + desired: NdarrayOrTensor, + type_test: bool | str = True, + device_test: bool = False, + *args, + **kwargs, +): + """ + Assert that types and all values of two data objects are close. + + Args: + actual: Pytorch Tensor or numpy array for comparison. + desired: Pytorch Tensor or numpy array to compare against. + type_test: whether to test that `actual` and `desired` are both numpy arrays or torch tensors. + if type_test == "tensor", it checks whether the `actual` is a torch.tensor or metatensor according to + `get_track_meta`. + device_test: whether to test the device property. + args: extra arguments to pass on to `np.testing.assert_allclose`. + kwargs: extra arguments to pass on to `np.testing.assert_allclose`. + + + """ + if isinstance(type_test, str) and type_test == "tensor": + if get_track_meta(): + np.testing.assert_equal(isinstance(actual, MetaTensor), True, "must be a MetaTensor") + else: + np.testing.assert_equal( + isinstance(actual, torch.Tensor) and not isinstance(actual, MetaTensor), True, "must be a torch.Tensor" + ) + elif type_test: + # check both actual and desired are of the same type + np.testing.assert_equal(isinstance(actual, np.ndarray), isinstance(desired, np.ndarray), "numpy type") + np.testing.assert_equal(isinstance(actual, torch.Tensor), isinstance(desired, torch.Tensor), "torch type") + + if isinstance(desired, torch.Tensor) or isinstance(actual, torch.Tensor): + if device_test: + np.testing.assert_equal(str(actual.device), str(desired.device), "torch device check") # type: ignore + actual = actual.detach().cpu().numpy() if isinstance(actual, torch.Tensor) else actual + desired = desired.detach().cpu().numpy() if isinstance(desired, torch.Tensor) else desired + np.testing.assert_allclose(actual, desired, *args, **kwargs) + + +@contextmanager +def skip_if_downloading_fails(): + try: + yield + except (ContentTooShortError, HTTPError, ConnectionError) + (http_error,) if has_req else () as e: # noqa: B030 + raise unittest.SkipTest(f"error while downloading: {e}") from e + except ssl.SSLError as ssl_e: + if "decryption failed" in str(ssl_e): + raise unittest.SkipTest(f"SSL error while downloading: {ssl_e}") from ssl_e + except (RuntimeError, OSError) as rt_e: + err_str = str(rt_e) + if any( + k in err_str + for k in ( + "unexpected EOF", # incomplete download + "network issue", + "gdown dependency", # gdown not installed + "md5 check", + "limit", # HTTP Error 503: Egress is over the account limit + "authenticate", + "timed out", # urlopen error [Errno 110] Connection timed out + "HTTPError", # HTTPError: 429 Client Error: Too Many Requests for huggingface hub + ) + ): + raise unittest.SkipTest(f"error while downloading: {rt_e}") from rt_e # incomplete download + + raise rt_e + + +def test_pretrained_networks(network, input_param, device): + with skip_if_downloading_fails(): + return network(**input_param).to(device) + + +def test_is_quick(): + return os.environ.get(quick_test_var, "").lower() == "true" + + +def is_tf32_env(): + """ + When we may be using TF32 mode, check the precision of matrix operation. + If the checking result is greater than the threshold 0.001, + set _tf32_enabled=True (and relax _rtol for tests). + """ + global _tf32_enabled + if _tf32_enabled is None: + _tf32_enabled = False + if torch.cuda.is_available() and (detect_default_tf32() or torch.backends.cuda.matmul.allow_tf32): + try: + # with TF32 enabled, the speed is ~8x faster, but the precision has ~2 digits less in the result + g_gpu = torch.Generator(device="cuda") + g_gpu.manual_seed(2147483647) + a_full = torch.randn(1024, 1024, dtype=torch.double, device="cuda", generator=g_gpu) + b_full = torch.randn(1024, 1024, dtype=torch.double, device="cuda", generator=g_gpu) + _tf32_enabled = (a_full.float() @ b_full.float() - a_full @ b_full).abs().max().item() > 0.001 # 0.1713 + except BaseException: + pass + print(f"tf32 enabled: {_tf32_enabled}") + return _tf32_enabled + + +def skip_if_quick(obj): + """ + Skip the unit tests if environment variable `quick_test_var=true`. + For example, the user can skip the relevant tests by setting ``export QUICKTEST=true``. + """ + is_quick = test_is_quick() + + return unittest.skipIf(is_quick, "Skipping slow tests")(obj) + + +class SkipIfNoModule: + """Decorator to be used if test should be skipped + when optional module is not present.""" + + def __init__(self, module_name): + self.module_name = module_name + self.module_missing = not optional_import(self.module_name)[1] + + def __call__(self, obj): + return unittest.skipIf(self.module_missing, f"optional module not present: {self.module_name}")(obj) + + +class SkipIfModule: + """Decorator to be used if test should be skipped + when optional module is present.""" + + def __init__(self, module_name): + self.module_name = module_name + self.module_avail = optional_import(self.module_name)[1] + + def __call__(self, obj): + return unittest.skipIf(self.module_avail, f"Skipping because optional module present: {self.module_name}")(obj) + + +def skip_if_no_cpp_extension(obj): + """ + Skip the unit tests if the cpp extension is not available. + """ + return unittest.skipUnless(USE_COMPILED, "Skipping cpp extension tests")(obj) + + +def skip_if_no_cuda(obj): + """ + Skip the unit tests if torch.cuda.is_available is False. + """ + return unittest.skipUnless(torch.cuda.is_available(), "Skipping CUDA-based tests")(obj) + + +def skip_if_windows(obj): + """ + Skip the unit tests if platform is win32. + """ + return unittest.skipIf(sys.platform == "win32", "Skipping tests on Windows")(obj) + + +def skip_if_darwin(obj): + """ + Skip the unit tests if platform is macOS (Darwin). + """ + return unittest.skipIf(sys.platform == "darwin", "Skipping tests on macOS/Darwin")(obj) + + +class SkipIfBeforePyTorchVersion: + """Decorator to be used if test should be skipped + with PyTorch versions older than that given.""" + + def __init__(self, pytorch_version_tuple): + self.min_version = pytorch_version_tuple + self.version_too_old = not pytorch_after(*pytorch_version_tuple) + + def __call__(self, obj): + return unittest.skipIf( + self.version_too_old, f"Skipping tests that fail on PyTorch versions before: {self.min_version}" + )(obj) + + +class SkipIfAtLeastPyTorchVersion: + """Decorator to be used if test should be skipped + with PyTorch versions newer than or equal to that given.""" + + def __init__(self, pytorch_version_tuple): + self.max_version = pytorch_version_tuple + self.version_too_new = pytorch_after(*pytorch_version_tuple) + + def __call__(self, obj): + return unittest.skipIf( + self.version_too_new, f"Skipping tests that fail on PyTorch versions at least: {self.max_version}" + )(obj) + + +class SkipIfBeforeComputeCapabilityVersion: + """Decorator to be used if test should be skipped + with Compute Capability older than that given.""" + + def __init__(self, compute_capability_tuple): + self.min_version = compute_capability_tuple + self.version_too_old = not compute_capabilities_after(*compute_capability_tuple) + + def __call__(self, obj): + return unittest.skipIf( + self.version_too_old, f"Skipping tests that fail on Compute Capability versions before: {self.min_version}" + )(obj) + + +def is_main_test_process(): + ps = torch.multiprocessing.current_process() + if not ps or not hasattr(ps, "name"): + return False + return ps.name.startswith("Main") + + +def has_cupy(): + """ + Returns True if the user has installed a version of cupy. + """ + cp, has_cp = optional_import("cupy") + if not is_main_test_process(): + return has_cp # skip the check if we are running in subprocess + if not has_cp: + return False + try: # test cupy installation with a basic example + x = cp.arange(6, dtype="f").reshape(2, 3) + y = cp.arange(3, dtype="f") + kernel = cp.ElementwiseKernel( + "float32 x, float32 y", "float32 z", """ if (x - 2 > y) { z = x * y; } else { z = x + y; } """, "my_kernel" + ) + flag = kernel(x, y)[0, 0] == 0 + del x, y, kernel + cp.get_default_memory_pool().free_all_blocks() + return flag + except Exception: + return False + + +HAS_CUPY = has_cupy() + + +def make_nifti_image( + array: NdarrayOrTensor, affine=None, dir=None, fname=None, suffix=".nii.gz", verbose=False, dtype=float +): + """ + Create a temporary nifti image on the disk and return the image name. + User is responsible for deleting the temporary file when done with it. + """ + if isinstance(array, torch.Tensor): + array, *_ = convert_data_type(array, np.ndarray) + if isinstance(affine, torch.Tensor): + affine, *_ = convert_data_type(affine, np.ndarray) + if affine is None: + affine = np.eye(4) + test_image = nib.Nifti1Image(array.astype(dtype), affine) # type: ignore + + # if dir not given, create random. Else, make sure it exists. + if dir is None: + dir = tempfile.mkdtemp() + else: + os.makedirs(dir, exist_ok=True) + + # If fname not given, get random one. Else, concat dir, fname and suffix. + if fname is None: + temp_f, fname = tempfile.mkstemp(suffix=suffix, dir=dir) + os.close(temp_f) + else: + fname = os.path.join(dir, fname + suffix) + + nib.save(test_image, fname) + if verbose: + print(f"File written: {fname}.") + return fname + + +def make_rand_affine(ndim: int = 3, random_state: np.random.RandomState | None = None): + """Create random affine transformation (with values == -1, 0 or 1).""" + rs = np.random.random.__self__ if random_state is None else random_state # type: ignore + + vals = rs.choice([-1, 1], size=ndim) + positions = rs.choice(range(ndim), size=ndim, replace=False) + af = np.zeros([ndim + 1, ndim + 1]) + af[ndim, ndim] = 1 + for i, (v, p) in enumerate(zip(vals, positions)): + af[i, p] = v + return af + + +def get_arange_img(size, dtype=np.float32, offset=0): + """ + Returns an image as a numpy array (complete with channel as dim 0) + with contents that iterate like an arange. + """ + n_elem = np.prod(size) + img = np.arange(offset, offset + n_elem, dtype=dtype).reshape(size) + return np.expand_dims(img, 0) + + +class DistTestCase(unittest.TestCase): + """ + testcase without _outcome, so that it's picklable. + """ + + def __getstate__(self): + self_dict = self.__dict__.copy() + del self_dict["_outcome"] + return self_dict + + def __setstate__(self, data_dict): + self.__dict__.update(data_dict) + + +class DistCall: + """ + Wrap a test case so that it will run in multiple processes on a single machine using `torch.distributed`. + It is designed to be used with `tests.utils.DistTestCase`. + + Usage: + + decorate a unittest testcase method with a `DistCall` instance:: + + class MyTests(unittest.TestCase): + @DistCall(nnodes=1, nproc_per_node=3, master_addr="localhost") + def test_compute(self): + ... + + the `test_compute` method should trigger different worker logic according to `dist.get_rank()`. + + Multi-node tests require a fixed master_addr:master_port, with node_rank set manually in multiple scripts + or from environment variable "NODE_RANK". + """ + + def __init__( + self, + nnodes: int = 1, + nproc_per_node: int = 1, + master_addr: str = "localhost", + master_port: int | None = None, + node_rank: int | None = None, + timeout=60, + init_method=None, + backend: str | None = None, + daemon: bool | None = None, + method: str | None = "spawn", + verbose: bool = False, + ): + """ + + Args: + nnodes: The number of nodes to use for distributed call. + nproc_per_node: The number of processes to call on each node. + master_addr: Master node (rank 0)'s address, should be either the IP address or the hostname of node 0. + master_port: Master node (rank 0)'s free port. + node_rank: The rank of the node, this could be set via environment variable "NODE_RANK". + timeout: Timeout for operations executed against the process group. + init_method: URL specifying how to initialize the process group. + Default is "env://" or "file:///d:/a_temp" (windows) if unspecified. + If ``"no_init"``, the `dist.init_process_group` must be called within the code to be tested. + backend: The backend to use. Depending on build-time configurations, + valid values include ``mpi``, ``gloo``, and ``nccl``. + daemon: the process’s daemon flag. + When daemon=None, the initial value is inherited from the creating process. + method: set the method which should be used to start a child process. + method can be 'fork', 'spawn' or 'forkserver'. + verbose: whether to print NCCL debug info. + """ + self.nnodes = int(nnodes) + self.nproc_per_node = int(nproc_per_node) + if self.nnodes < 1 or self.nproc_per_node < 1: + raise ValueError( + f"number of nodes and processes per node must be >= 1, got {self.nnodes} and {self.nproc_per_node}" + ) + self.node_rank = int(os.environ.get("NODE_RANK", "0")) if node_rank is None else int(node_rank) + self.master_addr = master_addr + self.master_port = np.random.randint(10000, 20000) if master_port is None else master_port + + if backend is None: + self.backend = "nccl" if torch.distributed.is_nccl_available() and torch.cuda.is_available() else "gloo" + else: + self.backend = backend + self.init_method = init_method + if self.init_method is None and sys.platform == "win32": + self.init_method = "file:///d:/a_temp" + self.timeout = datetime.timedelta(0, timeout) + self.daemon = daemon + self.method = method + self.verbose = verbose + + def run_process(self, func, local_rank, args, kwargs, results): + _env = os.environ.copy() # keep the original system env + try: + os.environ["MASTER_ADDR"] = self.master_addr + os.environ["MASTER_PORT"] = str(self.master_port) + os.environ["LOCAL_RANK"] = str(local_rank) + if self.verbose: + os.environ["NCCL_DEBUG"] = "INFO" + os.environ["NCCL_DEBUG_SUBSYS"] = "ALL" + os.environ["TORCH_NCCL_BLOCKING_WAIT"] = str(1) + os.environ["OMP_NUM_THREADS"] = str(1) + os.environ["WORLD_SIZE"] = str(self.nproc_per_node * self.nnodes) + os.environ["RANK"] = str(self.nproc_per_node * self.node_rank + local_rank) + + if torch.cuda.is_available(): + torch.cuda.set_device(int(local_rank)) # using device ids from CUDA_VISIBILE_DEVICES + + if self.init_method != "no_init": + dist.init_process_group( + backend=self.backend, + init_method=self.init_method, + timeout=self.timeout, + world_size=int(os.environ["WORLD_SIZE"]), + rank=int(os.environ["RANK"]), + ) + func(*args, **kwargs) + # the primary node lives longer to + # avoid _store_based_barrier, RuntimeError: Broken pipe + # as the TCP store daemon is on the rank 0 + if int(os.environ["RANK"]) == 0: + time.sleep(0.1) + results.put(True) + except Exception as e: + results.put(False) + raise e + finally: + os.environ.clear() + os.environ.update(_env) + try: + dist.destroy_process_group() + except RuntimeError as e: + warnings.warn(f"While closing process group: {e}.") + + def __call__(self, obj): + if not torch.distributed.is_available(): + return unittest.skipIf(True, "Skipping distributed tests because not torch.distributed.is_available()")(obj) + if torch.cuda.is_available() and torch.cuda.device_count() < self.nproc_per_node: + return unittest.skipIf( + True, + f"Skipping distributed tests because it requires {self.nnodes} devices " + f"but got {torch.cuda.device_count()}", + )(obj) + + _cache_original_func(obj) + + @functools.wraps(obj) + def _wrapper(*args, **kwargs): + tmp = torch.multiprocessing.get_context(self.method) + processes = [] + results = tmp.Queue() + func = _call_original_func + args = [obj.__name__, obj.__module__] + list(args) + for proc_rank in range(self.nproc_per_node): + p = tmp.Process( + target=self.run_process, args=(func, proc_rank, args, kwargs, results), daemon=self.daemon + ) + p.start() + processes.append(p) + for p in processes: + p.join() + assert results.get(), "Distributed call failed." + _del_original_func(obj) + + return _wrapper + + +class TimedCall: + """ + Wrap a test case so that it will run in a new process, raises a TimeoutError if the decorated method takes + more than `seconds` to finish. It is designed to be used with `tests.utils.DistTestCase`. + """ + + def __init__( + self, + seconds: float = 60.0, + daemon: bool | None = None, + method: str | None = "spawn", + force_quit: bool = True, + skip_timing=False, + ): + """ + + Args: + seconds: timeout seconds. + daemon: the process’s daemon flag. + When daemon=None, the initial value is inherited from the creating process. + method: set the method which should be used to start a child process. + method can be 'fork', 'spawn' or 'forkserver'. + force_quit: whether to terminate the child process when `seconds` elapsed. + skip_timing: whether to skip the timing constraint. + this is useful to include some system conditions such as + `torch.cuda.is_available()`. + """ + self.timeout_seconds = seconds + self.daemon = daemon + self.force_quit = force_quit + self.skip_timing = skip_timing + self.method = method + + @staticmethod + def run_process(func, args, kwargs, results): + try: + output = func(*args, **kwargs) + results.put(output) + except Exception as e: + e.traceback = traceback.format_exc() + results.put(e) + + def __call__(self, obj): + if self.skip_timing: + return obj + + _cache_original_func(obj) + + @functools.wraps(obj) + def _wrapper(*args, **kwargs): + tmp = torch.multiprocessing.get_context(self.method) + func = _call_original_func + args = [obj.__name__, obj.__module__] + list(args) + results = tmp.Queue() + p = tmp.Process(target=TimedCall.run_process, args=(func, args, kwargs, results), daemon=self.daemon) + p.start() + + p.join(timeout=self.timeout_seconds) + + timeout_error = None + try: + if p.is_alive(): + # create an Exception + timeout_error = torch.multiprocessing.TimeoutError( + f"'{obj.__name__}' in '{obj.__module__}' did not finish in {self.timeout_seconds}s." + ) + if self.force_quit: + p.terminate() + else: + warnings.warn( + f"TimedCall: deadline ({self.timeout_seconds}s) " + f"reached but waiting for {obj.__name__} to finish." + ) + finally: + p.join() + + _del_original_func(obj) + res = None + try: + res = results.get(block=False) + except queue.Empty: # no result returned, took too long + pass + if isinstance(res, Exception): # other errors from obj + if hasattr(res, "traceback"): + raise RuntimeError(res.traceback) from res + raise res + if timeout_error: # no force_quit finished + raise timeout_error + return res + + return _wrapper + + +_original_funcs = {} + + +def _cache_original_func(obj) -> None: + """cache the original function by name, so that the decorator doesn't shadow it.""" + _original_funcs[obj.__name__] = obj + + +def _del_original_func(obj): + """pop the original function from cache.""" + _original_funcs.pop(obj.__name__, None) + if torch.cuda.is_available(): # clean up the cached function + torch.cuda.synchronize() + torch.cuda.empty_cache() + + +def _call_original_func(name, module, *args, **kwargs): + if name not in _original_funcs: + _original_module = importlib.import_module(module) # reimport, refresh _original_funcs + if not hasattr(_original_module, name): + # refresh module doesn't work + raise RuntimeError(f"Could not recover the original {name} from {module}: {_original_funcs}.") + f = _original_funcs[name] + return f(*args, **kwargs) + + +class NumpyImageTestCase2D(unittest.TestCase): + im_shape = (128, 64) + input_channels = 1 + output_channels = 4 + num_classes = 3 + + def setUp(self): + im, msk = create_test_image_2d( + self.im_shape[0], self.im_shape[1], num_objs=4, rad_max=20, noise_max=0.0, num_seg_classes=self.num_classes + ) + + self.imt = im[None, None] + self.seg1 = (msk[None, None] > 0).astype(np.float32) + self.segn = msk[None, None] + + +class TorchImageTestCase2D(NumpyImageTestCase2D): + + def setUp(self): + NumpyImageTestCase2D.setUp(self) + self.imt = torch.tensor(self.imt) + self.seg1 = torch.tensor(self.seg1) + self.segn = torch.tensor(self.segn) + + +class NumpyImageTestCase3D(unittest.TestCase): + im_shape = (64, 48, 80) + input_channels = 1 + output_channels = 4 + num_classes = 3 + + def setUp(self): + im, msk = create_test_image_3d( + self.im_shape[0], + self.im_shape[1], + self.im_shape[2], + num_objs=4, + rad_max=20, + noise_max=0.0, + num_seg_classes=self.num_classes, + ) + + self.imt = im[None, None] + self.seg1 = (msk[None, None] > 0).astype(np.float32) + self.segn = msk[None, None] + + +class TorchImageTestCase3D(NumpyImageTestCase3D): + + def setUp(self): + NumpyImageTestCase3D.setUp(self) + self.imt = torch.tensor(self.imt) + self.seg1 = torch.tensor(self.seg1) + self.segn = torch.tensor(self.segn) + + +def test_script_save(net, *inputs, device=None, rtol=1e-4, atol=0.0): + """ + Test the ability to save `net` as a Torchscript object, reload it, and apply inference. The value `inputs` is + forward-passed through the original and loaded copy of the network and their results returned. + The forward pass for both is done without gradient accumulation. + + The test will be performed with CUDA if available, else CPU. + """ + # TODO: would be nice to use GPU if available, but it currently causes CI failures. + device = "cpu" + with tempfile.TemporaryDirectory() as tempdir: + convert_to_torchscript( + model=net, + filename_or_obj=os.path.join(tempdir, "model.ts"), + verify=True, + inputs=inputs, + device=device, + rtol=rtol, + atol=atol, + ) + + +def test_onnx_save(net, *inputs, device=None, rtol=1e-4, atol=0.0): + """ + Test the ability to save `net` in ONNX format, reload it and validate with runtime. + The value `inputs` is forward-passed through the `net` without gradient accumulation + to do onnx export and PyTorch inference. + PyTorch model inference is performed with CUDA if available, else CPU. + Saved ONNX model is validated with onnxruntime, if available, else ONNX native implementation. + """ + # TODO: would be nice to use GPU if available, but it currently causes CI failures. + device = "cpu" + _, has_onnxruntime = optional_import("onnxruntime") + with tempfile.TemporaryDirectory() as tempdir: + convert_to_onnx( + model=net, + filename=os.path.join(tempdir, "model.onnx"), + verify=True, + inputs=inputs, + device=device, + use_ort=has_onnxruntime, + rtol=rtol, + atol=atol, + ) + + +def download_url_or_skip_test(*args, **kwargs): + """``download_url`` and skip the tests if any downloading error occurs.""" + with skip_if_downloading_fails(): + download_url(*args, **kwargs) + + +def query_memory(n=2): + """ + Find best n idle devices and return a string of device ids using the `nvidia-smi` command. + """ + bash_string = "nvidia-smi --query-gpu=power.draw,temperature.gpu,memory.used --format=csv,noheader,nounits" + + try: + print(f"query memory with n={n}") + p1 = Popen(bash_string.split(), stdout=PIPE) + output, error = p1.communicate() + free_memory = [x.split(",") for x in output.decode("utf-8").split("\n")[:-1]] + free_memory = np.asarray(free_memory, dtype=float).T + free_memory[1] += free_memory[0] # combine 0/1 column measures + ids = np.lexsort(free_memory)[:n] + except (TypeError, ValueError, IndexError, OSError): + ids = range(n) if isinstance(n, int) else [] + return ",".join(f"{int(x)}" for x in ids) + + +def test_local_inversion(invertible_xform, to_invert, im, dict_key=None): + """test that invertible_xform can bring to_invert back to im""" + im_item = im if dict_key is None else im[dict_key] + if not isinstance(im_item, MetaTensor): + return + im_ref = copy.deepcopy(im) + im_inv = invertible_xform.inverse(to_invert) + if dict_key: + im_inv = im_inv[dict_key] + im_ref = im_ref[dict_key] + np.testing.assert_array_equal(im_inv.applied_operations, []) + assert_allclose(im_inv.shape, im_ref.shape) + assert_allclose(im_inv.affine, im_ref.affine, atol=1e-3, rtol=1e-3) + + +def command_line_tests(cmd, copy_env=True): + test_env = os.environ.copy() if copy_env else os.environ + print(f"CUDA_VISIBLE_DEVICES in {__file__}", test_env.get("CUDA_VISIBLE_DEVICES")) + try: + normal_out = subprocess.run(cmd, env=test_env, check=True, capture_output=True) + print(repr(normal_out).replace("\\n", "\n").replace("\\t", "\t")) + return repr(normal_out) + except subprocess.CalledProcessError as e: + output = repr(e.stdout).replace("\\n", "\n").replace("\\t", "\t") + errors = repr(e.stderr).replace("\\n", "\n").replace("\\t", "\t") + raise RuntimeError(f"subprocess call error {e.returncode}: {errors}, {output}") from e + + +def equal_state_dict(st_1, st_2): + """ + assert equal state_dict (for the shared keys between st_1 and st_2). + """ + for key_st_1, val_st_1 in st_1.items(): + if key_st_1 in st_2: + val_st_2 = st_2.get(key_st_1) + assert_allclose(val_st_1, val_st_2) + + +TEST_TORCH_TENSORS: tuple = (torch.as_tensor,) +if torch.cuda.is_available(): + gpu_tensor: Callable = partial(torch.as_tensor, device="cuda") + TEST_TORCH_TENSORS = TEST_TORCH_TENSORS + (gpu_tensor,) + +DEFAULT_TEST_AFFINE = torch.tensor( + [[2.0, 0.0, 0.0, 0.0], [0.0, 2.0, 0.0, 0.0], [0.0, 0.0, 2.0, 0.0], [0.0, 0.0, 0.0, 1.0]] +) +_metatensor_creator = partial(MetaTensor, meta={"a": "b", "affine": DEFAULT_TEST_AFFINE}) +TEST_NDARRAYS_NO_META_TENSOR: tuple[Callable] = (np.array,) + TEST_TORCH_TENSORS +TEST_NDARRAYS: tuple[Callable] = TEST_NDARRAYS_NO_META_TENSOR + (_metatensor_creator,) # type: ignore +TEST_TORCH_AND_META_TENSORS: tuple[Callable] = TEST_TORCH_TENSORS + (_metatensor_creator,) +# alias for branch tests +TEST_NDARRAYS_ALL = TEST_NDARRAYS + +TEST_DEVICES = [[torch.device("cpu")]] +if torch.cuda.is_available(): + TEST_DEVICES.append([torch.device("cuda")]) + +if __name__ == "__main__": + parser = argparse.ArgumentParser(prog="util") + parser.add_argument("-c", "--count", default=2, help="max number of gpus") + args = parser.parse_args() + print("\n", query_memory(int(args.count)), sep="\n") # print to stdout + sys.exit(0) 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..b2c875c2d3 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.utils.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..797750a3e2 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.utils.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/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..4a37142458 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.utils.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..aca7c5ffd7 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.utils.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( [