0
0
PyTesttesting~10 mins

Shared expensive resource patterns 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 that runs once per module.

PyTest
import pytest

@pytest.fixture(scope=[1])
def expensive_resource():
    print("Setup expensive resource")
    yield
    print("Teardown expensive resource")
Drag options to blanks, or click blank then click option'
Afunction
Bmodule
Cclass
Dsession
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'function' scope causes the fixture to run before every test, which is inefficient for expensive resources.
2fill in blank
medium

Complete the code to use the fixture in a test function.

PyTest
def test_example([1]):
    assert True
Drag options to blanks, or click blank then click option'
Aexpensive_resource
Bresource
Cfixture
Dsetup
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different parameter name than the fixture name will not inject the fixture.
3fill in blank
hard

Fix the error in the fixture scope to share the resource across all tests in all modules.

PyTest
import pytest

@pytest.fixture(scope=[1])
def global_resource():
    print("Setup global resource")
    yield
    print("Teardown global resource")
Drag options to blanks, or click blank then click option'
Afunction
Bmodule
Csession
Dclass
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'module' scope only shares the fixture within one module, not across modules.
4fill in blank
hard

Fill both blanks to create a fixture that sets up a database connection once per class and tears it down after all tests in the class.

PyTest
import pytest

@pytest.fixture(scope=[1])
def db_connection():
    print("Connect to DB")
    yield
    print("Disconnect from DB")

class TestDB:
    def test_query1(self, [2]):
        assert True
Drag options to blanks, or click blank then click option'
Aclass
Bdb_connection
Cmodule
Dfunction
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'function' scope causes the fixture to run before every test method, not once per class.
5fill in blank
hard

Fill all three blanks to create a session-scoped fixture that returns a resource and is used in a test.

PyTest
import pytest

@pytest.fixture(scope=[1])
def shared_resource():
    resource = "Expensive Resource"
    yield resource
    print("Cleanup resource")

def test_use_resource([2]):
    assert [3] == "Expensive Resource"
Drag options to blanks, or click blank then click option'
Asession
Bshared_resource
Dmodule
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the fixture parameter and assertion variable causes errors.