pytest icon indicating copy to clipboard operation
pytest copied to clipboard

Pytest reevaluates walrus operations within assert statements

Open regananalytics opened this issue 2 years ago • 5 comments

  • [x] a detailed description of the bug or problem you are having
  • [x] output of pip list from the virtual environment you are using
  • [x] pytest and operating system versions
  • [x] minimal example if possible

Ubuntu 22.04, pytest 7.3.2, python 3.10.11

Package Version


exceptiongroup 1.1.1 iniconfig 2.0.0 packaging 23.1 pip 23.1.2 pluggy 1.0.0 pytest 7.3.2 setuptools 67.8.0 tomli 2.0.1 wheel 0.38.4

Pytest 7.3.2 re-evaluates walrus operator statements if they appear in assert statements.

def test_walrus():
    assert (x := 2) == 2
    x  =  3
    assert x == 3, "This test fails because (x := 2) is reevaluated by pytest"
    
def test_walrus_no_assert():
    (x := 2) == 2
    x = 3
    assert x == 3, "This test passes because (x := 2) is not reevaluated"

regananalytics avatar Jun 15 '23 18:06 regananalytics

Bisected to 331bc1be4634cf95fdb33021d4355c35723b73fe:

  • #11041

As a workaround, --assert=plain works.

cc @aless10

The-Compiler avatar Jun 15 '23 18:06 The-Compiler

Oh no! I'm thinking that a lot of edge cases are really really "edge", and I hope that nobody writes tests like this one. But I'm going to look at this. Is that ok with you? Thanks

aless10 avatar Jun 19 '23 07:06 aless10

Yeah, this is obviously not a real test. I wrote it as a super simple and replicable example of the issue.

regananalytics avatar Jun 20 '23 16:06 regananalytics

@aless10 Sure, please go ahead! No worries, sometimes things can be unexpectedly tricky. It's much appreciated that you're taking care of those follow-up issues!

The-Compiler avatar Jun 21 '23 08:06 The-Compiler

Just came across this issue as well when using pytest = "^8.3.3" Took me couple of hours to find out what is going on...

AdamVerner avatar Oct 15 '24 15:10 AdamVerner