Bird
Raised Fist0
PyTesttesting~20 mins

Factory fixtures in PyTest - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Factory Fixture Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a pytest factory fixture with parameter
What is the output of this pytest test when run?

Consider the factory fixture creates a dictionary with a key 'value' set to the parameter.
PyTest
import pytest

@pytest.fixture
@pytest.mark.parametrize('data_factory', [10], indirect=True)
def data_factory(request):
    return {"value": request.param}

def test_value(data_factory):
    assert data_factory["value"] == 10
    print(f"Value is {data_factory['value']}")
AValue is '10'
BAssertionError
CValue is 10
DTypeError
Attempts:
2 left
💡 Hint
Look at how the parameter is passed and used inside the fixture.
assertion
intermediate
1:30remaining
Correct assertion for a factory fixture output
Given a factory fixture that returns a list of user names, which assertion correctly verifies the list contains exactly 3 users?
PyTest
import pytest

@pytest.fixture
def user_factory():
    return ["alice", "bob", "carol"]

def test_users(user_factory):
    # Which assertion is correct here?
Aassert len(user_factory) == 3
Bassert user_factory.count == 3
Cassert user_factory.size() == 3
Dassert user_factory.length == 3
Attempts:
2 left
💡 Hint
Remember how to get the length of a list in Python.
🔧 Debug
advanced
2:00remaining
Identify the error in this factory fixture usage
What error will this pytest code raise when running the test?
PyTest
import pytest

@pytest.fixture
def number_factory():
    return 5

def test_number(number_factory):
    assert number_factory == 5

@pytest.mark.parametrize('number_factory', [10], indirect=True)
def test_number_param(number_factory):
    assert number_factory == 10
ANo error, tests pass
BTypeError
CValueError
DFixtureLookupError
Attempts:
2 left
💡 Hint
Check how the fixture is used with and without parameters.
🧠 Conceptual
advanced
1:30remaining
Purpose of factory fixtures in pytest
What is the main advantage of using factory fixtures in pytest?
ATo automatically generate test reports in different formats
BTo create reusable test data or objects dynamically for multiple tests
CTo replace the need for test parametrization entirely
DTo speed up test execution by caching results automatically
Attempts:
2 left
💡 Hint
Think about why you might want to generate data or objects fresh for each test.
framework
expert
2:30remaining
Best practice for factory fixture scope and cleanup
Which pytest fixture scope and cleanup method is best for a factory fixture that creates temporary files needed only during each test?
AUse function scope and yield the resource, then cleanup after yield
BUse session scope and cleanup in a finalizer registered with addfinalizer
CUse module scope and cleanup manually inside the test function
DUse class scope and rely on garbage collection for cleanup
Attempts:
2 left
💡 Hint
Consider how long the resource is needed and how pytest manages fixture cleanup.

Practice

(1/5)
1. What is the main purpose of a factory fixture in pytest?
easy
A. To run tests in parallel automatically
B. To create reusable test data with flexible parameters
C. To generate test reports in HTML format
D. To mock external API calls during tests

Solution

  1. Step 1: Understand what factory fixtures do

    Factory fixtures return a function that can create test data with different parameters as needed.
  2. Step 2: Compare with other options

    Running tests in parallel, generating reports, or mocking APIs are different pytest features, not factory fixtures.
  3. Final Answer:

    To create reusable test data with flexible parameters -> Option B
  4. Quick Check:

    Factory fixture = reusable flexible test data creator [OK]
Hint: Factory fixtures build test data functions fast [OK]
Common Mistakes:
  • Confusing factory fixtures with mocking
  • Thinking factory fixtures run tests
  • Assuming factory fixtures generate reports
2. Which of the following is the correct way to define a simple factory fixture in pytest?
easy
A. @pytest.fixture def user_factory(name): return {'name': name}
B. def user_factory(): return {'name': 'default'}
C. @pytest.fixture def user_factory(): def create_user(name): return {'name': name} return create_user
D. @pytest.fixture def user_factory(): return {'name': 'default'}

Solution

  1. Step 1: Identify factory fixture structure

    A factory fixture returns a function that accepts parameters to create test data dynamically.
  2. Step 2: Check each option

    @pytest.fixture def user_factory(): def create_user(name): return {'name': name} return create_user defines a fixture returning a function that takes a name and returns a dict, which is correct. Options A, C, and D do not return a function, so they are not factory fixtures.
  3. Final Answer:

    @pytest.fixture def user_factory(): def create_user(name): return {'name': name} return create_user -> Option C
  4. Quick Check:

    Factory fixture = fixture returning a function [OK]
