0
0
PyTesttesting~15 mins

pytest-django for Django testing - Build an Automation Script

Choose your learning style9 modes available
Test Django view returns correct status and content
Preconditions (2)
Step 1: Use Django test client to send a GET request to '/'
Step 2: Check that the response status code is 200
Step 3: Check that the response content contains the text 'Welcome to Home Page'
✅ Expected Result: The response status code is 200 and the response content includes 'Welcome to Home Page'
Automation Requirements - pytest with pytest-django plugin
Assertions Needed:
Assert response status code equals 200
Assert response content contains expected text
Best Practices:
Use pytest fixtures for Django test client
Use assert statements for validations
Keep tests isolated and independent
Automated Solution
PyTest
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.

Common Mistakes - 3 Pitfalls
{'mistake': 'Not using the pytest-django client fixture and instead creating a Django test client manually', 'why_bad': "This bypasses pytest-django's integration and can cause setup issues or missing fixtures.", 'correct_approach': "Use the provided 'client' fixture in the test function parameters."}
Forgetting to add @pytest.mark.django_db when the view accesses the database
{'mistake': 'Checking response content as a string instead of bytes', 'why_bad': 'Django response content is bytes, so string checks will fail or cause errors.', 'correct_approach': "Check for bytes in response.content, e.g., b'Welcome to Home Page'."}
Bonus Challenge

Now add data-driven testing to check multiple URLs and expected texts

Show Hint