简体   繁体   中英

Recording and asserting an empty mock list in python unittest

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[:] = [] in foo .

But I also realized that passing create=True is 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM