From 670ef4df32dc865c61703fdaf586685632ab214b Mon Sep 17 00:00:00 2001 From: MadhurBagdare <85842108+MadhurBagdare@users.noreply.github.com> Date: Sat, 5 Dec 2026 02:43:57 +0530 Subject: [PATCH] fix(rewrite): let runpy re-run rewritten modules runpy.run_module() calls loader.get_code(). AssertionRewritingHook only implemented exec_module(), so re-running a rewritten module raised AttributeError. get_code returns the rewritten code and does not execute the module, so a nested pytest.main() is not started from the loader. --- AUTHORS | 1 + changelog/9007.bugfix.rst | 1 + src/_pytest/assertion/rewrite.py | 43 +++++++++++++++------ testing/test_assertrewrite.py | 64 ++++++++++++++++++++++++++++++++ 4 files changed, 98 insertions(+), 11 deletions(-) create mode 100644 changelog/9007.bugfix.rst diff --git a/AUTHORS b/AUTHORS index f04403e2d5c..a620c1da541 100644 --- a/AUTHORS +++ b/AUTHORS @@ -306,6 +306,7 @@ Lukas Bednar Luke Murphy Maciek Fijalkowski Madan Kumar +MadhurBagdare Maggie Chung Maho Maik Figura diff --git a/changelog/9007.bugfix.rst b/changelog/9007.bugfix.rst new file mode 100644 index 00000000000..6ffd2e3ff1c --- /dev/null +++ b/changelog/9007.bugfix.rst @@ -0,0 +1 @@ +Fixed ``runpy.run_module()`` crashing with ``AttributeError: 'AssertionRewritingHook' object has no attribute 'get_code'`` on a module pytest had rewritten. diff --git a/src/_pytest/assertion/rewrite.py b/src/_pytest/assertion/rewrite.py index 01188af19af..3c62087b097 100644 --- a/src/_pytest/assertion/rewrite.py +++ b/src/_pytest/assertion/rewrite.py @@ -146,18 +146,39 @@ def exec_module(self, module: types.ModuleType) -> None: assert module.__spec__ is not None assert module.__spec__.origin is not None fn = Path(module.__spec__.origin) - state = self.config.stash[assertstate_key] - self._rewritten_names[module.__name__] = fn + exec(self._rewritten_code(fn), module.__dict__) - # The requested module looks like a test file, so rewrite it. This is - # the most magical part of the process: load the source, rewrite the - # asserts, and load the rewritten source. We also cache the rewritten - # module code in a special pyc. We must be aware of the possibility of - # concurrent pytest processes rewriting and loading pycs. To avoid - # tricky race conditions, we maintain the following invariant: The - # cached pyc is always a complete, valid pyc. Operations on it must be - # atomic. POSIX's atomic rename comes in handy. + def get_code(self, fullname: str) -> types.CodeType: + """Return rewritten code for ``runpy`` without executing the module. + + ``runpy`` loads through ``loader.get_code()``, not ``exec_module()``. + Executing here would start a nested pytest session when the module + calls ``pytest.main()`` at import time. ``find_spec`` selects the + hook, so a nested session rewrites with its own hook and config. + """ + fn = self._rewritten_names.get(fullname) + if fn is None: + module = sys.modules.get(fullname) + origin = getattr(getattr(module, "__spec__", None), "origin", None) + if isinstance(origin, str): + fn = Path(origin) + else: + spec = self.find_spec(fullname) + if spec is None or not spec.origin: + raise ImportError(f"cannot find source for {fullname!r}") + fn = Path(spec.origin) + self._rewritten_names[fullname] = fn + return self._rewritten_code(fn) + + def _rewritten_code(self, fn: Path) -> types.CodeType: + """Load or rewrite the code object for a source file. + + The cached pyc is always a complete, valid pyc. Operations on it must + be atomic. POSIX's atomic rename comes in handy. Concurrent pytest + processes can rewrite and load the same pyc. + """ + state = self.config.stash[assertstate_key] write = not sys.dont_write_bytecode cache_dir = get_cache_dir(fn) if write: @@ -182,7 +203,7 @@ def exec_module(self, module: types.ModuleType) -> None: self._writing_pyc = False else: state.trace(f"found cached rewritten pyc for {fn}") - exec(co, module.__dict__) + return co def _early_rewrite_bailout(self, name: str, state: AssertionState) -> bool: """A fast way to get out of rewriting modules. diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index 3ca422dd755..9a6fc3de1a5 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -2573,3 +2573,67 @@ def test_method_still_rewritten(): result = pytester.runpytest() result.assert_outcomes(passed=1, failed=1) result.stdout.fnmatch_lines(["*E*assert 100 == 2*"]) + + +def test_runpy_run_module_on_rewritten_module(pytester: Pytester) -> None: + """runpy.run_module() must not crash on a module the assertion hook loaded (#9007).""" + pytester.makepyfile( + """ + import runpy + + def fail(): + assert 1 == 2 + + def test_rerun_self(): + namespace = runpy.run_module(__name__) + try: + namespace["fail"]() + except AssertionError as exc: + assert "assert 1 == 2" in str(exc) + else: + raise AssertionError("expected AssertionError") + """ + ) + result = pytester.runpytest("-q") + result.assert_outcomes(passed=1) + + +def test_runpy_after_nested_pytest_session(pytester: Pytester) -> None: + """A nested session's rewrite hook and the outer one must both serve get_code.""" + pytester.makepyfile( + inner=""" + import runpy + + def fail(): + assert 5 == 6 + + def test_inner_runpy(): + namespace = runpy.run_module(__name__) + try: + namespace["fail"]() + except AssertionError as exc: + assert "assert 5 == 6" in str(exc) + else: + raise AssertionError("expected AssertionError") + """, + test_outer=""" + import runpy + + import pytest + + def fail(): + assert 3 == 4 + + def test_nested_then_runpy(): + assert pytest.main(["-q", "inner.py"]) == 0 + namespace = runpy.run_module(__name__) + try: + namespace["fail"]() + except AssertionError as exc: + assert "assert 3 == 4" in str(exc) + else: + raise AssertionError("expected AssertionError") + """, + ) + result = pytester.runpytest("-q", "test_outer.py") + result.assert_outcomes(passed=1)