D. @pytest.fixture
def user_factory():
return {'name': 'default'}
Solution
Step 1: Identify factory fixture structure
A factory fixture returns a function that accepts parameters to create test data dynamically.
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.
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
Step 1: Check the factory function parameters
The factory function create_item expects two arguments: name and price.
Step 2: Analyze the test call
The test calls item_factory('Book') with only one argument, missing price, causing an error or wrong data.
Final Answer:
The factory function is missing the 'price' argument; fix by passing price when calling. -> Option D
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?
Step 1: Understand factory fixture with optional/default parameters
The factory fixture should return a function that accepts parameters with defaults for optional values.
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.