Skip to content

Commit a0f58fa

Browse files
Zac-HDbluetech
authored andcommitted
Merge pull request #11143 from tushar-deepsource/patch-1
(cherry picked from commit 084d756) [ran: adapted to 7.4.x, fixed changelog issue number]
1 parent 2cdd619 commit a0f58fa

File tree

4 files changed

+26
-4
lines changed

4 files changed

+26
-4
lines changed

Diff for: AUTHORS

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

Diff for: 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.

Diff for: 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

Diff for: testing/test_assertrewrite.py

+14
Original file line numberDiff line numberDiff line change
@@ -2077,3 +2077,17 @@ def test_max_increased_verbosity(self, pytester: Pytester) -> None:
20772077
self.create_test_file(pytester, DEFAULT_REPR_MAX_SIZE * 10)
20782078
result = pytester.runpytest("-vv")
20792079
result.stdout.no_fnmatch_line("*xxx...xxx*")
2080+
2081+
2082+
class TestIssue11140:
2083+
def test_constant_not_picked_as_module_docstring(self, pytester: Pytester) -> None:
2084+
pytester.makepyfile(
2085+
"""\
2086+
0
2087+
2088+
def test_foo():
2089+
pass
2090+
"""
2091+
)
2092+
result = pytester.runpytest()
2093+
assert result.ret == 0

0 commit comments

Comments
 (0)