Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

prioritize outputting relative paths #12974

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
outout relative_path
  • Loading branch information
dongfangtianyu committed Nov 17, 2024
commit cf384584e96ee18254b6bcb895b67f902ce27837
6 changes: 5 additions & 1 deletion src/_pytest/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1175,13 +1175,17 @@ def notify_exception(
sys.stderr.write(f"INTERNALERROR> {line}\n")
sys.stderr.flush()

def cwd_relative_path(self, fullpath: pathlib.Path | os.PathLike[str] | str) -> str:
path = pathlib.Path(str(fullpath))
return bestrelpath(self.invocation_params.dir, path)

def cwd_relative_nodeid(self, nodeid: str) -> str:
# nodeid's are relative to the rootpath, compute relative to cwd.
if self.invocation_params.dir != self.rootpath:
base_path_part, *nodeid_part = nodeid.split("::")
# Only process path part
fullpath = self.rootpath / base_path_part
relative_path = bestrelpath(self.invocation_params.dir, fullpath)
relative_path = self.cwd_relative_path(fullpath)

nodeid = "::".join([relative_path, *nodeid_part])
return nodeid
Expand Down
2 changes: 2 additions & 0 deletions src/_pytest/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -811,6 +811,8 @@ def formatrepr(self) -> FixtureLookupErrorRepr:
stack = stack[:-1]
for function in stack:
fspath, lineno = getfslineno(function)
fspath = self.request.config.cwd_relative_path(fspath)

try:
lines, _ = inspect.getsourcelines(get_real_func(function))
except (OSError, IndexError, TypeError):
Expand Down
3 changes: 2 additions & 1 deletion src/_pytest/python.py
Original file line number Diff line number Diff line change
Expand Up @@ -519,8 +519,9 @@ def importtestmodule(
else exc_info.exconly()
)
formatted_tb = str(exc_repr)
relative_path = config.cwd_relative_path(path)
raise nodes.Collector.CollectError(
f"ImportError while importing test module '{path}'.\n"
f"ImportError while importing test module '{relative_path}'.\n"
"Hint: make sure your test modules/packages have valid Python names.\n"
"Traceback:\n"
f"{formatted_tb}"
Expand Down
6 changes: 4 additions & 2 deletions src/_pytest/reports.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,9 +367,11 @@ def from_item_and_call(cls, item: Item, call: CallInfo[None]) -> TestReport:
if excinfo.value._use_item_location:
path, line = item.reportinfo()[:2]
assert line is not None
longrepr = os.fspath(path), line + 1, r.message
relative_path = item.config.cwd_relative_path(path)
longrepr = relative_path, line + 1, r.message
else:
longrepr = (str(r.path), r.lineno, r.message)
relative_path = item.config.cwd_relative_path(r.path)
longrepr = (relative_path, r.lineno, r.message)
else:
outcome = "failed"
if call.when == "call":
Expand Down
3 changes: 3 additions & 0 deletions src/_pytest/warnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ def catch_warnings_for_item(
yield
finally:
for warning_message in log:
warning_message.filename = config.cwd_relative_path(
warning_message.filename
)
ihook.pytest_warning_recorded.call_historic(
kwargs=dict(
warning_message=warning_message,
Expand Down
16 changes: 16 additions & 0 deletions testing/python/collect.py
Original file line number Diff line number Diff line change
Expand Up @@ -1682,3 +1682,19 @@ def test_collection_hierarchy(pytester: Pytester) -> None:
],
consecutive=True,
)


def test_output_relative_path_when_import_error(pytester: Pytester) -> None:
pytester.makepyfile(
**{"tests/test_p1": "raise ImportError('Something bad happened ☺')"}
)
relative_path = os.path.join("tests", "test_p1.py")

result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
f"ImportError while importing test module '{relative_path}'*",
"Traceback:",
"*raise ImportError*Something bad happened*",
]
)
24 changes: 24 additions & 0 deletions testing/test_junitxml.py
Original file line number Diff line number Diff line change
Expand Up @@ -1760,3 +1760,27 @@ def test_func():
assert junit_logging == "no"
assert len(node.find_by_tag("system-err")) == 0
assert len(node.find_by_tag("system-out")) == 0


def test_output_relative_path_when_skip(pytester: Pytester) -> None:
pytester.makepyfile(
**{
"tests/test_p1": """
import pytest
@pytest.mark.skip("balabala")
def test_skip():
pass
"""
}
)
pytester.runpytest("--junit-xml=junit.xml")

dom = minidom.parse(str(pytester.path / "junit.xml"))

el = dom.getElementsByTagName("skipped")[0]

assert el.getAttribute("message") == "balabala"

text = el.childNodes[0].nodeValue
relative_path = os.path.join("tests", "test_p1.py")
assert text == f"{relative_path}:2: balabala"
15 changes: 15 additions & 0 deletions testing/test_terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -3069,6 +3069,21 @@ def test_pass():
)


