Skip to content

Commit 54f46d7

Browse files
committed
13403: Disable assertion rewriting for external modules - refactor
1 parent 5d5ad4e commit 54f46d7

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
@@ -1882,7 +1882,6 @@ def hook(
18821882
if PathFinder.find_spec has been called.
18831883
"""
18841884
import importlib.machinery
1885-
18861885
self.find_spec_calls: list[str] = []
18871886
self.initial_paths: set[Path] = set()
18881887

@@ -1956,6 +1955,7 @@ def test_simple_failure():
19561955
assert hook.find_spec("file") is not None
19571956
assert self.find_spec_calls == ["file"]
19581957

1958+
19591959
def test_assert_excluded_rootpath(
19601960
self, pytester: Pytester, hook: AssertionRewritingHook, monkeypatch
19611961
) -> None:
@@ -1970,12 +1970,26 @@ def test_simple_failure():
19701970
"""
19711971
}
19721972
)
1973+
with mock.patch.object(hook, "fnpats", ["*.py"]):
1974+
assert hook.find_spec("file") is not None
19731975
root_path = f"{os.getcwd()}/tests"
1974-
mkdir(root_path)
1976+
1977+
if not os.path.exists(root_path):
1978+
mkdir(root_path)
19751979
monkeypatch.chdir(root_path)
19761980
with mock.patch.object(hook, "fnpats", ["*.py"]):
19771981
assert hook.find_spec("file") is None
19781982

1983+
1984+
def test_assert_excluded_rewrite_for_plugins(
1985+
self, pytester: Pytester, hook: AssertionRewritingHook, monkeypatch
1986+
) -> None:
1987+
plugins= {"ayncio", "fnpats", "pytest_bdd", "django", "mock", "pytest_twisted", "trio"}
1988+
with mock.patch.object(hook, "fnpats", ["*.py"]):
1989+
for plugin in plugins:
1990+
assert hook.find_spec(plugin) is None
1991+
1992+
19791993
@pytest.mark.skipif(
19801994
sys.platform.startswith("win32"), reason="cannot remove cwd on Windows"
19811995
)

0 commit comments

Comments
 (0)