Search code examples
pythondjangopython-mockfreezegun

freeze_time doesn't work inside invoked functions


# test.py
from freezegun import freeze_time
from actual import DummyClass

class DummyClassMock(DummyClass):
   def some_function(self):
     # does something


class TestClass():
   def setUp(self):
      self.dummy = DummyClassMock()

   @freeze_time('2021-01-01')
   def test_dummy_function(self):
      self.assertTrue((self.dummy.dummy_function - datetime.utcnow()).total_seconds() >= 1)

# actual.py
from datetime import datetime, timedelta

class DummyClass():
   def dummy_function(self):
       return datetime.utcnow() + timedelta(5)

My code goes along the above structure. With this, if I am executing the test_dummy_function individually, dummy_function is returning 2021-01-01 and test case is a pass. However, when I running this along with all the other test cases in the project, it is failing. Content is not dependent either.


Solution

  • Not particularly a good solution but, the workaround I used was to define a function that would just return datetime.utcnow() and mock it. My test case will assign the date used in freeze_time as return value. It looks something like,

    @mock.patch(actual.DummyClass.now_function)
     @freeze_time('2021-01-01')
       def test_dummy_function(self, mock_dt):
          now = datetime.utcnow()
          mock_dt.return_value = now
          self.assertTrue((self.dummy.dummy_function - now).total_seconds() >= 1)
    
    
    # actual.py
    Class DummyClass():
        def now_function():
            return datetime.utcnow()
    
        def dummy_function():
            return now_function()+timedelta(days=5)