Python: How do I mock datetime.utcnow()?

mocking, python, unit-testing

Solution

in your test file:

from yourfile import get_report_month_key
import mock
import unittest
from datetime import datetime

class TestCase(unittest.TestCase):

    @mock.patch('yourfile.datetime')
    def test_dt(self, mock_dt):
        mock_dt.utcnow = mock.Mock(return_value=datetime(1901, 12, 21))
        r = get_report_month_key()
        self.assertEqual('190112', r)

Problem

I have the below: ``` from datetime import datetime def get_report_month_key(): month_for_report = datetime.utcnow() return month_for_report.strftime("%Y%m") ``` How do I mock datetime.utcnow() so that I can write unit test on this function? Tried reading this one but I am unable to get it working for me on utcnow()

Original source

Related problems