Skip to content

Commit bfe09b8

Browse files
freddiewanahKumoLiuatbenmurray
authored
Refactored others type of subotimal asserts (#7672)
### Description As discussed in PR #7609, I tried to break the suboptimal test refactors to smaller pieces. In this PR all asserts are checking textual content or instance of a parameter. Suboptimal Assert: Instead of using statements such as assertIsNone, assertIsInstance, always simply use assertTrue or assertFalse. This will decrease the code overall readability and increase the execution time as extra logic needed. ### Types of changes <!--- Put an `x` in all the boxes that apply, and remove the not applicable items --> - [x] Non-breaking change (fix or new feature that would not break existing functionality). - [ ] Breaking change (fix or new feature that would cause existing functionality to change). - [ ] New tests added to cover the changes. - [ ] Integration tests passed locally by running `./runtests.sh -f -u --net --coverage`. - [ ] Quick tests passed locally by running `./runtests.sh --quick --unittests --disttests`. - [ ] In-line docstrings updated. - [ ] Documentation updated, tested `make html` command in the `docs/` folder. --------- Signed-off-by: Han Wang <freddie.wanah@gmail.com> Signed-off-by: Ben Murray <ben.murray@gmail.com> Signed-off-by: YunLiu <55491388+KumoLiu@users.noreply.github.com> Co-authored-by: YunLiu <55491388+KumoLiu@users.noreply.github.com> Co-authored-by: Ben Murray <ben.murray@gmail.com>
1 parent c3e4457 commit bfe09b8

33 files changed

Lines changed: 111 additions & 112 deletions

tests/test_bundle_ckpt_export.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,9 @@ def test_export(self, key_in_ckpt, use_trace):
7272
_, metadata, extra_files = load_net_with_metadata(
7373
ts_file, more_extra_files=["inference.json", "def_args.json"]
7474
)
75-
self.assertTrue("schema" in metadata)
76-
self.assertTrue("meta_file" in json.loads(extra_files["def_args.json"]))
77-
self.assertTrue("network_def" in json.loads(extra_files["inference.json"]))
75+
self.assertIn("schema", metadata)
76+
self.assertIn("meta_file", json.loads(extra_files["def_args.json"]))
77+
self.assertIn("network_def", json.loads(extra_files["inference.json"]))
7878

7979
@parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3])
8080
def test_default_value(self, key_in_ckpt, use_trace):

tests/test_bundle_get_data.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -51,25 +51,26 @@ class TestGetBundleData(unittest.TestCase):
5151
def test_get_all_bundles_list(self, params):
5252
with skip_if_downloading_fails():
5353
output = get_all_bundles_list(**params)
54-
self.assertTrue(isinstance(output, list))
55-
self.assertTrue(isinstance(output[0], tuple))
56-
self.assertEqual(len(output[0]), 2)
54+
self.assertIsInstance(output, list)
55+
self.assertIsInstance(output[0], tuple)
56+
self.assertTrue(len(output[0]) == 2)
5757

5858
@parameterized.expand([TEST_CASE_1, TEST_CASE_5])
5959
@skip_if_quick
6060
def test_get_bundle_versions(self, params):
6161
with skip_if_downloading_fails():
6262
output = get_bundle_versions(**params)
63-
self.assertTrue(isinstance(output, dict))
64-
self.assertTrue("latest_version" in output and "all_versions" in output)
65-
self.assertTrue("0.1.0" in output["all_versions"])
63+
self.assertIsInstance(output, dict)
64+
self.assertIn("latest_version", output)
65+
self.assertIn("all_versions", output)
66+
self.assertIn("0.1.0", output["all_versions"])
6667

6768
@parameterized.expand([TEST_CASE_1, TEST_CASE_2])
6869
@skip_if_quick
6970
def test_get_bundle_info(self, params):
7071
with skip_if_downloading_fails():
7172
output = get_bundle_info(**params)
72-
self.assertTrue(isinstance(output, dict))
73+
self.assertIsInstance(output, dict)
7374
for key in ["id", "name", "size", "download_count", "browser_download_url"]:
7475
self.assertTrue(key in output)
7576

@@ -78,7 +79,7 @@ def test_get_bundle_info(self, params):
7879
def test_get_bundle_info_monaihosting(self, params):
7980
with skip_if_downloading_fails():
8081
output = get_bundle_info(**params)
81-
self.assertTrue(isinstance(output, dict))
82+
self.assertIsInstance(output, dict)
8283
for key in ["name", "browser_download_url"]:
8384
self.assertTrue(key in output)
8485

