Django’s built-in testing framework is based on Python’s unittest
module, but additional tools and libraries can enhance test coverage, performance, and maintainability.
unittest
– The Default Testing LibraryDjango tests inherit from Python’s standard unittest
module.
import unittest
class SimpleTestCase(unittest.TestCase):
def test_addition(self):
self.assertEqual(1 + 1, 2)
def test_subtraction(self):
self.assertNotEqual(5 - 2, 10)
Run it using:
python -m unittest
pytest
– A Powerful Alternative to unittest
Why use pytest
?
unittest.TestCase
classes).pytest
pip install pytest pytest-django
pytest
for DjangoCreate a pytest.ini
file:
[pytest]
DJANGO_SETTINGS_MODULE = myproject.settings
pytest
Testimport pytest
from myapp.models import Product
@pytest.mark.django_db
def test_product_creation():
product = Product.objects.create(name="Speaker", price=150)
assert product.name == "Speaker"
assert product.price == 150
pytest
pytest
For detailed output:
pytest -v
Run a specific test:
pytest tests/test_models.py::test_product_creation
factory_boy
– Generating Test DataInstead of manually creating test objects, factory_boy
automates the process.
factory_boy
pip install factory_boy
import factory
from myapp.models import Product
class ProductFactory(factory.django.DjangoModelFactory):
class Meta:
model = Product
name = factory.Faker("word")
price = factory.Faker("random_int", min=10, max=1000)
def test_product_factory(db):
product = ProductFactory()
assert product.name is not None
assert product.price > 0
faker
– Generating Fake DataThe faker
library is useful for generating random test data.
faker
pip install faker
faker
in Testsfrom faker import Faker
faker = Faker()
def test_fake_data():
name = faker.name()
email = faker.email()
assert "@" in email
mock
– Mocking External ServicesFor tests that interact with APIs or external services, mock
helps simulate responses.
from unittest.mock import patch
def get_data():
return "real data"
@patch("__main__.get_data", return_value="mocked data")
def test_mock_function(mock_get_data):
assert get_data() == "mocked data"
import requests
from unittest.mock import patch
def fetch_data():
response = requests.get("https://api.example.com/data")
return response.json()
@patch("requests.get")
def test_mock_api(mock_get):
mock_get.return_value.json.return_value = {"message": "Hello"}
assert fetch_data() == {"message": "Hello"}
responses
– Mocking HTTP RequestsThe responses
library is useful for testing Django apps that make external API calls.
responses
pip install responses
import responses
import requests
@responses.activate
def test_api_call():
responses.add(responses.GET, "https://api.example.com/user", json={"id": 1, "name": "John"}, status=200)
response = requests.get("https://api.example.com/user")
assert response.json() == {"id": 1, "name": "John"}
django-debug-toolbar
– Debugging Django AppsFor debugging SQL queries and request processing, django-debug-toolbar
is helpful.
pip install django-debug-toolbar
settings.py
INSTALLED_APPS += ["debug_toolbar"]
MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"]
from django.conf import settings
from django.conf.urls import include
from django.urls import path
if settings.DEBUG:
urlpatterns += [path("__debug__/", include("debug_toolbar.urls"))]
selenium
– Testing Django with a Real BrowserFor testing user interactions in Django applications, selenium
provides browser automation.
selenium
pip install selenium
from selenium import webdriver
def test_google_search():
driver = webdriver.Chrome()
driver.get("https://www.google.com")
assert "Google" in driver.title
driver.quit()
Ensure you have Google Chrome and Chromedriver installed, then run:
pytest test_selenium.py
For comprehensive testing, combine multiple tools:
pytest
for test execution.factory_boy
to generate test data.mock
and responses
for API calls.selenium
for UI testing.coverage
to check test coverage.