From 28ef3fbfc6ad3923689ddb39288b2e86bcf99297 Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Sun, 11 Apr 2021 15:38:32 -0700 Subject: [PATCH] Fix assertion rewriting on Python 3.10 Fixes https://github.com/pytest-dev/pytest/issues/8539 This seems to have been the result of https://bugs.python.org/issue43798 --- src/_pytest/assertion/rewrite.py | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/_pytest/assertion/rewrite.py b/src/_pytest/assertion/rewrite.py index 6a3222f333d..537ded257e9 100644 --- a/src/_pytest/assertion/rewrite.py +++ b/src/_pytest/assertion/rewrite.py @@ -684,12 +684,9 @@ def run(self, mod: ast.Module) -> None: if not mod.body: # Nothing to do. return + # Insert some special imports at the top of the module but after any # docstrings and __future__ imports. - aliases = [ - ast.alias("builtins", "@py_builtins"), - ast.alias("_pytest.assertion.rewrite", "@pytest_ar"), - ] doc = getattr(mod, "docstring", None) expect_docstring = doc is None if doc is not None and self.is_rewrite_disabled(doc): @@ -721,6 +718,19 @@ def run(self, mod: ast.Module) -> None: lineno = item.decorator_list[0].lineno else: lineno = item.lineno + if sys.version_info >= (3, 10): + aliases = [ + ast.alias("builtins", "@py_builtins", lineno=lineno, col_offset=0), + ast.alias( + "_pytest.assertion.rewrite", "@pytest_ar", + lineno=lineno, col_offset=0 + ), + ] + else: + aliases = [ + ast.alias("builtins", "@py_builtins"), + ast.alias("_pytest.assertion.rewrite", "@pytest_ar"), + ] imports = [ ast.Import([alias], lineno=lineno, col_offset=0) for alias in aliases ]