Mocking datetime in Python 2

Mocking dates is a well-known PITA with Python. But here’s a quick explanation of how I worked around this deficiency.

Step 1: Add the date as a property to the production class. I had to refactor my code, and I suspect you will too. Before mocking this date, I was calling date.today() from the build_widget method.

from datetime import date  
  
class WidgetWorker(object):
    date = date.today() 
    def build_widget(self):
        return {'date_created': self.date}

Step 2: Patch the date property in your test.

from mock import patch   
from unittest import TestCase   

class WidgetTests(TestCase):       
    @patch('WidgetWorker.date', date(2000, 01, 01))       
    def test_widget_date(self):           
        self.assertEqual(date(2000, 01, 01), WidgetWorker().date)