Skip to content

Commit a3e969f

Browse files
glaziermagclaudenedbat
authored
fix: dynamic_context for @staticmethod and @classmethod tests (issue 1923) (#2297)
* fix: give static and class method tests a dynamic context `qualname_from_frame()` found a test method through its `self` argument or through the module globals, so `@staticmethod` and `@classmethod` tests got no context under `dynamic_context = test_function`. Use the code object's `co_qualname` (Python 3.11+) when neither lookup works, but only for real function frames, so a class body with a test-like name (test_bug_829) is still ignored. Closes #1923. Co-Authored-By: Claude Fable 5.1 <[email protected]> * use a comment we will find when we drop 3.10 --------- Co-authored-by: glaziermag <[email protected]> Co-authored-by: Claude Fable 5.1 <[email protected]> Co-authored-by: Ned Batchelder <[email protected]>
1 parent 8ad7236 commit a3e969f

3 files changed

Lines changed: 62 additions & 0 deletions

File tree

‎CHANGES.rst‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@ upgrading your version of coverage.py.
2323
Unreleased
2424
----------
2525

26+
- Fix: with ``dynamic_context = test_function``, test methods written as
27+
``@staticmethod`` or ``@classmethod`` were not given a context of their own.
28+
Now they are, on Python 3.11 and later. Closes `issue 1923`_.
29+
2630
- Fix: on Python 3.14 and later, a ``for`` loop completing immediately before a
2731
function return could mistakenly report an uncovered branch. This is now
2832
fixed, closing `issue 2168`_.
@@ -31,6 +35,7 @@ Unreleased
3135
a ``with`` statement could incorrectly be reported as covered when the
3236
``with`` raised. This is now fixed, closing `issue 2289`_.
3337

38+
.. _issue 1923: https://github.com/coveragepy/coveragepy/issues/1923
3439
.. _issue 2168: https://github.com/coveragepy/coveragepy/issues/2168
3540
.. _issue 2289: https://github.com/coveragepy/coveragepy/issues/2289
3641

‎coverage/context.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from __future__ import annotations
77

88
from collections.abc import Sequence
9+
from inspect import CO_OPTIMIZED # pylint: disable=no-name-in-module
910
from types import FrameType
1011

1112
from coverage.types import TShouldStartContextFn
@@ -63,6 +64,12 @@ def qualname_from_frame(frame: FrameType) -> str | None:
6364
if method is None:
6465
func = frame.f_globals.get(fname)
6566
if func is None:
67+
# Static and class methods have no `self` and aren't in the module
68+
# globals, but the code object knows its own qualified name.
69+
# PYVERSIONS: co_qualname is 3.11+
70+
qualname = getattr(co, "co_qualname", None)
71+
if qualname and co.co_flags & CO_OPTIMIZED and "<locals>" not in qualname:
72+
return f"{frame.f_globals.get('__name__')}.{qualname}"
6673
return None
6774
return f"{func.__module__}.{fname}"
6875

‎tests/test_context.py‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import pytest
1414

1515
import coverage
16+
from coverage import env
1617
from coverage.context import qualname_from_frame
1718
from coverage.data import CoverageData, sorted_lines
1819
from coverage.types import TArc, TCovKwargs, TLineNo
@@ -207,6 +208,35 @@ def assert_context_lines(context: str, lines: list[TLineNo]) -> None:
207208
assert_context_lines("stat|two_tests.test_one", self.TEST_ONE_LINES)
208209
assert_context_lines("stat|two_tests.test_two", self.TEST_TWO_LINES)
209210

211+
@pytest.mark.skipif(env.PYVERSION < (3, 11), reason="Needs co_qualname")
212+
def test_static_and_class_methods(self) -> None:
213+
# Test methods without a `self` argument also get a context, issue 1923.
214+
self.make_file(
215+
"class_tests.py",
216+
"""\
217+
class TestSomething:
218+
@staticmethod
219+
def test_static():
220+
x = 4
221+
222+
@classmethod
223+
def test_class(cls):
224+
x = 8
225+
226+
TestSomething.test_static()
227+
TestSomething.test_class()
228+
""",
229+
)
230+
cov = coverage.Coverage(source=["."])
231+
cov.set_option("run:dynamic_context", "test_function")
232+
self.start_import_stop(cov, "class_tests")
233+
data = cov.get_data()
234+
235+
assert_count_equal(
236+
data.measured_contexts(),
237+
["", "class_tests.TestSomething.test_static", "class_tests.TestSomething.test_class"],
238+
)
239+
210240

211241
def get_qualname() -> str | None:
212242
"""Helper to return qualname_from_frame for the caller."""
@@ -259,6 +289,16 @@ def patch_meth(self: Any) -> str | None:
259289
return get_qualname()
260290

261291

292+
class StaticAndClass:
293+
@staticmethod
294+
def a_static() -> str | None:
295+
return get_qualname()
296+
297+
@classmethod
298+
def a_class(cls) -> str | None:
299+
return get_qualname()
300+
301+
262302
# pylint: enable=missing-class-docstring, missing-function-docstring, unused-argument
263303

264304

@@ -291,6 +331,16 @@ def test_fake_out(self) -> None:
291331
def test_property(self) -> None:
292332
assert Parent().a_property == "tests.test_context.Parent.a_property"
293333

334+
@pytest.mark.skipif(env.PYVERSION < (3, 11), reason="Needs co_qualname")
335+
def test_staticmethod(self) -> None:
336+
assert StaticAndClass.a_static() == "tests.test_context.StaticAndClass.a_static"
337+
assert StaticAndClass().a_static() == "tests.test_context.StaticAndClass.a_static"
338+
339+
@pytest.mark.skipif(env.PYVERSION < (3, 11), reason="Needs co_qualname")
340+
def test_classmethod(self) -> None:
341+
assert StaticAndClass.a_class() == "tests.test_context.StaticAndClass.a_class"
342+
assert StaticAndClass().a_class() == "tests.test_context.StaticAndClass.a_class"
343+
294344
def test_changeling(self) -> None:
295345
c = Child()
296346
c.meth = patch_meth # type: ignore[assignment]

0 commit comments

Comments
 (0)