Consider this Django test code snippet using Client to test a view that returns JSON data:
from django.test import Client
client = Client()
response = client.get('/api/data/')
print(response.status_code)
print(response.json())The view at /api/data/ returns {"name": "Alice", "age": 30} with status 200.
What will be printed?
from django.test import Client client = Client() response = client.get('/api/data/') print(response.status_code) print(response.json())
Check the status code and the JSON content returned by the view.
The view returns status 200 and a JSON object. The response.json() method parses the JSON string into a Python dictionary.
You want to send JSON data {"username": "bob", "password": "123"} to the /login/ endpoint using Django's test Client. Which code snippet is correct?
Remember to set the content type to application/json and send data as a JSON string.
Option A sends a JSON string with the correct content type. Option A sends form data, C uses an invalid argument, and A sends form-encoded data but claims JSON content type.
Given this test code:
response = client.get('/profile/', data={'user': 'alice'})
print(response.status_code)The view expects the username as a URL parameter, not a query string. The test fails with a 404 error. Why?
response = client.get('/profile/', data={'user': 'alice'}) print(response.status_code)
Think about how URL parameters and query strings differ.
The view expects the username as part of the URL path (e.g., /profile/alice/), but the test sends it as a query string (?user=alice), so the URL does not match any route, causing 404.
Assume the view at /dashboard/ requires login and sets user in context. The test logs in a user 'jane' and requests the dashboard:
client.login(username='jane', password='pass123')
response = client.get('/dashboard/')
print(response.context['user'].username)What will be printed?
client.login(username='jane', password='pass123') response = client.get('/dashboard/') print(response.context['user'].username)
Think about what client.login does and how context is set in views.
After successful login, the user in context is the logged-in user object with username 'jane'.
When using Django's test Client, each test method starts with a fresh session. Why is this behavior important?
Think about test reliability and isolation.
Resetting sessions ensures each test runs independently without leftover data from previous tests, making tests reliable and repeatable.