Testing numerical code with pytest and Hypothesis
Numerical code fails silently: it returns plausible but incorrect numbers. Build a specific testing strategy: dtype-justified tolerances, tests against slow but obvious reference implementations, metamorphic relations without an oracle, Hypothesis properties over generated arrays, and stochastic-code tests with a controlled false-positive rate, all organized with pytest.
After this lesson you can
- Organize a pytest suite using fixtures, parametrization, conftest.py, and markers (slow, gpu).
- Choose rtol and atol justified by dtype and calculation, and use np.testing.assert_allclose and torch.testing.assert_close.
- Write reference-implementation and metamorphic-relation tests (permutation, scaling, symmetry, conservation).
- Write property-based tests with Hypothesis, including arrays of varying shapes and dtypes, and interpret minimal counterexamples.
- Test stochastic code with fixed seeds and statistical thresholds with a known false-failure rate.
Before you start
Motivation: the bug that raises no exceptions
A syntax error is visible. An out-of-range index raises an exception. But a typical numerical-code error does neither: it returns numbers of the correct shape and size that look perfectly reasonable. They are wrong, and nothing says so.
The most cited case is Geoffrey Chang, a crystallographer at the Scripps Research Institute. In 2006 he retracted five papers, three in Science, published between 2001 and 2005: an analysis program written in his laboratory swapped two data columns, inverting the electron-density map from which protein structures were derived (G. Miller, “A Scientist’s Nightmare: Software Problem Leads to Five Retractions,” Science 314, 2006). The program did not crash. It produced coherent structures that passed peer review and were used by other groups for years, until another laboratory published the structure of a homologous protein and it proved incompatible with his.
In machine learning the problem is even more treacherous because training compensates: a network with incorrectly normalized softmax, an attention mask shifted one position, or a loss that unintentionally broadcasts shapes still learns something and its loss curve falls. Consider this example:
import numpy as np
def softmax_filas(X):
"""Softmax de cada fila de X (una fila = los logits de un ejemplo)."""
E = np.exp(X - X.max(axis=1, keepdims=True))
return E / E.sum(axis=0, keepdims=True) # bug: debería ser axis=1
rng = np.random.default_rng(0)
X = rng.normal(size=(4, 4))
P = softmax_filas(X)
print("forma correcta: ", P.shape == X.shape)
print("valores en [0, 1]: ", bool(((P >= 0) & (P <= 1)).all()))
print("suma total = número de filas:", bool(np.isclose(P.sum(), X.shape[0])))
def softmax_referencia(fila): # una fila con un bucle: lenta, pero obviamente correcta
e = [np.exp(v) for v in fila]
s = sum(e)
return [v / s for v in e]
R = np.array([softmax_referencia(fila) for fila in X])
print("\nerror máximo frente a la referencia:", np.abs(P - R).max())
print("suma de cada fila:", P.sum(axis=1))The first three checks are what one writes in a hurry, and all pass: the shape is right, all values are probabilities, and the total sum is expected (because the matrix is square and column normalization also distributes one unit of mass per column). Only comparison with an obvious row-by-row implementation reveals an error on the order of 0.2. This lesson builds a testing strategy for numerical code, which has three distinctive problems:
- There is no exact equality. Two correct implementations of the same formula differ in their last bits. Approximate equality needs justified tolerances, neither so strict that rounding fails nor so loose that bugs pass.
- There is often no oracle. If you knew the exact result you would not need the program. Construct partial oracles: reference implementations, cases with closed-form solutions, and relationships that must hold even without knowing the result.
- Failures live at extremes. Overflow, zeros, empty arrays, repeated values: these rarely appear with
rng.normal. Generate inputs that deliberately seek them.
Serious pytest
pytest is Python’s standard testing tool. Its model is simple: a test is a function whose name starts with test_ and fails if it raises an exception, usually AssertionError.
- Discovery.
pytesttraverses the given directories (or configuredtestpaths) and collectstest_*.pyor*_test.pyfiles; within them,test_*functions andtest_*methods ofTest*classes without__init__. - Assertions. A normal
assertsuffices. pytest rewrites assertions when importing the test module and, when one fails, shows intermediate expression values. Noself.assertEqualis needed. - Expected exceptions and warnings.
with pytest.raises(ValueError, match="forma"):andwith pytest.warns(RuntimeWarning):fail if the block does not raise the expected item.
The three pieces turning a collection of functions into a maintainable suite are fixtures, parametrization, and markers.
Both are decorators in the sense of lesson 3: parametrize executes nothing, only annotates the function so collection can generate cases. The best way to demystify them is to write them. Here is a minimal runner with fixtures injected by name, fixtures using yield, and stackable parametrization:
import inspect
FIXTURES = {}
def fixture(fn):
"""Registra una fixture: se inyecta en los tests que tengan un argumento con su nombre."""
FIXTURES[fn.__name__] = fn
return fn
def parametrize(nombres, valores):
"""Como pytest.mark.parametrize: guarda los casos en un atributo de la función."""
nombres = [n.strip() for n in nombres.split(",")]
def decorador(fn):
previos = getattr(fn, "_casos", [{}])
nuevos = [dict(zip(nombres, v if len(nombres) > 1 else (v,))) for v in valores]
fn._casos = [{**p, **n} for p in previos for n in nuevos] # apilar = producto cartesiano
return fn
return decorador
def resolver(nombre, cache, pendientes):
"""Valor de una fixture, resolviendo antes las fixtures de las que depende."""
if nombre not in cache:
fn = FIXTURES[nombre]
args = {p: resolver(p, cache, pendientes) for p in inspect.signature(fn).parameters}
valor = fn(**args)
if inspect.isgenerator(valor): # fixture con yield: lo que sigue al yield es la limpieza
pendientes.append(valor)
valor = next(valor)
cache[nombre] = valor
return cache[nombre]
def ejecutar(espacio):
resultados = []
for nombre, fn in list(espacio.items()):
if not (nombre.startswith("test_") and callable(fn)):
continue
for caso in getattr(fn, "_casos", [{}]):
ident = nombre + (f"[{'-'.join(map(str, caso.values()))}]" if caso else "")
cache, pendientes = {}, [] # alcance «function»: fixtures nuevas en cada caso
try:
args = {p: caso[p] if p in caso else resolver(p, cache, pendientes)
for p in inspect.signature(fn).parameters}
fn(**args)
resultados.append(("PASA", ident, ""))
except AssertionError as e:
resultados.append(("FALLA", ident, str(e)))
except Exception as e:
resultados.append(("ERROR", ident, f"{type(e).__name__}: {e}"))
finally:
for gen in reversed(pendientes): # limpieza en orden inverso al montaje
next(gen, None)
return resultadosWith a few dozen lines we have the essentials. Try it with three tests: one parametrized with two stacked decorators, one that fails, and one raising an unexpected exception.
import numpy as np
@fixture
def rng():
return np.random.default_rng(0)
@fixture
def datos(rng):
print(" montaje: datos nuevos")
yield rng.normal(size=(5, 3))
print(" limpieza")
@parametrize("eje", [0, 1])
@parametrize("escala", [1.0, 1e6])
def test_media_traslada(datos, eje, escala):
x = escala * datos
assert np.allclose((x + 7).mean(axis=eje), x.mean(axis=eje) + 7), "la media no se traslada"
def test_igualdad_exacta():
assert 0.1 + 0.2 == 0.3, f"0.1 + 0.2 = {0.1 + 0.2!r}"
def test_formas(datos):
datos @ datos # (5, 3) @ (5, 3)
for estado, ident, msg in ejecutar(dict(globals())):
print(f"{estado:5s} {ident} {msg}")
# pytest importa cada fichero de tests como un módulo aparte; aquí todas las celdas comparten
# un mismo espacio de nombres, así que retiramos estos tests para que no se mezclen con otros
for nombre in [n for n in globals() if n.startswith("test_")]:
del globals()[nombre]Notice three details pytest handles the same way. Fixture datos is set up and cleaned up once per case: with function scope, each test receives fresh data and no test can contaminate another. datos itself requests rng, and the runner resolves the chain by name. There are two kinds of failure: an unmet assert (FALLA, fail) and an unexpected exception (ERROR); pytest distinguishes them in its report too.
What our runner does not do is what makes pytest useful in a real project:
conftest.py. A file with that name in any test directory defines fixtures and hooks visible to every test in that directory and its subdirectories, without importing it. Shared random generators, test data, and marker configuration live there.- Markers.
@pytest.mark.slowor@pytest.mark.gpulabel tests, and-m "not slow"selects by labels with Boolean expressions.-k "softmax and not grande"selects by name substrings. Custom markers are declared (inpyproject.tomlorpytest_configure) and--strict-markersturns a misspelled marker into an error. - Built-in markers.
skip,skipif(condición, reason=...), andxfail(expected failure; withstrict=True, unexpected success is also an error). - Built-in fixtures.
tmp_path(a unique temporary directory per test),monkeypatch(replace attributes or environment variables during a test),capsys(capture output), andrequest(information about the test requesting the fixture).
Real pytest is available in the browser. The next cell writes conftest.py and a test file in a temporary directory and runs pytest three times, as you would in a terminal:
import os, io, textwrap, tempfile, contextlib
import numpy as np
import pytest
carpeta = tempfile.mkdtemp()
def escribe(nombre, codigo):
with open(os.path.join(carpeta, nombre), "w", encoding="utf-8") as f:
f.write(textwrap.dedent(codigo))
escribe("conftest.py", '''
import numpy as np
import pytest
def pytest_configure(config):
config.addinivalue_line("markers", "slow: test lento")
@pytest.fixture(scope="session")
def datos():
return np.random.default_rng(0).normal(size=(200, 3))
''')
escribe("test_estandarizar.py", '''
import numpy as np
import pytest
def estandarizar(X):
s = X.std(axis=0)
if np.any(s == 0):
raise ValueError("columna constante: no se puede estandarizar")
return (X - X.mean(axis=0)) / s
@pytest.mark.parametrize("escala", [1e-3, 1.0, 1e3])
@pytest.mark.parametrize("desplazamiento", [0.0, 50.0])
def test_invariante_afin(datos, escala, desplazamiento):
Z = estandarizar(escala * datos + desplazamiento)
np.testing.assert_allclose(Z, estandarizar(datos), rtol=1e-9, atol=1e-12)
def test_media_cero_y_varianza_uno(datos):
Z = estandarizar(datos)
assert Z.mean(axis=0) == pytest.approx(0, abs=1e-12)
assert Z.std(axis=0) == pytest.approx(1)
def test_columna_constante_falla():
with pytest.raises(ValueError, match="constante"):
estandarizar(np.ones((4, 2)))
@pytest.mark.slow
def test_muchos_datos():
X = np.random.default_rng(1).normal(size=(10**6, 3))
assert abs(estandarizar(X).mean()) < 1e-12
''')
def pytest_(*args):
salida = io.StringIO()
with contextlib.redirect_stdout(salida):
codigo = pytest.main(["-p", "no:cacheprovider", *args])
print(f"$ pytest {' '.join(args)} (código de salida {int(codigo)})")
print(salida.getvalue().strip(), "\n")
anterior = os.getcwd()
os.chdir(carpeta)
try:
pytest_("--collect-only", "-q")
pytest_("-q", "-m", "not slow", "--tb=line")
pytest_("-q", "-k", "media or constante")
finally:
os.chdir(anterior)Collection shows nine tests from four functions: the two stacked parametrize decorators generate cases, with identifiers like [50.0-0.001] that can be passed to -k. The second run deselects the slow test and, above all, finds a real failure: test_invariante_afin[50.0-0.001]. Standardization is invariant to affine transforms in exact arithmetic, but with offset 50 and scale , subtracting the mean cancels almost all digits: each datum carries absolute rounding of about , which divided by standard deviation becomes a error on the order of . For elements of size 1 that error fits , but near 0 only the requested absolute tolerance remains, which is stricter: failing elements are precisely the small-valued ones. The code has no bug; the test tolerance is wrong. The next sections explain how to choose it.
Approximate equality
The assert_allclose condition
If is the obtained value and the desired one, absolute error is and relative error is (defined if ). Relative error is natural for floating-point numbers, whose rounding is relative: by the standard model, each operation satisfies with , where is unit roundoff: in float32 and in float64 (machine epsilon returned by np.finfo(dtype).eps is ). But relative error explodes as approaches zero, and a result that should be exactly 0 rarely is.
Geometrically, in the (desired, obtained) plane the accepted region surrounds diagonal : a cone of slope closing at , widened by a band of half-width . For the band dominates; for the cone does. On a logarithmic scale the boundary is a hockey stick: horizontal at and then a line of slope 1.
Three lessons emerge. First: without atol there is no way to accept a rounded zero. gives in float64 because is not representable, and with tolerance at is zero. Second: atol has units. With , the default of np.isclose, a normal density evaluated at , worth , passes even without factor and with 151% error. Third: rounding and bugs are often orders of magnitude apart. In float64 rounding errors are below relatively and bugs above , so almost any intermediate works. In float32 the margin narrows to less than an order of magnitude, and no pair gets all thirteen cases right: rounded zeros need and the density needs . The practical conclusion is each test must choose its own tolerance based on its problem’s scale; one global tolerance for the suite does not work.
How much error a correct calculation produces
Tolerances are derived from the calculation rather than chosen by trying values until the test passes. The model case is summation, appearing in almost everything (means, dot products, matrix products, normalizations).
The proof is a short induction on the standard model, done step by step in the guided exercise at the end. The theorem says three useful things for choosing :
- The bound grows with , but is pessimistic. It assumes all rounding errors align in the worst direction. If rounding errors behave as independent centered variables, typical error grows as ; Higham and Mary (2019) turned this into a probabilistic theorem with bounds of form valid with high probability.
- Order matters. Pairwise summation, which splits an array in half, recursively sums each half, and adds results, has bound .
np.sumuses a blocked version when reducing along a contiguous axis, making it much more accurate than a loop. - Cancellation dominates. When is small relative to , relative error can be huge even when absolute error is tiny. This is where is needed, and the theorem indicates which: absolute error is on the order of , that is, times the data scale, not result scale.
import math
import numpy as np
import matplotlib.pyplot as plt
u32 = 2.0**-24 # unidad de redondeo de float32
rng = np.random.default_rng(1)
ns = np.unique(np.logspace(1, 6, 16).astype(int))
err_rec, err_pares = [], []
for n in ns:
x = rng.uniform(0, 1, n).astype(np.float32)
exacta = math.fsum(x.astype(np.float64)) # suma exacta de esos mismos float32
recursiva = float(np.cumsum(x, dtype=np.float32)[-1]) # s = s + x[i], uno detrás de otro
por_pares = float(np.sum(x, dtype=np.float32)) # np.sum: suma por pares
err_rec.append(abs(recursiva - exacta) / exacta)
err_pares.append(max(abs(por_pares - exacta) / exacta, 1e-10)) # 1e-10 = «exacta»
for n, a, b in zip(ns[::3], err_rec[::3], err_pares[::3]):
print(f"n = {n:>7d} recursiva {a:.1e} np.sum {b:.1e} √n·u = {math.sqrt(n) * u32:.1e} (n-1)u = {(n - 1) * u32:.1e}")
plt.loglog(ns, err_rec, "o-", label="suma recursiva (bucle)")
plt.loglog(ns, err_pares, "s-", label="np.sum (por pares)")
plt.loglog(ns, (ns - 1) * u32, "k--", label="cota del peor caso (n − 1)u")
plt.loglog(ns, np.sqrt(ns) * u32, "k:", label="√n · u")
plt.xlabel("n"); plt.ylabel("error relativo en float32"); plt.legend(); plt.show()A detail in the cell is itself a testing lesson: results are converted with float(...) before subtraction. If a np.float32 and a Python float are subtracted, NumPy 2 promotion rules treat float as a “weak” scalar and subtract in float32, so the exact value rounds to float32 before comparison and measured error is 0 precisely when it matters most. A test measuring error in the wrong dtype measures nothing.
Measurements confirm the theory: recursive summation stays far below the worst-case bound, even below , and np.sum barely accumulates error. This gives a rule for choosing tolerances.
Oracles: what do you compare against?
An assertion needs a desired value. In testing terminology, the mechanism identifying the correct result for an input is an oracle, and the oracle problem is particularly hard in scientific software, as Kanewala and Bieman (2014) document in their systematic review: the program exists precisely because we do not know the answer. There are three classic sources of partial oracles.
Common variants are:
- The definition in loops. Vectorization in lesson 5 rewrites loops as operations on whole arrays; the original loop is the natural reference. Slowness does not matter: the test runs it on small inputs.
- Closed-form cases. Inputs with analytically known results: softmax of a constant vector is uniform, regression on noiseless data recovers coefficients, the gradient of is , the standard deviation of is 1. They are cheap and expressive, but cover few points in input space.
- An established library or higher precision. SciPy,
math.fsum(exact sum rounded once), float64 versus float32,mpmathwith 50 digits, or CPU versus GPU. This is called differential testing.
The reference also helps choose tolerances because it shows how far two correct implementations differ. Sometimes the surprise is that the “fast” implementation is less correct than expected:
import numpy as np
def dists_vectorizada(X, Y):
return (X**2).sum(1)[:, None] + (Y**2).sum(1)[None, :] - 2 * X @ Y.T
def dists_bucles(X, Y): # la referencia: la definición, en float64
return np.array([[float(np.sum((x.astype(np.float64) - y.astype(np.float64))**2)) for y in Y] for x in X])
rng = np.random.default_rng(0)
for centro in [0.0, 100.0]:
X = (centro + rng.normal(size=(3, 8))).astype(np.float32)
Y = X + np.float32(1e-3) * rng.normal(size=(3, 8)).astype(np.float32) # puntos muy cercanos
V, R = dists_vectorizada(X, Y), dists_bucles(X, Y)
escala = float((X.astype(np.float64)**2).sum(1).max())
print(f"centro {centro:5.0f}: diagonal vectorizada {np.diag(V)}")
print(f" diagonal de referencia {np.diag(R).astype(np.float32)}")
print(f" error máximo {np.abs(V - R).max():.1e} u·escala = {2**-24 * escala:.1e}\n")The formula is the standard way to vectorize distances (used in lesson 5), but subtracts numbers of size to obtain one of size : catastrophic cancellation. With points centered at 100, distances of come out 0 or even negative, and a subsequent np.sqrt would give NaN. Error is on the scale predicted by theory, so a well-written test uses atol proportional to ; the implementation should clip at 0 (np.maximum(D, 0)) and document that small distances have no correct digits. torch.cdist uses this same trick for large sets and offers compute_mode="donot_use_mm_for_euclid_dist" for direct calculation when precision matters.
Metamorphic relations
What if there is no reference? A numerical solution to a differential equation, model training, a randomized algorithm: often no independent calculation exists for comparison. What often exists are relations between runs: even without knowing , you know how it should change when transforming .
T. Y. Chen and coauthors formulated the idea in 1998 for the oracle problem, and Chen and coauthors’ review (2018) covers its use in compilers, bioinformatics, simulation, and machine learning. Relations most used in numerical code come from problem symmetries:
| Function | Transformation | Required relation |
|---|---|---|
| Pairwise distances | permute rows of with | |
| translate and by the same | unchanged | |
| scale and by | multiplied by | |
| swap and | transposed | |
| softmax | add a constant to all logits | unchanged |
| permute logits | permutes probabilities | |
| Regression with intercept | permute examples | same coefficients |
| add to | same ; increases by | |
| duplicate dataset | same coefficients (without regularization) | |
| Numerical integration | split interval at | |
| Optimizer | rescale loss by | same minimum (with adapted step if method is not invariant) |
| Physical simulation | rotate system | result rotates; energy is conserved |
Conservation (mass, energy, total probability), idempotence ( for projections, normalizations, and sorts), and inverse relations (, such as encode and decode) are also metamorphic in the broad sense. Their great advantage is turning each input into a test without knowing the answer. Their limitation is that they are necessary conditions: an implementation can satisfy every relation written and still be wrong (the zero function is invariant to almost everything).
The next example is a classic ridge-regression bug: add a column of ones for the intercept and regularize every coefficient, including it. The result is reasonable and training error small, but the model is no longer translation-equivariant: the intercept shrinks toward 0.
import numpy as np
def ridge(X, y, lam):
"""Ridge con término independiente (bug: también penaliza el término independiente)."""
A = np.column_stack([X, np.ones(len(X))])
w = np.linalg.solve(A.T @ A + lam * np.eye(A.shape[1]), A.T @ y)
return w[:-1], w[-1]
def ridge_bien(X, y, lam):
"""Correcta: centrar X e y saca el término independiente del problema penalizado."""
mx, my = X.mean(0), y.mean()
Xc, yc = X - mx, y - my
w = np.linalg.solve(Xc.T @ Xc + lam * np.eye(X.shape[1]), Xc.T @ yc)
return w, my - mx @ w
rng = np.random.default_rng(0)
X = rng.normal(size=(50, 3))
y = X @ np.array([1.0, -2.0, 0.5]) + 3 + 0.1 * rng.normal(size=50)
p = rng.permutation(50)
for nombre, f in [("con bug", ridge), ("correcta", ridge_bien)]:
w, b = f(X, y, 5.0)
w2, b2 = f(X, y + 10, 5.0)
relaciones = {
"permutar filas": np.allclose(f(X[p], y[p], 5.0)[0], w),
"y + 10 => b + 10": np.allclose(w2, w) and np.isclose(b2, b + 10),
"X + 1.5 => mismo w": np.allclose(f(X + 1.5, y, 5.0)[0], w),
"2y => 2w": np.allclose(f(X, 2 * y, 5.0)[0], 2 * w),
}
print(f"{nombre:9s}", " ".join(f"{k}: {'sí' if v else 'NO'}" for k, v in relaciones.items()))Observe which relations detect the bug and which do not. Permutation and scaling hold for both versions (the intercept penalty is invariant to both), so those tests see nothing. Both translations expose it. Choosing metamorphic relations means thinking which symmetry each plausible bug would break.
Property tests with Hypothesis
A test with fixed examples checks cases you thought of. Bugs live in cases you did not. Property-based tests reverse the approach: instead of cases, write a statement that must hold for every valid input, and a tool searches for counterexamples.
The idea began with QuickCheck, Claessen and Hughes’s Haskell library (2000). In Python the tool is Hypothesis (MacIver, Hatfield-Dodds, and collaborators, 2019). Useful numerical-code properties are of kinds already seen: invariants and bounds (probabilities sum to 1, distance is nonnegative, ), metamorphic relations, and comparison with a reference on generated inputs. The inputs are new.
Why generating is not the same as sampling
A Hypothesis strategy does not sample from a “natural” distribution: it searches corners. For floats it frequently generates zero, integer values, range extremes, exponents of all kinds, subnormals, and infinity and NaN unless excluded. For arrays, empty shapes, single elements, and size-1 axes. This choice matters enormously. Naive softmax, without subtracting the maximum (seen in lesson 5; its numerical analysis is the log-sum-exp trick), overflows in float64 when any exceeds (the log of the maximum float). With rng.normal(size=5) * 10 this needs a 71-sigma deviation, which will never occur. By contrast, nearly half of representable positive floats exceed 709.78, and a strategy traversing exponents finds them quickly.
The method’s second half, shrinking, makes the result readable. The first failing array is often something like [4.37, -67.0, 2.1e-222, 4.19e+287, 7.37]. Knowing it fails is useful; knowing the minimal failing array is [710.0] is a diagnosis.
The shrinker is greedy descent: it starts from the counterexample and tries transformations simplifying it in a fixed order (fewer elements, values closer to 0, positive before negative, integers before decimals); it accepts the first that still fails and repeats until none works. The result is a local minimum for that order: no one-step simplification still fails. It is not necessarily the only counterexample or the global minimum. In normalization, [0.0] is the simplest representative of a class of failures also including vectors whose norm overflows or underflows to zero, such as [1e200] or [1e-200]: each component’s square leaves float64 range even though the component does not.
Hypothesis shrinks not values directly but the sequence of random decisions that generated them (MacIver and Donaldson describe this “internal” shrinker in a 2020 paper). This lets it shrink any strategy, including ones you build by combining others, without writing a shrinker for each type. The homemade version in the next cell works on values, enough to understand the idea:
import numpy as np
def generar(rng):
"""Array 1-D «a lo Hypothesis»: valores corrientes, enteros, el cero, extremos y diminutos."""
def valor():
r, s = rng.random(), rng.choice([-1.0, 1.0])
if r < 0.30: return round(rng.uniform(-10, 10), 2)
if r < 0.48: return s * float(rng.integers(0, 100))
if r < 0.58: return 0.0
if r < 0.80: return s * 10 ** rng.uniform(0, 6)
if r < 0.92: return s * 10 ** rng.uniform(0, 308)
return s * 10 ** -rng.uniform(0, 320)
return [valor() for _ in range(rng.integers(1, 6))]
def falla(prop, x):
try:
with np.errstate(all="ignore"):
prop(np.array(x))
return False
except AssertionError:
return True
def reducir(prop, x):
"""Reducción voraz: acepta cualquier simplificación que siga fallando, hasta que ninguna lo haga."""
intentos = 0
def sigue(c):
nonlocal intentos
intentos += 1
return falla(prop, c)
cambio = True
while cambio:
cambio = False
i = 0
while i < len(x) and len(x) > 1: # 1. borrar elementos
if sigue(x[:i] + x[i + 1:]):
x, cambio = x[:i] + x[i + 1:], True
else:
i += 1
for i, v in enumerate(x): # 2. simplificar valores
poner = lambda w: x[:i] + [w] + x[i + 1:]
if v != 0 and sigue(poner(0.0)):
x, cambio = poner(0.0), True
continue
if v < 0 and sigue(poner(-v)): # preferimos positivos
x, cambio, v = poner(-v), True, -v
a, s = abs(v), np.sign(v)
if a >= 2: # bisección en el exponente...
lo, hi = 0, int(np.floor(np.log2(a)))
if sigue(poner(s * 2.0**hi)):
x, cambio = poner(s * 2.0**hi), True
while hi - lo > 1:
m = (lo + hi) // 2
if sigue(poner(s * 2.0**m)):
x, hi = poner(s * 2.0**m), m
else:
lo = m
lo, hi = 2**lo, 2**hi
else: # 2^hi ya pasa: el borde está entre 2^hi y a
lo, hi = 2**hi, a
while hi - lo > 1: # ...y después en los enteros
m = (lo + hi) // 2
if sigue(poner(s * float(m))):
x, hi, cambio = poner(s * float(m)), m, True
else:
lo = m
return x, intentos
def comprobar(prop, n_ejemplos=200, semilla=0):
rng = np.random.default_rng(semilla)
for k in range(1, n_ejemplos + 1):
x = generar(rng)
if falla(prop, x):
minimo, intentos = reducir(prop, x)
print(f" falla en el ejemplo {k}: {np.array(x)}")
print(f" reducido en {intentos} intento{'s' if intentos != 1 else ''} a x = {np.array(minimo)}")
return
print(f" {n_ejemplos} ejemplos sin fallos")
def softmax_ingenua(x):
e = np.exp(x)
return e / e.sum()
def prop_softmax(x):
p = softmax_ingenua(x)
assert np.isfinite(p).all() and np.isclose(p.sum(), 1)
def prop_normalizar(x):
y = x / np.linalg.norm(x)
assert np.isclose(np.linalg.norm(y), 1)
for nombre, prop in [("softmax ingenua", prop_softmax), ("normalizar", prop_normalizar)]:
print(nombre)
for semilla in range(3):
comprobar(prop, semilla=semilla)
rng = np.random.default_rng(0)
fallos = sum(falla(prop_softmax, list(rng.normal(size=5) * 10)) for _ in range(10_000))
print("\nfallos de la softmax ingenua con 10 000 arrays normales (σ = 10):", fallos)Three different starts reach the same counterexample, [710.], the smallest integer overflowing in float64. Ten thousand normal arrays find nothing: generation strategy is half the test.
Hypothesis in practice
With Hypothesis, the softmax property is written as follows (this code needs pip install hypothesis or uv add --dev hypothesis; you will run it in the final local lab):
import numpy as np
from hypothesis import given, settings, example, strategies as st
from hypothesis.extra import numpy as hnp
floats = st.floats(allow_nan=False, allow_infinity=False)
@given(hnp.arrays(np.float64, st.integers(1, 10), elements=floats))
def test_softmax_es_una_distribucion(x):
p = softmax(x)
assert np.isfinite(p).all()
np.testing.assert_allclose(p.sum(), 1, rtol=1e-12)
With the naive version, pytest reports:
Falsifying example: test_softmax_es_una_distribucion(
x=array([710.]),
)
The most-used pieces:
- Basic strategies.
st.integers(a, b),st.floats(a, b, allow_nan=..., allow_infinity=..., width=32),st.lists(...),st.tuples(...),st.sampled_from([...]), and combinators.map(f),.filter(pred), andst.builds(Clase, ...).width=32generates float32-representable floats. - Arrays.
hnp.arrays(dtype, shape, elements=...)generates arrays;shapemay be fixed or a strategy such ashnp.array_shapes(min_dims=1, max_dims=3, max_side=8).hnp.floating_dtypes()generates dtypes,hnp.mutually_broadcastable_shapes(num_shapes=2)generates compatible shapes to test broadcasting, andhnp.basic_indices(shape)generates indices. Note: with floating dtype and noelements, arrays includeNaNand infinities. - Dependencies between values.
st.data()permits drawing values inside the test (for example, akdependent on array length);@st.compositedefines custom strategies. - Assumptions.
assume(cond)discards an example failing a precondition. If too many are discarded, Hypothesis warns via a health check: it is better to construct the strategy to generate valid inputs directly. - Explicit examples.
@example(np.array([0.0]))adds a case always tested: a way to turn a discovered counterexample into a regression test. - Configuration.
@settings(max_examples=..., deadline=...); defaults are 100 examples and 200 ms per example, which should be disabled (deadline=None) for numerical functions with variable timing.
Bug hunt: no single test type is enough
You now have four test types: reference, metamorphic, property, and closed-form cases. Does one cover everything? The next interactive presents five functions with subtle bugs of the kind surviving months in a repository, and actually applies all four test types to correct and buggy versions. Implementations run in float32, as a GPU kernel would, and references in float64.
What the table shows:
- The reference is the strongest test, but not infallible. It detects four of five bugs. The fifth, dividing by instead of in a standard deviation with , changes the result by factor , a relative error of . But the correct version, with sequential float32 sums of terms, already has relative error about : the bug is eight times smaller than rounding. For some data rounding and bug push in the same direction, leaving a narrow gap between correct and buggy errors (with several seeds, rtol detects the bug without false alarm), but the gap moves with data: no rtol detects the bug for every seed without false alarms for some. Tuning a tolerance until the test distinguishes versions on specific data is coincidence, not a test.
- The closed-form case catches exactly that bug. The standard deviation of is 1 with and with : with the bug has an 18% effect. Bugs dependent on show up better with small .
- Metamorphic and property tests see little here, but remain essential. A linear layer with a forgotten transpose is still linear, so the linearity relation misses it; with the closed-form case misses it too, because . Only the reference with nonsymmetric detects it. Conversely, MSE broadcasting with to is invariant under simultaneously permuting predictions and labels (the metamorphic test passes), but violates the most basic error property: .
- Each test type has different blind spots, so their combination covers far more than any alone. Designing a suite resembles a good experiment: varied inputs (square and nonsquare, symmetric and nonsymmetric, small and large ) and varied checks.
Testing stochastic code
Samplers, dropout, initializations, data augmentation, randomized algorithms: their output is random and any test on it is fundamentally a hypothesis test. There are two strategies, and both are useful.
Fixed seed. With a seeded generator (np.random.default_rng(1234) or torch.Generator().manual_seed(1234)), stochastic code is deterministic and tested like any other: against a reference, with metamorphic relations, or by checking that the result does not change between versions (regression test). It is fast and never fails spuriously. Its limitation is checking only one realization: it does not say whether the distribution is correct. A sample of 1000 values from a sampler with shifted mean can pass a fixed-seed test if nobody checks the mean.
Statistical threshold. Check a distribution property with a statistic and threshold. If theoretical mean is and variance , the sample mean of independent values has, by the central limit theorem, an approximately normal distribution, and the test
fails with probability even when code is correct. The formula’s “falla si” means “fails if.” This is the test’s type-I error (type-I and type-II errors), which can be controlled but not eliminated.
Proof
(1) Each execution of each test is Bernoulli with parameter ; expectation of the sum is the sum of expectations, , without requiring independence. (2) Chebyshev: . (3) With the bug, , and is the sum of both tails. Power exceeds if , the condition on .
∎In numbers: a threshold of 3 standard deviations has . That seems small, but a suite with 20 such tests run 50 times a day by a team produces spurious failures daily. A test failing for no reason several times a week eventually gets ignored, worse than not having it. Chebyshev’s bound also shows why improvisation is unwise: without normality, “3 sigma” only guarantees . This is the multiple comparisons problem applied to your own suite.
import numpy as np
from math import erf, sqrt
Phi = lambda z: 0.5 * (1 + erf(z / sqrt(2)))
R, n, sesgo = 4000, 1000, 0.06 # 4000 ejecuciones del test; un bug que desplaza la media 0.06σ
rng = np.random.default_rng(0)
z_bien = np.array([rng.normal(size=n).mean() * sqrt(n) for _ in range(R)])
z_bug = np.array([(rng.normal(size=n) + sesgo).mean() * sqrt(n) for _ in range(R)])
d = sesgo * sqrt(n)
for k in [2, 3, 4, 5]:
alfa = 2 * (1 - Phi(k))
potencia = 1 - Phi(k - d) + Phi(-k - d)
print(f"k = {k}: falsas alarmas {np.mean(np.abs(z_bien) > k):.4f} (teoría {alfa:.4f}) "
f"detecta el bug {np.mean(np.abs(z_bug) > k):.3f} (teoría {potencia:.3f})")
beta_z = 1.2816 # z_{0.9}: potencia del 90 %
for k in [3, 5]:
print(f"muestras para detectar el sesgo con probabilidad 0.9 y k = {k}: {((k + beta_z) / sesgo) ** 2:,.0f}")The simulation agrees with theory and shows the tradeoff: raising the threshold from 3 to 5 lowers false alarms from to , but with the same samples power against that bias falls from 13% to 0.1%. Detecting it with probability 0.9 needs about 5100 samples with and 11 000 with : a little over twice as many, and generating 11 000 normals takes less than a millisecond. Rule of thumb:
For stochastic code, combine a fast deterministic fixed-seed test in the suite for every change with statistical tests using a demanding threshold (, or corrected for the number of tests) and sufficient samples for required power, marked slow and with their calculated false-alarm rate written in a comment.
Fix the seed of those statistical tests too and change it only deliberately: then failures are reproducible, and false-alarm rate refers to what happens when the seed changes, not each run. Lessons on seeding and generators and streams explain giving each test its own random stream independent of execution order; the rng fixture in the lab below derives the seed from the test identifier.
A fast suite
A suite taking ten minutes is not run before every change, and one not run detects nothing. The usual organization separates three levels:
- Fast (seconds): unit, reference on small inputs, metamorphic, and property tests with few examples. Run on each change, including before each commit.
- Slow (minutes): large inputs, statistical tests with many samples, Hypothesis with thousands of examples, a short end-to-end training run. Marked
@pytest.mark.slowand run in continuous integration or before merging. - GPU: marked
@pytest.mark.gpuand skipped automatically without CUDA.
Configuration lives in the project’s pyproject.toml (lesson 1):
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-ra --strict-markers"
markers = [
"slow: tarda más de un segundo; excluir con -m 'not slow'",
"gpu: necesita CUDA",
]
filterwarnings = ["error::RuntimeWarning"]
The last line deserves attention: it turns every RuntimeWarning into an error, and in NumPy these warn of overflow, division by zero, and invalid operations preceding NaN. A test causing overflow encountered in exp fails even if nobody checks the result. If a test should produce a warning, declare it with pytest.warns. (Warnings depend on the processor signaling floating-point exceptions; WebAssembly does not, so NumPy in browser cells does not emit them. Tests depending on them must run locally.)
To run fast tests before every commit, use a local pre-commit hook (covered in more detail in quality automation):
repos:
- repo: local
hooks:
- id: tests-rapidos
name: tests rápidos
entry: pytest -m "not slow and not gpu" -x -q
language: system
pass_filenames: false
types: [python]
Three more options help keep the suite fast: --durations=10 lists slowest tests, -x stops at the first failure, and pytest-xdist (-n auto) distributes tests across cores. Hypothesis configuration profiles permit few examples locally and many in continuous integration without changing tests.
The next lab combines everything on functions from earlier lessons: pairwise distances, softmax, top-k, and group aggregation. Write a small library, conftest.py with markers, an rng fixture per test and Hypothesis profiles, a reference and metamorphic test file (with one slow and one GPU test), and another of Hypothesis properties. If Hypothesis is not installed in your environment, that module is skipped with pytest.importorskip and appears in the report; install it with uv add --dev hypothesis.
import os, sys, io, textwrap, tempfile, contextlib
import numpy as np
import pytest
d = tempfile.mkdtemp(prefix="atlas_tests_")
def escribe(nombre, codigo):
with open(os.path.join(d, nombre), "w", encoding="utf-8") as f:
f.write(textwrap.dedent(codigo))
# 1. la librería que se va a testear (funciones de las lecciones 5 y 6)
escribe("atlas_lib.py", '''
import numpy as np
def pairwise_sq_dists(X, Y):
"""D[i, j] = ||X[i] - Y[j]||^2 sin bucles: ||x||^2 + ||y||^2 - 2 x.y"""
D = (X**2).sum(1)[:, None] + (Y**2).sum(1)[None, :] - 2 * X @ Y.T
return np.maximum(D, 0) # la cancelación puede dejar valores como -1e-13
def softmax(x, axis=-1):
z = x - x.max(axis=axis, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=axis, keepdims=True)
def topk(x, k):
idx = np.argpartition(-x, k - 1, axis=-1)[..., :k]
vals = np.take_along_axis(x, idx, -1)
orden = np.argsort(-vals, axis=-1, kind="stable")
return np.take_along_axis(vals, orden, -1), np.take_along_axis(idx, orden, -1)
def groupby_sum(claves, valores):
grupos, cod = np.unique(claves, return_inverse=True)
return grupos, np.bincount(cod, weights=valores, minlength=len(grupos))
''')
# 2. configuración compartida: marcas, una semilla por test y perfiles de Hypothesis
escribe("conftest.py", '''
import zlib
import numpy as np
import pytest
def pytest_configure(config):
config.addinivalue_line("markers", "slow: tarda más de un segundo")
config.addinivalue_line("markers", "gpu: necesita CUDA")
def pytest_collection_modifyitems(config, items):
try:
import torch
hay_cuda = torch.cuda.is_available()
except ImportError:
hay_cuda = False
if not hay_cuda:
saltar = pytest.mark.skip(reason="no hay CUDA")
for item in items:
if "gpu" in item.keywords:
item.add_marker(saltar)
@pytest.fixture
def rng(request):
"""Generador propio de cada test: distinto entre tests, idéntico entre ejecuciones."""
return np.random.default_rng(zlib.crc32(request.node.nodeid.encode()))
try:
from hypothesis import settings
settings.register_profile("rapido", max_examples=60, deadline=None)
settings.register_profile("ci", max_examples=1000, deadline=None, derandomize=True)
settings.load_profile("rapido")
except ImportError:
pass
''')
# 3. referencias lentas pero obvias y relaciones metamórficas
escribe("test_referencia.py", '''
import numpy as np
import pytest
from atlas_lib import pairwise_sq_dists, softmax, topk, groupby_sum
EPS = np.finfo(np.float64).eps
def dists_bucles(X, Y):
return np.array([[sum((a - b) ** 2 for a, b in zip(x, y)) for y in Y] for x in X])
@pytest.mark.parametrize("n, m, d", [(1, 1, 1), (5, 3, 2), (7, 7, 16)])
def test_dists_referencia(rng, n, m, d):
X, Y = rng.normal(size=(n, d)), rng.normal(size=(m, d))
# la cancelación de ||x||^2 + ||y||^2 - 2 x.y deja un error absoluto del orden de eps * escala
escala = (X**2).sum(1).max() + (Y**2).sum(1).max()
np.testing.assert_allclose(pairwise_sq_dists(X, Y), dists_bucles(X, Y), rtol=1e-12, atol=16 * EPS * escala)
def test_dists_metamorficas(rng):
X, Y = rng.normal(size=(6, 4)), rng.normal(size=(5, 4))
D = pairwise_sq_dists(X, Y)
p = rng.permutation(6)
np.testing.assert_allclose(pairwise_sq_dists(X[p], Y), D[p]) # permutar filas
np.testing.assert_allclose(pairwise_sq_dists(Y, X), D.T) # intercambiar
np.testing.assert_allclose(pairwise_sq_dists(3 * X, 3 * Y), 9 * D) # escalar
v = rng.normal(size=4)
np.testing.assert_allclose(pairwise_sq_dists(X + v, Y + v), D, atol=1e-12) # trasladar
@pytest.mark.parametrize("forma", [(5,), (3, 4), (2, 3, 6)])
def test_softmax_relaciones(rng, forma):
x = rng.normal(size=forma) * 5
p = softmax(x)
np.testing.assert_allclose(p.sum(-1), 1, rtol=1e-13)
np.testing.assert_allclose(softmax(x + 100.0), p, rtol=1e-12, atol=1e-15) # invariancia
np.testing.assert_allclose(softmax(x[..., ::-1]), p[..., ::-1]) # equivariancia
def test_topk_frente_a_ordenar(rng):
x = rng.normal(size=(4, 50))
vals, idx = topk(x, 5)
np.testing.assert_array_equal(vals, -np.sort(-x, axis=-1)[:, :5])
np.testing.assert_array_equal(np.take_along_axis(x, idx, -1), vals)
def test_groupby_frente_a_diccionario(rng):
claves = rng.integers(0, 6, size=200)
valores = rng.normal(size=200)
ref = {}
for c, v in zip(claves, valores):
ref[c] = ref.get(c, 0.0) + v
grupos, sumas = groupby_sum(claves, valores)
np.testing.assert_allclose(sumas, [ref[g] for g in grupos], rtol=1e-12)
@pytest.mark.slow
def test_dists_grande_float32(rng):
X = rng.normal(size=(2000, 64)).astype(np.float32)
D = pairwise_sq_dists(X, X)
X64 = X.astype(np.float64)
D64 = pairwise_sq_dists(X64, X64)
escala = 2 * (X64**2).sum(1).max()
np.testing.assert_allclose(D, D64, rtol=1e-5, atol=32 * np.finfo(np.float32).eps * escala)
@pytest.mark.gpu
def test_dists_gpu_frente_a_numpy(rng):
import torch
X = rng.normal(size=(500, 32)).astype(np.float32)
Dt = torch.cdist(torch.from_numpy(X).cuda(), torch.from_numpy(X).cuda()).pow(2).cpu()
escala = 2 * float((X.astype(np.float64)**2).sum(1).max())
torch.testing.assert_close(Dt, torch.from_numpy(pairwise_sq_dists(X, X)),
rtol=1e-4, atol=64 * float(np.finfo(np.float32).eps) * escala)
''')
# 4. propiedades con Hypothesis sobre arrays generados
escribe("test_propiedades.py", '''
import numpy as np
import pytest
hypothesis = pytest.importorskip("hypothesis") # si no está instalado, el módulo se salta
from hypothesis import given, strategies as st
from hypothesis.extra import numpy as hnp
from atlas_lib import pairwise_sq_dists, softmax, topk
finitos = st.floats(-1e3, 1e3, allow_nan=False, allow_infinity=False)
matrices = hnp.arrays(np.float64, hnp.array_shapes(min_dims=2, max_dims=2, max_side=8), elements=finitos)
@given(matrices)
def test_dists_no_negativas_y_simetricas(X):
D = pairwise_sq_dists(X, X)
escala = 4 * (X**2).sum(1).max()
# residuo de la cancelación, más tiny: con subnormales el redondeo deja de ser relativo
tol = 64 * np.finfo(float).eps * escala + np.finfo(float).tiny
assert (D >= 0).all()
np.testing.assert_allclose(D, D.T, atol=tol) # X @ X.T no es exactamente simétrica
assert np.abs(np.diag(D)).max() <= tol
@given(hnp.arrays(np.float64, hnp.array_shapes(min_dims=1, max_dims=3, max_side=6),
elements=st.floats(-1e4, 1e4)))
def test_softmax_es_una_distribucion(x):
p = softmax(x)
assert np.isfinite(p).all() and (p >= 0).all()
np.testing.assert_allclose(p.sum(-1), 1, rtol=1e-12)
@given(hnp.arrays(np.float64, st.integers(1, 30), elements=finitos), st.data())
def test_topk_son_los_mayores(x, data):
k = data.draw(st.integers(1, x.size), label="k")
vals, idx = topk(x, k)
assert (np.diff(vals) <= 0).all() # en orden descendente
assert len(set(idx.tolist())) == k # sin índices repetidos
assert vals[-1] >= np.delete(x, idx).max(initial=-np.inf) # nadie fuera es mayor
''')
# 5. ejecución: primero la batería rápida, después los lentos y los de GPU
anterior = os.getcwd()
os.chdir(d)
sys.path.insert(0, d)
try:
for titulo, args in [("rápidos", ["-m", "not slow and not gpu"]),
("lentos y GPU", ["-m", "slow or gpu", "--durations=2"])]:
salida = io.StringIO()
with contextlib.redirect_stdout(salida):
codigo = pytest.main(["-q", "-p", "no:cacheprovider", "-rs", *args])
print(f"--- {titulo}: código de salida {int(codigo)}")
print(salida.getvalue().strip())
finally:
os.chdir(anterior)
sys.path.remove(d)npm run lab and open the connection link.Some lab details are worth copying into your projects. Distance tolerances are absolute and proportional to the scale because of the cancellation seen earlier. References share no code with the library: the distance reference is the definition with a loop, and aggregation uses a dictionary. The distance property needs atol even to check symmetry, because X @ X.T is not exactly symmetric and the cancellation residual is on the order of ; it also needs an absolute floor, np.finfo(float).tiny, because Hypothesis generates rows like [9.3e-162], whose square is subnormal and no longer has relative error bounded by . Both corrections came from real Hypothesis counterexamples while writing this suite. The top-k property test checks the three defining properties (order, no repeats, and nothing outside exceeds the last) instead of comparing to a sort, making it valid with ties. The rng fixture derives the seed from the test identifier: each test has its own random stream, and adding or reordering tests does not change other tests’ data.
Common mistakes
Exercises
rtol = 1e-5 and atol = 1e-8, what is the maximum difference accepted by np.testing.assert_allclose(a, d, rtol=1e-5, atol=1e-8) when the desired value is ?test_normalizar fails with x=array([0.]). Which conclusion is correct?More than one answer may be correct.
my_isclose(a, b, rtol=1e-5, atol=1e-8, equal_nan=False) with np.isclose semantics (except the pathological case where atol + rtol * abs(b) overflows to infinity): accept scalars or arrays (with broadcasting) and return a Boolean array with elementwise. Infinities are close only to infinity of the same sign (even if the formula says otherwise), NaN is never close to anything unless equal_nan=True and both are NaN, and it must emit no warnings. Tests compare with np.isclose at edge cases.import numpy as np
def my_isclose(a, b, rtol=1e-5, atol=1e-8, equal_nan=False):
a = np.asarray(a, dtype=float)
b = np.asarray(b, dtype=float)
# tu código: casos finitos con la fórmula; infinitos; NaN
return np.abs(a - b) <= atol + rtol * np.abs(b)lse_ingenua and lse_estable calculate . Write three parts of a property test, run by the tests in a loop of 300 Hypothesis-style examples: gen_x(rng), returning a 1-D float array of length 1 to 8 capable of reaching the overflow region (tests pass it a np.random.Generator); prop_acotada(lse, x), using assert to check that lse(x) is finite and lies between and with small relative tolerance; and prop_traslacion(lse, x, c), checking with tolerance proportional to the scale of and . Your properties must fail with the naive version, always pass with the stable one (tests use ), and reject incorrect implementations.import numpy as np
def lse_ingenua(x):
return np.log(np.sum(np.exp(x)))
def lse_estable(x):
m = np.max(x)
return m + np.log(np.sum(np.exp(x - m)))
def gen_x(rng):
# tu código: arrays 1-D de longitud 1 a 8 que lleguen a la zona de desbordamiento
return rng.normal(size=rng.integers(1, 9))
def prop_acotada(lse, x):
# tu código: finito y entre max(x) y max(x) + log(n), con tolerancia
assert np.isfinite(lse(x))
def prop_traslacion(lse, x, c):
# tu código: lse(x + c) = lse(x) + c, con tolerancia
passStep 1 of 3. What closed expression does have?
Summary
- pytest discovers
test_*functions, rewritesassertto explain failures, and injects fixtures by argument name.parametrizemultiplies cases, markers (slow,gpu) and-m/-kselect what to run, andconftest.pyshares fixtures and configuration by directory. - Approximate equality is : a cone closing at 0 plus a band. comes from of the computation dtype times error growth (typical to worst-case ) and conditioning; from times data scale. Libraries’ defaults differ and none is neutral.
- A reference must be obvious and independent; sharing the formula shares the bug. Closed-form cases catch what the reference cannot distinguish from rounding.
- Metamorphic relations (permuting, translating, scaling, reflecting, conservation, idempotence) test without an oracle; each sees bugs breaking its symmetry.
- Property tests generate inputs seeking extremes and shrink the first failure to a minimal counterexample. In Python use Hypothesis with
hypothesis.extra.numpy; save each counterexample as@example. - A stochastic test is a hypothesis test: fixed seed for the fast suite and, for the distribution, thresholds with calculated false-alarm rate () and sufficient sample size for desired power.
- No one test type suffices: combine types, use shapes with distinct axes, and check that every test can fail.