Testing and Quality Assurance¶
Testing is how you know your code works, not just now, but after every change. This file covers the test pyramid, unit tests with pytest, mocking, testing ML-specific code, CI/CD pipelines, linting, formatting, and code review, the practices that catch bugs before they reach production.
-
ML code is notoriously undertested. "It trains, therefore it works" is the prevailing attitude. This leads to silent bugs: a data loader that shuffles incorrectly, a loss function with a sign error, a preprocessing step that drops 5% of the data. These bugs do not crash your program. They just make your model quietly worse, and you waste weeks debugging metrics that "should be higher."
-
Testing is not overhead. It is the fastest way to move fast without breaking things.
The Test Pyramid¶
-
Tests are organised in layers, from fast and narrow to slow and broad:
-
Unit tests (base): test individual functions and classes in isolation. Fast (milliseconds), numerous (hundreds to thousands). "Does
normalise_imageproduce values in [0, 1]?" -
Integration tests (middle): test that components work together. Slower (seconds). "Does the data loader produce batches in the format the model expects?"
-
End-to-end tests (top): test the full pipeline from input to output. Slow (minutes). "Does
python train.py --config test.yamlcomplete without errors and produce a valid checkpoint?"
-
-
The pyramid shape means: write many unit tests, fewer integration tests, and a handful of end-to-end tests. Unit tests catch most bugs and run in seconds. End-to-end tests catch integration issues but are slow and fragile.
Unit Tests with pytest¶
- pytest is the standard Python testing framework. A test is a function starting with
test_in a file starting withtest_:
# tests/test_utils.py
def test_normalise_image():
import numpy as np
image = np.array([0, 128, 255], dtype=np.uint8)
result = normalise_image(image, mean=128, std=128)
assert result.min() >= -1.0
assert result.max() <= 1.0
assert abs(result[1]) < 1e-6 # 128 normalised by mean=128 should be ~0
def test_normalise_empty():
import numpy as np
image = np.array([], dtype=np.uint8)
result = normalise_image(image, mean=128, std=128)
assert len(result) == 0
pub fn normalise_image(image: &[u8], mean: f64, std: f64) -> Vec<f64> {
image.iter().map(|&px| (px as f64 - mean) / std).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_normalise_image() {
let image: [u8; 3] = [0, 128, 255];
let result = normalise_image(&image, 128.0, 128.0);
let min = result.iter().copied().fold(f64::INFINITY, f64::min);
let max = result.iter().copied().fold(f64::NEG_INFINITY, f64::max);
assert!(min >= -1.0);
assert!(max <= 1.0);
assert!(result[1].abs() < 1e-6); // 128 normalised by mean=128 should be ~0
}
#[test]
fn test_normalise_empty() {
let result = normalise_image(&[], 128.0, 128.0);
assert!(result.is_empty());
}
}
pytest tests/ # run all tests
pytest tests/test_utils.py # run one file
pytest -v # verbose output
pytest -x # stop on first failure
pytest -k "normalise" # run tests matching name pattern
pytest --tb=short # shorter tracebacks
Fixtures¶
- Fixtures provide reusable setup for tests. Instead of repeating setup code in every test, define it once:
import pytest
@pytest.fixture
def sample_dataset():
"""Create a small dataset for testing."""
return {
"inputs": torch.randn(10, 3, 32, 32),
"labels": torch.randint(0, 10, (10,))
}
@pytest.fixture
def trained_model():
"""Load a small pretrained model."""
model = SmallModel()
model.load_state_dict(torch.load("tests/fixtures/small_model.pt"))
return model
def test_model_output_shape(trained_model, sample_dataset):
output = trained_model(sample_dataset["inputs"])
assert output.shape == (10, 10) # batch_size x num_classes
use std::sync::OnceLock;
pub struct SampleDataset {
pub inputs: Vec<Vec<f32>>, // [batch_size][features]
pub labels: Vec<usize>,
}
pub struct SmallModel {
num_classes: usize,
}
impl SmallModel {
pub fn load_fixture() -> Self {
Self { num_classes: 10 }
}
pub fn forward(&self, batch: &[Vec<f32>]) -> Vec<Vec<f32>> {
batch.iter().map(|_| vec![0.0; self.num_classes]).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
// Function-scoped fixture: fresh data per test
fn sample_dataset() -> SampleDataset {
SampleDataset {
inputs: vec![vec![0.1; 3 * 32 * 32]; 10],
labels: (0..10).collect(),
}
}
// Session-scoped fixture: initialised once and shared across tests
fn trained_model() -> &'static SmallModel {
static MODEL: OnceLock<SmallModel> = OnceLock::new();
MODEL.get_or_init(SmallModel::load_fixture)
}
#[test]
fn test_model_output_shape() {
let dataset = sample_dataset();
let output = trained_model().forward(&dataset.inputs);
assert_eq!((output.len(), output[0].len()), (10, 10)); // batch_size x num_classes
}
}
- Fixtures can have scopes:
scope="function"(default, fresh per test),scope="module"(once per file),scope="session"(once per test run). Usescope="session"for expensive setup like loading a model.
Parametrised Tests¶
- Test the same function with multiple inputs without duplicating code:
#[cfg(test)]
mod tests {
#[test]
fn test_sum_cases() {
let cases: &[(&[i64], i64)] = &[
(&[1, 2, 3], 6),
(&[], 0),
(&[-1, 1], 0),
(&[1_000_000, 1_000_000], 2_000_000),
];
for &(input, expected) in cases {
let actual: i64 = input.iter().sum();
assert_eq!(actual, expected, "failed for input {input:?}");
}
}
}
Mocking and Patching¶
- Mocking replaces a real dependency with a fake one during testing. This lets you test a function in isolation, without needing a database, API, or GPU.
from unittest.mock import patch, MagicMock
def test_training_logs_metrics():
mock_logger = MagicMock()
with patch("my_project.training.trainer.wandb") as mock_wandb:
trainer = Trainer(logger=mock_logger)
trainer.train_one_epoch()
# verify that the trainer logged metrics
mock_logger.log.assert_called()
# verify it logged a loss value
call_args = mock_logger.log.call_args
assert "loss" in call_args[1]
use std::collections::HashMap;
pub trait MetricLogger {
fn log(&mut self, metrics: HashMap<String, f64>);
}
pub struct Trainer<L: MetricLogger> {
pub logger: L,
}
impl<L: MetricLogger> Trainer<L> {
pub fn train_one_epoch(&mut self) {
let mut metrics = HashMap::new();
metrics.insert("loss".to_string(), 0.25);
self.logger.log(metrics);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Default)]
struct MockLogger {
calls: Vec<HashMap<String, f64>>,
}
impl MetricLogger for MockLogger {
fn log(&mut self, metrics: HashMap<String, f64>) {
self.calls.push(metrics);
}
}
#[test]
fn test_training_logs_metrics() {
let mut trainer = Trainer { logger: MockLogger::default() };
trainer.train_one_epoch();
// verify that the trainer logged metrics
assert!(!trainer.logger.calls.is_empty());
// verify it logged a loss value
let last_call = trainer.logger.calls.last().unwrap();
assert!(last_call.contains_key("loss"));
}
}
-
When to mock: external services (APIs, databases, cloud storage), expensive operations (GPU computation, large file I/O), and non-deterministic behaviour (random number generators, timestamps).
-
When NOT to mock: your own code. If you mock everything, your tests verify that mocks behave as expected, not that your code works. Mock at the boundaries, test your logic directly.
Testing ML Code¶
- ML code has unique testing challenges: outputs are probabilistic, training is slow, and "correct" is fuzzy.
Deterministic Seeds¶
- Set random seeds everywhere to make tests reproducible:
// Rust avoids hidden global RNG state: pass an explicit seeded generator instead
// (in production, use `rand::SeedableRng` with `StdRng::seed_from_u64(42)`).
#[derive(Clone)]
pub struct SeededRng {
state: u64,
}
impl SeededRng {
pub fn from_seed(seed: u64) -> Self {
Self { state: seed.max(1) }
}
pub fn next_u64(&mut self) -> u64 {
// xorshift64* deterministic PRNG
let mut x = self.state;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
self.state = x;
x.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
pub fn next_f64(&mut self) -> f64 {
(self.next_u64() >> 11) as f64 / ((1u64 << 53) as f64)
}
}
Numerical Tolerances¶
- Floating-point comparisons require tolerances (chapter 16, IEEE 754):
pub fn is_close(a: f64, b: f64, atol: f64) -> bool {
(a - b).abs() <= atol
}
pub fn all_close(actual: &[f64], expected: &[f64], atol: f64) -> bool {
actual.len() == expected.len()
&& actual.iter().zip(expected).all(|(&a, &b)| is_close(a, b, atol))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_numerical_tolerances() {
let model_output = 0.1_f64 + 0.2_f64 + 0.2_f64;
// BAD: exact equality is fragile with IEEE 754 floats
// assert_eq!(model_output, 0.5);
// GOOD: approximate comparison with explicit tolerance
assert!(is_close(model_output, 0.5, 1e-5));
// For slices / tensors
let output = [0.25001, 0.74999];
let expected = [0.25, 0.75];
assert!(all_close(&output, &expected, 1e-4));
}
}
What to Test in ML¶
- Shape tests: verify that outputs have the expected dimensions.
pub struct Tensor {
pub shape: Vec<usize>,
pub data: Vec<f32>,
}
pub struct MyModel {
d_model: usize,
n_classes: usize,
}
impl MyModel {
pub fn forward(&self, x: &Tensor) -> Tensor {
assert_eq!(x.shape.len(), 3, "expected [batch, seq, d_model]");
assert_eq!(x.shape[2], self.d_model, "input dim mismatch");
let batch = x.shape[0];
Tensor {
shape: vec![batch, self.n_classes],
data: vec![0.0; batch * self.n_classes],
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_model_output_shape() {
let model = MyModel { d_model: 256, n_classes: 10 };
let x = Tensor {
shape: vec![8, 32, 256], // batch=8, seq=32, dim=256
data: vec![0.0; 8 * 32 * 256],
};
let output = model.forward(&x);
assert_eq!(output.shape, vec![8, 10]);
}
}
- Gradient flow: verify that gradients are non-zero for trainable parameters.
def test_gradients_flow():
model = MyModel()
x = torch.randn(4, 3, 32, 32)
y = torch.randint(0, 10, (4,))
output = model(x)
loss = F.cross_entropy(output, y)
loss.backward()
for name, param in model.named_parameters():
assert param.grad is not None, f"No gradient for {name}"
assert param.grad.abs().sum() > 0, f"Zero gradient for {name}"
pub struct LinearLayer {
pub weights: Vec<Vec<f64>>, // [out_dim][in_dim]
pub bias: Vec<f64>,
pub grad_w: Option<Vec<Vec<f64>>>,
pub grad_b: Option<Vec<f64>>,
}
impl LinearLayer {
pub fn new(in_dim: usize, out_dim: usize) -> Self {
Self {
weights: vec![vec![0.1; in_dim]; out_dim],
bias: vec![0.0; out_dim],
grad_w: None,
grad_b: None,
}
}
pub fn forward(&self, x: &[f64]) -> Vec<f64> {
self.weights.iter().zip(&self.bias)
.map(|(row, &b)| row.iter().zip(x).map(|(w, xi)| w * xi).sum::<f64>() + b)
.collect()
}
pub fn backward_cross_entropy(&mut self, x: &[f64], logits: &[f64], target: usize) {
let max_l = logits.iter().copied().fold(f64::NEG_INFINITY, f64::max);
let exps: Vec<f64> = logits.iter().map(|&l| (l - max_l).exp()).collect();
let sum_exp: f64 = exps.iter().sum();
let dlogits: Vec<f64> = exps.iter().enumerate()
.map(|(i, &e)| e / sum_exp - if i == target { 1.0 } else { 0.0 })
.collect();
self.grad_w = Some(dlogits.iter()
.map(|&dl| x.iter().map(|&xi| dl * xi).collect())
.collect());
self.grad_b = Some(dlogits);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_gradients_flow() {
let mut layer = LinearLayer::new(4, 3);
let x = [1.0, -0.5, 0.25, 2.0];
let logits = layer.forward(&x);
layer.backward_cross_entropy(&x, &logits, 1);
let gw = layer.grad_w.as_ref().expect("No gradient for weights");
let gw_l1: f64 = gw.iter().flatten().map(|g| g.abs()).sum();
assert!(gw_l1 > 0.0, "Zero gradient for weights");
let gb = layer.grad_b.as_ref().expect("No gradient for bias");
let gb_l1: f64 = gb.iter().map(|g| g.abs()).sum();
assert!(gb_l1 > 0.0, "Zero gradient for bias");
}
}
- Overfit on one batch: a model should be able to memorise a single batch. If it cannot, something is fundamentally wrong.
def test_overfit_one_batch():
model = MyModel()
optimiser = torch.optim.Adam(model.parameters(), lr=1e-3)
x, y = get_single_batch()
for _ in range(100):
loss = F.cross_entropy(model(x), y)
loss.backward()
optimiser.step()
optimiser.zero_grad()
assert loss.item() < 0.01, f"Cannot overfit one batch: loss={loss.item()}"
#[cfg(test)]
mod tests {
fn softmax(logits: &[f64]) -> Vec<f64> {
let m = logits.iter().copied().fold(f64::NEG_INFINITY, f64::max);
let exps: Vec<f64> = logits.iter().map(|&z| (z - m).exp()).collect();
let s: f64 = exps.iter().sum();
exps.into_iter().map(|e| e / s).collect()
}
#[test]
fn test_overfit_one_batch() {
let batch = [([1.0, 0.0], 0usize), ([0.0, 1.0], 1usize)];
let mut weights = [[0.0_f64; 2]; 2]; // [class][feature]
let lr = 2.0;
let mut loss = f64::INFINITY;
for _ in 0..100 {
let mut grad = [[0.0_f64; 2]; 2];
loss = 0.0;
for &(x, y) in &batch {
let logits = [
weights[0][0] * x[0] + weights[0][1] * x[1],
weights[1][0] * x[0] + weights[1][1] * x[1],
];
let probs = softmax(&logits);
loss -= probs[y].ln() / batch.len() as f64;
for c in 0..2 {
let dl = (probs[c] - if c == y { 1.0 } else { 0.0 }) / batch.len() as f64;
for j in 0..2 {
grad[c][j] += dl * x[j];
}
}
}
for c in 0..2 {
for j in 0..2 {
weights[c][j] -= lr * grad[c][j];
}
}
}
assert!(loss < 0.01, "Cannot overfit one batch: loss={loss:.4}");
}
}
- Data validation: verify data loading produces valid outputs.
pub struct Sample {
pub shape: [usize; 3],
pub pixels: Vec<f32>,
pub label: usize,
}
#[cfg(test)]
mod tests {
use super::*;
fn load_fixture_dataset() -> Vec<Sample> {
vec![Sample {
shape: [3, 224, 224],
pixels: vec![0.5; 3 * 224 * 224],
label: 3,
}]
}
#[test]
fn test_dataset_basics() {
let dataset = load_fixture_dataset();
assert!(!dataset.is_empty());
let sample = &dataset[0];
assert_eq!(sample.shape, [3, 224, 224]);
assert!(sample.label < 10);
assert!(sample.pixels.iter().all(|v| v.is_finite())); // rejects both NaN and Inf
}
}
- Determinism: same input + same seed → same output.
pub fn seeded_forward(input: &[f64], seed: u64) -> Vec<f64> {
let mut state = seed.max(1);
input.iter().map(|&x| {
state ^= state >> 12;
state ^= state << 25;
state ^= state >> 27;
let noise = ((state.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 11) as f64)
/ ((1u64 << 53) as f64);
x + 0.01 * noise
}).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_determinism() {
let input_data = [0.5, -1.2, 3.4, 0.0];
let output1 = seeded_forward(&input_data, 42);
let output2 = seeded_forward(&input_data, 42);
assert!(output1.iter().zip(&output2).all(|(a, b)| (a - b).abs() <= 1e-12));
}
}
Evaluation-Driven Development for LLM and AI Systems¶
-
Traditional unit tests assume that each input has a single exact answer. Large language models and agentic workflows break that assumption because valid responses can be phrased in many ways, tool paths can vary, and small prompt or model changes can quietly shift behaviour across edge cases. Evaluation-driven development (evals) extends the testing mindset to probabilistic AI systems.
-
Golden datasets and task rubrics. Start by curating a versioned suite of representative inputs paired with expected properties, reference answers, or grading rubrics. Include everyday user queries, tricky domain edge cases, and every production failure you have ever fixed so old bugs cannot silently return. Storing this dataset in version control alongside prompts and code turns subjective impressions ("the new prompt feels better") into measurable comparisons.
-
Layer deterministic checks before model-based grading. Not every aspect of an LLM output needs another model to judge it. Check everything you can deterministically first, such as valid JSON schemas, required tool-call arguments, citation links that actually exist in retrieved sources, latency budgets, and unit tests over generated code. Deterministic checks are fast, cheap, and reproducible, leaving softer questions like helpfulness or tone for higher-level graders.
-
LLM-as-a-judge and its pitfalls. For open-ended tasks where exact matching fails, teams often use a strong model to score candidate outputs against a structured rubric. Used carelessly, automated judges introduce systematic distortions that can mislead engineering decisions.
- Position bias causes a judge comparing two answers to favour whichever option appears first (mitigate this by running each comparison in both orders and checking agreement).
- Verbosity bias rewards longer, more polished responses even when they are less accurate or padded with filler.
- Self-preference bias makes a model rate outputs from its own model family higher than equivalent outputs from another provider.
- Rubric drift and weak calibration happen when judge prompts are never validated against human labels. Periodically audit a stratified sample of judge scores against domain experts and measure agreement (such as Cohen's kappa) so you know the metric still tracks real user quality.
-
Regression gates in CI. Treat evals like an upper layer of the test pyramid. Run a fast, inexpensive smoke subset on pull requests to catch broken tool calls, prompt regressions, and schema failures immediately, then run the full golden suite nightly or before model releases. Because LLM outputs carry sampling variance, track pass rates across multiple trials or confidence intervals, and block deployment whenever quality drops or token cost and latency drift past acceptable thresholds.
CI/CD Pipelines¶
-
Continuous Integration (CI): automatically run tests on every commit or PR. If tests fail, the PR cannot be merged. This prevents broken code from reaching
main. -
GitHub Actions example (
.github/workflows/ci.yml):
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
- run: pip install -e ".[dev]"
- run: ruff check src/
- run: mypy src/
- run: pytest tests/ -v --tb=short
- Pre-commit hooks: run checks before each commit (locally), catching issues before they reach CI:
# .pre-commit-config.yaml
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.3.0
hooks:
- id: ruff
args: [--fix]
- id: ruff-format
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
Modern Python Toolchain, Linting, and Formatting¶
-
Linting catches bugs and style issues without running the code, while formatting enforces consistent layout automatically. Over recent years the Python ecosystem has consolidated around fast Rust-based tools that replace half a dozen slower legacy utilities with a single coherent workflow.
-
uvfor fast deterministic environments. Managing Python versions, virtual environments, dependency resolution, and lockfiles used to require jugglingpyenv,venv,pip,pip-tools, andpoetry.uvunifies all of those jobs into one fast executable that resolves dependencies and installs packages orders of magnitude faster thanpip. Its cross-platformuv.lockfile guarantees that every teammate and CI runner installs the exact same dependency graph.
uv init my-project # create pyproject.toml and project skeleton
uv add torch pydantic # add dependencies and update uv.lock
uv add --dev pytest ruff mypy
uv sync --frozen # reproduce the exact locked environment in CI
uv run pytest tests/ # run commands directly inside the project environment
rufffor unified linting and formatting. Built in Rust alongsideuv,ruffreplacesflake8,black,isort, and dozens of lint plugins in a single binary that checks an entire codebase in milliseconds. Keeping both lint rules and formatting settings insidepyproject.tomleliminates configuration sprawl and makes style debates obsolete.
uv run ruff check src/ # lint across the package
uv run ruff check --fix src/ # lint and apply safe auto-fixes
uv run ruff format src/ # format consistently
uv run ruff format --check src/ # verify formatting in CI without modifying files
mypyfor static type checking. Type checkers catch mismatched argument types, missingNoneguards, and broken refactors before code ever executes.
uv run mypy src/
# src/model.py:42: error: Argument 1 to "forward" has incompatible type "int"; expected "Tensor"
- Type hints make code self-documenting and catch bugs early.
pub trait Module {
fn forward(&self, batch: &[f32]) -> Vec<f32>;
}
pub trait Optimiser {
fn step(&mut self, loss: f64);
}
/// Train model across `num_epochs` and return the final epoch loss.
pub fn train<M, O, B>(
model: &mut M,
batches: &[B],
optimiser: &mut O,
num_epochs: usize,
) -> Result<f64, String>
where
M: Module,
O: Optimiser,
B: AsRef<[f32]>,
{
if batches.is_empty() {
return Err("dataloader yielded no batches".into());
}
let mut final_loss = 0.0;
for _epoch in 0..num_epochs {
for batch in batches {
let preds = model.forward(batch.as_ref());
final_loss = preds.iter().map(|&p| (p as f64).powi(2)).sum::<f64>()
/ preds.len().max(1) as f64;
optimiser.step(final_loss);
}
}
Ok(final_loss)
}
Code Review Best Practices¶
-
For the author:
- Self-review your diff before requesting review. You will catch obvious issues.
- Keep PRs small and focused. One concern per PR.
- Write a clear description: what, why, how to test.
- Respond to every comment (even if just "done").
-
For the reviewer:
- Be kind. Critique the code, not the person. "This could be clearer" not "this is confusing."
- Distinguish blocking issues (bugs, security) from suggestions (style, naming). Use labels: "nit:", "suggestion:", "blocking:".
- Ask questions instead of making demands. "What happens if this list is empty?" is more helpful than "handle the empty case."
- Approve promptly. A PR waiting days for review blocks the author and encourages large, batched PRs (which are harder to review).