MCPcopy Create free account
hub / github.com/pytest-dev/pytest / test_rewrite_infinite_recursion

Function test_rewrite_infinite_recursion

testing/test_assertrewrite.py:1344–1375  ·  view source on GitHub ↗

Fix infinite recursion when writing pyc files: if an import happens to be triggered when writing the pyc file, this would cause another call to the hook, which would trigger another pyc writing, which could trigger another import, and so on. (#3506)

(
    pytester: Pytester, pytestconfig, monkeypatch
)

Source from the content-addressed store, hash-verified

1342
1343
1344def test_rewrite_infinite_recursion(
1345 pytester: Pytester, pytestconfig, monkeypatch
1346) -> None:
1347 """Fix infinite recursion when writing pyc files: if an import happens to be triggered when writing the pyc
1348 file, this would cause another call to the hook, which would trigger another pyc writing, which could
1349 trigger another import, and so on. (#3506)"""
1350 from _pytest.assertion import rewrite as rewritemod
1351
1352 pytester.syspathinsert()
1353 pytester.makepyfile(test_foo="def test_foo(): pass")
1354 pytester.makepyfile(test_bar="def test_bar(): pass")
1355
1356 original_write_pyc = rewritemod._write_pyc
1357
1358 write_pyc_called = []
1359
1360 def spy_write_pyc(*args, **kwargs):
1361 # make a note that we have called _write_pyc
1362 write_pyc_called.append(True)
1363 # try to import a module at this point: we should not try to rewrite this module
1364 assert hook.find_spec("test_bar") is None
1365 return original_write_pyc(*args, **kwargs)
1366
1367 monkeypatch.setattr(rewritemod, "_write_pyc", spy_write_pyc)
1368 monkeypatch.setattr(sys, "dont_write_bytecode", False)
1369
1370 hook = AssertionRewritingHook(pytestconfig)
1371 spec = hook.find_spec("test_foo")
1372 assert spec is not None
1373 module = importlib.util.module_from_spec(spec)
1374 hook.exec_module(module)
1375 assert len(write_pyc_called) == 1
1376
1377
1378class TestEarlyRewriteBailout:

Callers

nothing calls this directly

Calls 6

find_specMethod · 0.95
exec_moduleMethod · 0.95
setattrMethod · 0.80
syspathinsertMethod · 0.45
makepyfileMethod · 0.45

Tested by

no test coverage detected