tests/test_bundle_trt_export.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -91,9 +91,9 @@ def test_trt_export(self, convert_precision, input_shape, dynamic_batch):
9191
_, metadata, extra_files = load_net_with_metadata(
9292
ts_file, more_extra_files=["inference.json", "def_args.json"]
9393
)
94-
self.assertTrue("schema" in metadata)
95-
self.assertTrue("meta_file" in json.loads(extra_files["def_args.json"]))
96-
self.assertTrue("network_def" in json.loads(extra_files["inference.json"]))
94+
self.assertIn("schema", metadata)
95+
self.assertIn("meta_file", json.loads(extra_files["def_args.json"]))
96+
self.assertIn("network_def", json.loads(extra_files["inference.json"]))
9797

9898
@parameterized.expand([TEST_CASE_3, TEST_CASE_4])
9999
@unittest.skipUnless(
@@ -129,9 +129,9 @@ def test_onnx_trt_export(self, convert_precision, input_shape, dynamic_batch):
129129
_, metadata, extra_files = load_net_with_metadata(
130130
ts_file, more_extra_files=["inference.json", "def_args.json"]
131131
)
132-
self.assertTrue("schema" in metadata)
133-
self.assertTrue("meta_file" in json.loads(extra_files["def_args.json"]))
134-
self.assertTrue("network_def" in json.loads(extra_files["inference.json"]))
132+
self.assertIn("schema", metadata)
133+
self.assertIn("meta_file", json.loads(extra_files["def_args.json"]))
134+
self.assertIn("network_def", json.loads(extra_files["inference.json"]))
135135

136136

137137
if __name__ == "__main__":

tests/test_bundle_workflow.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -138,11 +138,11 @@ def test_train_config(self, config_file):
138138
self.assertListEqual(trainer.check_properties(), [])
139139
# test read / write the properties
140140
dataset = trainer.train_dataset
141-
self.assertTrue(isinstance(dataset, Dataset))
141+
self.assertIsInstance(dataset, Dataset)
142142
inferer = trainer.train_inferer
143-
self.assertTrue(isinstance(inferer, SimpleInferer))
143+
self.assertIsInstance(inferer, SimpleInferer)
144144
# test optional properties get
145-
self.assertTrue(trainer.train_key_metric is None)
145+
self.assertIsNone(trainer.train_key_metric)
146146
trainer.train_dataset = deepcopy(dataset)
147147
trainer.train_inferer = deepcopy(inferer)
148148
# test optional properties set

tests/test_component_store.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,17 +48,17 @@ def test_add2(self):
4848
self.cs.add("test_obj2", "Test object", test_obj2)
4949

5050
self.assertEqual(len(self.cs), 2)
51-
self.assertTrue("test_obj1" in self.cs)
52-
self.assertTrue("test_obj2" in self.cs)
51+
self.assertIn("test_obj1", self.cs)
52+
self.assertIn("test_obj2", self.cs)
5353

5454
def test_add_def(self):
55-
self.assertFalse("test_func" in self.cs)
55+
self.assertNotIn("test_func", self.cs)
5656

5757
@self.cs.add_def("test_func", "Test function")
5858
def test_func():
5959
return 123
6060

61-
self.assertTrue("test_func" in self.cs)
61+
self.assertIn("test_func", self.cs)
6262

6363
self.assertEqual(len(self.cs), 1)
6464
self.assertEqual(list(self.cs), [("test_func", test_func)])

tests/test_compute_ho_ver_maps.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,8 @@ class ComputeHoVerMapsTests(unittest.TestCase):
6767
def test_horizontal_certical_maps(self, in_type, arguments, mask, hv_mask):
6868
input_image = in_type(mask)
6969
result = ComputeHoVerMaps(**arguments)(input_image)
70-
self.assertTrue(isinstance(result, torch.Tensor))
71-
self.assertTrue(str(result.dtype).split(".")[1] == arguments.get("dtype", "float32"))
70+
self.assertIsInstance(result, torch.Tensor)
71+
self.assertEqual(str(result.dtype).split(".")[1], arguments.get("dtype", "float32"))
7272
assert_allclose(result, hv_mask, type_test="tensor")
7373

7474

tests/test_compute_ho_ver_maps_d.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,8 @@ def test_horizontal_certical_maps(self, in_type, arguments, mask, hv_mask):
7171
for k in mask.keys():
7272
input_image[k] = in_type(mask[k])
7373
result = ComputeHoVerMapsd(keys="mask", **arguments)(input_image)[hv_key]
74-
self.assertTrue(isinstance(result, torch.Tensor))
75-
self.assertTrue(str(result.dtype).split(".")[1] == arguments.get("dtype", "float32"))
74+
self.assertIsInstance(result, torch.Tensor)
75+
self.assertEqual(str(result.dtype).split(".")[1], arguments.get("dtype", "float32"))
7676
assert_allclose(result, hv_mask[hv_key], type_test="tensor")
7777

7878

tests/test_concat_itemsd.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def test_tensor_values(self):
3030
"img2": torch.tensor([[0, 1], [1, 2]], device=device),
3131
}
3232
result = ConcatItemsd(keys=["img1", "img2"], name="cat_img")(input_data)
33-
self.assertTrue("cat_img" in result)
33+
self.assertIn("cat_img", result)
3434
result["cat_img"] += 1
3535
assert_allclose(result["img1"], torch.tensor([[0, 1], [1, 2]], device=device))
3636
assert_allclose(result["cat_img"], torch.tensor([[1, 2], [2, 3], [1, 2], [2, 3]], device=device))
@@ -42,8 +42,8 @@ def test_metatensor_values(self):
4242
"img2": MetaTensor([[0, 1], [1, 2]], device=device),
4343
}
4444
result = ConcatItemsd(keys=["img1", "img2"], name="cat_img")(input_data)
45-
self.assertTrue("cat_img" in result)
46-
self.assertTrue(isinstance(result["cat_img"], MetaTensor))
45+
self.assertIn("cat_img", result)
46+
self.assertIsInstance(result["cat_img"], MetaTensor)
4747
self.assertEqual(result["img1"].meta, result["cat_img"].meta)
4848
result["cat_img"] += 1
4949
assert_allclose(result["img1"], torch.tensor([[0, 1], [1, 2]], device=device))
@@ -52,7 +52,7 @@ def test_metatensor_values(self):
5252
def test_numpy_values(self):
5353
input_data = {"img1": np.array([[0, 1], [1, 2]]), "img2": np.array([[0, 1], [1, 2]])}
5454
result = ConcatItemsd(keys=["img1", "img2"], name="cat_img")(input_data)
55-
self.assertTrue("cat_img" in result)
55+
self.assertIn("cat_img", result)
5656
result["cat_img"] += 1
5757
np.testing.assert_allclose(result["img1"], np.array([[0, 1], [1, 2]]))
5858
np.testing.assert_allclose(result["cat_img"], np.array([[1, 2], [2, 3], [1, 2], [2, 3]]))

tests/test_config_parser.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@ def test_function(self, config):
185185
if id in ("compute", "cls_compute"):
186186
parser[f"{id}#_mode_"] = "callable"
187187
func = parser.get_parsed_content(id=id)
188-
self.assertTrue(id in parser.ref_resolver.resolved_content)
188+
self.assertIn(id, parser.ref_resolver.resolved_content)
189189
if id == "error_func":
190190
with self.assertRaises(TypeError):
191191
func(1, 2)

tests/test_cucim_dict_transform.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,8 @@ class TestCuCIMDict(unittest.TestCase):
8080
def test_tramsforms_numpy_single(self, params, input, expected):
8181
input = {"image": input}
8282
output = CuCIMd(keys="image", **params)(input)["image"]
83-
self.assertTrue(output.dtype == expected.dtype)
84-
self.assertTrue(isinstance(output, np.ndarray))
83+
self.assertEqual(output.dtype, expected.dtype)
84+
self.assertIsInstance(output, np.ndarray)
8585
cp.testing.assert_allclose(output, expected)
8686

8787
@parameterized.expand(
@@ -98,8 +98,8 @@ def test_tramsforms_numpy_batch(self, params, input, expected):
9898
input = {"image": input[cp.newaxis, ...]}
9999
expected = expected[cp.newaxis, ...]
100100
output = CuCIMd(keys="image", **params)(input)["image"]
101-
self.assertTrue(output.dtype == expected.dtype)
102-
self.assertTrue(isinstance(output, np.ndarray))
101+
self.assertEqual(output.dtype, expected.dtype)
102+
self.assertIsInstance(output, np.ndarray)
103103
cp.testing.assert_allclose(output, expected)
104104

105105
@parameterized.expand(
@@ -116,8 +116,8 @@ def test_tramsforms_cupy_single(self, params, input, expected):
116116
input = {"image": cp.asarray(input)}
117117
expected = cp.asarray(expected)
118118
output = CuCIMd(keys="image", **params)(input)["image"]
119-
self.assertTrue(output.dtype == expected.dtype)
120-
self.assertTrue(isinstance(output, cp.ndarray))
119+
self.assertEqual(output.dtype, expected.dtype)
120+
self.assertIsInstance(output, cp.ndarray)
121121
cp.testing.assert_allclose(output, expected)
122122

123123
@parameterized.expand(
@@ -134,8 +134,8 @@ def test_tramsforms_cupy_batch(self, params, input, expected):
134134
input = {"image": cp.asarray(input)[cp.newaxis, ...]}
135135
expected = cp.asarray(expected)[cp.newaxis, ...]
136136
output = CuCIMd(keys="image", **params)(input)["image"]
137-
self.assertTrue(output.dtype == expected.dtype)
138-
self.assertTrue(isinstance(output, cp.ndarray))
137+
self.assertEqual(output.dtype, expected.dtype)
138+
self.assertIsInstance(output, cp.ndarray)
139139
cp.testing.assert_allclose(output, expected)
140140

141141

0 commit comments

Comments
 (0)