Interview Prep/Python for DevOps/Testing, services & metrics

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.

All Python for DevOps questions Roadmap: Python for automation

More on Testing, services & metrics