Skip to main content
← Build a Django task trackerStep 3 of 4

Backend Development

Build a Django Task Tracker, Part 3: Test Permissions and Failure Cases

Test ownership, validation, pagination, template escaping, and CSRF with Django’s test client.

A page can look correct while returning another user's records. Tests make that boundary explicit and keep it intact as the application changes. This chapter tests the task tracker from part two, focusing on observable behavior rather than whether a particular helper was called.

Run the example's tests

From the downloaded django-task-tracker directory, with its virtual environment active:

python manage.py test tasks

Django creates a separate test database. The example tests create their own users and tasks, so they do not depend on tasks you entered manually. When the run completes, Django removes the test database. Keep this command in the example project; running CodeEasy's manage.py tests a different application.

The expected result for the supplied version is nine passing tests. A failure is a prompt to inspect the reported assertion and the behavior it describes. Do not fix a failure by weakening an ownership check or removing the assertion.

Build fixtures that can expose a privacy bug

The setup creates Alice, Bob, and a task belonging to each. A test containing only Alice's records cannot demonstrate whether Bob's data leaks into Alice's list. Two owners let us test both inclusion and exclusion.

The passwords below are throwaway values in a temporary test database. force_login() sets up the authenticated session without exercising password entry; it keeps these tests focused on task behavior. The browser login page still needs a manual check.

tasks/tests.py

from django.contrib.auth import get_user_model
from django.test import Client, TestCase
from django.urls import reverse
from .models import Task


class TaskTests(TestCase):
    def setUp(self):
        self.alice = get_user_model().objects.create_user('alice', password='test-only-password')
        self.bob = get_user_model().objects.create_user('bob', password='test-only-password')
        self.task = Task.objects.create(owner=self.alice, title='Learn ownership')
        self.foreign = Task.objects.create(owner=self.bob, title='Private Bob task')
        self.client.force_login(self.alice)

    def test_anonymous_users_must_sign_in(self):
        self.client.logout()
        self.assertRedirects(self.client.get('/'), '/accounts/login/?next=/')

    def test_list_is_scoped_to_owner(self):
        response = self.client.get('/')
        self.assertContains(response, 'Learn ownership')
        self.assertNotContains(response, 'Private Bob task')

    def test_owner_cannot_be_forged(self):
        response = self.client.post('/', {'title':'My new task', 'owner':self.bob.pk, 'completed':True})
        self.assertRedirects(response, '/')
        task = Task.objects.get(title='My new task')
        self.assertEqual(task.owner, self.alice)
        self.assertFalse(task.completed)

    def test_blank_and_long_titles_are_rejected(self):
        for title in ['', '   ', 'x' * 161]:
            response = self.client.post('/', {'title':title})
            self.assertEqual(response.status_code, 200)
            self.assertTrue(response.context['form'].errors)
        self.assertEqual(Task.objects.count(), 2)

    def test_toggle_requires_post_and_ownership(self):
        url = reverse('tasks:toggle', args=[self.task.pk])
        self.assertEqual(self.client.get(url).status_code, 405)
        self.assertRedirects(self.client.post(url), '/')
        self.task.refresh_from_db()
        self.assertTrue(self.task.completed)
        self.assertEqual(self.client.post(reverse('tasks:toggle', args=[self.foreign.pk])).status_code, 404)
        self.foreign.refresh_from_db()
        self.assertFalse(self.foreign.completed)

    def test_csrf_is_enforced(self):
        browser = Client(enforce_csrf_checks=True)
        browser.force_login(self.alice)
        self.assertEqual(browser.post('/', {'title':'No token'}).status_code, 403)
        browser.get('/')
        token = browser.cookies['csrftoken'].value
        self.assertRedirects(browser.post('/', {'title':'Valid token'}, HTTP_X_CSRFTOKEN=token), '/')

    def test_template_escapes_task_titles(self):
        Task.objects.create(owner=self.alice, title='<script>alert(1)</script>')
        response = self.client.get('/')
        self.assertNotContains(response, '<script>alert(1)</script>')
        self.assertContains(response, '<script>alert(1)</script>')

    def test_pagination_is_per_user(self):
        Task.objects.bulk_create([Task(owner=self.alice, title=f'Task {i}') for i in range(21)])
        self.assertEqual(len(self.client.get('/').context['page_obj']), 20)
        self.assertEqual(len(self.client.get('/', {'page':2}).context['page_obj']), 2)

    def test_logout_uses_post(self):
        self.assertEqual(self.client.get('/accounts/logout/').status_code, 405)
        self.assertRedirects(self.client.post('/accounts/logout/'), '/accounts/login/')

What the tests prove

The anonymous-user test expects a redirect to the login page, including the destination the user tried to reach. The list test checks that Alice's title is present and Bob's title is absent. That negative assertion catches a query accidentally changed from an owner filter to Task.objects.all().

The forged-owner test submits fields that the page does not offer. The saved task must belong to Alice, and completion must remain false. This tests the server boundary rather than assuming that hiding a form input prevents tampering.

The title test checks empty text, whitespace, and excessive length. A 200 response is correct for this server-rendered form: Django displays the form again with errors. The database count must remain unchanged. A successful redirect would be incorrect for those inputs.

The toggle test exercises allowed and disallowed methods and users. It confirms the user's task changes and another user's task does not. The foreign lookup returns 404; the test does not rely on the exact error-page wording.

Check CSRF separately

Django's ordinary test client does not enforce CSRF checks by default. A test that simply calls client.post() cannot prove the real middleware accepts or rejects the right requests. We use Client(enforce_csrf_checks=True) for that case.

The first POST has no CSRF token and must return 403. After the browser fetches the form, the second POST supplies the token and succeeds. This is an integration check of the middleware, cookie, header, view, and form flow. It does not prove that every possible deployment proxy is configured correctly.

The escaping test adds a task whose title resembles a script tag. The response must contain escaped text, and it must not contain an executable script element. This catches an accidental safe filter in the template. It is a targeted regression test, not a complete security review.

Use a deliberate regression to understand the suite

In a disposable working copy, temporarily remove the owner filter from the list view. Run the tests and find the failing privacy assertion. Restore the filter immediately. Next, try adding owner to TaskForm.Meta.fields; the forged-owner test should help you understand why field selection matters, although assigning the owner on the server remains another line of defense.

Change only one thing at a time. The purpose is to learn which behavior each assertion protects, not to accumulate a test count. For the final code, all nine tests should pass again.

Know the boundary of automated checks

These tests do not measure rendering quality on a phone, network failures, concurrent request throughput, password-reset delivery, or the capacity of a production database. The SQL boolean update avoids a Python lost-update toggle, but the suite does not load-test SQLite. Make an actual browser pass through login, creation, completion, pagination, and logout.

As an exercise, add a due date or a completion filter. First write down its behavior: does an invalid date preserve the submitted title, and should filters affect pagination? Then add a test that fails before implementing it. That sequence makes the feature's contract visible.

Next, deploy the task tracker behind HTTPS. Django's testing tools documentation explains the client and test database lifecycle in more detail.

Step 3 of 4 · Build a Django task tracker

Put this step into practice.

Run the nine example tests and explain which regression each protects.

Enable JavaScript to save progress. You can still continue through the path.

Stay curious

A new idea for your inbox.

Occasional updates when we publish new guides. No noise.

Subscribing...