Bird
0
0

Examine the following pytest fixture code:

medium📝 Debug Q6 of 15
PyTest - Fixtures
Examine the following pytest fixture code:
import pytest

def sample_fixture(request):
    def cleanup():
        print('Cleaning up')
    cleanup()
    request.addfinalizer(cleanup)
    return 42

What is the main issue with this fixture?
Arequest.addfinalizer is called after the cleanup function
BThe fixture returns a non-callable value
CThe cleanup function is called immediately instead of being deferred
DThe fixture is missing the @pytest.fixture decorator
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the cleanup call

    The line cleanup() calls the cleanup function immediately during fixture setup.
  2. Step 2: Understand addfinalizer purpose

    request.addfinalizer(cleanup) registers the cleanup function to run after the test finishes.
  3. Step 3: Identify the problem

    Calling cleanup() immediately defeats the purpose of finalization; cleanup should only run after the test.
  4. Final Answer:

    The cleanup function is called immediately instead of being deferred -> Option C
  5. Quick Check:

    Ensure cleanup is registered, not called upfront [OK]
Quick Trick: Do not call cleanup; just register it with addfinalizer [OK]
Common Mistakes:
MISTAKES
  • Calling the cleanup function inside the fixture instead of registering it
  • Forgetting to decorate the fixture with @pytest.fixture (not the main issue here)
  • Returning a non-callable value (allowed in fixtures)

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes