Skip to content

Instantly share code, notes, and snippets.

@za
Last active June 27, 2018 17:09
Show Gist options
  • Save za/2a217c47582737f88259 to your computer and use it in GitHub Desktop.
Save za/2a217c47582737f88259 to your computer and use it in GitHub Desktop.
django-testing: mock datetime.datetime.now()
import mock
from django.test import TestCase, Client
import datetime
class StubDate(datetime.datetime):
pass
class TestApp(TestCase):
@mock.patch('app.views.datetime.datetime', StubDate) #app is the $django_application_name
def test_now(self):
from datetime import datetime
StubDate.now = classmethod(lambda cls: datetime(2015, 03, 11, 00, 16, 31, 99))
response = self.client.get('/holiday/')
self.assertEqual(response.status_code, 200)
print response.content
self.assertContains(response, '2015-03-11 00:16:31.000099')
import datetime
from django.http import HttpResponse
def now():
return datetime.datetime.now()
def index(request):
return HttpResponse(now())
@danielroseman
Copy link

This wouldn't even work - did you try it? mock.patch passes an extra parameter to the test method being decorated, which is the mock object itself - so test_now needs to take two parameters.

Aside from that, the approach is still not right. The only thing you need to to patch is views.now(), so that it returns the value you want. There's no need for the StubDate class at all.

The whole thing can just be:

class TestApp(TestCase):
    @mock.patch('app.views.now', return_value=datetime.datetime(2015, 3, 11, 0, 16, 31, 99))
    def test_now(self):
        response = self.client.get('/holiday/')
        self.assertContains(response, '2015-03-11 00:16:31.000099')

@za
Copy link
Author

za commented Mar 23, 2015

My test code worked. OK, let me try to update it based on your feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment