What are pytest fixtures, and what scopes exist?
IntermediateConceptTesting, services & metrics
Answer
Fixtures provide setup (and teardown after yield) to tests that name them as arguments. They live in the test file or a shared conftest.py.
@pytest.fixture
def ec2(aws): # depends on another fixture
return boto3.client("ec2", region_name="us-east-1")
@pytest.fixture(scope="session")
def docker_image():
subprocess.run(["docker", "build", "-t", "app:test", "."], check=True)
yield "app:test"
subprocess.run(["docker", "rmi", "app:test"])
Scopes: function (default), class, module, package, session. Wider scopes save time but share state, so keep mutable resources function-scoped.
More on Testing, services & metrics
Why should automation scripts have tests at all?BeginnerHow does pytest discover and run tests?BeginnerWhy does pytest use plain `assert` instead of `assertEqual`?BeginnerWhat built-in fixtures do you use most?IntermediateHow does `@pytest.mark.parametrize` work?BeginnerWhat is moto, and how do you use it with pytest?Intermediate