--- `pytest` Unit And Integration Tests • Python Cabinet

pytest Unit And Integration Tests

  • Tag slow or live-server tests with @pytest.mark.integration so 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 produces 0.9999999999999999 instead of 1.0. Always use pytest.approx(1.0).
  • Unregistered custom markers: pytest emits a PytestUnknownMarkWarning for @pytest.mark.integration until you register integration in pyproject.toml or pytest.ini.
  • Running pytest without -m: Running bare .venv/bin/pytest failed with ModuleNotFoundError: No module named 'app'; .venv/bin/python -m pytest puts the repo root on sys.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.