How can I unit test a method using a datetime?
<p>I have the follow class and method:</p>

<pre><code>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
</code></pre>

<p>How can I unit test it? I am completely stumped although this is simple. It's my first unit test. </p>

<p>Use the <a href="https://docs.python.org/3/library/unittest.mock.html" rel="nofollow"><code>unittest.mock</code> library</a> (Python 3.3 and newer, backported as <a href="https://pypi.python.org/pypi/mock" rel="nofollow"><code>mock</code></a>), to replace calls to any code external to your code-under-test.</p>

<p>Here, I'd mock out not only <code>utcnow()</code> but <code>strftime()</code> too, to just return a string object:</p>

<pre><code>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()
</code></pre>

<p>If you feel that testing the <code>strftime()</code> argument is important, give  <code>dt_mock.utcnow.return_value</code> an explicit <code>datetime</code> object to return instead; you'd have to create that test object <em>before</em> you mock however, as you can't mock out just the <code>datetime.datetime.utcnow</code> class method:</p>

<pre><code>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()
</code></pre>

<p>or, in your unittests, use <code>from datetime import datetime</code> to keep a reference to the class that isn't mocked.</p>

<p>Demo:</p>

<pre><code>&gt;&gt;&gt; from unittest import mock
&gt;&gt;&gt; import datetime
&gt;&gt;&gt; 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
...
&gt;&gt;&gt; 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()
...
&gt;&gt;&gt; result
'2016-08-04 12:22:44.123'
&gt;&gt;&gt; testdt = datetime.datetime(2016, 8, 4, 12, 22, 44, 123456)
&gt;&gt;&gt; with mock.patch('datetime.datetime') as dt_mock:
...     dt_mock.utcnow.return_value = testdt
...     result = DateTimeHelper.get_utc_millisecond_timestamp()
...
&gt;&gt;&gt; result
'2016-08-04 12:22:44.123'
</code></pre>

python unit-testing datetime