Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,7 @@ Lukas Bednar
Luke Murphy
Maciek Fijalkowski
Madan Kumar
MadhurBagdare
Maggie Chung
Maho
Maik Figura
Expand Down
1 change: 1 addition & 0 deletions changelog/9007.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed ``runpy.run_module()`` crashing with ``AttributeError: 'AssertionRewritingHook' object has no attribute 'get_code'`` on a module pytest had rewritten.
43 changes: 32 additions & 11 deletions src/_pytest/assertion/rewrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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.
Expand Down
64 changes: 64 additions & 0 deletions testing/test_assertrewrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Loading