0

I'm writing tests for models that trigger various functions which go beyond the scope of the testing (some functions invoke network functionality and other undesired things, which are not part of the test, can be slow to just let run and is easier to just switch off for testing purposes). We do this by using a series of @patch decorators above every test function as required.

I don't like putting the same decorators over every test function in the test class because they clutter up the code. Is it possible to move all my patches into a function and just call it from there? I tried a simple implementation like below but it didn't work for me:


from unittest.mock import patch

class MyTest(APITestCase):

def patch_all(self):
    p1 = patch('mod1.func1')
    p2 = patch('mod1.func2')
    ...
    return (p1, p2, ...)

def test_function(self):
    p1, p2, ... = self.patch_all()
    perform_actual_test()

Is there a way to patch out the functions without writing decorators everywhere and just calling a function instead?

Mark Ang
  • 149
  • 1
  • 11
  • As a step towards what you want you can apply `patch()` to your test class: https://stackoverflow.com/questions/15821465/how-to-properly-use-mock-in-python-with-unittest-setup – quamrana Feb 13 '20 at 10:24
  • Also you can combine multiple decorators (patches) into one to make it easier to apply the same patches to many test classes: https://stackoverflow.com/questions/5409450/can-i-combine-two-decorators-into-a-single-one-in-python – quamrana Feb 13 '20 at 10:28
  • Thanks! The answers are exactly what I was looking for. – Mark Ang Feb 14 '20 at 03:18

0 Answers0