mock.patch-ing the .append method of the Python list

333 Views Asked by At

I am unit testing a single line of code within an if statement where I append an item onto a list if a variable has a specific value.

foo = []
if bar == 'a':
    foo.append(bar)

I would like to assert that such an append has been called. I have patched methods from a variety of sources before, but not methods belonging to basic Python data types. What class would I specify as the path for the mock.patch decorator?

@mock.patch('append')
def test_appends_bar_to_foo(mock_append):
    assert mock_append.called

With the above code, I get TypeError: Need a valid target to patch. You supplied: 'append'

1

There are 1 best solutions below

2
blhsing On

You can patch foo instead and assert that its append method has been called:

foo = []
with mock.patch('__main__.foo') as mock_foo:
    foo.append(1)
    mock_foo.append.assert_called() # assertion success