1

I have a function that carries out some logic based on today's date:

def do_work()
  todays_date = datetime.datetime.today().date()
  #do something based on todays_date

I want to write some unit tests that verify that this function does what it is supposed to on given days of the year. Is there any way that I can change the value that get's stored in todays_date without changing the function?

I suspect not, but just thought I'd ask.

jamiet
  • 10,501
  • 14
  • 80
  • 159

1 Answers1

1

The mock module can come in handy in this case. The documentation has an example on how to partially-mock a fixed date.

>>> from datetime import date
>>> with patch('mymodule.date') as mock_date:
...     mock_date.today.return_value = date(2010, 10, 8)
...     mock_date.side_effect = lambda *args, **kw: date(*args, **kw)
...
...     assert mymodule.date.today() == date(2010, 10, 8)
...     assert mymodule.date(2009, 6, 8) == date(2009, 6, 8)
...
Jonah Bishop
  • 12,279
  • 6
  • 49
  • 74
  • great thanks, will give it a go. – jamiet Jan 16 '19 at 14:56
  • Just fixed the link to the example (it was pointing to the wrong place). – Jonah Bishop Jan 16 '19 at 14:57
  • I couldn't get it working with the example that you linked to however it contained a further link to https://williambert.online/2011/07/how-to-unit-testing-in-django-with-mocking-and-patching/ which did work for me. Thank you. – jamiet Jan 16 '19 at 16:08