liveBook · Manning

Assertion method

As explained in Django in Action

An assertion method is a test operation that checks a stated condition and raises an exception when the condition is false.

An assertion method checks a stated condition during a test and raises an exception when the condition is false. In Django, assertEqual() can verify that a view returns the expected HTTP status code. section 8.2

A typical test uses Django’s client to request a URL, then asserts something about the response. For the credits() view, the expected status is 200, meaning the request succeeded. Keeping the expected value first makes failures easier to read. section 8.2

Checking a view response

response = self.client.get("/credits/") self.assertEqual(200, response.status_code) If the test is changed to self.assertEqual(42, response.status_code), Django reports AssertionError: 42 != 200, with a stack trace showing where the failure occurred. section 8.2

Listing 8.1 A test case for the credits() view
# home/tests.py
from django.test import TestCase  #1

class TestHome(TestCase): #2
    def test_credits(self):  #3
        response = self.client.get("/credits/")  #4
        self.assertEqual(200, response.status_code)  #5

Use the complete test listing to see the TestCase class, client request, and assertion working together. section 8.2

How Django in Action covers it

How deep it goes
Defines condition checking and failure exceptions, but does not detail the complete assertion-method catalog.
Examples
Uses the credits() view, a /credits/ request, status code 200, and an intentionally incorrect value of 42.
What it assumes
Assumes basic Python testing and HTTP-response concepts while demonstrating Django’s client and TestCase workflow.
What you can do after
Diagnose failed Django tests by reading assertion messages and stack traces produced by the test command.
How it connects
Connects Python TestCase, Django’s test runner, HTTP responses, and unit testing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.