Test Case Design and Edge Case Analysis Questions
Systematically deriving the cases, inputs, and conditions most likely to expose defects. Covers formal test-design techniques (equivalence partitioning, boundary value analysis, decision tables, state transitions, and pairwise/combinatorial design) and writing clear, maintainable test cases with documented expected results. Also covers the edge-case mindset: boundary conditions, invalid and unexpected inputs, corner cases, and the attention to detail that anticipates failures when validating complex behavior.
Design a fuzz-testing harness for your inference API that detects crashes, hangs and logical failures when given unexpected inputs (malformed JSON, extra fields, very long strings, extreme numeric values, wrong types). Describe mutation strategies (bit flips, boundary values), generation vs mutation fuzzers, how to measure coverage of code paths, how to reduce flakiness, and how to integrate the harness into CI.
Sample Answer
Direct answer
A fuzz-testing harness for an ML (machine learning) inference API applies the same generic edge-case-discovery technique as parser fuzzing (mutation, coverage feedback, crash triage) to the API's REQUEST SURFACE rather than its model weights, targeting three failure classes the question names explicitly: hard crashes (the process dies), hangs (a request that never returns, e.g. a pathological input driving an unbounded loop in preprocessing), and logical failures (the request completes and returns 200, but produces a nonsensical or unsafely-formed response), using malformed JSON, extra fields, very long strings, extreme numeric values, and wrong types as the mutation dimensions.
Structured elaboration
- Generation vs mutation fuzzers: a mutation-based fuzzer starts from real, valid request payloads (captured from production logs or hand-written examples) and perturbs them; a generation-based fuzzer builds requests from a schema (e.g. the API's OpenAPI/JSON-schema definition) without needing real seed examples, which is the more practical starting point for an inference API, because the request schema is usually well-defined even before real traffic exists, and generation naturally produces the "extra fields" and "wrong types" cases the question names by construction (generate a request, then add an undeclared field, or substitute a field's declared type for an incompatible one).
- Mutation strategies (bit flips, boundary values) mapped onto the five named request-shape categories: malformed JSON is produced by bit-flipping a byte inside an otherwise valid payload, or by truncating it at a random offset, or by corrupting a structural character (a brace, a comma); extra fields are produced by injecting undeclared keys into an otherwise valid payload, testing whether the API's deserializer strictly rejects unknown fields or silently (and possibly dangerously) passes them through to downstream logic; very long strings and extreme numeric values are boundary-value mutations applied specifically to fields the model consumes (e.g. a text field mutated to megabytes of repeated tokens, or a numeric feature field mutated to
1e308,-1,0, orNaN-equivalent JSON representations); wrong types substitutes a string where a number is expected and vice versa, which is the case most likely to reveal whether the API validates against its schema BEFORE invoking the model or lets a type-confused value flow into featurization code that assumes a specific type. - Measuring coverage of code paths: instrument the request-handling and preprocessing/featurization code (not the model's internal weights, which are not meaningfully "covered" by input fuzzing in the traditional sense) with the same line/branch coverage tooling used for any Python service (e.g.
coverage.py), and track which validation and preprocessing branches a growing corpus of mutated requests has exercised; a mutation corpus that only ever reaches the "happy path" featurization code and never the type-mismatch or out-of-range handling branches indicates the fuzzer's mutation strategy needs to be more aggressive on those specific fields, not that the API is well-tested. - Reducing flakiness in the harness itself (a harness-design concern here, not diagnosing an already-flaky test suite): pin the inference call's non-determinism sources before fuzzing (fix random seeds in any stochastic decoding path, disable GPU-nondeterministic kernels or pin to CPU execution for the harness run, and add an explicit request timeout so a hang is detected deterministically rather than the harness itself hanging indefinitely), so that a crash or hang found by the fuzzer reproduces reliably when replayed, which is a prerequisite for the crash to be triage-able at all.
- CI (continuous integration) integration: run a short, time-boxed fuzzing pass (a fixed number of mutated requests, not a fixed wall-clock duration, so the check is reproducible across CI runners of different speeds) against every change to the request-handling or featurization code, and separately run the full campaign continuously as a longer-lived background job rather than gating every commit, mirroring how coverage-guided fuzzing is normally integrated for any parser or request-handling surface.
Worked example: malformed JSON feature payload
For a concrete inference endpoint accepting {"features": {"age": 34, "income": 52000.0, "region": "west"}}, the mutation corpus would include: {"features": {"age": "34"}} (wrong type: string where a number is expected, testing whether the schema validator rejects it before it reaches feature encoding); {"features": {"age": 34, "income": 52000.0, "region": "west", "__proto__": "x"}} (an extra, potentially dangerous field name, testing that unknown keys are rejected or ignored rather than passed to an unsafe deserializer); {"features": {"age": 999999999999, "income": -1e308}} (extreme numeric values, testing whether featurization clamps, rejects, or silently produces a garbage prediction on out-of-distribution numeric input); and a truncated payload {"features": {"age": 34, "inc (malformed JSON, testing that the API returns a clean 400-class error rather than a 500 or a hang). Each of these targets a different point in the request pipeline: schema validation, key allow-listing, feature-range validation, and JSON parsing itself, so a single fuzzing pass that only exercises one of these four is not exercising the full pipeline the question asks about.
Trade-offs and pitfalls
The most common wrong turn is fuzzing only the JSON structure (malformed JSON, extra fields) and never the semantic content of well-formed-but-extreme values, which misses the logical-failure class the question explicitly names: a request that is syntactically perfect JSON with a region value the model was never trained on, or an income value far outside the training distribution, will not crash or hang, but can produce a confidently wrong prediction, which is arguably the most dangerous of the three failure classes because nothing in the API's error handling signals it. The other pitfall is fuzzing the LIVE model in a way that is not reproducible (letting decoding randomness vary run to run), which makes every "logical failure" finding impossible to confirm was actually caused by the mutated input rather than ordinary model stochasticity; pinning determinism in the harness, as described above, is a prerequisite for the whole exercise to produce trustworthy findings.
Implement a numerically stable softmax function in Python that handles very large and very small logits, and write two unit tests: one for extremely large positive values and one for extremely negative values. Explain briefly why your implementation avoids overflow/underflow.
Sample Answer
Direct answer
A numerically stable softmax subtracts the maximum logit from every logit before exponentiating. This shifts the largest value to exactly 0 (so its exponential is 1, never overflowing) while shifting every other value further negative (so their exponentials underflow toward 0 rather than the numerator and denominator both blowing up to inf). The shift does not change the mathematical result because it cancels in the normalization.
Structured elaboration
softmax(x)i=∑jexjexi=∑jexj−mexi−m,m=maxjxj
The middle and right expressions are algebraically identical for any constant m, since exi−m=exi⋅e−m and the e−m factor cancels between numerator and denominator. Choosing m=maxjxj is what makes the computation, not just the math, stable:
- Every shifted value xi−m≤0, so every exi−m∈(0,1]: the exponential can never overflow, no matter how large the raw logits are.
- The largest shifted value is exactly 0, so at least one term in the denominator sum is exactly 1, meaning the denominator can never underflow to 0 (which would otherwise produce a
0/0 = NaN). - The relative ratios between probabilities are preserved exactly, since the shift is a genuine algebraic identity, not an approximation.
Worked example (executed)
import numpy as np
def stable_softmax(logits):
logits = np.asarray(logits, dtype=np.float64)
shifted = logits - np.max(logits)
exps = np.exp(shifted)
return exps / np.sum(exps)
def naive_softmax(logits):
logits = np.asarray(logits, dtype=np.float64)
exps = np.exp(logits)
return exps / np.sum(exps)
def test_extremely_large_positive():
logits = np.array([1000.0, 1001.0, 999.0])
p = stable_softmax(logits)
assert np.allclose(p.sum(), 1.0)
assert np.argmax(p) == 1 # the 1001 logit should dominate
def test_extremely_large_negative():
logits = np.array([-1000.0, -1001.0, -999.0])
p = stable_softmax(logits)
assert np.allclose(p.sum(), 1.0)
assert np.argmax(p) == 2 # the -999 logit (largest, i.e. least negative) should dominate
Driver that actually runs both functions and prints the results (the two test_* functions above only assert; this is what produced the transcript below):
for label, logits in [("large positive", [1000.0, 1001.0, 999.0]), ("large negative", [-1000.0, -1001.0, -999.0])]:
arr = np.array(logits)
try:
r = naive_softmax(arr)
print(f"{label}: naive_softmax -> {r}, sum={r.sum()}")
except Exception as e:
print(f"{label}: naive_softmax raised {type(e).__name__}: {e}")
s = stable_softmax(arr)
print(f"{label}: stable_softmax -> {s}, sum={s.sum()}")
Running naive_softmax and stable_softmax against the same two inputs (verified this session, numpy 2.4.5, Python 3):
Test 1 (logits = [1000, 1001, 999]):
naive_softmax: RuntimeWarning: overflow encountered in exp; RuntimeWarning: invalid value encountered in divide
result = [nan nan nan] sum = nan
stable_softmax: [0.24472847 0.66524096 0.09003057] sum = 0.9999999999999999
Test 2 (logits = [-1000, -1001, -999]):
naive_softmax: RuntimeWarning: invalid value encountered in divide
result = [nan nan nan] sum = nan
stable_softmax: [0.24472847 0.09003057 0.66524096] sum = 0.9999999999999999
naive_softmax genuinely fails both directions, but NumPy's default float error handling does not raise an exception for either: exp(1000) and exp(1001) overflow a 64-bit float (double's max representable exponent is around e^709) to inf, which NumPy reports as a RuntimeWarning (not a FloatingPointError, since NumPy's default seterr mode is 'warn', not 'raise') and the subsequent inf / inf division produces nan for every entry; exp(-1000) underflows to exactly 0.0 for all three values, so the normalization becomes 0/0 = NaN there too, also surfaced only as a RuntimeWarning. A caller relying on an exception to detect this failure would be silently handed a [nan, nan, nan] array instead, which is itself a reason to prefer the numerically stable version outright rather than trying to catch the naive version's failure after the fact. stable_softmax produces the same relative ranking both times, and both sums land at 0.9999999999999999 rather than exactly 1.0, an honestly-reported floating-point rounding artifact, not a bug (16 significant digits of precision, off in the 16th digit).
Complexity and edge cases
stable_softmax is O(n) time and O(n) space for a 1D input of length n (one pass to find the max, one to exponentiate, one to sum and normalize); the batched 2D case is O(n*m) for a batch of m rows of length n, with the max/sum reductions taken per-row. Edge cases: extremely large positive logits (would overflow the naive version), extremely large negative logits (would underflow the naive version to NaN), a single-element input (softmax of one logit must return exactly 1.0), and a batch where different rows have very different logit magnitudes (the per-row max must not be shared across rows).
Trade-offs & pitfalls
The most common mistake is computing max once outside a batch loop and reusing it for every row; for a batch of logit vectors, the max must be taken per-row (axis=1, keepdims=True), not globally, or rows with smaller logits will be shifted incorrectly. A second pitfall is testing "large" values that aren't actually large enough to trigger the failure (e.g. logits of 10 or 20 won't overflow float64 on their own), the test has to use values that provably exceed float64's safe exponent range to be a real regression guard rather than a test that would pass even against the naive, unstable implementation.
Design a test plan to validate an int8-quantized transformer model for edge device inference. Include functional correctness tests, numeric accuracy drift thresholds, edge inputs (too short, too long), dynamic shape handling, operator availability checks, calibration dataset selection, and acceptance criteria for release on target hardware.
Sample Answer
Direct answer
A test plan for an int8-quantized transformer model has to validate two different things that are easy to conflate: functional correctness (does the quantized model still run and produce sane outputs across the same input space as the float model) and numeric accuracy drift (how much did quantization degrade prediction quality, and is that degradation within an agreed threshold). Edge inputs, dynamic-shape handling, and operator availability are functional-correctness risks specific to the edge-device deployment target; drift thresholds and calibration-dataset selection are accuracy risks specific to quantization itself; both need dedicated test cases, not one combined pass/fail check.
Structured elaboration
- Functional correctness tests: run the quantized model against the same test inputs as the float32 baseline and confirm it executes without error, on the TARGET hardware or its accurate emulator, not just on the development machine, since operator support and numeric behavior can differ by device.
- Numeric accuracy drift thresholds: measure per-layer or end-to-end output deviation (not just final-task accuracy, which can mask a large deviation on an unlucky input that happens not to flip a classification decision) against a defined tolerance, agreed with the team BEFORE testing starts, not fit retroactively to whatever number the quantized model happens to produce.
- Edge inputs: sequences at or near the model's minimum and maximum supported length (too short: does the model handle it without crashing on padding/masking logic; too long: does truncation behave as documented), plus activation-distribution edge cases like all-zero or unusually large-magnitude inputs, which stress the quantization scale factor itself.
- Dynamic shape handling: if the deployment target supports variable batch size or sequence length, test the actual shape-inference and buffer-allocation paths at multiple shapes, not just the shape used during quantization calibration; a common real bug is a quantized model that only works at the exact shape it was calibrated on.
- Operator availability checks: confirm every operator in the model graph has an int8-quantized kernel available on the target hardware; an operator that silently falls back to float32 (a common runtime behavior in several inference engines) can produce a technically-working model that is far slower than expected without any test catching it unless operator dtype is explicitly asserted per-node.
- Calibration dataset selection: the calibration set (used to determine per-tensor or per-channel quantization scale factors) must be REPRESENTATIVE of production input distribution; a calibration set that is too small, or skewed away from the actual deployment traffic, produces scale factors tuned to the wrong range and silently worse accuracy than a properly calibrated model would show, even though nothing in the pipeline errors.
Worked example
Quantization drift measured directly (NumPy, seed=7, symmetric per-tensor int8 quantization simulating a post-LayerNorm activation tensor of 2,048 values):
import numpy as np
rng = np.random.default_rng(seed=7)
x = rng.normal(loc=0.0, scale=1.0, size=2048).astype(np.float32)
def quantize_int8_symmetric(values):
scale = np.max(np.abs(values)) / 127.0
q = np.clip(np.round(values / scale), -127, 127).astype(np.int8)
return q, scale
q, scale = quantize_int8_symmetric(x)
x_dq = q.astype(np.float32) * scale
Actual measured results: scale = 0.025602, max absolute dequantization error = 0.012798, mean absolute error = 0.006426, MSE (mean squared error) = 0.00005515. These are the numbers a drift-threshold test would assert against a pinned tolerance (e.g. "max absolute error must stay under 0.02 on the calibration-representative distribution").
Two edge inputs were tested directly against the same quantizer, real findings, not hypothesized:
- All-zero activation (16 zeros): produces
scale = 0.0. Dividing by that scale raisesRuntimeWarning: invalid value encountered in divide(a0/0), which produces transientNaNvalues in the intermediate float array; but casting that intermediateNaNarray toint8(as the quantizer's last step does) silently converts everyNaNto0, so the actual returnedqarray is[0, 0, 0, ...], notNaN, and the final dequantized output is[0.0, 0.0, 0.0, ...], confirmed withnp.isnan(dequantized).any() == False. This is arguably a worse bug than the NaN a first read might expect: the function returns a plausible-looking, silently wrong all-zero result with only a runtime warning (easy to suppress or miss in a production log) rather than a loud, unmistakable failure, exactly the kind of edge input a test plan exists to catch before it reaches production, where an all-zero activation (e.g. from a masked or padded position) is a realistic occurrence, not a contrived one. - Outlier-dominated tensor (999 values drawn from the same
N(0,1)distribution as the main worked example, seed=7, plus a single value of 50.0 appended): measured directly, the typical-values-only scale (no outlier) is 0.025602, matching the main example's scale exactly since it's the same 999-sample draw; adding the single 50.0 outlier inflates the shared per-tensor scale to 0.393701 (simply50.0 / 127), a 15.4x increase, and the mean absolute dequantization error on the 999 OTHER, non-outlier values rises to 10.4% of their standard deviation (up from a baseline near the main example's 0.006426 mean absolute error). A single extreme activation value degrades the precision of every other value sharing that tensor's quantization scale; this is a well-documented real phenomenon in large transformer models (activation outliers), which is why per-channel (rather than per-tensor) quantization or outlier-aware calibration is often required in practice, not just a generic scale computation. (Correction: an earlier draft of this answer claimed a 136x scale inflation and a 76.6%-of-stddev error, evidently from an unshown, different typical-value distribution; the numbers above are the actual measured result of running the exactquantize_int8_symmetricfunction shown earlier against aN(0,1)-seed=7 draw, reproducible end to end.)
Acceptance criteria for release: functional tests pass 100% on target hardware across the full edge-input and dynamic-shape matrix (no crashes, no silent float32 fallback on any operator); accuracy drift stays within the pre-agreed threshold on a held-out, production-representative evaluation set, not just the calibration set itself (testing only on calibration data overstates achieved accuracy, since the model was tuned to that exact distribution); and the all-zero and outlier edge cases specifically are either handled with a defined fallback (e.g. a scale floor to avoid division by zero) or explicitly documented as an unsupported input class with upstream validation preventing it from reaching the model.
Trade-offs and pitfalls
The most common mistake is validating quantization accuracy only with end-task metrics (like classification accuracy) on a clean test set, which can look nearly unchanged even when per-tensor drift is large, because task accuracy is often robust to small activation shifts right up until it isn't; direct numeric drift measurement catches degradation before it becomes a task-level failure. A second mistake is calibrating on a small, convenient dataset (e.g. the first 100 examples from a training set) rather than one that reflects the actual range of production inputs, including outliers, which the worked example shows can distort the shared scale factor for an entire tensor. Finally, treating "it exports and runs" as sufficient functional validation misses the operator-fallback risk: a model that silently runs slower on the target device because one operator quietly fell back to float32 still "works," but violates the actual reason for quantizing in the first place.
Implement a Python function robust_mean(values: List[Optional[float]]) -> float that computes the arithmetic mean while ignoring None and NaN. It should raise ValueError if no valid numbers are present. Consider numerically stable accumulation to reduce overflow risk when values have large magnitude; mention algorithm choice (Kahan or incremental). State complexity, behavior on infinities, and assumptions about IEEE floats.
Sample Answer
Direct answer
robust_mean should use Kahan summation to control floating-point accumulation error on large or high-magnitude inputs, skip None and NaN values while counting only the valid ones, raise ValueError when no valid numbers remain, and treat infinities as a special case rather than letting them flow through Kahan's compensation arithmetic, which silently produces NaN if left unguarded.
Structured elaboration and worked example (executed)
import math
from typing import List, Optional
def robust_mean(values: List[Optional[float]]) -> float:
total = 0.0
compensation = 0.0
count = 0
saw_pos_inf = False
saw_neg_inf = False
for v in values:
if v is None:
continue
if isinstance(v, float) and math.isnan(v):
continue
if v == float('inf'):
saw_pos_inf = True; count += 1; continue
if v == float('-inf'):
saw_neg_inf = True; count += 1; continue
y = v - compensation
t = total + y
compensation = (t - total) - y
total = t
count += 1
if count == 0:
raise ValueError("no valid numbers present")
if saw_pos_inf and saw_neg_inf:
return float('nan')
if saw_pos_inf:
return float('inf')
if saw_neg_inf:
return float('-inf')
return total / count
The infinity bug this design deliberately avoids
A first implementation without the explicit infinity branches was tried and FAILED at execution: calling robust_mean([float('inf'), 1, 2]) returned nan instead of inf. The root cause is that Kahan's compensation step computes (t - total) - y; the moment an infinite value flows through it, t becomes inf, and inf - inf (inside that compensation formula) evaluates to nan, which then poisons every subsequent element because compensation stays nan for the rest of the loop. The fix shown above tracks infinities OUTSIDE the Kahan accumulator entirely and reasons about them algebraically afterward (both signs present -> nan, since +inf and -inf together have no defined mean; one sign present -> that infinity dominates the mean regardless of the finite values).
Demonstrated numerical stability gain (executed, not asserted)
N = 10_000_000
vals = [0.1] * N
naive_total = 0.0
for v in vals:
naive_total += v
naive_mean = naive_total / N
kahan_mean = robust_mean(vals)
print("naive_running_mean =", repr(naive_mean))
print("naive abs error from 0.1 =", abs(naive_mean - 0.1))
print("kahan robust_mean =", repr(kahan_mean))
print("kahan abs error from 0.1 =", abs(kahan_mean - 0.1))
Actual output:
naive_running_mean = 0.09999999998389754
naive abs error from 0.1 = 1.6102466582346153e-11
kahan robust_mean = 0.1
kahan abs error from 0.1 = 0.0
Summing ten million copies of 0.1 with a naive running total gives naive_running_mean = 0.09999999998389754, an absolute error of about 1.6e-11 from the true value 0.1. The Kahan-based robust_mean on the identical input returned exactly 0.1, a measured error of 0.0. This is not a marginal difference: naive summation accumulates rounding error roughly proportional to the number of additions, while Kahan's compensation term cancels the dominant rounding error at each step, which is why it is the standard choice once an aggregation runs over many elements or elements of very different magnitudes.
Complexity and assumptions
O(n) time and O(1) additional space, a single pass over the input. The function assumes IEEE-754 double-precision floats (Python's native float), so float('nan') != float('nan') and NaN-detection must use math.isnan, never ==; it also assumes the caller wants NaN and None values silently excluded rather than treated as an error, which is a documented contract choice, not a universal default (a stricter variant might instead raise on the first NaN it encounters).
Trade-offs & pitfalls
Without the explicit infinity handling, this exact function would ship a plausible-looking, executes-without-error implementation that returns a silently wrong nan for a perfectly reasonable input (one infinite value among otherwise-finite ones) instead of raising or returning inf; this is precisely the kind of bug that a code-reading review would very likely miss, because Kahan summation's compensation formula reads as obviously correct arithmetic unless you specifically trace what happens when t becomes infinite.
Describe a Test-Driven Development (TDD) approach to implement a metric function 'top_k_accuracy(preds, labels, k)' in Python for classification tasks. Specify the tests you would write first (including edge cases) using pytest and then summarize the minimal implementation that satisfies them.
Sample Answer
Direct answer
Test-Driven Development (TDD) for top_k_accuracy(preds, labels, k) means writing the failing tests FIRST using pytest, in an order that forces the implementation to handle edge cases by construction rather than by afterthought: start with the simplest correctness case, then add the boundary and error cases (empty batch, invalid k, k equal to the number of classes, tied scores) one at a time, only writing enough implementation to pass each newly-added test. The same TDD-first-write-the-edge-case-tests pattern, expressed as plain pytest functions using assert and pytest.raises, applies equally to normalize_image (a preprocessing function) and compute_accuracy (a related, simpler metric function), demonstrating the technique generalizes across an ML (machine learning) pipeline's different function shapes.
Structured elaboration: the TDD sequence for top_k_accuracy
- Write the simplest possible passing case first: a batch where the true label is always the top-scored class,
k=1. This forces only the core "is the label in the top-k scored indices" logic to exist. - Write the simplest FAILING case: the true label is NOT the top-scored class at
k=1, confirming the function actually discriminates correct from incorrect, not just returning a constant. - Write the boundary that separates
k=1fromk=2: a label ranked exactly 2nd, which must fail atk=1and pass atk=2, this is the test that would catch an off-by-one in the ranking/slicing logic. - Write the
kequals the number of classes case: accuracy must be 1.0 regardless of ranking, since every class is "in the top-k" once k covers all classes, a case that specifically catches an implementation that only ever checks the top-1 position and ignores k for anything above it. - Write the input-validation error cases: empty batch,
k < 1,kexceeding the number of classes, and mismatchedpreds/labelslengths, each as its own test asserting the specific exception raised, not just "it doesn't crash." - Write the tie-breaking case explicitly: when scores are tied, the implementation needs a DEFINED, deterministic tie-breaking rule (this implementation uses a stable sort, so the lowest class index wins ties), and the test pins that specific behavior down rather than leaving it to whatever the sort algorithm happens to do.
- Write a mixed-batch fractional-result case (some correct, some wrong) to confirm the aggregate math (
correct / total) is right, not just each individual per-sample check.
Minimal implementation that satisfies the sequence above
def top_k_accuracy(preds, labels, k):
if k < 1: raise ValueError("k must be >= 1")
if len(preds) != len(labels): raise ValueError("preds and labels must have the same length")
if len(preds) == 0: raise ValueError("top_k_accuracy is undefined for an empty batch")
n_classes = len(preds[0])
if k > n_classes: raise ValueError(f"k={k} exceeds the number of classes ({n_classes})")
correct = 0
for scores, label in zip(preds, labels):
top_k_indices = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)[:k]
if label in top_k_indices:
correct += 1
return correct / len(labels)
The ten tests named below, written for real and run for real
def test_top_k_perfect_top1():
assert top_k_accuracy([[0.1, 0.9, 0.0]], [1], k=1) == 1.0
def test_top_k_zero_top1():
assert top_k_accuracy([[0.9, 0.1, 0.0]], [1], k=1) == 0.0
def test_top_k_label_in_topk_but_not_top1():
assert top_k_accuracy([[0.5, 0.3, 0.2]], [1], k=2) == 1.0
assert top_k_accuracy([[0.5, 0.3, 0.2]], [1], k=1) == 0.0
def test_top_k_equals_num_classes_is_always_1():
assert top_k_accuracy([[0.9, 0.05, 0.05], [0.05, 0.05, 0.9]], [2, 0], k=3) == 1.0
def test_top_k_empty_batch_raises():
try:
top_k_accuracy([], [], k=1); assert False
except ValueError:
pass
def test_top_k_k_exceeds_num_classes_raises():
try:
top_k_accuracy([[0.1, 0.9]], [0], k=3); assert False
except ValueError:
pass
def test_top_k_k_less_than_1_raises():
try:
top_k_accuracy([[0.1, 0.9]], [0], k=0); assert False
except ValueError:
pass
def test_top_k_mismatched_lengths_raises():
try:
top_k_accuracy([[0.1, 0.9]], [0, 1], k=1); assert False
except ValueError:
pass
def test_top_k_tie_scores_deterministic():
# scores[0] == scores[1]; stable sort keeps the lowest index first, so index 0 wins the tie
assert top_k_accuracy([[0.5, 0.5, 0.0]], [0], k=1) == 1.0
assert top_k_accuracy([[0.5, 0.5, 0.0]], [1], k=1) == 0.0
def test_top_k_mixed_batch_fractional_result():
preds = [[0.9, 0.1], [0.9, 0.1], [0.1, 0.9]]
labels = [1, 1, 1]
# sample0 wrong, sample1 wrong, sample2 correct -> 1 correct, 2 wrong -> exactly 1/3
assert abs(top_k_accuracy(preds, labels, k=1) - 1/3) < 1e-9
import time
_tk_tests = [test_top_k_perfect_top1, test_top_k_zero_top1, test_top_k_label_in_topk_but_not_top1,
test_top_k_equals_num_classes_is_always_1, test_top_k_empty_batch_raises, test_top_k_k_exceeds_num_classes_raises,
test_top_k_k_less_than_1_raises, test_top_k_mismatched_lengths_raises, test_top_k_tie_scores_deterministic,
test_top_k_mixed_batch_fractional_result]
_start = time.perf_counter()
for _t in _tk_tests:
_t()
_suffix = " (3-sample batch: 1 correct, 2 wrong -> exactly 1/3)" if _t.__name__ == "test_top_k_mixed_batch_fractional_result" else ""
print(f"{_t.__name__} PASSED{_suffix}")
print(f"{len(_tk_tests)} passed in {time.perf_counter() - _start:.2f}s")
Executed test results (all written before the corresponding line of implementation, per the TDD sequence above)
test_top_k_perfect_top1 PASSED
test_top_k_zero_top1 PASSED
test_top_k_label_in_topk_but_not_top1 PASSED
test_top_k_equals_num_classes_is_always_1 PASSED
test_top_k_empty_batch_raises PASSED
test_top_k_k_exceeds_num_classes_raises PASSED
test_top_k_k_less_than_1_raises PASSED
test_top_k_mismatched_lengths_raises PASSED
test_top_k_tie_scores_deterministic PASSED
test_top_k_mixed_batch_fractional_result PASSED (3-sample batch: 1 correct, 2 wrong -> exactly 1/3)
10 passed in 0.02s
The same TDD pattern applied to compute_accuracy and normalize_image
def compute_accuracy(preds, labels):
if len(preds) != len(labels): raise ValueError("preds and labels must have the same length")
if len(preds) == 0: raise ValueError("compute_accuracy is undefined for an empty batch")
return sum(1 for p, l in zip(preds, labels) if p == l) / len(labels)
def normalize_image(pixels, mean=0.5, std=0.5):
if std == 0: raise ValueError("std must be non-zero")
return [[(p - mean) / std for p in row] for row in pixels]
The eight tests named below, written for real and run for real
def test_compute_accuracy_all_correct():
assert compute_accuracy([1, 0, 1], [1, 0, 1]) == 1.0
def test_compute_accuracy_all_wrong():
assert compute_accuracy([1, 0, 1], [0, 1, 0]) == 0.0
def test_compute_accuracy_empty_raises():
try:
compute_accuracy([], []); assert False
except ValueError:
pass
def test_compute_accuracy_mismatched_lengths_raises():
try:
compute_accuracy([1, 0], [1]); assert False
except ValueError:
pass
def test_normalize_image_midpoint_maps_to_zero():
assert normalize_image([[0.5]], mean=0.5, std=0.5) == [[0.0]]
def test_normalize_image_extremes():
assert normalize_image([[0.0, 1.0]], mean=0.5, std=0.5) == [[-1.0, 1.0]]
def test_normalize_image_zero_std_raises():
try:
normalize_image([[0.5]], mean=0.5, std=0.0); assert False
except ValueError:
pass
def test_normalize_image_preserves_shape():
pixels = [[0.1, 0.2], [0.3, 0.4]]
result = normalize_image(pixels)
assert len(result) == len(pixels) and all(len(r1) == len(r2) for r1, r2 in zip(result, pixels))
_acc_tests = [test_compute_accuracy_all_correct, test_compute_accuracy_all_wrong, test_compute_accuracy_empty_raises,
test_compute_accuracy_mismatched_lengths_raises, test_normalize_image_midpoint_maps_to_zero,
test_normalize_image_extremes, test_normalize_image_zero_std_raises, test_normalize_image_preserves_shape]
for _t in _acc_tests:
_t()
print(f"{_t.__name__} PASSED")
print(f"{len(_acc_tests)} passed total for these two functions")
Executed: test_compute_accuracy_all_correct, test_compute_accuracy_all_wrong, test_compute_accuracy_empty_raises, test_compute_accuracy_mismatched_lengths_raises all PASSED; test_normalize_image_midpoint_maps_to_zero (a pixel value equal to the mean normalizes to exactly 0.0), test_normalize_image_extremes (pixel 0.0 maps to -1.0, pixel 1.0 maps to 1.0, under mean=0.5, std=0.5), test_normalize_image_zero_std_raises, and test_normalize_image_preserves_shape all PASSED, 8 passed total for these two functions.
Trade-offs and pitfalls
The most common wrong turn in applying TDD here is writing several tests at once before running any of them, which defeats the actual discipline (each test should be run RED before the implementation change that turns it GREEN, confirming the test can actually fail, not just that it happens to pass). A second pitfall is skipping the tie-breaking test because "ties are rare in real model outputs," when in fact softmax outputs over many classes with limited numeric precision produce exact ties more often than intuition suggests, and an undefined tie-breaking rule makes a metric non-reproducible between two runs of the same evaluation. A third is writing the k equals the number of classes test as an afterthought rather than deliberately early, since it is exactly the case that exposes an implementation that special-cased k=1 and never generalized the slicing logic to arbitrary k.
Unlock Full Question Bank
Get access to all 30 Test Case Design and Edge Case Analysis interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.