I’m using unittest and mock (Michael Foord’s module) to test some python code.
I have something like this (this is a proof of concept that could be rewritten more cleanly, but my real code needs to behave like that foo function):
import unittest
from mock import patch
def foo():
my_list = []
class Test(unittest.TestCase):
def test_foo(self):
with patch('__main__.my_list', new=[], create=True) as baz:
baz.extend(['foo', 'bar'])
self.assertEqual(foo(), None)
self.assertListEqual([], baz)
if __name__ == '__main__':
unittest.main()
So the problem is that my baz mock object doesn’t change accordingly after the foo() call and the last assertion fails.
If I use my_list.remove(x) in foo() then I can see the changes in my test case, but I just want to empty that list, I don’t want to pass through every element of the list then remove it, no, I want a fast empty operation.
How can I check if my mock object is emptied without using .remove(x), but using the current implementation of function foo?
So, I end up answering my own question…
The solution was to use
my_list[:] = []infoo.But I also realized that passing
create=Trueis bad because if that list doesn’t exist (exactly the case of this POC) it will be created and I’ll possibly test broken code that passes the tests.