Introduction to Testing in Django
Why Django needs automated tests
As a project grows, it becomes impossible to manually click through every page after every change. Automated tests run in seconds and check behavior for you, so bugs are caught before deployment instead of after.
Note: Run your test suite before every commit, not just before a release.
Example: Why Django needs automated tests
As a project grows, it becomes impossible to manually click through every page after every change. Automated tests run in seconds and check behavior for you, so bugs are caught before deployment instead of after.
python manage.py test
⚠️ Run this command in your terminal.
Where tests live
A newly created Django app comes with a tests.py file. Larger apps often replace it with a tests/ package containing multiple files, but Django's test runner discovers both automatically as long as file and method names start with test.
Note: Keep test file names starting with test_ so Django's discovery finds them.
Example: Where tests live
startapp scaffolds tests.py automatically inside every new app — cat prints its default starting content, ready for you to add test classes to.
python manage.py startapp myapp
cat myapp/tests.py
⚠️ Run this command in your terminal.
What a test checks
A test calls some part of your code with known input and asserts the output matches what you expect. If the assertion fails, the test runner reports exactly which test broke and why.
Example: What a test checks
A test calls some part of your code with known input and asserts the output matches what you expect. If the assertion fails, the test runner reports exactly which test broke and why.
from django.test import TestCase
class MathCheckTests(TestCase):
def test_addition_is_correct(self):
self.assertEqual(2 + 2, 4)
{# Django-only code -- models.py/views.py/urls.py/settings.py
snippets, or template markup using Django template tags/variables
-- can't run standalone via Judge0 or the browser preview, since
it needs a real Django project. Only this course's pure-Python
examples (example_lang == 'python', no Django imports) are
actually runnable, so those still get the button below. #}
- Skipping tests entirely because the app 'looks fine' in the browser, then breaking it silently with the next change.
- Treating tests as optional documentation instead of code that must be run and kept passing.
- Writing one giant test that checks everything at once instead of small focused tests.
- Django ships a built-in testing framework built on Python's unittest module.
- Tests live in each app's tests.py file (or a tests/ package) and are discovered automatically.
- Automated tests catch regressions early, before real users ever see a bug.
- Every serious Django project treats its test suite as part of the codebase, not an afterthought.
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: