π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
test: complete PT018 cleanup and enforce it repository-wide (#5595)
Daniele Loru31ffd430888d
diff --git a/benchmarks/common_test.py b/benchmarks/common_test.pyindex 9461e4c34..a6e6f721a 100644--- a/benchmarks/common_test.py+++ b/benchmarks/common_test.py@@ -33,7 +33,8 @@ from common import git_commit, run_batch_sweep, run_metadata, save_json, time_usdef test_time_us_returns_median_and_spread():median, iqr = time_us(lambda: sum(range(100)), min_run_time=0.05)- assert median > 0 and not math.isnan(median)+ assert median > 0+ assert not math.isnan(median)assert iqr >= 0@@ -42,7 +43,8 @@ def test_time_us_failure_is_nan():raise RuntimeError("expected")median, iqr = time_us(boom, min_run_time=0.05)- assert math.isnan(median) and math.isnan(iqr)+ assert math.isnan(median)+ assert math.isnan(iqr)def test_time_us_accepts_sync_callable():@@ -124,15 +126,19 @@ def test_run_batch_sweep_rows_and_skip_cells(capsys):rows = run_batch_sweep([1, 2], build, ["fast", "missing"], row_fields=lambda b: {"size": 8}, min_run_time=0.05)measured = [r for r in rows if r.get("error") is None]assert [r["batch"] for r in measured] == [1, 2]- assert measured[0]["op"] == "opA" and measured[0]["backend"] == "fast" and measured[0]["size"] == 8- assert measured[0]["median_us"] > 0 and measured[0]["throughput_per_s"] > 0+ assert measured[0]["op"] == "opA"+ assert measured[0]["backend"] == "fast"+ assert measured[0]["size"] == 8+ assert measured[0]["median_us"] > 0+ assert measured[0]["throughput_per_s"] > 0# the unavailable backend is recorded, not dropped, so the JSON shows the gapskipped = [r for r in rows if r["backend"] == "missing"]assert len(skipped) == 2assert all(r["median_us"] is None and r["throughput_per_s"] is None for r in skipped)assert all(r["error"] == "unavailable" for r in skipped)out = capsys.readouterr().out- assert "batch=1" in out and "batch=2" in out+ assert "batch=1" in out+ assert "batch=2" in outassert "-" in out # the skip cell@@ -150,17 +156,21 @@ def test_run_batch_sweep_accepts_non_batch_configs(capsys):units="LAFs/s",min_run_time=0.05,)- assert rows[0]["batch"] == 2 and rows[0]["n"] == 100 # row_fields overrides the config object+ # row_fields overrides the config object+ assert rows[0]["batch"] == 2+ assert rows[0]["n"] == 100per_call_s = rows[0]["median_us"] * 1e-6assert math.isclose(rows[0]["throughput_per_s"], 200 / per_call_s) # items_fn drives it, not the configout = capsys.readouterr().out- assert "B=2 N=100" in out and "(LAFs/s)" in out+ assert "B=2 N=100" in out+ assert "(LAFs/s)" in outdef test_versions_line_reports_stack_and_gaps():line = versions_line({"torch": "2.9.1", "kornia": "0.9.0", "torchvision": None})assert line.startswith("#")- assert "torch 2.9.1" in line and "kornia 0.9.0" in line+ assert "torch 2.9.1" in line+ assert "kornia 0.9.0" in lineassert "torchvision -" in line # missing libs shown as '-', never dropped@@ -206,7 +216,8 @@ def test_run_batch_sweep_records_warmup_failure_in_rows(): # 'compile' in a NAM)failed = next(r for r in rows if r["backend"] == "kornia (compiled)")assert failed["error"] == "InductorError" # the exception type reaches the JSON, not just stdout- assert failed["median_us"] is None and failed["throughput_per_s"] is None+ assert failed["median_us"] is None+ assert failed["throughput_per_s"] is Nonedef test_collect_load_metrics_aggregate_only() -> None:@@ -277,8 +288,11 @@ def _flagship_parser(**kwargs):def test_add_flagship_args_shared_defaults() -> None:args = _flagship_parser(ops=("a", "b")).parse_args([])assert (args.batches, args.size, args.device, args.dtype, args.threads) == ("1,8,32", 256, "cpu", "float32", 4)- assert args.ops is None and args.skip_compile_ops == frozenset() and args.min_run_time == 1.0- assert args.json is None and args.contribute is None+ assert args.ops is None+ assert args.skip_compile_ops == frozenset()+ assert args.min_run_time == 1.0+ assert args.json is None+ assert args.contribute is Nonedef test_add_flagship_args_rejects_unknown_ops(capsys) -> None:@@ -364,9 +378,12 @@ def test_run_batch_sweep_records_raising_backend(capsys) -> None:rows = run_batch_sweep([1], build, ["ok", "bad"], row_fields=lambda b: {}, min_run_time=0.05)bad = next(r for r in rows if r["backend"] == "bad")- assert bad["error"] == "ValueError" and bad["median_us"] is None and bad["throughput_per_s"] is None+ assert bad["error"] == "ValueError"+ assert bad["median_us"] is None+ assert bad["throughput_per_s"] is Noneout = capsys.readouterr().out- assert "β" in out and "a_very_long_operation_name_here/bad" in out+ assert "β" in out+ assert "a_very_long_operation_name_here/bad" in out# the label column grows to fit the longest op name instead of running into the first cellline = next(line for line in out.splitlines() if line.startswith("a_very_long_operation_name_here"))assert line[len("a_very_long_operation_name_here")] == " "@@ -414,7 +431,8 @@ def test_start_run_notes_when_opencv_ignores_threads(monkeypatch, capsys) -> Nonargs = _flagship_parser().parse_args([])common.start_run("flagship demo", args, torch.device("cpu"), units="img/s")out = capsys.readouterr().out- assert f"OpenCV ignored --threads {torch.get_num_threads()}" in out and "runs on 8 threads" in out+ assert f"OpenCV ignored --threads {torch.get_num_threads()}" in out+ assert "runs on 8 threads" in outdef test_setup_run_without_opencv_leaves_it_out(monkeypatch, capsys) -> None:@@ -443,4 +461,5 @@ def test_setup_run_without_opencv_leaves_it_out(monkeypatch, capsys) -> None:sys.modules.pop("cv2", None)assert meta["opencv_num_threads"] is Noneout = capsys.readouterr().out- assert "# device=cpu, dtype=float32, threads=3, size=" in out and "OpenCV ignored" not in out+ assert "# device=cpu, dtype=float32, threads=3, size=" in out+ assert "OpenCV ignored" not in outdiff --git a/benchmarks/filters/gaussian_cpu.py b/benchmarks/filters/gaussian_cpu.pyindex 91e0b89bd..e4082bc36 100644--- a/benchmarks/filters/gaussian_cpu.py+++ b/benchmarks/filters/gaussian_cpu.py@@ -126,7 +126,8 @@ def differences(actual: tuple[torch.Tensor, ...], reference: tuple[torch.Tensor,assert len(actual) == len(reference)stats = []for current, baseline in zip(actual, reference):- assert current.shape == baseline.shape and current.dtype == baseline.dtype+ assert current.shape == baseline.shape+ assert current.dtype == baseline.dtypedelta = (current.double() - baseline.double()).abs()scale = baseline.double().abs().max().item()norm = baseline.double().norm().item()diff --git a/benchmarks/results_schema_test.py b/benchmarks/results_schema_test.pyindex 8e6ce1454..b0930817d 100644--- a/benchmarks/results_schema_test.py+++ b/benchmarks/results_schema_test.py@@ -155,7 +155,8 @@ def test_non_object_payload_rejected(tmp_path) -> None:p.parent.mkdir()p.write_text(json.dumps(["metadata", "results"]))errors = results_schema.validate_result(p)- assert errors and "object" in errors[0]+ assert errors+ assert "object" in errors[0]def test_non_object_metadata_rejected(tmp_path) -> None:@@ -163,7 +164,8 @@ def test_non_object_metadata_rejected(tmp_path) -> None:p.parent.mkdir()p.write_text(json.dumps({"metadata": "oops", "results": []}))errors = results_schema.validate_result(p)- assert errors and "metadata must be an object" in errors[0]+ assert errors+ assert "metadata must be an object" in errors[0]def test_bool_batch_rejected(tmp_path) -> None:diff --git a/pyproject.toml b/pyproject.tomlindex 982de8c1d..44b07e7d3 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -219,6 +219,7 @@ select = ["PT013", # flake8-pytest-style: pytest imports"PT014", # flake8-pytest-style: duplicate parametrized cases"PT017", # flake8-pytest-style: assertions in exception handlers+ "PT018", # flake8-pytest-style: composite assertions"PT022", # flake8-pytest-style: useless yield fixtures"PT023", # flake8-pytest-style: mark parentheses"PT030", # flake8-pytest-style: specific warning matchesdiff --git a/tests/augmentation/container/test_random_crop.py b/tests/augmentation/container/test_random_crop.pyindex 8164b997b..8b9a5257d 100644--- a/tests/augmentation/container/test_random_crop.py+++ b/tests/augmentation/container/test_random_crop.py@@ -78,7 +78,9 @@ class TestRandomCropAnnotations(BaseTester):# The stored coordinates are separable, so read x along the first row and y down the first column.x_of_column, y_of_row = out[0, 0, 0], out[0, 1, :, 0]for (x, y), (px, py) in zip(points[0].tolist(), out_points[0].tolist()):- assert 0 < px < size[1] - 1 and 0 < py < size[0] - 1 # inside the rows and columns the resize clamps+ # inside the rows and columns the resize clamps+ assert 0 < px < size[1] - 1+ assert 0 < py < size[0] - 1x_lo, y_lo = int(px // 1), int(py // 1)sampled_x = torch.lerp(x_of_column[x_lo], x_of_column[x_lo + 1], px - x_lo)sampled_y = torch.lerp(y_of_row[y_lo], y_of_row[y_lo + 1], py - y_lo)diff --git a/tests/contrib/test_augmentation_audit.py b/tests/contrib/test_augmentation_audit.pyindex 907b9a83c..472231fbe 100644--- a/tests/contrib/test_augmentation_audit.py+++ b/tests/contrib/test_augmentation_audit.py@@ -210,7 +210,8 @@ class TestAugmentationAudit(BaseTester):outputs, report = audit(aug, image, points)self.assert_close(outputs[1], points)assert report.geometry_status == "unsupported"- assert report.matrix is None and report.inverse_matrix is None+ assert report.matrix is None+ assert report.inverse_matrix is Noneassert report.spatial[0].roundtrip_valid_count.item() == 0assert torch.isnan(report.spatial[0].roundtrip_max).all()assert "non-rigid" in report.summary()@@ -247,8 +248,11 @@ class TestAugmentationAudit(BaseTester):aug = K.AugmentationSequential(torch.nn.Identity(), data_keys=["input", "keypoints"])_, report = audit(aug, image, points)item = report.spatial[0]- assert item.count.item() == 4 and item.out_of_frame.item() == 1 and item.nonfinite.item() == 1- assert item.out_of_frame_fraction.item() == 0.25 and item.roundtrip_valid_count.item() == 3+ assert item.count.item() == 4+ assert item.out_of_frame.item() == 1+ assert item.nonfinite.item() == 1+ assert item.out_of_frame_fraction.item() == 0.25+ assert item.roundtrip_valid_count.item() == 3json.loads(report.to_json())def test_snapshots_and_gradients(self, device, dtype):@@ -320,7 +324,8 @@ class TestAugmentationAudit(BaseTester):image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)output, report = audit(K.AugmentationSequential(), image)self.assert_close(output, image)- assert report.steps == [] and report.params == []+ assert report.steps == []+ assert report.params == []assert report.geometry_status == "available"self.assert_close(report.matrix, torch.eye(3, device=device, dtype=report.matrix.dtype).unsqueeze(0))@@ -426,11 +431,13 @@ class TestAugmentationAudit(BaseTester):aug = K.AugmentationSequential(policy, data_keys=["input", "keypoints"])outputs, report = audit(aug, image, points)assert report.geometry_status == "unsupported"- assert report.matrix is None and report.inverse_matrix is None+ assert report.matrix is None+ assert report.inverse_matrix is Noneassert not report.invertible.any()assert report.spatial[0].roundtrip_valid_count.item() == 0assert report.steps == []- assert policy_name in report.summary() and "capture" in report.summary()+ assert policy_name in report.summary()+ assert "capture" in report.summary()replay = aug(image, points, params=report.params)for actual, expected in zip(outputs, replay):self.assert_close(actual, expected)@@ -521,7 +528,8 @@ class TestAugmentationAudit(BaseTester):image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)output, report = audit(aug, image, params=None if nested else [])self.assert_close(output, image)- assert report.steps == [] and report.geometry_status == "available"+ assert report.steps == []+ assert report.geometry_status == "available"assert not report.warnings@pytest.mark.parametrize("name", ["Resize", "LongestMaxSize"])@@ -679,6 +687,7 @@ class TestAugmentationAudit(BaseTester):)assert report.steps[0].flags["cropping_mode"] == effectiveassert module.flags["cropping_mode"] == configured- assert outputs[0][0, 0, 2, 3].item() == 1 and outputs[0][1, 0, 2, 3].item() == 1+ assert outputs[0][0, 0, 2, 3].item() == 1+ assert outputs[0][1, 0, 2, 3].item() == 1assert report.geometry_status == "available"self.assert_close(report.matrix[:, :2, 2], report.matrix.new_tensor([[0, 1], [0, 1]]))diff --git a/tests/core/test_download.py b/tests/core/test_download.pyindex 2b2d72047..09255f97a 100644--- a/tests/core/test_download.py+++ b/tests/core/test_download.py@@ -105,7 +105,8 @@ class TestHfCacheFileName:def test_the_result_is_one_path_component(self) -> None:name = _hf_cache_file_name("google/siglip2-base-patch16-224", "model.safetensors")- assert os.sep not in name and "/" not in name+ assert os.sep not in name+ assert "/" not in nameclass TestLoadStateDictFromUrl:@@ -1407,7 +1408,8 @@ class TestDownloadFileFromUrl:message = str(excinfo.value)assert "Failed to download the file from all 2 source" in message- assert "HTTPError" in message and "404" in message+ assert "HTTPError" in message+ assert "404" in messageassert os.path.join(str(tmp_path), "checkpoints", "m.safetensors") in messageassert isinstance(excinfo.value.__cause__, HTTPError)@@ -1914,10 +1916,12 @@ class TestTransferTimeout:assert isinstance(outcome, RuntimeError), f"expected the documented RuntimeError, got {outcome!r}"assert isinstance(outcome.__cause__, TimeoutError)message = str(outcome)- assert "TimeoutError" in message and f"{self._TIMEOUT:g} s" in message+ assert "TimeoutError" in message+ assert f"{self._TIMEOUT:g} s" in messageassert str(cache / "w.pth") in message# Where the bound can be raised, including for callers such as pretrained constructors that take no timeout=.- assert "timeout=" in message and "KORNIA_DOWNLOAD_TIMEOUT" in message+ assert "timeout=" in message+ assert "KORNIA_DOWNLOAD_TIMEOUT" in messageassert "_DOWNLOAD_TIMEOUT_SECONDS" not in message# A timeout is transient, so the retry logic got control on every attempt.assert len(stalled_server.connections) == download_mod._MAX_ATTEMPTS@@ -2594,7 +2598,8 @@ class TestDownloadTimeoutEnvironment:finally:server.close()- assert isinstance(outcome, RuntimeError) and isinstance(outcome.__cause__, TimeoutError)+ assert isinstance(outcome, RuntimeError)+ assert isinstance(outcome.__cause__, TimeoutError)assert "0.25 s" in str(outcome)def test_an_explicit_timeout_does_not_read_the_variable(self, scripted_server, monkeypatch, tmp_path) -> None:diff --git a/tests/core/test_helpers.py b/tests/core/test_helpers.pyindex fdc3b1320..e8eabf38d 100644--- a/tests/core/test_helpers.py+++ b/tests/core/test_helpers.py@@ -730,7 +730,8 @@ class TestInverseWithMask:def test_rule_reads_the_determinant_against_the_permanent(self, device, dtype, n):A = torch.tensor(_DEPENDENT_ROWS[n], device=device, dtype=dtype)det, perm = _det_perm_closed_form(A)- assert torch.equal(det, torch.zeros_like(det)) and perm.item() > 0+ assert torch.equal(det, torch.zeros_like(det))+ assert perm.item() > 0assert _is_singular(A).item()# [[1, 1], [1, 1 + d]] has determinant d, exact for a power of two d, against a permanent of 2 + d:# the threshold ``8 * n * eps * perm`` sits at about 32 eps, so 64 eps is regular and 24 eps singulardiff --git a/tests/core/test_small_linalg.py b/tests/core/test_small_linalg.pyindex 6b82a397b..7aae1785a 100644--- a/tests/core/test_small_linalg.py+++ b/tests/core/test_small_linalg.py@@ -260,7 +260,8 @@ class TestDetPermKernels(BaseTester):det, perm = DET_PERM[n](_well_conditioned(n, device, dtype))assert det.shape == ()assert perm.shape == ()- assert det.dtype == dtype and perm.dtype == dtype+ assert det.dtype == dtype+ assert perm.dtype == dtype@pytest.mark.parametrize("n", [2, 3, 4])@pytest.mark.parametrize("batch", [(), (2,), (2, 3)])diff --git a/tests/filters/test_guided.py b/tests/filters/test_guided.pyindex 19d7cb34b..8fb285a49 100644--- a/tests/filters/test_guided.py+++ b/tests/filters/test_guided.py@@ -104,12 +104,10 @@ def _scale_factor_interpolate(x, size=None, scale_factor=None, mode=None, **kwarassert not kwargs(h, w), (H, W) = x.shape[-2:], sizeratio = max(h, H) // min(h, H)- assert (- ratio > 1- and ratio * min(h, H) == max(h, H)- and ratio * min(w, W) == max(w, W)- and max(w, W) // min(w, W) == ratio- )+ assert ratio > 1+ assert ratio * min(h, H) == max(h, H)+ assert ratio * min(w, W) == max(w, W)+ assert max(w, W) // min(w, W) == ratioif H < h:return F.interpolate(x, scale_factor=1 / ratio, mode="nearest")return F.interpolate(x, scale_factor=ratio, mode="bilinear")diff --git a/tests/filters/test_median.py b/tests/filters/test_median.pyindex d1652c2a7..d996082b9 100644--- a/tests/filters/test_median.py+++ b/tests/filters/test_median.py@@ -410,7 +410,8 @@ class TestConventionsMedianBlur(BaseTester):for kernel_size, changed in ((3, 4), (5, 12)):self.assert_close(median_blur(image, kernel_size).detach(), image.detach())zero_padded = median_blur(image, kernel_size, border_type="constant").detach()- assert zero_padded[0, 0, 0, 0] == 0 and zero_padded[0, 0, -1, -1] == 0+ assert zero_padded[0, 0, 0, 0] == 0+ assert zero_padded[0, 0, -1, -1] == 0assert int((zero_padded != image.detach()).sum()) == changed# the default is 'reflect', not just a mode that keeps a constanttorch.manual_seed(0)diff --git a/tests/filters/test_unsharp_mask.py b/tests/filters/test_unsharp_mask.pyindex b6bc80720..3b60af308 100644--- a/tests/filters/test_unsharp_mask.py+++ b/tests/filters/test_unsharp_mask.py@@ -116,4 +116,5 @@ class TestConventionsUnsharpMask(BaseTester):out = unsharp_mask(step, (5, 5), (1.5, 1.5))expected = [0.0, 0.0, 0.0, -0.120078, -0.353959, 1.353959, 1.120078, 1.0, 1.0, 1.0]self.assert_close(out[0, 0, 3], torch.tensor(expected, device=device, dtype=dtype))- assert out.min() < -0.3 and out.max() > 1.3+ assert out.min() < -0.3+ assert out.max() > 1.3diff --git a/tests/geometry/liegroup/test_se2.py b/tests/geometry/liegroup/test_se2.pyindex cd68c1a9b..fe8afaefe 100644--- a/tests/geometry/liegroup/test_se2.py+++ b/tests/geometry/liegroup/test_se2.py@@ -496,12 +496,14 @@ class TestSe2(BaseTester):else:before_dtype = pose.so2.z.dtypeparent.to(device=device)- assert pose.so2.z.dtype == before_dtype and pose.t.dtype == source_dtype+ assert pose.so2.z.dtype == before_dtype+ assert pose.t.dtype == source_dtypename = {torch.float16: "half", torch.float32: "float", torch.float64: "double"}[dtype]getattr(parent, name)()assert pose.so2.z.device == pose.t.device == device- assert pose.so2.z.is_complex() and pose.so2.z.real.dtype == pose.t.dtype == dtype+ assert pose.so2.z.is_complex()+ assert pose.so2.z.real.dtype == pose.t.dtype == dtypeassert set(parent.state_dict()) == {"pose._rotation._z", "pose._translation"}assert set(dict(parent.named_buffers())) == {"pose._rotation._z", "pose._translation"}assert not dict(parent.named_parameters())@@ -535,9 +537,11 @@ class TestSe2(BaseTester):}target = Se2.identity(1, device, source_dtype).to(dtype=dtype)result = target.load_state_dict(legacy_state)- assert not result.missing_keys and not result.unexpected_keys+ assert not result.missing_keys+ assert not result.unexpected_keysassert set(target.state_dict()) == set(legacy_state)- assert target.so2.z.is_complex() and target.so2.z.real.dtype == target.t.dtype == dtype+ assert target.so2.z.is_complex()+ assert target.so2.z.real.dtype == target.t.dtype == dtypeexpected_matrix = torch.tensor([[[0.0, -1.0, 3.0], [1.0, 0.0, 4.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)diff --git a/tests/geometry/liegroup/test_so2.py b/tests/geometry/liegroup/test_so2.pyindex 9b51d244f..20a2768c0 100644--- a/tests/geometry/liegroup/test_so2.py+++ b/tests/geometry/liegroup/test_so2.py@@ -468,7 +468,8 @@ class TestSo2DtypeMigration(BaseTester):before = rotation.z.detach().clone()assert self._cast(rotation, dtype, method) is rotation- assert rotation.z.is_complex() and rotation.z.real.dtype == dtype+ assert rotation.z.is_complex()+ assert rotation.z.real.dtype == dtypeassert rotation.state_dict()["_z"].shape == shapeself.assert_close(rotation.z.real, before.real.to(dtype))self.assert_close(rotation.z.imag, before.imag.to(dtype))@@ -493,9 +494,11 @@ class TestSo2DtypeMigration(BaseTester):parent = torch.nn.ModuleDict({"rotation": rotation})assert self._cast(parent, dtype, method) is parent- assert rotation.z.is_complex() and rotation.z.real.dtype == dtype+ assert rotation.z.is_complex()+ assert rotation.z.real.dtype == dtypeassert rotation.extra.value.dtype == dtype- assert rotation.extra.weight.dtype == dtype and rotation.extra.weight.grad.dtype == dtype+ assert rotation.extra.weight.dtype == dtype+ assert rotation.extra.weight.grad.dtype == dtypeassert dict(parent.named_parameters())["rotation.extra.weight"] is rotation.extra.weightassert dict(parent.named_buffers())["rotation._z"] is rotation._z@@ -510,7 +513,8 @@ class TestSo2DtypeMigration(BaseTester):assert isinstance(rotation._z, torch.nn.Parameter)assert dict(rotation.named_parameters())["_z"] is rotation._z- assert rotation._z.grad.is_complex() and rotation._z.grad.real.dtype == dtype+ assert rotation._z.grad.is_complex()+ assert rotation._z.grad.real.dtype == dtypeself.assert_close(rotation._z.grad.real, torch.ones(2, device=device, dtype=dtype))self.assert_close(rotation._z.grad.imag, torch.full((2,), 2.0, device=device, dtype=dtype))torch.optim.SGD(rotation.parameters(), lr=0.125).step()@@ -573,10 +577,12 @@ class TestSo2DtypeMigration(BaseTester):target = So2.exp((-theta).requires_grad_()).to(dtype=dtype)assert target._z.data_ptr() != legacy_state["_z"].data_ptr()result = target.load_state_dict(legacy_state)- assert not result.missing_keys and not result.unexpected_keys+ assert not result.missing_keys+ assert not result.unexpected_keysassert list(target.state_dict()) == ["_z"]assert target.state_dict()["_z"].shape == legacy_state["_z"].shape- assert target.z.is_complex() and target.z.real.dtype == dtype+ assert target.z.is_complex()+ assert target.z.real.dtype == dtypeself.assert_close(target.z.real, legacy_state["_z"].real.to(dtype))self.assert_close(target.z.imag, legacy_state["_z"].imag.to(dtype))restored = So2.identity(2, device, dtype)@@ -601,7 +607,8 @@ class TestSo2DtypeMigration(BaseTester):else:parent.to(device=device)assert rotation.z.device == device- assert rotation.z.is_complex() and rotation.z.real.dtype == dtype+ assert rotation.z.is_complex()+ assert rotation.z.real.dtype == dtypeassert parent.state_dict()["rotation._z"].device == deviceassert isinstance(rotation._z, torch.nn.Parameter) == as_parameterc, s = angle.cos().to(device=device, dtype=dtype), angle.sin().to(device=device, dtype=dtype)diff --git a/tests/losses/test_divergence.py b/tests/losses/test_divergence.pyindex 735423bf2..08dd26f8c 100644--- a/tests/losses/test_divergence.py+++ b/tests/losses/test_divergence.py@@ -173,7 +173,8 @@ class TestDivergenceLoss(BaseTester):# tolerance.self.assert_close(actual, torch.zeros_like(actual))actual.backward()- assert torch.isfinite(pred.grad).all() and torch.isfinite(target.grad).all()+ assert torch.isfinite(pred.grad).all()+ assert torch.isfinite(target.grad).all()assert torch.equal(pred.grad[p == 0], torch.zeros_like(pred.grad[p == 0]))assert torch.equal(target.grad[p == 0], torch.zeros_like(target.grad[p == 0]))@@ -193,7 +194,8 @@ class TestDivergenceLoss(BaseTester):q = torch.tensor([0.1, 0.2, 0.3, 0.1, 0.2, 0.1], device=device, dtype=dtype).view(1, 1, 2, 3)pred, target = q.clone().requires_grad_(), p.clone().requires_grad_()loss(pred, target).backward()- assert torch.isfinite(pred.grad).all() and torch.isfinite(target.grad).all()+ assert torch.isfinite(pred.grad).all()+ assert torch.isfinite(target.grad).all()@pytest.mark.parametrize("loss", [kornia.losses.kl_div_loss_2d, kornia.losses.js_div_loss_2d])def test_invalid_cells_stay_nan(self, device, dtype, loss):diff --git a/tests/losses/test_ssim.py b/tests/losses/test_ssim.pyindex 1231816a1..0f827f97a 100644--- a/tests/losses/test_ssim.py+++ b/tests/losses/test_ssim.py@@ -457,7 +457,8 @@ class TestSSIM3DLoss(BaseTester):expected = ((1.0 - ssim_map) / 2).clamp(0, 1)actual = kornia.losses.ssim3d_loss(img1, img2, 5, reduction="none")self.assert_close(actual, expected, rtol=0, atol=0)- assert actual.min() >= 0 and actual.max() <= 1+ assert actual.min() >= 0+ assert actual.max() <= 1self.assert_close(kornia.losses.SSIM3DLoss(5)(img1, img2), expected.mean())def test_clamps_roundoff_into_the_unit_range(self, device, dtype):diff --git a/tests/models/test_model_common.py b/tests/models/test_model_common.pyindex 7f4134241..9600062d6 100644--- a/tests/models/test_model_common.py+++ b/tests/models/test_model_common.py@@ -149,7 +149,8 @@ class TestWindowPartition:# H=8, W=8, window_size=4 -> no paddingx = torch.rand(2, 8, 8, 16)windows, (Hp, Wp) = window_partition(x, window_size=4)- assert Hp == 8 and Wp == 8+ assert Hp == 8+ assert Wp == 8# 2 batches * (8/4)*(8/4) = 2*4 = 8 windowsassert windows.shape == (8, 4, 4, 16)diff --git a/tests/models/test_segmentation_models.py b/tests/models/test_segmentation_models.pyindex 19d5a1b60..38ee3bcda 100644--- a/tests/models/test_segmentation_models.py+++ b/tests/models/test_segmentation_models.py@@ -54,7 +54,8 @@ class TestSegmentationModelsBuilder(BaseTester):out = model(images)assert isinstance(out, torch.Tensor)assert out.shape == (2, 2, 8, 12)- assert out.device == images.device and out.dtype == dtype+ assert out.device == images.device+ assert out.dtype == dtypeassert torch.isfinite(out).all()# The softmax head normalizes over the class axis, so the output is not a degenerate map.self.assert_close(out.sum(dim=1), torch.ones(2, 8, 12, device=device, dtype=dtype))@@ -63,8 +64,10 @@ class TestSegmentationModelsBuilder(BaseTester):model = SegmentationModelsBuilder.build(_stand_in_network(), IMAGENET_PARAMS).to(device, dtype)images = [torch.rand(3, 8, 12, device=device, dtype=dtype), torch.rand(3, 6, 6, device=device, dtype=dtype)]out = model(images)- assert isinstance(out, list) and len(out) == 2- assert out[0].shape == (2, 8, 12) and out[1].shape == (2, 6, 6)+ assert isinstance(out, list)+ assert len(out) == 2+ assert out[0].shape == (2, 8, 12)+ assert out[1].shape == (2, 6, 6)self.assert_close(out[0], model(images[0][None])[0])def test_default_name(self):@@ -93,7 +96,9 @@ class TestSegmentationModelsBuilder(BaseTester):expected = (x64.flip(1) * 255.0 - mean_t) / std_tout64 = out.cpu().to(torch.float64)- assert out.shape == x.shape and out.dtype == dtype and out.device == x.device+ assert out.shape == x.shape+ assert out.dtype == dtype+ assert out.device == x.device# The pipeline chains three rounding ops in the working dtype at magnitudes up to ~1100, so the# accumulated error reaches ~2 eps (measured over 50 draws: 1.9 float32, 1.3 float16, 1.4 bfloat16)# while BaseTester's half-precision defaults are rtol ~1 eps and fail here. The pipeline builds its@@ -114,7 +119,8 @@ class TestSegmentationModelsBuilder(BaseTester):x = torch.tensor([0.0, 0.5, 1.0], device=device, dtype=dtype).view(1, 3, 1, 1).expand(1, 3, 2, 2)expected = torch.tensor([0.0, 127.5, 255.0], device=device, dtype=dtype).view(1, 3, 1, 1).expand(1, 3, 2, 2)out = pipeline(x)- assert out.dtype == dtype and out.device == x.device+ assert out.dtype == dtype+ assert out.device == x.deviceassert torch.equal(out, expected)def test_preprocessing_rgb_unit_range(self, device, dtype):@@ -171,8 +177,10 @@ class TestSemanticSegmentation(BaseTester):assert torch.isfinite(vis).all()# Same through the per-image list path, which draws a colormap per mask.vis_list = model.visualize([images[0], images[1]])- assert isinstance(vis_list, list) and len(vis_list) == 2- assert vis_list[0].shape == (3, 6, 6) and vis_list[0].device == images.device+ assert isinstance(vis_list, list)+ assert len(vis_list) == 2+ assert vis_list[0].shape == (3, 6, 6)+ assert vis_list[0].device == images.deviceself.assert_close(vis_list[0], vis[0])def test_visualize_rejects_logits(self, device, dtype):diff --git a/tests/onnx/test_download.py b/tests/onnx/test_download.pyindex f32a6b9ff..cc73bd090 100644--- a/tests/onnx/test_download.py+++ b/tests/onnx/test_download.py@@ -195,7 +195,8 @@ class TestCachedDownloader:server.server_close()server_thread.join(5)- assert len(errors) == 1 and isinstance(errors[0], TimeoutError), errors+ assert len(errors) == 1, errors+ assert isinstance(errors[0], TimeoutError), errorsassert not path.exists()assert not list(path.parent.glob("*.partial"))diff --git a/tests/scripts/test_check_changelog.py b/tests/scripts/test_check_changelog.pyindex 76c088b92..7022b5b17 100644--- a/tests/scripts/test_check_changelog.py+++ b/tests/scripts/test_check_changelog.py@@ -23,7 +23,8 @@ import pytest_SCRIPT = Path(__file__).parent.parent.parent / ".github" / "scripts" / "check_changelog.py"_SPEC = importlib.util.spec_from_file_location("check_changelog", _SCRIPT)-assert _SPEC is not None and _SPEC.loader is not None+assert _SPEC is not None+assert _SPEC.loader is not Nonecheck_changelog = importlib.util.module_from_spec(_SPEC)sys.modules[_SPEC.name] = check_changelog_SPEC.loader.exec_module(check_changelog)diff --git a/tests/scripts/test_check_import_surface.py b/tests/scripts/test_check_import_surface.pyindex afc8959ee..4dff2efb1 100644--- a/tests/scripts/test_check_import_surface.py+++ b/tests/scripts/test_check_import_surface.py@@ -1120,8 +1120,11 @@ def test_mixed_removals_have_separate_actionable_remedies(tmp_path, capsys):assert _in_repo(repo, lambda: main(["--base-ref", "base"])) == 1errors = [line for line in capsys.readouterr().out.splitlines() if "Removed from __all__" in line]assert len(errors) == 2- assert "['a']" in errors[0] and INVENTORY_PATH in errors[0] and REMOVALS_PATH not in errors[0]- assert "['b']" in errors[1] and REMOVALS_PATH in errors[1]+ assert "['a']" in errors[0]+ assert INVENTORY_PATH in errors[0]+ assert REMOVALS_PATH not in errors[0]+ assert "['b']" in errors[1]+ assert REMOVALS_PATH in errors[1]def test_explicit_record_does_not_replace_exact_inventory_update(tmp_path, capsys):diff --git a/tests/scripts/test_check_torch_env.py b/tests/scripts/test_check_torch_env.pyindex 2c8c26de3..daa41f0c6 100644--- a/tests/scripts/test_check_torch_env.py+++ b/tests/scripts/test_check_torch_env.py@@ -142,7 +142,8 @@ class TestCheckEnvironment:problems = check_environment("2.6.0+cpu", CPU_WHEEL_REQUIRES, installed, "pinned", "2.6.0", LINUX_PY311)assert len(problems) == 1- assert "sympy" in problems[0] and "not installed" in problems[0]+ assert "sympy" in problems[0]+ assert "not installed" in problems[0]def test_flags_a_requirement_left_at_the_locked_version(self):# The failure mode option 1 of #4199 addresses: a dependency the pin step did not move.diff --git a/tests/test_benchmark_timing.py b/tests/test_benchmark_timing.pyindex ff894ceac..c1e29cbd3 100644--- a/tests/test_benchmark_timing.py+++ b/tests/test_benchmark_timing.py@@ -38,7 +38,8 @@ def _load_filter_flagship():root = Path(__file__).parents[1]script = root / "benchmarks/filters/flagship.py"spec = importlib.util.spec_from_file_location("filter_flagship", script)- assert spec and spec.loader+ assert spec+ assert spec.loadermodule = importlib.util.module_from_spec(spec)benchmark_dir = str(script.parent.parent)sys.path.insert(0, benchmark_dir)@@ -63,8 +64,10 @@ def test_timing_preserves_configured_threads():try:torch.set_num_threads(2)median, spread = common.time_us(lambda: observed.append(torch.get_num_threads()), min_run_time=0.01)- assert median > 0 and spread >= 0- assert observed and set(observed) == {2}+ assert median > 0+ assert spread >= 0+ assert observed+ assert set(observed) == {2}assert torch.get_num_threads() == 2finally:torch.set_num_threads(previous)diff --git a/tests/test_generate_benchmarks.py b/tests/test_generate_benchmarks.pyindex 487440b2b..7c4796c7d 100644--- a/tests/test_generate_benchmarks.py+++ b/tests/test_generate_benchmarks.py@@ -53,9 +53,14 @@ def _seed(tmp_path: Path) -> Path:def test_render_page_contains_table_and_metadata(tmp_path: Path) -> None:rst = generate_benchmarks.render_page(_seed(tmp_path))- assert "Performance" in rst and "ColorJiggle" in rst- assert "317" in rst and "2526" in rst # numbers from the JSON, not hand-written- assert "apple-m3" in rst and "2026-08-08" in rst # machine + date disclosed+ assert "Performance" in rst+ assert "ColorJiggle" in rst+ # numbers from the JSON, not hand-written+ assert "317" in rst+ assert "2526" in rst+ # machine + date disclosed+ assert "apple-m3" in rst+ assert "2026-08-08" in rstassert "close other applications" in rst # hygiene box present@@ -96,7 +101,8 @@ def test_render_page_keeps_configs_that_share_a_batch(tmp_path: Path) -> None:"33","31",]- assert "n_lafs=2000" in rst and "n_lafs=20000" in rst+ assert "n_lafs=2000" in rst+ assert "n_lafs=20000" in rstassert "throughput in LAFs/s" in rst # the item is a LAF, not an image@@ -129,14 +135,16 @@ def test_refresh_llms_replaces_only_marker_block(tmp_path: Path) -> None:llms.write_text("before\n<!-- BENCH:BEGIN -->\nold\n<!-- BENCH:END -->\nafter\n")generate_benchmarks.refresh_llms(llms, _seed(tmp_path))text = llms.read_text()- assert text.startswith("before\n") and text.endswith("after\n")+ assert text.startswith("before\n")+ assert text.endswith("after\n")assert "old" not in text # marker block content was replaced, not appended to# digest is one headline line per result file, naming the actual op/batch that was# fastest/slowest so the numbers can't be misread as a blanket per-backend gapdigest_lines = [ln for ln in text.splitlines() if ln.startswith("- augmentation")]assert len(digest_lines) == 1assert "ColorJiggle@32" in digest_lines[0]- assert "0.9.0rc1" in text and "apple-m3" in text+ assert "0.9.0rc1" in text+ assert "apple-m3" in textdef test_refresh_llms_idempotent(tmp_path: Path) -> None:@@ -196,7 +204,8 @@ def test_superseded_results_are_not_published(tmp_path: Path) -> None:assert "0.9.0rc1" in generate_benchmarks.load_results(root) # the live run is still loadedassert list(generate_benchmarks.load_results(root)["0.9.0rc1"]) == ["augmentation--apple-m3--mps.json"]rst = generate_benchmarks.render_page(root)- assert "deadbeef" not in rst and "filters" not in rst+ assert "deadbeef" not in rst+ assert "filters" not in rstassert "superseded/" in rst # but the page says where the unpublished runs livellms = tmp_path / "llms-full.txt"llms.write_text("a\n<!-- BENCH:BEGIN -->\n<!-- BENCH:END -->\nb\n")@@ -210,4 +219,5 @@ def test_digest_line_names_version_and_commit(tmp_path: Path) -> None:llms.write_text("a\n<!-- BENCH:BEGIN -->\n<!-- BENCH:END -->\nb\n")generate_benchmarks.refresh_llms(llms, _seed(tmp_path))line = next(ln for ln in llms.read_text().splitlines() if ln.startswith("- augmentation"))- assert "kornia 0.9.0rc1 @ c670e2ab" in line and "2026-08-08" in line+ assert "kornia 0.9.0rc1 @ c670e2ab" in line+ assert "2026-08-08" in line