Wednesday, November 12, 2025

thumbnail

Writing Unit Tests for Django Projects

 🧠 What Are Unit Tests in Django?


In Django, unit tests are Python scripts that check small parts of your web application — such as models, views, forms, or utility functions — to make sure they work correctly.


Django includes a powerful testing framework built on top of Python’s built-in unittest module.


⚙️ Setting Up Testing in a Django Project


Django automatically supports testing out of the box.

When you create a new Django project, the testing tools are ready to use — you just need to write your tests.


Your project structure might look like this:


myproject/

├── manage.py

├── myapp/

│   ├── models.py

│   ├── views.py

│   ├── tests.py

│   └── ...

└── myproject/

    ├── settings.py

    ├── urls.py

    └── ...



You can put tests in:


tests.py (a single file), or


A tests/ package (recommended for larger apps).


Example:


myapp/

└── tests/

    ├── __init__.py

    ├── test_models.py

    ├── test_views.py

    └── test_forms.py


🧩 1. Writing a Simple Model Test

Example model (models.py)

from django.db import models


class Product(models.Model):

    name = models.CharField(max_length=100)

    price = models.DecimalField(max_digits=8, decimal_places=2)


    def discount_price(self, percentage):

        return self.price * (1 - percentage / 100)


Corresponding test (tests/test_models.py)

from django.test import TestCase

from myapp.models import Product

from decimal import Decimal


class ProductModelTest(TestCase):


    def test_discount_price(self):

        product = Product(name="Book", price=Decimal('100.00'))

        discounted = product.discount_price(10)

        self.assertEqual(discounted, Decimal('90.00'))


Run the test:

python manage.py test



✅ Output:


.

----------------------------------------------------------------------

Ran 1 test in 0.001s


OK


🧩 2. Testing Django Views

Example view (views.py)

from django.http import HttpResponse


def hello_world(request):

    return HttpResponse("Hello, world!")


Test the view (tests/test_views.py)

from django.test import TestCase

from django.urls import reverse


class HelloWorldViewTest(TestCase):


    def test_hello_world_view(self):

        response = self.client.get(reverse('hello_world'))

        self.assertEqual(response.status_code, 200)

        self.assertContains(response, "Hello, world!")



🧠 self.client is Django’s built-in test client — it lets you simulate browser requests without running a real server.


🧩 3. Testing Models with the Database


Django automatically sets up a temporary test database for you.

Each test runs in isolation, so your real data is never affected.


Example:


from django.test import TestCase

from myapp.models import Product


class ProductDatabaseTest(TestCase):


    def test_product_creation(self):

        Product.objects.create(name="Laptop", price=999.99)

        self.assertEqual(Product.objects.count(), 1)


🧩 4. Testing Forms and Validation

Example form (forms.py)

from django import forms


class ContactForm(forms.Form):

    name = forms.CharField(max_length=50)

    email = forms.EmailField()


Test (tests/test_forms.py)

from django.test import TestCase

from myapp.forms import ContactForm


class ContactFormTest(TestCase):


    def test_valid_data(self):

        form = ContactForm({'name': 'Alice', 'email': 'alice@example.com'})

        self.assertTrue(form.is_valid())


    def test_invalid_email(self):

        form = ContactForm({'name': 'Alice', 'email': 'not-an-email'})

        self.assertFalse(form.is_valid())


🧩 5. Testing APIs or JSON Responses


If you use Django REST Framework or JSON responses, you can still use Django’s test client.


Example:


from django.test import TestCase

from django.urls import reverse


class APITest(TestCase):


    def test_get_json_response(self):

        response = self.client.get(reverse('api-endpoint'))

        self.assertEqual(response.status_code, 200)

        self.assertJSONEqual(

            str(response.content, encoding='utf8'),

            {'message': 'success'}

        )


⚙️ Running Tests


You can run all tests in your Django project with:


python manage.py test



Run tests for a specific app:


python manage.py test myapp



Run tests from a specific file:


python manage.py test myapp.tests.test_models


🧭 Best Practices for Django Unit Tests

Best Practice Why It Matters

✅ Use descriptive test names Makes failures easier to understand

✅ Keep tests independent One test should not rely on another

✅ Use setUp() for reusable setup Simplifies repeated test code

✅ Test both valid and invalid cases Ensures robust behavior

✅ Run tests automatically (CI/CD) Catches regressions early


Example setup method:


class ProductTest(TestCase):


    def setUp(self):

        self.product = Product.objects.create(name="Phone", price=500)


🚀 Summary

Concept Description

Framework Django’s built-in unittest-based system

Test Types Models, Views, Forms, URLs, APIs

Command python manage.py test

Database Temporary test database for isolation

Goal Catch bugs early and ensure reliable behavior

Learn Fullstack Python Training in Hyderabad

Read More

Introduction to Unit Testing in Python

Testing and Debugging in Python

How to Test Your API Endpoints in Python

Building Versioned APIs in Python

At Our Quality Thought Training Institute in Hyderabad

Get Directions

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive