Learn Django Β· 12/13

Testing: Bulletproofing Your App πŸ›‘οΈ

7 min read

Imagine you are building a self-checkout software for a national grocery chain. You write the code, it looks great on your machine, and you deploy it to 500 stores. The next morning, a customer scans an apple, and the system accidentally charges them for a flat-screen TV. Panic ensues, the stores shut down the kiosks, and you are left sweating over logs trying to figure out what went wrong.

You could have avoided this by testing the system before it went live. In software development, relying on "it works on my machine" is a dangerous game. Let's learn how to bulletproof your Django applications.


1. Why Write Tests? Setting Up the Django Test Framework πŸ› οΈ

The Problem

When you write code, you usually open your browser, click around, fill out forms, and visually check if things work. This is called manual testing. As your application grows, manually checking every single page, form, and database interaction after every tiny code change becomes impossible. You will forget to check something, and a bug will slip into production.

The Solution: Automated Testing

Automated testing is the practice of writing code that runs your application code and verifies that it behaves exactly as expected. Instead of a human clicking buttons, a script executes operations in milliseconds.

If you change how your user login works, you run your automated tests. If the tests pass, you know you haven't broken the rest of the application.

Setting Up the Framework

Django comes with a built-in testing framework based on Python's standard unittest library. You do not need to install complex third-party tools to get started.

When you run tests, Django does something very specific under the hood: it builds a completely new, blank database (usually prefixed with test_), runs all your tests against this temporary database, and then destroys it. This ensures your production or local development data is never accidentally deleted or altered during testing.

Boilerplate and Structure

When you create an app in Django via python manage.py startapp myapp, Django automatically generates a tests.py file.

For industry standards, as your app grows, a single tests.py file gets too crowded. It is common practice to delete tests.py and replace it with a folder named tests/.

text
myapp/
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ views.py
    β”œβ”€β”€ models.py
    └── tests/
        β”œβ”€β”€ __init__.py      # Required to make it a Python package
        β”œβ”€β”€ test_models.py
        β”œβ”€β”€ test_views.py
        └── test_forms.py

(Note: Test files must start with the word test_ so Django can find them).

To run your tests, you use the Django management command:

bash
python manage.py test

To run tests for a specific app:

bash
python manage.py test myapp

2. Testing Models and Database Integrity πŸ—„οΈ

The Problem

Models are the single source of truth for your data. If your database logic is flawed, your entire application is compromised. For example, if you have a Product model, you need to ensure that products can be created correctly, default values are assigned, and custom methods return the right data.

The Solution

We use django.test.TestCase to create mock data and assert (verify) that the database behaves as intended.

Industry Standard: setUpTestData

In the industry, we prioritize test speed. Creating database records is slow. Instead of using the standard setUp() method (which runs before every single test), we use @classmethod setUpTestData(). This method runs only once per test class, saving the data at the class level, making your test suite significantly faster.

Let's test a simple Product model.

myapp/models.py

python
from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    stock = models.IntegerField(default=0)

    def __str__(self):
        return self.name

    def is_in_stock(self):
        return self.stock > 0

myapp/tests/test_models.py

python
from django.test import TestCase
from myapp.models import Product

class ProductModelTest(TestCase):
    
    @classmethod
    def setUpTestData(cls):
        # Set up non-modified objects used by all test methods
        Product.objects.create(name="Mechanical Keyboard", price=150.00, stock=5)
        Product.objects.create(name="Mousepad", price=20.00, stock=0)

    def test_product_creation_and_str(self):
        # Fetch the product we created
        product = Product.objects.get(id=1)
        
        # Assert the string representation is exactly what we expect
        self.assertEqual(str(product), "Mechanical Keyboard")
        
        # Assert the default values or saved values match
        self.assertEqual(product.price, 150.00)

    def test_is_in_stock_method(self):
        keyboard = Product.objects.get(id=1)
        mousepad = Product.objects.get(id=2)
        
        # assertTrue and assertFalse are standard unittest methods
        self.assertTrue(keyboard.is_in_stock())
        self.assertFalse(mousepad.is_in_stock())

What happens here? We create a keyboard and a mousepad in the temporary test database. Then, we use assertions like assertEqual to verify that our __str__ method and our custom is_in_stock() method output the literal values we expect.


3. Testing Views, Context Data, and URL Routing 🌐

The Problem

You have verified your database works. But what if the user visits /products/ and the server crashes? Or what if the URL loads, but the webpage is blank because the view failed to pass the list of products to the HTML template?

The Solution

We need to test three things for views:

  1. Routing: Does the URL point to the right place?
  2. Response: Does it return an HTTP 200 OK status?
  3. Context: Does the view send the correct dictionary of data (context) to the template?

The Implementation

Always use reverse() from django.urls in your tests. Hardcoding URLs (like '/products/') is a bad industry practice because if you change the URL path in urls.py tomorrow, your tests will fail even if the view works perfectly.

myapp/tests/test_views.py

python
from django.test import TestCase
from django.urls import reverse
from myapp.models import Product

