0
0
PyTesttesting~5 mins

pytest-django for Django testing

Choose your learning style9 modes available
Introduction

pytest-django helps you test Django apps easily. It makes writing and running tests simple and fast.

You want to check if your Django views return the right pages.
You need to test your Django models and database queries.
You want to verify that your forms work correctly.
You want to run tests with a real Django environment setup.
You want to use pytest features like fixtures and assertions in Django.
Syntax
PyTest
import pytest
from django.urls import reverse

@pytest.mark.django_db
def test_view(client):
    url = reverse('home')
    response = client.get(url)
    assert response.status_code == 200

Use @pytest.mark.django_db to allow database access in tests.

The client fixture simulates a web browser for requests.

Examples
Test that the database starts empty for the Item model.
PyTest
import pytest

@pytest.mark.django_db
def test_model_count():
    from myapp.models import Item
    count = Item.objects.count()
    assert count == 0
Test the home page loads and contains the word 'Welcome'.
PyTest
import pytest
from django.urls import reverse

@pytest.mark.django_db
def test_homepage(client):
    url = reverse('home')
    response = client.get(url)
    assert response.status_code == 200
    assert b"Welcome" in response.content
Sample Program

This test checks that the 'about' page loads successfully and contains the text 'About Us'.

PyTest
import pytest
from django.urls import reverse

@pytest.mark.django_db
def test_about_page(client):
    url = reverse('about')
    response = client.get(url)
    assert response.status_code == 200
    assert b"About Us" in response.content
OutputSuccess
Important Notes

Always add @pytest.mark.django_db when your test uses the database.

Use Django's reverse() to get URLs by name, so tests stay clear and stable.

The client fixture is like a fake browser to test your views.

Summary

pytest-django makes testing Django apps easier by combining pytest with Django features.

Use @pytest.mark.django_db to access the database in tests.

The client fixture helps simulate user requests to your Django app.