Sub topic 2
Comparing Results and Reusing Test Setup
This chapter assumes you can write Python functions, import modules, use a virtual environment, and understand basic exceptions.
Comparing floating-point numbers with `pytest.approx`
Floating-point arithmetic can produce tiny rounding differences. pytest.approx checks whether numbers are close enough instead of requiring identical binary values.
import pytest
def price_with_tax(price, rate):
return price * (1 + rate)
def test_price_with_tax():
assert price_with_tax(30, 0.1) == pytest.approx(33.0)Use exact assert checks for integers and strings. Use pytest.approx when calculations involve decimals. You can also set a tolerance with pytest.approx(expected, abs=0.01).
Fixtures: reusable setup and teardown
A fixture is a function that prepares data or resources for a test. A test requests a fixture by naming it as an argument.
import sqlite3
import pytest
@pytest.fixture
def db():
connection = sqlite3.connect(":memory:")
connection.execute("CREATE TABLE users (name TEXT)")
yield connection
connection.close()
def test_insert_user(db):
db.execute("INSERT INTO users VALUES ('ada')")
count = db.execute("SELECT COUNT(*) FROM users").fetchone()[0]
assert count == 1The code before yield is setup. The code after yield is teardown.
Fixture scope and cleanup with `yield`
By default, pytest creates a fixture separately for each test. This keeps tests isolated. You can choose a wider scope, such as module, when setup is expensive:
@pytest.fixture(scope="module")
def shared_value():
return {"ready": True}Wider scopes can improve speed but allow tests to share state. Use them only when the resource is safe to share.
Sharing fixtures through `conftest.py`
Put fixtures used by several test files in conftest.py. Pytest discovers this file automatically, so tests can request the fixture without importing it. Keep shared fixtures small and focused.
Running one test over many inputs with `parametrize`
pytest.mark.parametrize runs one test function once for each input case.
@pytest.mark.parametrize(
"items, expected",
[([], 0), ([5], 5), ([1, 2, 3], 6)],
)
def test_sum(items, expected):
assert sum(items) == expectedEach case appears separately in pytest output, making failures easy to identify.
Exercise
Why does a fixture use yield instead of simply returning a database connection?
Show answer
Code after yield runs after the test, so it can close the connection and perform other cleanup.