How to Test Django with pytest: Simple Guide
To test Django with
pytest, install pytest-django plugin and write test functions or classes using Django's test client or ORM. Run tests with the pytest command, which discovers and executes Django tests seamlessly.Syntax
Use pytest with the pytest-django plugin to test Django apps. Write test functions starting with test_ or test classes inheriting from django.test.TestCase. Use Django's client fixture to simulate HTTP requests.
Example parts:
def test_example(client):- test function with Django test clientresponse = client.get('/url/')- simulate GET requestassert response.status_code == 200- check response status
python
def test_homepage(client): response = client.get('/') assert response.status_code == 200
Example
This example shows a simple Django view test using pytest and pytest-django. It tests that the homepage returns HTTP 200 OK.
python
import pytest @pytest.mark.django_db def test_homepage(client): response = client.get('/') assert response.status_code == 200
Output
============================= test session starts =============================
collected 1 item
test_example.py . [100%]
============================== 1 passed in 0.05s ==============================
Common Pitfalls
Common mistakes when testing Django with pytest include:
- Not installing or configuring
pytest-django, so Django settings are missing. - Forgetting to add
@pytest.mark.django_dbwhen accessing the database. - Using Django's
TestCasewithout pytest fixtures, which can cause confusion. - Writing tests that depend on external services without mocking.
Correct usage example:
python
import pytest @pytest.mark.django_db def test_model_creation(): from myapp.models import Item item = Item.objects.create(name='Test') assert item.name == 'Test'
Quick Reference
| Command or Decorator | Purpose |
|---|---|
| pytest | Run all tests in the project |
| pytest-django | Plugin to integrate pytest with Django |
| @pytest.mark.django_db | Mark test to access the database |
| client fixture | Simulate HTTP requests in tests |
| assert | Check expected outcomes in tests |
Key Takeaways
Install and configure pytest-django to enable Django testing with pytest.
Use the client fixture to simulate web requests in your tests.
Mark tests that access the database with @pytest.mark.django_db.
Write simple test functions starting with test_ for pytest to discover.
Avoid missing Django settings or database access errors by proper setup.