I have the following function in my utils.py basically count the seconds from 1970 till curent time:
import datetime
def get_utc_timestamp():
d = datetime.datetime.utcnow()
epoch = datetime.datetime(1970, 1, 1)
t = (d - epoch).total_seconds()
return t
I want to run a test case on that function but it's time dependent so i looked for a solution and stumble upon this question on SO link i tried to apply it in my test_utils.py:
import unittest
from utils import *
from unittest import mock
import datetime
class TestUtils(unittest.TestCase):
@mock.patch('utils.datetime.datetime')
def test_get_utc_timestamp(self, mock_dt):
mock_dt.utcnow = mock.Mock(return_value = datetime.datetime(2019, 8, 27, 8, 52, 12, 703618))
result = get_utc_timestamp()
self.assertEqual(result, 1566895932.703618)
if __name__ == '__main__':
unittest.main()
I tested the result of it in the console:
d = datetime.datetime(2019, 8, 27, 8, 52, 12, 703618)
epoch = datetime.datetime(1970, 1, 1)
t = (d - epoch).total_seconds()
return t
And it returned
1566895932.703618
But when i run the test i got AssertionError:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/unittest/mock.py", line 1179, in patched
return func(*args, **keywargs)
File "/app/tests/test_utils.py", line 15, in test_get_utc_timestamp
self.assertEqual(result, 1566895932.703618)
AssertionError: <MagicMock name='datetime().__sub__().total_seconds()' id='140475857850040'> != 1566895932.703618
What am i doing wrong ?
Any help would be appreciate!
EDIT:
thank ipaleka for the explanation on what going on, since i can't change python built - in class with mock so i need to make a custom class of utcnow() to return the custom time in test_utils.py:
class NewDate(datetime.datetime):
@classmethod
def utcnow(cls):
return cls(2019, 8, 27, 8, 52, 12, 703618)
datetime.datetime = NewDate
and change test function to:
def test_get_utc_timestamp(self):
result = get_utc_timestamp()
self.assertEqual(result, 1566895932.703618)