Python how to reuse a Mock to avoid writing mock.patch multiple times? Python how to reuse a Mock to avoid writing mock.patch multiple times? flask flask

Python how to reuse a Mock to avoid writing mock.patch multiple times?


You could use patches and reuse them in a setUp block.

Patches are nice as you can "unpatch" things when you are done with the test, meaning you won't leave things mocked forever, as some other tests may require to run on the real code.

On the link above, you will see the following piece of code:

>>> class MyTest(TestCase):...     def setUp(self):...         patcher = patch('package.module.Class')...         self.MockClass = patcher.start()...         self.addCleanup(patcher.stop)......     def test_something(self):...         assert package.module.Class is self.MockClass...

It works fine, but I don't really like to call patch(), start() and addCleanup() for every patch.

You can easily factor this in a base class that you could reuse in your test classes:

class PatchMixin:    def patch(self, target, **kwargs):        p = mock.patch(target, **kwargs)        p.start()        self.addCleanup(p.stop)class TestBlockingIo(unittest.TestCase, PatchMixin):    def setUp(self):        self.patch('__main__.authorize')        self.patch('__main__.BlockingIo.do')    def test_1(self):        r = testapp.get('/1/')        self.assertEquals(r.data, b'1')    def test_2(self):        r = testapp.get('/2/')        self.assertEquals(r.data, b'2')