From fef682a53b1fd22a678b38b0ba6e82c53506f55b 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 --- AUTHORS | 1 + changelog/8539.bugfix.rst | 1 + src/_pytest/assertion/rewrite.py | 18 ++++++++++++++---- 3 files changed, 16 insertions(+), 4 deletions(-) create mode 100644 changelog/8539.bugfix.rst diff --git a/AUTHORS b/AUTHORS index 80fce539294..593e0e91a55 100644 --- a/AUTHORS +++ b/AUTHORS @@ -222,6 +222,7 @@ Samuele Pedroni Sankt Petersbug Segev Finer Serhii Mozghovyi +Shantanu Jain Simon Gomizelj Skylar Downes Srinivas Reddy Thatiparthy diff --git a/changelog/8539.bugfix.rst b/changelog/8539.bugfix.rst new file mode 100644 index 00000000000..a2098610e29 --- /dev/null +++ b/changelog/8539.bugfix.rst @@ -0,0 +1 @@ +Fixed assertion rewriting on Python 3.10. diff --git a/src/_pytest/assertion/rewrite.py b/src/_pytest/assertion/rewrite.py index 1c6161b212d..3cc17ad4526 100644 --- a/src/_pytest/assertion/rewrite.py +++ b/src/_pytest/assertion/rewrite.py @@ -652,12 +652,9 @@ def run(self, mod): 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(six.moves.builtins.__name__, "@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): @@ -684,6 +681,19 @@ def run(self, mod): pos += 1 else: lineno = item.lineno + if sys.version_info >= (3, 10): + aliases = [ + ast.alias(six.moves.builtins.__name__, "@py_builtins", lineno=lineno, col_offset=0), + ast.alias( + "_pytest.assertion.rewrite", "@pytest_ar", + lineno=lineno, col_offset=0 + ), + ] + else: + aliases = [ + ast.alias(six.moves.builtins.__name__, "@py_builtins"), + ast.alias("_pytest.assertion.rewrite", "@pytest_ar"), + ] imports = [ ast.Import([alias], lineno=lineno, col_offset=0) for alias in aliases ]