Bird
Raised Fist0
PyTesttesting~20 mins

Fixture factories in PyTest - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Fixture Factory Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a simple fixture factory
What is the output of this pytest test when run?

Note: The fixture factory creates a user object with a given name.
PyTest
import pytest

@pytest.fixture
def user_factory():
    def create_user(name):
        return {"name": name, "active": True}
    return create_user

def test_user_active(user_factory):
    user = user_factory("Alice")
    assert user["active"]
    print(user["name"])
AKeyError
BTrue
CAlice
DAssertionError
Attempts:
2 left
💡 Hint
Focus on what the fixture factory returns and what the test prints.
❓ assertion
intermediate
2:00remaining
Correct assertion for fixture factory output
Given this fixture factory, which assertion correctly verifies the created user's age is 30?
PyTest
import pytest

@pytest.fixture
def user_factory():
    def create_user(name, age):
        return {"name": name, "age": age}
    return create_user

def test_user_age(user_factory):
    user = user_factory("Bob", 30)
    # Which assertion is correct here?
Aassert user["age"] == 30
Bassert user.age == 30
Cassert user.get("name") == 30
Dassert user["age"] != 30
Attempts:
2 left
💡 Hint
Remember how dictionaries are accessed in Python.
🔧 Debug
advanced
2:00remaining
Identify the error in fixture factory usage
This test fails with a TypeError. What is the cause?

Code:
import pytest @pytest.fixture def user_factory(): def create_user(name, age=25): return {"name": name, "age": age} return create_user def test_user(user_factory): user = user_factory() assert user["age"] == 25
Auser_factory() is called without required positional argument 'name'
BThe fixture factory returns None instead of a function
CThe assertion compares wrong key 'age' instead of 'name'
DThe fixture is missing the @pytest.mark.usefixtures decorator
Attempts:
2 left
💡 Hint
Check the parameters of the inner function and how it is called.
❓ framework
advanced
2:00remaining
Best practice for fixture factory scope
Which scope is most appropriate for a fixture factory that creates fresh test data for each test?
A"class" scope to share data across test methods in a class
B"module" scope to reuse data across tests in a module
C"session" scope to share data across all tests in session
D"function" scope to ensure fresh data per test
Attempts:
2 left
💡 Hint
Think about test isolation and data freshness.
🧠 Conceptual
expert
2:00remaining
Why use fixture factories instead of simple fixtures?
Which reason best explains why fixture factories are preferred over simple fixtures when creating test objects with varying attributes?
AFixture factories reduce the number of test functions needed
BFixture factories allow dynamic creation of objects with different parameters per test
CSimple fixtures run faster and are better for varying test data
DSimple fixtures automatically reset database state between tests
Attempts:
2 left
💡 Hint
Consider flexibility in test data creation.

Practice

(1/5)
1. What is the main purpose of a fixture factory in pytest?
easy
A. To generate random test data without any input
B. To create reusable setup functions that can accept parameters
C. To run tests in parallel automatically
D. To replace the need for assertions in tests

Solution

  1. Step 1: Understand what a fixture factory does

    A fixture factory is a fixture that returns a function, allowing parameter input to create varied setups.
  2. Step 2: Compare options with this definition

    Only To create reusable setup functions that can accept parameters describes creating reusable setup functions that accept parameters, which matches the fixture factory concept.
  3. Final Answer:

    To create reusable setup functions that can accept parameters -> Option B
  4. Quick Check:

    Fixture factory = reusable setup with parameters [OK]
Hint: Fixture factories return functions to customize setup [OK]
Common Mistakes:
  • Thinking fixture factories run tests in parallel
  • Confusing fixture factories with random data generators
  • Believing fixture factories remove the need for assertions
2. Which of the following is the correct syntax to define a fixture factory in pytest?
easy
A. @pytest.fixture def data_factory(): def create_data(value): return {'key': value} return create_data
B. @pytest.fixture def data_factory(value): return {'key': value}
C. def data_factory(): return {'key': 'value'}
D. @pytest.fixture def data_factory(): return {'key': 'value'}

