Bird
Raised Fist0
PyTesttesting~20 mins

pytest-django for Django testing - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
pytest-django Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this pytest-django test?
Consider this Django model and pytest-django test. What will be the test result?
PyTest
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)

import pytest

@pytest.mark.django_db
def test_book_creation():
    book = Book.objects.create(title='Test Driven Development')
    assert Book.objects.count() == 1
    assert book.title == 'Test Driven Development'
ATest fails because assertion count is wrong
BTest fails because database access is not allowed
CTest raises AttributeError due to missing model
DTest passes successfully
Attempts:
2 left
💡 Hint
Remember to use @pytest.mark.django_db to allow database access in tests.
❓ assertion
intermediate
1:30remaining
Which assertion correctly checks the response status code in pytest-django?
You have a Django view that returns HTTP 200. Which assertion correctly verifies this in a pytest-django test?
PyTest
import pytest
from django.urls import reverse

@pytest.mark.django_db
def test_homepage(client):
    url = reverse('home')
    response = client.get(url)
    # Which assertion is correct here?
Aassert response.status_code == 200
Bassert response.code == 200
Cassert response.status == 200
Dassert response.status_code is '200'
Attempts:
2 left
💡 Hint
Check the attribute name for HTTP status code in Django test responses.
🔧 Debug
advanced
2:30remaining
Why does this pytest-django test raise an error?
This test tries to create a Django user but raises an error. Identify the cause.
PyTest
import pytest
from django.contrib.auth.models import User

@pytest.mark.django_db
def test_create_user():
    user = User.objects.create(username='tester')
    assert User.objects.count() == 1
    assert user.username == 'tester'

# Error: django.db.utils.IntegrityError: NOT NULL constraint failed: auth_user.password
ATest fails because User model is not imported
BUser creation fails because password field is required and missing
CTest fails because @pytest.mark.django_db is missing
DUser creation fails because username is not unique
Attempts:
2 left
💡 Hint
Check required fields for Django's User model when creating users.
❓ framework
advanced
1:30remaining
Which pytest-django fixture provides a test client with database access?
You want to test Django views with database access in pytest. Which fixture should you use?
Adjango_client
Bdb_client
Cclient
Dtransactional_db_client
Attempts:
2 left
💡 Hint
pytest-django provides a built-in fixture for HTTP client with DB access.
🧠 Conceptual
expert
2:00remaining
What happens if you omit @pytest.mark.django_db in a test that accesses the database?
In pytest-django, what is the result of running a test that queries the database but does NOT have @pytest.mark.django_db?
ATest raises RuntimeError about database access not allowed
BTest runs successfully but database changes are not saved
CTest silently skips database queries
DTest raises django.core.exceptions.ImproperlyConfigured error
Attempts:
2 left
💡 Hint
pytest-django restricts database access unless explicitly allowed.

Practice

(1/5)
1. What is the main purpose of using @pytest.mark.django_db in pytest-django tests?
easy
A. To skip the test when the database is not available
B. To disable database migrations during the test
C. To mark the test as a slow test
D. To allow the test to access and modify the Django database

Solution

  1. Step 1: Understand the role of @pytest.mark.django_db

    This marker tells pytest that the test needs database access, so pytest sets up the test database properly.
  2. Step 2: Identify what happens without the marker

    Without this marker, tests cannot access or modify the database and will fail if they try.
  3. Final Answer:

    To allow the test to access and modify the Django database -> Option D
  4. Quick Check:

    Database access marker = B [OK]
Hint: Use @pytest.mark.django_db to enable DB access in tests [OK]
Common Mistakes:
  • Thinking it skips tests instead of enabling DB access
  • Confusing it with marking tests as slow
  • Assuming it disables migrations
2. Which of the following is the correct way to use the Django test client fixture in pytest-django?
easy
A. def test_view(client): response = client.get('/'); assert response.status_code == 200
B. def test_view(): response = client.get('/'); assert response.status_code == 200
C. def test_view(client): response = client.post('/'); assert response.status_code = 200
D. def test_view(client): response = client.get('/'); assert response.status == 200

Solution

  1. Step 1: Check the function signature and usage

    The test function must accept the client fixture as a parameter to use it.
  2. Step 2: Verify the assertion syntax

    The assertion must use == to compare response.status_code to 200.
  3. Final Answer:

    def test_view(client): response = client.get('/'); assert response.status_code == 200 -> Option A
  4. Quick Check:

    Correct fixture use and assertion = C [OK]
Hint: Pass client as parameter and use response.status_code == 200 [OK]
Common Mistakes:
  • Not passing client as a parameter
  • Using single = instead of == in assertion
  • Checking response.status instead of response.status_code
3. Given the following test code using pytest-django, what will be the output when running the test?
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)
medium
A. Test fails because count is 0
B. Test passes and prints 2
C. Test raises a database error
D. Test passes but prints 0

Solution

  1. Step 1: Analyze database access and object creation

    The test uses @pytest.mark.django_db, so it can create User objects in the test database.
  2. Step 2: Count the User objects and assert

    Two users are created, so User.objects.count() returns 2, matching the assertion.
  3. Final Answer:

    Test passes and prints 2 -> Option B
  4. Quick Check:

    User count = 2 [OK]
Hint: Mark test with django_db to create and count users correctly [OK]
Common Mistakes:
  • Forgetting @pytest.mark.django_db causes DB errors
  • Assuming count is zero without creation
  • Confusing print output with test result
4. Identify the error in this pytest-django test code and how to fix it:
def test_create_user():
    User.objects.create(username='charlie')
    assert User.objects.count() == 1
medium
A. Test function name should start with 'test_'
B. User model is not imported
C. Missing @pytest.mark.django_db decorator to allow DB access
D. Assertion should check for 0 instead of 1

Solution

  1. Step 1: Check database access requirement

    The test tries to create a User in the database but lacks @pytest.mark.django_db, so DB access is not allowed.
  2. Step 2: Fix by adding the missing decorator

    Adding @pytest.mark.django_db above the test function enables database access and fixes the error.
  3. Final Answer:

    Missing @pytest.mark.django_db decorator to allow DB access -> Option C
  4. Quick Check:

    DB access decorator missing = D [OK]
Hint: Add @pytest.mark.django_db to tests using the database [OK]
Common Mistakes:
  • Not adding the django_db marker
  • Assuming import errors without checking imports
  • Misunderstanding assertion values
5. You want to test a Django view that requires a logged-in user using pytest-django. Which is the best way to simulate a logged-in user in your test?
hard
A. Use the client.force_login(user) method after creating a user in the test database
B. Set a session variable manually without creating a user
C. Call the view function directly without using the client fixture
D. Use @pytest.mark.django_db without logging in the user

Solution

  1. Step 1: Understand how to simulate login in pytest-django

    The client.force_login(user) method logs in the user for the test client session.
  2. Step 2: Create a user in the test database first

    You must create a user in the test database (with @pytest.mark.django_db) before calling force_login.
  3. Final Answer:

    Use the client.force_login(user) method after creating a user in the test database -> Option A
  4. Quick Check:

    Use force_login with created user = A [OK]
Hint: Create user and call client.force_login(user) to simulate login [OK]
Common Mistakes:
  • Trying to set session manually without user
  • Calling views directly without client
  • Forgetting to create user before login
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard