0
# 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.

mounika
  • 39
  • 8
  • If it works in one case,but not with the other test cases, chances are, the other test cases are giving the problem. Could you post them so that we can take a look? – Canbach Mar 24 '21 at 17:46
  • @Canbach its a huge suite of test cases and I am sure the other test cases wouldn't affect because, these tests are for a new piece of code and is completely unrelated to any of the existing code or test cases. And moreover, there is no input to the function I am testing. It just has to initiate datetime.utcnow() and add timedelta and return the date. – mounika Mar 24 '21 at 18:01

1 Answers1

0

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)

mounika
  • 39
  • 8