π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix parent fixture teardown for isolated half-precision tests (#4388)
SHILIN KONG40d68e428d47
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 890204d53..debbdbe02 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -369,6 +369,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* Fixed fixture teardown between files when running half-precision tests with+ `--isolate-half-precision`, including reporting parent fixture finalizer errors. (#4388)* Corrected the matrix-shape checks shared by `PinholeCamera` and `PinholeCamerasList`, the`pixel2cam` coordinate-shape check, and the `cam2pixel` coordinate/projection checks. Invalidinputs now raise the intended `ValueError` instead of being accepted or failing later in tensordiff --git a/conftest.py b/conftest.pyindex bd3703a2c..010305d2e 100644--- a/conftest.py+++ b/conftest.py@@ -30,9 +30,10 @@ import pytestimport torchtry:- from pytest import TestReport # public since pytest 7.x+ from pytest import CallInfo, TestReport # public since pytest 7.xexcept ImportError: # pragma: no coverfrom _pytest.reports import TestReport # type: ignore[no-redef]+ from _pytest.runner import CallInfo # type: ignore[no-redef]import kornia@@ -832,10 +833,22 @@ def pytest_runtest_protocol(item, nextitem):for rep in [_report("setup", "passed", None),_report("call", outcome, longrepr, duration),- _report("teardown", "passed", None),]:item.ihook.pytest_runtest_logreport(report=rep)+ # The previous normal item may have kept module/class fixtures alive for this item.+ # Unwind them for the next item without setting up the isolated item's fixtures here.+ # Capture finalizer failures as teardown errors rather than aborting the runner.+ if item.session.shouldfail or item.session.shouldstop:+ nextitem = None+ teardown = CallInfo.from_call(+ lambda: item.session._setupstate.teardown_exact(nextitem),+ when="teardown",+ reraise=(KeyboardInterrupt, pytest.exit.Exception),+ )+ report = item.ihook.pytest_runtest_makereport(item=item, call=teardown)+ item.ihook.pytest_runtest_logreport(report=report)+item.ihook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location)return Truediff --git a/tests/test_conftest.py b/tests/test_conftest.pyindex ca4c95310..f10016a45 100644--- a/tests/test_conftest.py+++ b/tests/test_conftest.py@@ -193,6 +193,67 @@ class TestSkipHalfPrecisionOnCuda:class TestIntegrationLocalHalfPrecision:+ @pytest.mark.parametrize("teardown_error", [False, True])+ def test_isolated_item_tears_down_previous_module(self, pytester, monkeypatch, teardown_error):+ """An isolated item must release parent fixtures before the next module runs (#4149)."""+ # Load the real isolation plugin in both the parent and its child. The test requests+ # device_name rather than device, so the protocol runs without requiring a CUDA kernel.+ monkeypatch.setenv("PYTEST_PLUGINS", "conftest")+ events = pytester.path / "events.txt"+ pytester.makepyfile(+ test_first=f"""+ import os+ from pathlib import Path+ import pytest++ events = Path({str(events)!r})+ child = bool(os.environ.get("KORNIA_TEST_IN_SUBPROCESS"))++ def record(event):+ with events.open("a") as stream:+ stream.write(event + "\\n")++ @pytest.fixture(scope="module", autouse=True)+ def module_fixture():+ record("setup child" if child else "setup parent")+ yield+ record("teardown child" if child else "teardown parent")+ if not child and {teardown_error!r}:+ raise RuntimeError("parent finalizer failed")++ def test_normal():+ record("normal")++ @pytest.fixture+ def isolated_fixture():+ assert child, "isolated fixtures must not run in the parent"++ def test_isolated(device_name, dtype_name, isolated_fixture):+ assert child+ record("isolated")+ """,+ test_next=f"""+ from pathlib import Path++ def test_next_module():+ assert Path({str(events)!r}).read_text().splitlines() == [+ "setup parent", "normal", "setup child", "isolated",+ "teardown child", "teardown parent",+ ]+ """,+ )+ result = pytester.runpytest_subprocess(+ "test_first.py",+ "test_next.py",+ "--device=cuda",+ "--dtype=float16",+ "--isolate-half-precision",+ "-q",+ )+ result.assert_outcomes(passed=3, errors=int(teardown_error))+ if teardown_error:+ result.stdout.fnmatch_lines(["*ERROR at teardown of test_isolated*", "*parent finalizer failed*"])+def test_local_half_dtype_lifecycle_with_pytester(self, pytester):"""Integration test: verify real pytest execution with local half_dtype."""test_file = pytester.makepyfile(