def test_output_relative_path_by_fixture(pytester: Pytester) -> None:
pytester.makepyfile(
**{
"tests/test_p1": """
def test_pass(miss_setup):
print('hi there')
"""
}
)
result = pytester.runpytest("-rX")

relative_path = os.path.join("tests", "test_p1.py")
result.stdout.fnmatch_lines([f"file {relative_path}, line 1"])


class TestNodeIDHandling:
def test_nodeid_handling_windows_paths(self, pytester: Pytester, tmp_path) -> None:
"""Test the correct handling of Windows-style paths with backslashes."""
Expand Down
38 changes: 33 additions & 5 deletions testing/test_warnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import warnings

from _pytest.fixtures import FixtureRequest
from _pytest.pathlib import bestrelpath
from _pytest.pytester import Pytester
import pytest

Expand Down Expand Up @@ -589,15 +590,15 @@ def test_group_warnings_by_message(pytester: Pytester) -> None:
"test_group_warnings_by_message.py::test_foo[[]3[]]",
"test_group_warnings_by_message.py::test_foo[[]4[]]",
"test_group_warnings_by_message.py::test_foo_1",
" */test_group_warnings_by_message.py:*: UserWarning: foo",
" test_group_warnings_by_message.py:*: UserWarning: foo",
" warnings.warn(UserWarning(msg))",
"",
"test_group_warnings_by_message.py::test_bar[[]0[]]",
"test_group_warnings_by_message.py::test_bar[[]1[]]",
"test_group_warnings_by_message.py::test_bar[[]2[]]",
"test_group_warnings_by_message.py::test_bar[[]3[]]",
"test_group_warnings_by_message.py::test_bar[[]4[]]",
" */test_group_warnings_by_message.py:*: UserWarning: bar",
" test_group_warnings_by_message.py:*: UserWarning: bar",
" warnings.warn(UserWarning(msg))",
"",
"-- Docs: *",
Expand All @@ -617,11 +618,11 @@ def test_group_warnings_by_message_summary(pytester: Pytester) -> None:
f"*== {WARNINGS_SUMMARY_HEADER} ==*",
"test_1.py: 21 warnings",
"test_2.py: 1 warning",
" */test_1.py:10: UserWarning: foo",
" test_1.py:10: UserWarning: foo",
" warnings.warn(UserWarning(msg))",
"",
"test_1.py: 20 warnings",
" */test_1.py:10: UserWarning: bar",
" test_1.py:10: UserWarning: bar",
" warnings.warn(UserWarning(msg))",
"",
"-- Docs: *",
Expand Down Expand Up @@ -762,10 +763,11 @@ def test_it():
"""
)
result = pytester.runpytest_subprocess()
relative_path = bestrelpath(pytester.path, testfile)
# with stacklevel=2 the warning should originate from the above created test file
result.stdout.fnmatch_lines_random(
[
f"*{testfile}:3*",
f"*{relative_path}:3*",
"*Unknown pytest.mark.unknown*",
]
)
Expand Down Expand Up @@ -837,3 +839,29 @@ def test_resource_warning(tmp_path):
else []
)
result.stdout.fnmatch_lines([*expected_extra, "*1 passed*"])


@pytest.mark.filterwarnings("always::UserWarning")
def test_output_relative_path_when_warnings(pytester: Pytester) -> None:
pytester.makeini("[pytest]")
pytester.makepyfile(
**{
"tests/test_p1": """
import pytest

@pytest.mark.unknown_mark
def test_pass():
pass
"""
}
)
result = pytester.runpytest()

relative_path = os.path.join("tests", "test_p1.py")
result.stdout.fnmatch_lines(
[
f"*== {WARNINGS_SUMMARY_HEADER} ==*",
f"{relative_path}:3",
f"* {relative_path}:3: PytestUnknownMarkWarning: Unknown pytest.mark.unknown_mark - is this a typo?*",
]
)