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())
@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