How to mock datetime.today()

gui commited 7 years ago · 🐍 Python mock tests

I was thinking about how to achieve it some days ago. There's a method that uses today's date to choose which transactions should be returned and I have no idea how to mock this!

Well, after some research, here it is:

views.py

from datetime import datetime

... # more code that uses datetime.today()
views.py

tests.py

Pay attention to mock.patch, we're overriding datetime module only inside of views.py!

from unittest import mock
... #more imports

@mock.patch('transactions.views.datetime', side_effect=lambda *args, **kw: date(*args, **kw))
def test_returns_only_from_current_month_by_default(self, mock_date):
    '''
    Returns only transactions from current month. Considering today is 15/02/2017
    '''
    mocked_today = datetime.datetime(2017, 2, 15)
    mock_date.today.return_value = mocked_today
    #old transactions
    self.create_transaction(value=self.value, due_date=datetime.date(2016, 12, 1))
    self.create_transaction(value=self.value, due_date=datetime.date(2017, 1, 1))
    #current month
    self.create_transaction(value=self.value, due_date=datetime.date(2017, 2, 1))
    self.create_transaction(value=self.value, due_date=datetime.date(2017, 2, 7))
    self.create_transaction(value=self.value, due_date=datetime.date(2017, 2, 8))
    self.create_transaction(value=self.value, due_date=datetime.date(2017, 2, 14))

    response = self.client.get(self.url)

    self.assertEqual(response.status_code, status.HTTP_200_OK)
    self.assertEqual(len(response.data), 4)
tests.py
  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket