0

I am writing unit tests in python.

My code uses redis frequently and I want to mock this. I'd like to do this globally and not worry about mocking it in each test, but I don't think this is possible using the @patch decorator.

Example of working test-

class ExamplesTests(AbstractTestCase, unittest.TestCase):

    @patch('main.redis')
    def test_the_thing(self, redis: MagicMock):
        redis.set = self._my_mock_set # method that sets a dict val
        redis.get = self._my_mock_get # method that gets a dict val

        result = main.do_the_thing()

        self.assertTrue(result)

I don't actually need what's in the mock cache, i'm just trying to prevent the need to cleanup the actual redis cache that's being used by other processes. I tried doing this in the setUp-

class AbstractTestCase(ABC):

    @patch('main.redis')
    def setUp(self, redis: MagicMock):
        redis.set = self._my_mock_set # method that sets a dict val
        redis.get = self._my_mock_get # method that gets a dict val

Error: setUp() takes 2 positional arguments but 3 were given

Instead of patching every test, is it possible to use setup without the decorator? Something like this?-

class AbstractTestCase(ABC):

    def setUp(self):
        redis = patch('main.redis')
        redis.set = self._my_mock_set # method that sets a dict val
        redis.get = self._my_mock_get # method that gets a dict val
which_part
  • 792
  • 3
  • 11
  • 26
micah
  • 7,596
  • 10
  • 49
  • 90

1 Answers1

1

You can indeed create the patch like that, but you then need to explicitly enable it as well. You'll want to stop the patch as well after the test completes.

def setUp(self):
    self.redis = redis = patch('main.redis')
    redis.set = ...
    redis.get = ...
    redis.start()
    self.addCleanup(redis.stop)
chepner
  • 497,756
  • 71
  • 530
  • 681