Search code examples
pythontimezonepatch

In python, how can I add a patch decorator that does not add a mock input argument?


In python, how can I add a patch that does not add a mock input argument?

I want to add a patch on all methods in a class like so:

@patch('django.utils.timezone.now', return_value=datetime.datetime(2022, 4, 22, tzinfo=timezone.utc))
class TestmanyMethods(unittest.TestCase):
    # my test methods here

But when I do that, a mock must be added to all test methods. How can I patch the function without adding the mock input to all test methods?


Solution

  • One can do this by using the new keyword arg in the patch like so:

    @patch('django.utils.timezone.now', new=Mock(return_value=datetime.datetime(2022, 4, 22, tzinfo=timezone.utc)))
    class TestmanyMethods(unittest.TestCase):
        # my test methods here
    

    With that, the mock input is not added to the class's test methods