0
0
PyTesttesting~10 mins

Fixture teardown (yield) in PyTest - Interactive Code Practice

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

Complete the code to create a pytest fixture that uses yield for setup and teardown.

PyTest
import pytest

@pytest.fixture
def resource():
    print("Setup resource")
    [1]
    print("Teardown resource")
Drag options to blanks, or click blank then click option'
Acontinue
Byield
Cbreak
Dreturn
Attempts:
3 left
💡 Hint
Common Mistakes
Using return instead of yield causes teardown code to never run.
Using break or continue are invalid in this context.
2fill in blank
medium

Complete the fixture to yield a value that tests can use.

PyTest
import pytest

@pytest.fixture
def data():
    setup_data = {'key': 'value'}
    [1] setup_data
    print("Cleanup after test")
Drag options to blanks, or click blank then click option'
Araise
Breturn
Cyield
Dprint
Attempts:
3 left
💡 Hint
Common Mistakes
Using return ends the fixture immediately, skipping teardown.
Using print or raise does not provide the data correctly.
3fill in blank
hard

Fix the error in the fixture to ensure teardown runs after the test.

PyTest
import pytest

@pytest.fixture
def connection():
    print("Open connection")
    [1] 'conn'
    print("Close connection")
Drag options to blanks, or click blank then click option'
Ayield
Breturn
Cbreak
Dcontinue
Attempts:
3 left
💡 Hint
Common Mistakes
Using return causes teardown code to never execute.
Using break or continue is invalid syntax here.
4fill in blank
hard

Fill both blanks to create a fixture that yields a resource and prints messages before and after the test.

PyTest
import pytest

@pytest.fixture
def file_resource():
    print("Opening file")
    [1] 'file'
    print([2])
Drag options to blanks, or click blank then click option'
Ayield
B"File closed"
C"File opened"
Dreturn
Attempts:
3 left
💡 Hint
Common Mistakes
Using return instead of yield skips teardown.
Printing "File opened" after yield is incorrect.
5fill in blank
hard

Fill all three blanks to create a fixture that sets up, yields a value, and cleans up with a print message.

PyTest
import pytest

@pytest.fixture
def setup_teardown():
    print([1])
    [2] 42
    print([3])
Drag options to blanks, or click blank then click option'
A"Setup started"
Byield
C"Teardown done"
Dreturn
Attempts:
3 left
💡 Hint
Common Mistakes
Using return instead of yield skips teardown.
Swapping setup and teardown messages.