Bird
Raised Fist0
PyTesttesting~10 mins

@pytest.fixture decorator - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a fixture using pytest.

PyTest
import pytest

@pytest.[1]()
def sample_data():
    return [1, 2, 3]
Drag options to blanks, or click blank then click option'
Atest
Bfixture
Csetup
Dparametrize
Attempts:
3 left
💡 Hint
Common Mistakes
Using @pytest.test instead of @pytest.fixture
Forgetting the parentheses after the decorator
Confusing fixture with parametrize
2fill in blank
medium

Complete the test function to use the fixture named 'sample_data'.

PyTest
def test_sum([1]):
    assert sum(sample_data) == 6
Drag options to blanks, or click blank then click option'
Afixture
Bdata
Csample_data
Dinput_data
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different parameter name than the fixture
Not including the fixture as a parameter
Trying to call the fixture inside the test instead of using it as a parameter
3fill in blank
hard

Fix the error in the fixture definition by completing the decorator correctly.

PyTest
import pytest

@[1]
def config():
    return {'url': 'http://example.com'}
Drag options to blanks, or click blank then click option'
Apytest.setup
Bpytest.fixture
Cpytest.test
Dpytest.fixture()
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting parentheses in the decorator
Using '@pytest.test' instead of '@pytest.fixture()'
Using '@pytest.setup' which is not a valid decorator
4fill in blank
hard

Fill both blanks to create a fixture that runs once per module and a test that uses it.

PyTest
import pytest

@pytest.fixture(scope=[1])
def resource():
    return 'db_connection'

def test_resource([2]):
    assert resource == 'db_connection'
Drag options to blanks, or click blank then click option'
A'module'
Bresource
C'function'
Dconn
Attempts:
3 left
💡 Hint
Common Mistakes
Using scope 'function' which runs before every test
Using a different parameter name than the fixture
Forgetting quotes around the scope value
5fill in blank
hard

Fill all three blanks to create a fixture with autouse enabled and a test that uses it implicitly.

PyTest
import pytest

@pytest.fixture(autouse=[1])
def setup_env():
    print('Setup environment')


def test_example():
    assert True  # setup_env is used [2] without being [3] as a parameter
Drag options to blanks, or click blank then click option'
ATrue
Bimplicitly
Cpassed
DFalse
Attempts:
3 left
💡 Hint
Common Mistakes
Setting autouse to False so fixture does not run automatically
Thinking the fixture must be passed as a parameter when autouse=True
Misunderstanding implicit usage of fixtures

Practice

(1/5)
1. What is the main purpose of the @pytest.fixture decorator in pytest?
easy
A. To define a test case with parameters
B. To mark a test as expected to fail
C. To create reusable setup code that can be shared across multiple tests
D. To skip a test during execution

Solution

  1. Step 1: Understand what @pytest.fixture does

    The @pytest.fixture decorator is used to create setup code that can be reused in many tests to avoid repetition.
  2. Step 2: Compare options with the fixture purpose

    Options A, B, and C describe other pytest features, not fixtures.
  3. Final Answer:

    To create reusable setup code that can be shared across multiple tests -> Option C
  4. Quick Check:

    Fixture = reusable setup code [OK]
Hint: Fixtures provide shared setup for tests to avoid repetition [OK]
Common Mistakes:
  • Confusing fixtures with test skipping or marking
  • Thinking fixtures run tests themselves
  • Believing fixtures are only for cleanup
2. Which of the following is the correct syntax to define a fixture named db_connection in pytest?
easy
A. def db_connection(): pass
B. @pytest.fixture def db_connection(): pass
C. @fixture def db_connection(): pass
D. @pytest.test def db_connection(): pass

Solution

  1. Step 1: Identify correct decorator usage

    The correct decorator for fixtures is @pytest.fixture, fully qualified with the pytest module.
  2. Step 2: Check each option

    @pytest.fixture def db_connection(): pass uses @pytest.fixture correctly. def db_connection(): pass misses the decorator. @fixture def db_connection(): pass uses @fixture without importing. @pytest.test def db_connection(): pass uses @pytest.test which is invalid.
  3. Final Answer:

    @pytest.fixture def db_connection(): pass -> Option B
  4. Quick Check:

    Use @pytest.fixture before function [OK]
Hint: Always prefix fixture with @pytest.fixture decorator [OK]
Common Mistakes:
  • Omitting the @pytest.fixture decorator
  • Using @fixture without importing pytest
  • Confusing @pytest.test with fixture decorator
3. Given the following pytest code, what will be the output when running the test?
import pytest

@pytest.fixture
def sample_data():
    return [1, 2, 3]

def test_sum(sample_data):
    assert sum(sample_data) == 6
    print('Test passed')
medium
A. No output printed, test passes silently
B. Test fails with assertion error
C. SyntaxError due to fixture usage
D. Test passed printed and test passes

Solution

  1. Step 1: Understand fixture usage

    The fixture sample_data returns a list [1, 2, 3]. The test receives this list as argument.
  2. Step 2: Check assertion and print

    The sum of [1, 2, 3] is 6, so the assertion passes. The print statement runs and outputs 'Test passed'.
  3. Final Answer:

    Test passed printed and test passes -> Option D
  4. Quick Check:

    Fixture provides data, assertion true, print runs [OK]
Hint: Fixture returns data; test uses it and prints on success [OK]
Common Mistakes:
  • Assuming fixture causes syntax error
  • Thinking print won't show during test run
  • Believing assertion fails with correct sum
4. Identify the error in this fixture code and how to fix it:
import pytest

@pytest.fixture
def resource():
    setup = open('file.txt')
    yield setup
    setup.close()
medium
A. File 'file.txt' may not exist causing runtime error
B. No error; code is correct
C. Missing parentheses in yield statement
D. Fixture must return value, not yield

Solution

  1. Step 1: Analyze fixture code

    The fixture opens a file and yields the file object, then closes it after test.
  2. Step 2: Identify potential runtime issue

    If 'file.txt' does not exist, open() will raise an error before yield. This is a runtime error, not syntax.
  3. Final Answer:

    File 'file.txt' may not exist causing runtime error -> Option A
  4. Quick Check:

    File open can fail if file missing [OK]
Hint: Check external resources exist before opening in fixture [OK]
Common Mistakes:
  • Thinking yield needs parentheses
  • Believing fixtures cannot use yield
  • Ignoring file existence errors
5. How can you modify this fixture to ensure cleanup code runs after the test, even if the test fails?
import pytest

@pytest.fixture
def temp_file():
    f = open('temp.txt', 'w')
    yield f
    f.close()
hard
A. Use try-finally inside the fixture around yield
B. Replace yield with return
C. Remove yield and close file before returning
D. Add a separate test to close the file

Solution

  1. Step 1: Understand fixture cleanup with yield

    Using yield in fixtures allows code after yield to run as cleanup after the test finishes.
  2. Step 2: Ensure cleanup runs even if test fails

    Wrapping yield with try-finally ensures the cleanup code (file close) runs no matter what happens in the test.
  3. Final Answer:

    Use try-finally inside the fixture around yield -> Option A
  4. Quick Check:

    try-finally ensures cleanup after yield [OK]
Hint: Wrap yield with try-finally to guarantee cleanup [OK]
Common Mistakes:
  • Replacing yield with return loses cleanup
  • Closing file before yield stops test using it
  • Adding separate test for cleanup is incorrect
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