I have the follow class and method:
class DateTimeHelper(object):
@staticmethod
def get_utc_millisecond_timestamp():
(dt, micro) = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f').split('.')
return "%s.%03d" % (dt, int(micro) / 1000) # UTC time with millisecond
How can I unit test it? I am completely stumped although this is simple. It's my first unit test.
Use the unittest.mock
library (Python 3.3 and newer, backported as mock
), to replace calls to any code external to your code-under-test.
Here, I'd mock out not only utcnow()
but strftime()
too, to just return a string object:
with mock.patch('datetime.datetime') as dt_mock:
dt_mock.utcnow.return_value.strftime.return_value = '2016-08-04 12:22:44.123456'
result = DateTimeHelper.get_utc_millisecond_timestamp()
If you feel that testing the strftime()
argument is important, give dt_mock.utcnow.return_value
an explicit datetime
object to return instead; you'd have to create that test object before you mock however, as you can't mock out just the datetime.datetime.utcnow
class method:
testdt = datetime.datetime(2016, 8, 4, 12, 22, 44, 123456)
with mock.patch('datetime.datetime') as dt_mock:
dt_mock.utcnow.return_value = testdt
result = DateTimeHelper.get_utc_millisecond_timestamp()
or, in your unittests, use from datetime import datetime
to keep a reference to the class that isn't mocked.
Demo:
>>> from unittest import mock
>>> import datetime
>>> class DateTimeHelper(object):
... @staticmethod
... def get_utc_millisecond_timestamp():
... (dt, micro) = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f').split('.')
... return "%s.%03d" % (dt, int(micro) / 1000) # UTC time with millisecond
...
>>> with mock.patch('datetime.datetime') as dt_mock:
... dt_mock.utcnow.return_value.strftime.return_value = '2016-08-04 12:22:44.123456'
... result = DateTimeHelper.get_utc_millisecond_timestamp()
...
>>> result
'2016-08-04 12:22:44.123'
>>> testdt = datetime.datetime(2016, 8, 4, 12, 22, 44, 123456)
>>> with mock.patch('datetime.datetime') as dt_mock:
... dt_mock.utcnow.return_value = testdt
... result = DateTimeHelper.get_utc_millisecond_timestamp()
...
>>> result
'2016-08-04 12:22:44.123'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With