Last active
June 27, 2018 17:09
-
-
Save za/2a217c47582737f88259 to your computer and use it in GitHub Desktop.
django-testing: mock datetime.datetime.now()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
from django.http import HttpResponse | |
def now(): | |
return datetime.datetime.now() | |
def index(request): | |
return HttpResponse(now()) |
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
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 - sotest_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: