Skip to content

Commit 76c107c

Browse files
authored
Merge pull request #11751 from bluetech/backport-11143-to-7.4.x
(cherry picked from commit 084d756) [ran: adapted to 7.4.x, fixed changelog issue number]
2 parents 531d76d + a0f58fa commit 76c107c

File tree

4 files changed

+26
-4
lines changed

4 files changed

+26
-4
lines changed

AUTHORS

+1
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,7 @@ Tomer Keren
377377
Tony Narlock
378378
Tor Colvin
379379
Trevor Bekolay
380+
Tushar Sadhwani
380381
Tyler Goodlet
381382
Tyler Smart
382383
Tzu-ping Chung

changelog/11140.bugfix.rst

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix non-string constants at the top of file being detected as docstrings on Python>=3.8.

src/_pytest/assertion/rewrite.py

+10-4
Original file line numberDiff line numberDiff line change
@@ -604,6 +604,13 @@ def _write_and_reset() -> None:
604604
return ret
605605

606606

607+
def _get_ast_constant_value(value: astStr) -> object:
608+
if sys.version_info >= (3, 8):
609+
return value.value
610+
else:
611+
return value.s
612+
613+
607614
class AssertionRewriter(ast.NodeVisitor):
608615
"""Assertion rewriting implementation.
609616
@@ -700,11 +707,10 @@ def run(self, mod: ast.Module) -> None:
700707
expect_docstring
701708
and isinstance(item, ast.Expr)
702709
and isinstance(item.value, astStr)
710+
and isinstance(_get_ast_constant_value(item.value), str)
703711
):
704-
if sys.version_info >= (3, 8):
705-
doc = item.value.value
706-
else:
707-
doc = item.value.s
712+
doc = _get_ast_constant_value(item.value)
713+
assert isinstance(doc, str)
708714
if self.is_rewrite_disabled(doc):
709715
return
710716
expect_docstring = False

testing/test_assertrewrite.py

+14
Original file line numberDiff line numberDiff line change
@@ -2096,3 +2096,17 @@ def test_max_increased_verbosity(self, pytester: Pytester) -> None:
20962096
self.create_test_file(pytester, DEFAULT_REPR_MAX_SIZE * 10)
20972097
result = pytester.runpytest("-vv")
20982098
result.stdout.no_fnmatch_line("*xxx...xxx*")
2099+
2100+
2101+
class TestIssue11140:
2102+
def test_constant_not_picked_as_module_docstring(self, pytester: Pytester) -> None:
2103+
pytester.makepyfile(
2104+
"""\
2105+
0
2106+
2107+
def test_foo():
2108+
pass
2109+
"""
2110+
)
2111+
result = pytester.runpytest()
2112+
assert result.ret == 0

0 commit comments

Comments
 (0)