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()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My test code worked. OK, let me try to update it based on your feedback.