Complete the code to define a fixture that runs once per module.
import pytest @pytest.fixture(scope=[1]) def expensive_resource(): print("Setup expensive resource") yield print("Teardown expensive resource")
The module scope makes the fixture run once per module, sharing the expensive resource among tests in that module.
Complete the code to use the fixture in a test function.
def test_example([1]): assert True
The test function must accept the fixture name as a parameter to use it.
Fix the error in the fixture scope to share the resource across all tests in all modules.
import pytest @pytest.fixture(scope=[1]) def global_resource(): print("Setup global resource") yield print("Teardown global resource")
The session scope shares the fixture across all tests in all modules during the test session.
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.
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
Using class scope makes the fixture run once per test class. The test method must accept the fixture name db_connection to use it.
Fill all three blanks to create a session-scoped fixture that returns a resource and is used in a test.
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"
The fixture uses session scope to share the resource across all tests. The test function accepts the fixture name shared_resource and asserts the returned value.