File tree Expand file tree Collapse file tree 3 files changed +37
-2
lines changed Expand file tree Collapse file tree 3 files changed +37
-2
lines changed Original file line number Diff line number Diff line change
1
+ Paths appearing in error messages are now correct in case the current working directory has
2
+ changed since the start of the session.
Original file line number Diff line number Diff line change 29
29
from _pytest .mark .structures import MarkDecorator
30
30
from _pytest .mark .structures import NodeKeywords
31
31
from _pytest .outcomes import fail
32
+ from _pytest .pathlib import Path
32
33
from _pytest .store import Store
33
34
34
35
if TYPE_CHECKING :
@@ -348,9 +349,14 @@ def _repr_failure_py(
348
349
else :
349
350
truncate_locals = True
350
351
352
+ # excinfo.getrepr() formats paths relative to the CWD if `abspath` is False.
353
+ # It is possible for a fixture/test to change the CWD while this code runs, which
354
+ # would then result in the user seeing confusing paths in the failure message.
355
+ # To fix this, if the CWD changed, always display the full absolute path.
356
+ # It will be better to just always display paths relative to invocation_dir, but
357
+ # this requires a lot of plumbing (#6428).
351
358
try :
352
- os .getcwd ()
353
- abspath = False
359
+ abspath = Path (os .getcwd ()) != Path (self .config .invocation_dir )
354
360
except OSError :
355
361
abspath = True
356
362
Original file line number Diff line number Diff line change @@ -58,3 +58,30 @@ class FakeSession:
58
58
59
59
outside = py .path .local ("/outside" )
60
60
assert nodes ._check_initialpaths_for_relpath (FakeSession , outside ) is None
61
+
62
+
63
+ def test_failure_with_changed_cwd (testdir ):
64
+ """
65
+ Test failure lines should use absolute paths if cwd has changed since
66
+ invocation, so the path is correct (#6428).
67
+ """
68
+ p = testdir .makepyfile (
69
+ """
70
+ import os
71
+ import pytest
72
+
73
+ @pytest.fixture
74
+ def private_dir():
75
+ out_dir = 'ddd'
76
+ os.mkdir(out_dir)
77
+ old_dir = os.getcwd()
78
+ os.chdir(out_dir)
79
+ yield out_dir
80
+ os.chdir(old_dir)
81
+
82
+ def test_show_wrong_path(private_dir):
83
+ assert False
84
+ """
85
+ )
86
+ result = testdir .runpytest ()
87
+ result .stdout .fnmatch_lines ([str (p ) + ":*: AssertionError" , "*1 failed in *" ])
You can’t perform that action at this time.
0 commit comments