Solution

  1. Step 1: Identify fixture factory structure

    A fixture factory is a fixture that returns a function which accepts parameters.
  2. Step 2: Check each option

    @pytest.fixture def data_factory(): def create_data(value): return {'key': value} return create_data defines a fixture returning a function that takes a parameter, matching fixture factory syntax. Others either lack the inner function or parameter handling.
  3. Final Answer:

    @pytest.fixture\ndef data_factory():\n def create_data(value):\n return {'key': value}\n return create_data -> Option A
  4. Quick Check:

    Fixture factory = fixture returning a function [OK]
Hint: Fixture factory returns a function inside a fixture [OK]
Common Mistakes:
  • Defining fixture with parameters directly (not allowed)
  • Returning data directly without inner function
  • Missing @pytest.fixture decorator
3. Given the following pytest fixture factory and test, what will be the output of the assertion?
@pytest.fixture
def user_factory():
    def create_user(name):
        return {'name': name, 'active': True}
    return create_user

def test_user_active(user_factory):
    user = user_factory('Alice')
    assert user['active'] is True
medium
A. Test passes because 'active' is True
B. Test fails because 'active' key is missing
C. Test fails due to TypeError in fixture
D. Test fails because 'name' is not 'Alice'

Solution

  1. Step 1: Understand fixture factory behavior

    The fixture returns a function that creates a user dict with 'name' and 'active' set to True.
  2. Step 2: Analyze the test

    The test calls user_factory('Alice'), getting {'name': 'Alice', 'active': True}, then asserts user['active'] is True, which is correct.
  3. Final Answer:

    Test passes because 'active' is True -> Option A
  4. Quick Check:

    user['active'] = True, assertion passes [OK]
Hint: Check returned dict keys and values carefully [OK]
Common Mistakes:
  • Assuming 'active' key is missing
  • Confusing fixture factory return with direct dict
  • Thinking 'name' must be 'Bob' instead of 'Alice'
4. Identify the error in the following fixture factory code:
@pytest.fixture
def product_factory():
    def create_product(name, price):
        return {'name': name, 'price': price}
    return create_product

def test_product(product_factory):
    product = product_factory('Book')
    assert product['price'] > 0
medium
A. Incorrect return statement in fixture factory
B. Fixture factory missing @pytest.fixture decorator
C. Missing price argument when calling product_factory in test
D. Assertion compares string to integer

Solution

  1. Step 1: Check fixture factory parameters

    The inner function create_product requires two parameters: name and price.
  2. Step 2: Check test call to fixture factory

    The test calls product_factory('Book') with only one argument, missing price, causing a TypeError.
  3. Final Answer:

    Missing price argument when calling product_factory in test -> Option C
  4. Quick Check:

    Function call missing required argument [OK]
Hint: Match all required parameters when calling fixture factory [OK]
Common Mistakes:
  • Forgetting to pass all parameters to inner function
  • Assuming fixture factory itself takes parameters
  • Ignoring error messages about missing arguments
5. You want to test a function that processes orders with different quantities and prices. How can you use a fixture factory to create varied order data for multiple tests efficiently?
hard
A. Hardcode order data inside each test function
B. Write separate fixtures for each order variation without parameters
C. Use a global variable to store order data and modify it in tests
D. Create a fixture factory that returns a function accepting quantity and price, returning an order dict

Solution

  1. Step 1: Understand the need for varied test data

    Testing different quantities and prices requires flexible data creation without repeating code.
  2. Step 2: Apply fixture factory concept

    A fixture factory returning a function that accepts quantity and price allows creating varied order dicts efficiently.
  3. Final Answer:

    Create a fixture factory that returns a function accepting quantity and price, returning an order dict -> Option D
  4. Quick Check:

    Fixture factory = flexible, reusable test data creator [OK]
Hint: Use fixture factory to pass parameters for varied data [OK]
Common Mistakes:
  • Writing many similar fixtures instead of one factory
  • Using global variables causing test interference
  • Hardcoding data reduces test flexibility and reuse
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