Q1.How do pytest fixtures work, and what does yield do inside one?
Short answer: a fixture is a function that prepares something a test needs; tests ask for it by naming it as a parameter. Code before yield is setup, code after it is teardown, and teardown runs even if the test fails.
import pytest
import requests
@pytest.fixture(scope="session")
def api():
session = requests.Session()
session.headers["Accept"] = "application/json"
yield session
session.close() # teardown
def test_health(api):
r = api.get("https://httpbin.org/status/200", timeout=10)
assert r.status_code == 200
Scopes are function (default), class, module, package and session. Put shared fixtures in conftest.py; pytest finds them without imports.
- Using session scope for data that tests modify - one test then breaks another
- How does a fixture use another fixture?
- What does autouse=True do?
