Test Django view returns correct status and content
Preconditions (2)
✅ Expected Result: The response status code is 200 and the response content includes 'Welcome to Home Page'
import pytest @pytest.mark.django_db def test_home_view(client): response = client.get('/') assert response.status_code == 200 assert b'Welcome to Home Page' in response.content
The test uses the client fixture provided by pytest-django to simulate a browser request to the home page URL '/'.
The @pytest.mark.django_db decorator allows database access if needed by the view.
Assertions check that the HTTP status code is 200 (OK) and that the response content includes the expected welcome text in bytes format.
This test is simple, clear, and uses pytest best practices for Django testing.
Now add data-driven testing to check multiple URLs and expected texts
@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