Test Overview
This test uses pytest-django to check if the Django homepage loads correctly and contains the expected welcome message.
This test uses pytest-django to check if the Django homepage loads correctly and contains the expected welcome message.
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 to Django' in response.content
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | pytest-django test runner initialized with Django settings | — | PASS |
| 2 | Django test client fixture 'client' is provided | Test client ready to send HTTP requests to Django app | — | PASS |
| 3 | Reverse URL lookup for 'home' view | URL '/' resolved for homepage | — | PASS |
| 4 | Client sends GET request to homepage URL | Django processes request and returns HTTP response | — | PASS |
| 5 | Check response status code is 200 | Response status code is 200 OK | assert response.status_code == 200 | PASS |
| 6 | Check response content contains 'Welcome to Django' | Response body includes welcome message bytes | assert b'Welcome to Django' in response.content | PASS |
| 7 | Test ends successfully | All assertions passed, test complete | — | PASS |
@pytest.mark.django_db in pytest-django tests?@pytest.mark.django_dbclient fixture as a parameter to use it.== to compare response.status_code to 200.import pytest
from django.contrib.auth.models import User
@pytest.mark.django_db
def test_user_count():
User.objects.create(username='alice')
User.objects.create(username='bob')
count = User.objects.count()
assert count == 2
print(count)@pytest.mark.django_db, so it can create User objects in the test database.User.objects.count() returns 2, matching the assertion.def test_create_user():
User.objects.create(username='charlie')
assert User.objects.count() == 1@pytest.mark.django_db, so DB access is not allowed.@pytest.mark.django_db above the test function enables database access and fixes the error.client.force_login(user) method logs in the user for the test client session.@pytest.mark.django_db) before calling force_login.Pass the test and this pattern moves unknown