Skip to content

Commit 3918365

Browse files
committed
13403: Disable assertion rewriting for external modules - refactor
1 parent fc0c87c commit 3918365

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

src/_pytest/assertion/__init__.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,16 @@ def __init__(self, config: Config, mode) -> None:
108108
self.mode = mode
109109
self.trace = config.trace.root.get("assertion")
110110
self.hook: rewrite.AssertionRewritingHook | None = None
111-
self.root_path=os.getcwd()
111+
112+
@property
113+
def root_path(self):
114+
try:
115+
return os.getcwd()
116+
except FileNotFoundError:
117+
# Fixes for py's trying to os.getcwd() on py34
118+
# when current working directory doesn't exist (previously triggered via xdist only).
119+
# Ref: https://github.com/pytest-dev/py/pull/207
120+
return os.path.dirname(os.path.abspath(sys.argv[0]))
112121

113122
def install_importhook(config: Config) -> rewrite.AssertionRewritingHook:
114123
"""Try to install the rewrite hook, raise SystemError if it fails."""

testing/test_assertrewrite.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1900,7 +1900,6 @@ def hook(
19001900
if PathFinder.find_spec has been called.
19011901
"""
19021902
import importlib.machinery
1903-
19041903
self.find_spec_calls: list[str] = []
19051904
self.initial_paths: set[Path] = set()
19061905

@@ -1974,6 +1973,7 @@ def test_simple_failure():
19741973
assert hook.find_spec("file") is not None
19751974
assert self.find_spec_calls == ["file"]
19761975

1976+
19771977
def test_assert_excluded_rootpath(
19781978
self, pytester: Pytester, hook: AssertionRewritingHook, monkeypatch
19791979
) -> None:
@@ -1988,12 +1988,26 @@ def test_simple_failure():
19881988
"""
19891989
}
19901990
)
1991+
with mock.patch.object(hook, "fnpats", ["*.py"]):
1992+
assert hook.find_spec("file") is not None
19911993
root_path = f"{os.getcwd()}/tests"
1992-
mkdir(root_path)
1994+
1995+
if not os.path.exists(root_path):
1996+
mkdir(root_path)
19931997
monkeypatch.chdir(root_path)
19941998
with mock.patch.object(hook, "fnpats", ["*.py"]):
19951999
assert hook.find_spec("file") is None
19962000

2001+
2002+
def test_assert_excluded_rewrite_for_plugins(
2003+
self, pytester: Pytester, hook: AssertionRewritingHook, monkeypatch
2004+
) -> None:
2005+
plugins= {"ayncio", "fnpats", "pytest_bdd", "django", "mock", "pytest_twisted", "trio"}
2006+
with mock.patch.object(hook, "fnpats", ["*.py"]):
2007+
for plugin in plugins:
2008+
assert hook.find_spec(plugin) is None
2009+
2010+
19972011
@pytest.mark.skipif(
19982012
sys.platform.startswith("win32"), reason="cannot remove cwd on Windows"
19992013
)

0 commit comments

Comments
 (0)