Skip to content

Commit e787d2e

Browse files
Merge pull request #11317 from tjsmart/fix-issue-11237
Fix doctest collection of `functools.cached_property` objects.
2 parents f6b6478 + a357c7a commit e787d2e

File tree

4 files changed

+38
-0
lines changed

4 files changed

+38
-0
lines changed

AUTHORS

+1
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,7 @@ Tor Colvin
382382
Trevor Bekolay
383383
Tushar Sadhwani
384384
Tyler Goodlet
385+
Tyler Smart
385386
Tzu-ping Chung
386387
Vasily Kuznetsov
387388
Victor Maryama

changelog/11237.bugfix.rst

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix doctest collection of `functools.cached_property` objects.

src/_pytest/doctest.py

+18
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Discover and run doctests in modules and test files."""
22
import bdb
3+
import functools
34
import inspect
45
import os
56
import platform
@@ -536,6 +537,23 @@ def _find(
536537
tests, obj, name, module, source_lines, globs, seen
537538
)
538539

540+
if sys.version_info < (3, 13):
541+
542+
def _from_module(self, module, object):
543+
"""`cached_property` objects are never considered a part
544+
of the 'current module'. As such they are skipped by doctest.
545+
Here we override `_from_module` to check the underlying
546+
function instead. https://github.com/python/cpython/issues/107995
547+
"""
548+
if isinstance(object, functools.cached_property):
549+
object = object.func
550+
551+
# Type ignored because this is a private function.
552+
return super()._from_module(module, object) # type: ignore[misc]
553+
554+
else: # pragma: no cover
555+
pass
556+
539557
if self.path.name == "conftest.py":
540558
module = self.config.pluginmanager._importconftest(
541559
self.path,

testing/test_doctest.py

+18
Original file line numberDiff line numberDiff line change
@@ -482,6 +482,24 @@ def test_doctestmodule(self, pytester: Pytester):
482482
reprec = pytester.inline_run(p, "--doctest-modules")
483483
reprec.assertoutcome(failed=1)
484484

485+
def test_doctest_cached_property(self, pytester: Pytester):
486+
p = pytester.makepyfile(
487+
"""
488+
import functools
489+
490+
class Foo:
491+
@functools.cached_property
492+
def foo(self):
493+
'''
494+
>>> assert False, "Tacos!"
495+
'''
496+
...
497+
"""
498+
)
499+
result = pytester.runpytest(p, "--doctest-modules")
500+
result.assert_outcomes(failed=1)
501+
assert "Tacos!" in result.stdout.str()
502+
485503
def test_doctestmodule_external_and_issue116(self, pytester: Pytester):
486504
p = pytester.mkpydir("hello")
487505
p.joinpath("__init__.py").write_text(

0 commit comments

Comments
 (0)