1

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

piyush daga
  • 501
  • 4
  • 17

1 Answers1

2

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'.

Bernardo Duarte
  • 4,074
  • 4
  • 19
  • 34
  • Thanks, that string formatting is more of a technicality, but if I have multiple test cases, would I have to import within each function / class (unittest.TestCase)? – piyush daga Jun 03 '20 at 05:49
  • @piyushdaga You could make a [raw use](https://github.com/spulec/freezegun#raw-use) at the top of your test suite around your import, this way you should only do it once, but I haven't tested. – Bernardo Duarte Jun 03 '20 at 05:55
  • 1
    @piyushdaga Have this answered your question? If it did, don't forget to mark it as answer. Hope I helped ;D – Bernardo Duarte Jan 29 '21 at 21:05