0
0
PyTesttesting~10 mins

Fixture scope with parallel tests 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 define a fixture with session scope.

PyTest
import pytest

@pytest.fixture(scope=[1])
def setup_db():
    print("Setup DB")
    yield
    print("Teardown DB")
Drag options to blanks, or click blank then click option'
Afunction
Bsession
Cmodule
Dclass
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'function' scope when you want to share setup across tests.
Confusing 'module' and 'session' scopes.
2fill in blank
medium

Complete the code to run tests in parallel using pytest-xdist.

PyTest
# Run tests with pytest-xdist
pytest -n [1]
Drag options to blanks, or click blank then click option'
Aauto
B4
Call
Dparallel
Attempts:
3 left
💡 Hint
Common Mistakes
Using invalid values like 'all' or 'parallel' for '-n'.
Not installing pytest-xdist before using '-n'.
3fill in blank
hard

Fix the error in the fixture to avoid sharing state in parallel tests.

PyTest
import pytest

@pytest.fixture(scope="session")
def resource():
    data = []
    yield data
    data.clear()

# Tests modify resource by appending values
# Problem: parallel tests share the same list causing conflicts
# Fix by changing [1]
Drag options to blanks, or click blank then click option'
Ascope to 'module'
Bdata to a global variable
Cyield to return
Dscope to 'function'
Attempts:
3 left
💡 Hint
Common Mistakes
Keeping session scope and causing test interference.
Using global variables which are shared across tests.
4fill in blank
hard

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

PyTest
@pytest.fixture(scope=[1], autouse=[2])
def setup_env():
    print("Setup environment")
    yield
    print("Teardown environment")
Drag options to blanks, or click blank then click option'
Amodule
Bfunction
CTrue
DFalse
Attempts:
3 left
💡 Hint
Common Mistakes
Setting autouse to False and expecting automatic use.
Using function scope when module scope is needed.
5fill in blank
hard

Fill all three blanks to create a parametrized fixture with session scope and proper teardown.

PyTest
@pytest.fixture(scope=[1], params=["chrome", "firefox"])
def browser(request):
    driver = start_driver([2])
    yield driver
    [3](driver)
Drag options to blanks, or click blank then click option'
Asession
Brequest.param
Cstop_driver
Dfunction
Attempts:
3 left
💡 Hint
Common Mistakes
Using function scope instead of session for sharing.
Not using request.param to get parameter value.
Forgetting to stop the driver in teardown.