diff --git a/AUTHORS b/AUTHORS index 062f565c9ce..f507fea75e9 100644 --- a/AUTHORS +++ b/AUTHORS @@ -374,6 +374,7 @@ Tomer Keren Tony Narlock Tor Colvin Trevor Bekolay +Tushar Sadhwani Tyler Goodlet Tzu-ping Chung Vasily Kuznetsov diff --git a/changelog/11146.bugfix.rst b/changelog/11146.bugfix.rst new file mode 100644 index 00000000000..03b468f3018 --- /dev/null +++ b/changelog/11146.bugfix.rst @@ -0,0 +1 @@ +- Prevent constants at the top of file from being detected as docstrings. diff --git a/src/_pytest/assertion/rewrite.py b/src/_pytest/assertion/rewrite.py index 157903faf7c..9bf79f1e107 100644 --- a/src/_pytest/assertion/rewrite.py +++ b/src/_pytest/assertion/rewrite.py @@ -676,6 +676,7 @@ def run(self, mod: ast.Module) -> None: expect_docstring and isinstance(item, ast.Expr) and isinstance(item.value, ast.Constant) + and isinstance(item.value.value, str) ): doc = item.value.value if self.is_rewrite_disabled(doc): diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index d0180320400..e1b71ded69c 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -2042,3 +2042,17 @@ def test_max_increased_verbosity(self, pytester: Pytester) -> None: self.create_test_file(pytester, DEFAULT_REPR_MAX_SIZE * 10) result = pytester.runpytest("-vv") result.stdout.no_fnmatch_line("*xxx...xxx*") + + +class TestIssue11140: + def test_constant_not_picked_as_module_docstring(self, pytester: Pytester) -> None: + pytester.makepyfile( + """\ + 0 + + def test_foo(): + pass + """ + ) + result = pytester.runpytest() + assert result.ret == 0