From 3e90bf573f4415e6b34b9187f625ef265d634aeb Mon Sep 17 00:00:00 2001 From: Alessio Izzo Date: Wed, 22 Feb 2023 22:28:18 +0100 Subject: [PATCH] add version check for py<38 --- changelog/10743.bugfix.rst | 2 +- src/_pytest/assertion/rewrite.py | 9 +++++++-- testing/test_assertrewrite.py | 3 +++ 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/changelog/10743.bugfix.rst b/changelog/10743.bugfix.rst index 943d27ee2..db8eb73b0 100644 --- a/changelog/10743.bugfix.rst +++ b/changelog/10743.bugfix.rst @@ -1 +1 @@ -Fixed different behavior from std lib unittest of asserts with expression that contains the walrus operator in it that changes the value of a variable +Fixed different behavior from std lib unittest of asserts with expression that contains the walrus operator in it that changes the value of a variable. diff --git a/src/_pytest/assertion/rewrite.py b/src/_pytest/assertion/rewrite.py index 548a3fce3..2f011bba8 100644 --- a/src/_pytest/assertion/rewrite.py +++ b/src/_pytest/assertion/rewrite.py @@ -44,6 +44,11 @@ from _pytest.stash import StashKey if TYPE_CHECKING: from _pytest.assertion import AssertionState +if sys.version_info > (3, 8): + namedExpr = ast.NamedExpr +else: + namedExpr = ast.Expr + assertstate_key = StashKey["AssertionState"]() @@ -937,7 +942,7 @@ class AssertionRewriter(ast.NodeVisitor): ast.copy_location(node, assert_) return self.statements - def visit_NamedExpr(self, name: ast.NamedExpr) -> Tuple[ast.NamedExpr, str]: + def visit_NamedExpr(self, name: namedExpr) -> Tuple[namedExpr, str]: # Display the repr of the target name if it's a local variable or # _should_repr_global_name() thinks it's acceptable. locs = ast.Call(self.builtin("locals"), [], []) @@ -1061,7 +1066,7 @@ class AssertionRewriter(ast.NodeVisitor): results = [left_res] for i, op, next_operand in it: next_res, next_expl = self.visit(next_operand) - if isinstance(next_operand, (ast.Compare, ast.BoolOp, ast.NamedExpr)): + if isinstance(next_operand, (ast.Compare, ast.BoolOp)): next_expl = f"({next_expl})" results.append(next_res) sym = BINOP_MAP[op.__class__] diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index 89f2f8f6e..624947d74 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -1265,6 +1265,9 @@ class TestIssue2121: result.stdout.fnmatch_lines(["*E*assert (1 + 1) == 3"]) +@pytest.mark.skipif( + sys.version_info < (3, 8), reason="walrus operator not available in py<38" +) class TestIssue10743: def test_assertion_walrus_operator(self, pytester: Pytester) -> None: pytester.makepyfile(