Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
1 change: 1 addition & 0 deletions changelog/15051.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed crash when using :option:`--fixtures-per-test` on a fixture-using doctest.
12 changes: 5 additions & 7 deletions src/_pytest/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -2455,10 +2455,6 @@ def _show_fixtures_per_test(config: Config, session: Session) -> None:
tw = _pytest.config.create_terminal_writer(config)
verbose = config.get_verbosity()

def get_best_relpath(func) -> str:
loc = getlocation(func, invocation_dir)
return bestrelpath(invocation_dir, Path(loc))

def write_fixture(fixture_def: FixtureDef[object]) -> None:
argname = fixture_def.argname
if verbose <= 0 and argname.startswith("_"):
Expand All @@ -2484,11 +2480,13 @@ def write_item(item: nodes.Item) -> None:
# This test item does not use any fixtures.
return

path, lineno, _test_name = item.reportinfo()
relpath = str(bestrelpath(invocation_dir, Path(path)))
title = f"{relpath}:{lineno + 1}" if lineno is not None else relpath

tw.line()
tw.sep("-", f"fixtures used by {item.name}")
# TODO: Fix this type ignore.
tw.sep("-", f"({get_best_relpath(item.function)})") # type: ignore[attr-defined]

tw.sep("-", f"({title})")
for fixturedef in fixturedefs:
write_fixture(fixturedef)

Expand Down
30 changes: 26 additions & 4 deletions testing/python/show_fixtures_per_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,27 +161,49 @@ def test_args(arg2, arg3):


def test_doctest_items(pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest

@pytest.fixture(autouse=True)
def one():
return 1
"""
)
pytester.makepyfile(
'''
def foo():
"""
>>> 1 + 1
>>> getfixture('one') + 1
2
"""
'''
)
pytester.maketxtfile(
"""
>>> 1 + 1
>>> getfixture('one') + 1
2
"""
)

result = pytester.runpytest(
"--fixtures-per-test", "--doctest-modules", "--doctest-glob=*.txt", "-v"
)
assert result.ret == 0

result.stdout.fnmatch_lines(["*collected 2 items*"])
assert result.ret == 0
result.stdout.fnmatch_lines(
[
"*collected 2 items*",
"* fixtures used by test_doctest_items.foo *",
"* (test_doctest_items.py:2) *",
"one -- conftest.py:3",
"* no docstring available",
"* fixtures used by test_doctest_items.txt *",
"* (test_doctest_items.txt:1) *",
"one -- conftest.py:3",
"* no docstring available",
]
)


def test_multiline_docstring_in_module(pytester: Pytester) -> None:
Expand Down