Search code examples
pythontestingpython-unittestfreezegun

Freeze Time test cases fail when a variable is used to reference the time


I'm using freeze-time to run my python unittest Test cases.

A dummy test case:

@freeze_time('2020-01-01')
def test_something(self):
  expected_output = {'time': '2020-01-01'}

  output = call_tested_code()

  self.assertEqual(expected_output, output)

Main code / Code that is being tested:

GET_CURRENT_TIME = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')

def call_tested_code():
  return {'time': GET_CURRENT_TIME}

This is failing, as the output is giving current_date instead of frozen date. It was working when the GET_CURRENT_TIME was a lambda, but that results in different timestamps for my code, which I don't want.

Feel free to comment if any additional Information is required. Thanks


Solution

  • Your tested code is being imported before your test function, so GET_CURRENT_TIME is evaluated before your freeze_time so that's the problem.

    To solve if either import call_tested_code inside the test function or put it inside a lambda or another callable, as mentioned by you.

    @freeze_time('2020-01-01')
    def test_something(self):
        from package import call_tested_code # edit here with your correct import
        expected_output = {'time': '2020-01-01'}
        output = call_tested_code()
        self.assertEqual(expected_output, output)
    

    Also, I think you should change the expected output to be a datetime string not only date as your GET_CURRENT_TIME uses this format '%Y-%m-%d %H:%M:%S'.