def test_rewrite_infinite_recursion(testdir, pytestconfig, monkeypatch): """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)""" from _pytest.assertion import rewrite testdir.syspathinsert() testdir.makepyfile(test_foo="def test_foo(): pass") testdir.makepyfile(test_bar="def test_bar(): pass") original_write_pyc = rewrite._write_pyc write_pyc_called = [] def spy_write_pyc(*args, **kwargs): # make a note that we have called _write_pyc write_pyc_called.append(True) # try to import a module at this point: we should not try to rewrite this module assert hook.find_spec("test_bar") is None return original_write_pyc(*args, **kwargs) monkeypatch.setattr(rewrite, "_write_pyc", spy_write_pyc) monkeypatch.setattr(sys, "dont_write_bytecode", False) hook = AssertionRewritingHook(pytestconfig) spec = hook.find_spec("test_foo") assert spec is not None module = importlib.util.module_from_spec(spec) hook.exec_module(module) assert len(write_pyc_called) == 1
def test_remember_rewritten_modules(self, pytestconfig, testdir, monkeypatch): """`AssertionRewriteHook` should remember rewritten modules so it doesn't give false positives (#2005).""" monkeypatch.syspath_prepend(testdir.tmpdir) testdir.makepyfile(test_remember_rewritten_modules="") warnings = [] hook = AssertionRewritingHook(pytestconfig) monkeypatch.setattr( hook, "_warn_already_imported", lambda code, msg: warnings.append(msg) ) spec = hook.find_spec("test_remember_rewritten_modules") assert spec is not None module = importlib.util.module_from_spec(spec) hook.exec_module(module) hook.mark_rewrite("test_remember_rewritten_modules") hook.mark_rewrite("test_remember_rewritten_modules") assert warnings == []
def test_remember_rewritten_modules_warnings_stack_level( self, pytestconfig, testdir, monkeypatch): """ AssertionRewriteHook should raise warning with expected stack level """ def mock__issue_warning_captured(warning, hook, stacklevel=0): assert 5 == stacklevel monkeypatch.syspath_prepend(testdir.tmpdir) monkeypatch.setattr(_pytest.warnings, "_issue_warning_captured", mock__issue_warning_captured) testdir.makepyfile(test_remember_rewritten_modules="") hook = AssertionRewritingHook(pytestconfig) spec = hook.find_spec("test_remember_rewritten_modules") module = importlib.util.module_from_spec(spec) hook.exec_module(module) hook.mark_rewrite(*{"builtins": "<module 'builtins' (built-in)>"})