CodeOath
← All posts
Python70 min total · 18 parts

Django Fundamentals: MVT Architecture, the ORM, and Middleware

Contents — Part 17 of 18: Testing in Django
Part 17 of 18 · ~1 min

Testing in Django

from django.test import TestCase

class OrderModelTests(TestCase):
    def setUp(self):
        self.customer = Customer.objects.create(name="Ana")

    def test_order_total_must_be_positive(self):
        order = Order(customer=self.customer, total=-5)
        with self.assertRaises(ValidationError):
            order.full_clean()

    def test_order_list_view(self):
        Order.objects.create(customer=self.customer, total=100)
        response = self.client.get(reverse("order-list"))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Ana")

django.test.TestCase wraps every test in a database transaction that's rolled back at the end — tests don't leak state into each other and don't need to manually clean up rows they created, which is a large part of why Django tests can run fast even with real database reads and writes. self.client is a built-in test client that can simulate GET/POST requests against actual views (including running through the full middleware stack) without needing a real running server.