Skip to content

Assignment expression changes value of variable in unrelated test case #11239

@cdce8p

Description

@cdce8p

The assert rewriting in test2 effects the result of test_1 just because both asserts are using the same identifier state.
Tested with pytest 7.3.2 and 7.4.0.

def test_1():
    state = {"x": 2}.get("x")
    assert state is not None

def test_2():
    db = {"x": 2}
    assert (state := db.get("x")) is not None
    def test_1():
        state = {"x": 2}.get("x")
>       assert state is not None
E       NameError: name 'db' is not defined

custom_tests/test_a.py:3: NameError

I bisected the issue to #11041. From what I can tell, the assertion rewriter doesn't track the current context. Thus state in test_1 is replaced with db.get("x") from test_2 even though they are in separate functions.

This behavior can be quite surprising as a user typically doesn't expect test cases with purely local variables and without side effects to influence one another.

As there is another regression (#11115) with this PR already, maybe it would be best to revert it?

/CC @aless10

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: rewriterelated to the assertion rewrite mechanismtype: regressionindicates a problem that was introduced in a release which was working previously

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions