When you created your books app with Django's startapp
command, it created a file called tests.py
in your app directory. This is where any tests for the books app should go. So let's get right to it and write a test:
import datetime from django.utils import timezone from django.test import TestCase from .models import Book class BookMethodTests(TestCase): def test_recent_pub(self): """ recent_publication() should return False for future publication dates. """ futuredate = timezone.now().date() + datetime.timedelta(days=5) future_pub = Book(publication_date=futuredate) self.assertEqual(future_pub.recent_publication(), False)
This should all be pretty straight forward as it's nearly exactly what we did in the Django shell, the only real difference is that we now have encapsulated our test code in a class and created an assertion that tests our recent_publication()
method against a future date.
We will be covering test classes and the assertEqual
method in greater detail later in the chapter-for now, we just want to look at how tests work at a very basic level before getting onto more complicated topics.