How to mock

latrova commited 2 years, 10 months ago

I was thinking about how to achieve it some days ago. There's a method that uses todays date to choose which transactions should be returned and I have no idea how to mock this! Well, after some research, here it is:

from datetime import datetime

... #more code that uses

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

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) = mocked_today
    #old transactions
    self.create_transaction(value=self.value,, 12, 1))
    self.create_transaction(value=self.value,, 1, 1))
    #current month
    self.create_transaction(value=self.value,, 2, 1))
    self.create_transaction(value=self.value,, 2, 7))
    self.create_transaction(value=self.value,, 2, 8))
    self.create_transaction(value=self.value,, 2, 14))

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

    self.assertEqual(response.status_code, status.HTTP_200_OK)
    self.assertEqual(len(, 4)
blog comments powered by Disqus