01 Choose behavior to verify
Use the Note model from the ORM tutorial and the home route from the first-view tutorial. Test the behavior your application promises: how a note is represented and whether the homepage responds successfully.
02 Test the model
Put this in core/tests.py. TestCase supplies database isolation so records created by this test do not become normal application data. Use an isolated test database, never a production database, when running tests.
from django.test import TestCase
from django.urls import reverse
from .models import Note
class NoteTests(TestCase):
def test_note_has_readable_title(self):
note = Note.objects.create(title="First note")
self.assertEqual(str(note), "First note")
self.assertEqual(Note.objects.count(), 1)03 Test the page
Add this second class to the same file. reverse() finds the address using the route name. The built-in client makes a request without requiring a running development server.
class HomeTests(TestCase):
def test_homepage_is_available(self):
response = self.client.get(reverse("home"))
self.assertEqual(response.status_code, 200)04 Run only what you need
Start with the core tests. During an edit to model behavior, run only NoteTests. A failing assertion tells you which expected behavior changed; investigate the failure before changing the expectation.
python manage.py test core
python manage.py test core.tests.NoteTestsRead the official Django documentation for details and more examples.