class ProductListViewTest(TestCase):

    @classmethod
    def setUpTestData(cls):
        # Create 3 products for the view to list
        for i in range(3):
            Product.objects.create(name=f"Monitor {i}", price=200.00, stock=10)

    def test_product_list_url_exists_at_desired_location(self):
        # Simulates a GET request to the exact URL path
        response = self.client.get('/products/')
        self.assertEqual(response.status_code, 200)

    def test_product_list_url_accessible_by_name(self):
        # Industry standard: Use reverse to resolve the URL by its name
        url = reverse('product_list')
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

    def test_product_list_uses_correct_template(self):
        response = self.client.get(reverse('product_list'))
        # Asserts that the response was rendered using the specified template
        self.assertTemplateUsed(response, 'myapp/product_list.html')

    def test_product_list_context_data(self):
        response = self.client.get(reverse('product_list'))
        
        # The 'context' is the data passed from the view to the HTML
        # We check if 'products' is in the context and has 3 items
        self.assertTrue('products' in response.context)
        self.assertEqual(len(response.context['products']), 3)

4. The Test Client: Simulating User Interactions πŸ§‘β€πŸ’»

The Problem

Checking if a page loads is great, but users don't just look at pages. They interact. They submit forms, they log in, and they get redirected. How do you test a form submission without opening a browser and typing into input fields?

The Solution: The Django Test Client

The Django Test Client (self.client) is a Python class that acts like a dummy web browser. It allows you to simulate GET and POST requests, handle cookies, and track sessions directly in your Python code, completely bypassing the need for a real web server or network connection.

Handling POST Requests and Authentication

Let's simulate a user submitting a form to create a new product. We will also imagine this view requires the user to be logged in.

myapp/tests/test_interactions.py

python
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import User
from myapp.models import Product

class ProductCreateInteractionTest(TestCase):

    def setUp(self):
        # We use setUp instead of setUpTestData because we are dealing with 
        # sessions and logins which modify state per test.
        self.user = User.objects.create_user(username='admin', password='securepassword123')
        self.create_url = reverse('product_create')

    def test_redirect_if_not_logged_in(self):
        # Simulating a logged-out user trying to access the create page
        response = self.client.get(self.create_url)
        
        # 302 is the HTTP status code for a Redirect (usually to a login page)
        self.assertEqual(response.status_code, 302)
        self.assertTrue(response.url.startswith('/login/'))

    def test_post_form_creates_product(self):
        # 1. Simulate the user logging in
        login_success = self.client.login(username='admin', password='securepassword123')
        self.assertTrue(login_success)

        # 2. Simulate the user submitting a form via POST request
        form_data = {
            'name': 'Ergonomic Chair',
            'price': '299.99',
            'stock': 2
        }
        response = self.client.post(self.create_url, data=form_data)

        # 3. Verify the server responds correctly (often a redirect to a success page)
        self.assertEqual(response.status_code, 302)

        # 4. Query the database to ensure the product was actually created!
        self.assertEqual(Product.objects.count(), 1)
        
        new_product = Product.objects.first()
        self.assertEqual(new_product.name, 'Ergonomic Chair')

What happens under the hood?

When you call self.client.post(), Django gathers your dictionary (form_data), encodes it exactly how an HTML <form> would, and pushes it through your URL routing, into your view, and through your forms. If there is a validation error in your form, the database count won't increase, and your assertion self.assertEqual(Product.objects.count(), 1) will fail, saving you from a nasty production bug!


πŸ“š References & Further Reading

Challenge

You are tasked with writing a comprehensive test suite for a simple blog application. The application has a Post model and views for listing, detailing, and creating posts. The PostCreateView requires a user to be logged in.

Your goal is to write a single test class in tests.py that covers model behavior, view rendering, and user interactions.

Requirements:

  1. Create a test class named PostTests that inherits from django.test.TestCase.
  2. Use the setUpTestData class method to create a test user and at least one initial Post instance. Remember, this data will be shared across all test methods in the class.
  3. Write a test method test_post_model_str to verify that the Post model's __str__ method returns its title.
  4. Write a test method test_post_list_view to check the following for the post list page:
    • It returns an HTTP 200 status code.
    • It uses the correct template ('posts/post_list.html').
    • The initial post created in setUpTestData is present in the view's context.
  5. Write a test method test_post_create_view_unauthenticated that verifies an unauthenticated user trying to access the post creation page is redirected (HTTP 302) to the login page. Use reverse('login') to get the login URL.
  6. Write a test method test_post_create_view_authenticated_post that simulates a logged-in user creating a new post:
    • Use the setUp instance method to log the test user in.
    • Simulate a POST request to the create page URL with valid form data for a new post (title, content).
    • Assert that the response is a redirect (HTTP 302) to the post list page.
    • Assert that a new Post object with the submitted title has been created in the database.

Expected result

Your solution should be a complete Python script for a tests.py file. It must contain a single class PostTests inheriting from TestCase.

The class must implement the following methods:

  • setUpTestData(cls): A class method that creates a user using get_user_model().objects.create_user() and a Post instance associated with that user.
  • setUp(self): An instance method that uses self.client.login() to log in the test user created in setUpTestData.
  • test_post_model_str(): Contains an assertion (self.assertEqual()) to check if the post's string representation matches its title.
  • test_post_list_view(): Simulates a GET request to the 'post_list' URL. It must include assertions for the status code (self.assertEqual(response.status_code, 200)), the template used (self.assertTemplateUsed(response, 'posts/post_list.html')), and the presence of the post in the context (self.assertContains(response, self.post.title)).
  • test_post_create_view_unauthenticated(): Simulates a GET request to the 'post_create' URL without logging in. It should assert that the response status code is 302 and that the redirect location points to the URL resolved by reverse('login').
  • test_post_create_view_authenticated_post(): Simulates a POST request to the 'post_create' URL with a dictionary containing 'title' and 'content'. It must assert a 302 redirect to the 'post_list' URL and assert that the Post.objects.count() has increased by one.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.