pytest Unit And Integration Tests
- Tag slow or live-server tests with
@pytest.mark.integrationso you can run pure logic unit tests in milliseconds even when Ollama or the network is offline.
How it works
Follow the Arrange → Act → Assert pattern for unit tests, use pytest.approx() when comparing floating-point numbers, and mark tests that hit external services:
@pytest.mark.integration
def test_retrieve_semantic_broadband_match():
result = retrieve_semantic("Does Northstar help pay for my home broadband?", min_score=0.60)
assert "$65 per month" in result
Run only fast unit tests with:
.venv/bin/python -m pytest tests/test_semantic_retrieval.py -m "not integration" -v
What can go wrong
- Exact
==on floats: Floating-point math produces0.9999999999999999instead of1.0. Always usepytest.approx(1.0). - Unregistered custom markers:
pytestemits aPytestUnknownMarkWarningfor@pytest.mark.integrationuntil you registerintegrationinpyproject.tomlorpytest.ini. - Running
pytestwithout-m: Running bare.venv/bin/pytestfailed withModuleNotFoundError: No module named 'app';.venv/bin/python -m pytestputs the repo root onsys.path.
Referenced code
From tests/test_semantic_retrieval.py in ai-security-lab:
def test_semantic_retrieval_against_known_identical_directions():
vec_a = [1.0, 0.0]
vec_b = [5.0, 0.0]
return_val = cosine_similarity(vec_a, vec_b)
assert return_val == pytest.approx(1.0)
def test_semantic_retrieval_against_known_zerovector_directions():
vec_a = [0.0, 0.0]
vec_b = [1.0, 0.0]
return_val = cosine_similarity(vec_a, vec_b)
assert return_val == pytest.approx(0.0)
Evidence: tests/test_semantic_retrieval.py in ai-security-lab (3 unit tests verified passing via python -m pytest -m "not integration"). Related: Basic structure and imports and Semantic document retrieval.