Hint: Factory fixtures return a function inside the fixture [OK]
Common Mistakes:
  • Returning data directly instead of a function
  • Missing @pytest.fixture decorator
  • Defining fixture with parameters directly
3. Given the following pytest code, what will be the output of the test?
@pytest.fixture
def number_factory():
    def create_number(x):
        return x * 2
    return create_number

def test_double(number_factory):
    result = number_factory(5)
    assert result == 10
    print(result)
medium
A. Test passes and prints 10
B. Test fails with AssertionError
C. SyntaxError due to fixture usage
D. Test passes but prints 5

Solution

  1. Step 1: Understand the factory fixture behavior

    The fixture returns a function that doubles the input number.
  2. Step 2: Analyze the test function

    The test calls number_factory(5), which returns 5 * 2 = 10, then asserts result == 10, which is true, so test passes and prints 10.
  3. Final Answer:

    Test passes and prints 10 -> Option A
  4. Quick Check:

    5 * 2 = 10, assertion true [OK]
Hint: Factory fixture returns function; call it with argument [OK]
Common Mistakes:
  • Thinking fixture itself is called with argument
  • Expecting print output to fail test
  • Confusing assertion logic
4. Identify the error in this factory fixture code and how to fix it:
@pytest.fixture
def item_factory():
    def create_item(name, price):
        return {'name': name, 'price': price}
    return create_item

def test_item(item_factory):
    item = item_factory('Book')
    assert item['price'] == 10
medium
A. The fixture is missing @pytest.mark.parametrize decorator; add it.
B. The fixture should not return a function; fix by returning a dict directly.
C. The test should not use the fixture as a function; fix by removing parentheses.
D. The factory function is missing the 'price' argument; fix by passing price when calling.

Solution

  1. Step 1: Check the factory function parameters

    The factory function create_item expects two arguments: name and price.
  2. Step 2: Analyze the test call

    The test calls item_factory('Book') with only one argument, missing price, causing an error or wrong data.
  3. Final Answer:

    The factory function is missing the 'price' argument; fix by passing price when calling. -> Option D
  4. Quick Check:

    Factory args must match call args [OK]
Hint: Match factory function parameters with call arguments [OK]
Common Mistakes:
  • Calling factory with fewer arguments than defined
  • Returning dict directly instead of function
  • Misusing fixture as a simple variable
5. You want to create a factory fixture that builds user dictionaries with optional age and default country='USA'. Which of the following implementations correctly achieves this?
hard
A. @pytest.fixture def user_factory(): def create_user(name, age=None, country='USA'): return {'name': name, 'age': age, 'country': country} return create_user
B. @pytest.fixture def user_factory(name, age=None, country='USA'): return {'name': name, 'age': age, 'country': country}
C. @pytest.fixture def user_factory(): return {'name': 'default', 'age': None, 'country': 'USA'}
D. @pytest.fixture def user_factory(): def create_user(name, age, country): return {'name': name, 'age': age, 'country': country} return create_user

Solution

  1. Step 1: Understand factory fixture with optional/default parameters

    The factory fixture should return a function that accepts parameters with defaults for optional values.
  2. Step 2: Evaluate each option

    @pytest.fixture def user_factory(): def create_user(name, age=None, country='USA'): return {'name': name, 'age': age, 'country': country} return create_user correctly defines a fixture returning a function with default age=None and country='USA'. @pytest.fixture def user_factory(name, age=None, country='USA'): return {'name': name, 'age': age, 'country': country} is not a factory fixture because it takes parameters directly. @pytest.fixture def user_factory(): return {'name': 'default', 'age': None, 'country': 'USA'} returns a fixed dict, not a factory. @pytest.fixture def user_factory(): def create_user(name, age, country): return {'name': name, 'age': age, 'country': country} return create_user requires all parameters without defaults, so age and country are not optional.
  3. Final Answer:

    @pytest.fixture def user_factory(): def create_user(name, age=None, country='USA'): return {'name': name, 'age': age, 'country': country} return create_user -> Option A
  4. Quick Check:

    Factory fixture returns function with defaults [OK]
Hint: Factory fixture returns function with default parameters [OK]
Common Mistakes:
  • Defining fixture with parameters directly
  • Not providing default values for optional args
  • Returning fixed data instead of a function