1

What does pytest actually do when it invokes a function for testing, particularly if the function being tested has an optional parameter?

See the simple code below.

import pytest

def foo(ans = [ ]):
    ans.append(1)
    ans.append(2)
    ans.append(3)

    return ans 

def test_foo():
    x = foo()
    assert x == [1, 2, 3]

pytest.main(["-v"])

When this code is run, pytest reports this error:

    def test_foo():
        x = foo()
>       assert x == [1, 2, 3]
E       assert [1, 2, 3, 1, 2, 3] == [1, 2, 3]
E         Left contains 3 more items, first extra item: 1
E         Full diff:
E         - [1, 2, 3, 1, 2, 3]
E         + [1, 2, 3]

The error suggests that pytest invokes the function being tested twice, somehow passing the optional parameter back into the function!

Note that if I make a small change to the code, the test succeeds:

def foo(ans = [ ]):
    ans = [ ]
    ans.append(1)
    ans.append(2)
    ans.append(3)

    return ans 
Aljay
  • 11
  • 2
  • 2
    Lol. I suggest that pytest has done its job perfectly but in an unexpected way. It's thrown up an issue before it bites you in your actual code – roganjosh Mar 03 '20 at 17:07
  • 2
    There's nothing wrong with `pytest`, just don't use mutables in defaults. Try calling `print(foo())` multiple times in the interactive shell to verify. – hoefling Mar 03 '20 at 17:15

0 Answers0