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.
Binary search is simple but prone to subtle bugs. Enumerate edge cases you would test for a classic binary_search(arr, target) implementation: empty array, one element, two elements, target at boundaries, not present, repeated elements, and mid calculation overflow. Provide specific inputs that would reveal a bug if mid is computed as (low+high)/2 in a 32-bit signed integer implementation.
Sample Answer
Direct answer
Beyond the standard empty/single/two-element/target-at-boundaries/not-present/duplicates cases, binary search has one classic implementation-specific bug: computing the midpoint as (low + high) / 2 overflows a fixed-width signed integer once low + high exceeds the type's maximum, silently producing a negative or wrapped midpoint; the fix is low + (high - low) / 2, which can never overflow because the intermediate value stays within the array's index range.
Structured elaboration and worked example (executed; the original draft's while/if/elif/else body was flattened to a single indent level and did not parse as Python at all, fixed below)
def binary_search_safe(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = low + (high - low) // 2 # overflow-safe
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
Edge cases and results, all executed and passing:
- Empty array:
binary_search_safe([], 5) == -1 - One element (found and not found):
binary_search_safe([7], 7) == 0,binary_search_safe([7], 3) == -1 - Two elements, target at boundaries:
binary_search_safe([1,5], 1) == 0,binary_search_safe([1,5], 5) == 1 - Target at first/last index of a larger array: confirmed on
[1,3,5,7,9,11,13] - Not present:
binary_search_safe([1,3,5,7,9,11,13], 4) == -1 - Repeated elements:
binary_search_safe([2,2,2,2,2], 2)returns SOME correct index (any is acceptable unless the contract specifies first/last occurrence, which needs its own explicit test if required)
Mid-calculation overflow, demonstrated concretely
Python integers never overflow, so the overflow bug can't reproduce natively in Python; it was simulated explicitly as it would behave in a 32-bit signed language (Java int, C int):
low, high = 1_500_000_000, 1_500_000_000 # low+high = 3,000,000,000 > INT32_MAX (2,147,483,647)
correct_mid = low + (high - low) // 2 # = 1,500,000,000
# simulated 32-bit signed wraparound of (low+high)//2:
Executed result: low+high = 3000000000 (exceeds INT32_MAX = 2147483647); the overflow-safe formula correctly computes mid = 1500000000; the simulated 32-bit-signed-wraparound formula instead produces mid = -647483648, a NEGATIVE index. In a real Java or C implementation using (low + high) / 2 on int, this specific input (a large array with both low and high above roughly 1.07 billion, achievable in an array with more than ~2.1 billion elements, or more realistically whenever low and high are both large due to a huge search space) would compute a negative or otherwise invalid midpoint and crash with an out-of-bounds access or return an incorrect result, a bug that famously shipped in real production binary-search implementations (documented in Java's own Arrays.binarySearch history) for years before being fixed.
Trade-offs & pitfalls
This bug is specifically invisible on small test arrays: any array under roughly a billion elements never drives low + high past INT32_MAX, so a test suite exercising only 'reasonable-sized' arrays (which is the overwhelming majority of real test suites) will never catch it; the only reliable way to test for it is to reason about the arithmetic directly (as done here) rather than trying to construct an actual multi-gigabyte array, which is why this is one of the rare cases where an ANALYTICAL proof of the formula's safety is the practical test, not an executed one at full scale.
When you replace a simple correctness-first implementation with a vectorized or approximate version for performance, how do you ensure the optimized version preserves correctness across edge cases? Describe a test strategy that includes equivalence tests on representative inputs, property tests on invariants, tolerance-based numerical comparisons, and regression tests against historical outputs.
Sample Answer
Direct answer
Confirming that an optimized or approximate implementation preserves a baseline's correctness needs four distinct techniques because they catch different failure classes: equivalence tests on representative inputs prove the common case matches, property tests on invariants catch violations no fixed input set would happen to sample, tolerance-based numerical comparisons acknowledge that a different computation order is legitimately allowed to differ in the last few bits, and regression tests against historical outputs catch the case where both implementations agree with each other while having quietly drifted from what production actually depended on.
Structured elaboration
- Equivalence tests on representative inputs: run the baseline and the optimized implementation on a curated set of inputs representing the real distribution, typical values, known historical edge cases, degenerate inputs, and assert the outputs match, exactly or within tolerance per the next point. This is differential testing, treating the old implementation as the oracle for the new one.
- Property tests on invariants: when the input space is too large to enumerate by hand, or the failure mode is rare, state an invariant that must hold for every input, both implementations must agree, and let a property-based tool generate many inputs automatically rather than relying only on hand-picked examples.
- Tolerance-based numerical comparisons: when the optimized version reorders floating-point operations, vectorization changes summation order, a different algorithm accumulates error differently, bit-exact equality is the wrong assertion and will spuriously fail a genuinely correct implementation. Use a relative and absolute tolerance sized to the actual numerical method's expected error, not an arbitrarily loose tolerance chosen just to make the test pass.
- Regression tests against historical outputs: separately from comparing the two implementations to each other, pin a set of real, previously-computed outputs, captured before the optimization, as fixed expected values. This catches a bug that affects both implementations identically, for example a shared upstream data assumption that turns out to be wrong, which pure differential testing between the two implementations cannot catch by construction, since both would agree with each other while both are wrong.
Related case: memoization is the case where equivalence should be exact, not tolerance-based, because it changes only the computation strategy, caching repeated subproblems, not the arithmetic itself. I tested this below with recursive Fibonacci (naive versus memoized), asserting bit-for-bit equality, the correct assertion strength for this class of optimization, unlike the vectorized floating-point case above. Replacing an O(n log n) sort-based exact computation with an O(n) approximation, illustrated below with a randomized quickselect-based median replacing a sort-based exact median, is a case where the algorithmic technique changes, and randomization enters through pivot choice, but the result is still expected to be exactly correct, not merely close; "approximate" here describes the algorithmic technique, randomized pivoting, not a license for the result's precision to loosen. Recognizing that distinction, does a faster technique change the answer's precision or only its computation path, is exactly the judgment call this question is testing.
Worked example (executed)
import math
import numpy as np
from hypothesis import given, strategies as st, settings, seed
def std_baseline(xs):
n = len(xs); mean = sum(xs) / n
return math.sqrt(sum((x - mean) ** 2 for x in xs) / n)
def std_vectorized(xs):
return float(np.std(np.asarray(xs, dtype=float)))
@settings(max_examples=200)
@seed(11)
@given(st.lists(st.floats(min_value=-1e6, max_value=1e6, allow_nan=False, allow_infinity=False), min_size=1, max_size=200))
def test_std_vectorized_matches_baseline(xs):
assert math.isclose(std_baseline(xs), std_vectorized(xs), rel_tol=1e-9, abs_tol=1e-9)
PASSED, 200 generated examples, seed 11, tolerance rel_tol=1e-9, abs_tol=1e-9, the tolerance-based case.
def fib_naive(n, _cache={}):
if n < 2: return n
return fib_naive(n - 1) + fib_naive(n - 2)
def fib_memoized(n, cache=None):
if cache is None: cache = {}
if n < 2: return n
if n in cache: return cache[n]
cache[n] = fib_memoized(n - 1, cache) + fib_memoized(n - 2, cache)
return cache[n]
def test_fib_memoized_exactly_matches_naive():
for n in range(0, 21):
assert fib_naive(n) == fib_memoized(n)
PASSED, exact equality for n=0 through 20, the memoization case.
For the median example (quickselect-based O(n)-expected median versus a sort-based O(n log n) exact median):
import random
def median_sort(xs):
s = sorted(xs)
n = len(s)
mid = n // 2
if n % 2 == 1:
return s[mid]
return (s[mid - 1] + s[mid]) / 2
def quickselect(arr, k):
arr = list(arr)
while True:
if len(arr) == 1:
return arr[0]
pivot = random.choice(arr)
lows = [el for el in arr if el < pivot]
highs = [el for el in arr if el > pivot]
pivots = [el for el in arr if el == pivot]
if k < len(lows):
arr = lows
elif k < len(lows) + len(pivots):
return pivots[0]
else:
arr = highs
k -= len(lows) + len(pivots)
def median_quickselect(xs):
n = len(xs)
if n % 2 == 1:
return quickselect(xs, n // 2)
lo = quickselect(xs, n // 2 - 1)
hi = quickselect(xs, n // 2)
return (lo + hi) / 2
@settings(max_examples=200)
@seed(22)
@given(st.lists(st.integers(min_value=-10**6, max_value=10**6), min_size=1, max_size=100))
def test_median_quickselect_matches_sort(xs):
assert median_quickselect(xs) == median_sort(xs)
PASSED, 200 generated examples, seed 22, confirming the randomized algorithm is exactly correct, not merely close, for this problem.
Trade-offs and pitfalls
- Picking a numerical tolerance without justification is the most common wrong turn.
abs_tol=1e-9is defensible for the standard-deviation example specifically because 64-bit floating-point summation error over up to 200 terms in the stated value range is bounded well below that; a blanket "just use 1e-6 everywhere" tolerance can silently hide a real bug where the true expected error is far smaller. - Relying only on differential testing between baseline and optimized, with no separate historical regression fixture, means a shared bug in the original assumption survives the optimization completely undetected, since both versions agree with each other while being equally wrong. Historical regression fixtures are the specific check against this failure mode.
- For a genuinely approximate technique, reservoir sampling or a sketching data structure, unlike the quickselect example here which is exact despite being randomized, the exact-equality bar is wrong, and the test needs a statistical tolerance, the approximate result falling within a stated confidence interval over repeated trials, rather than a numeric tolerance on a single run. Conflating "randomized but exact" with "genuinely approximate" produces either an unfairly strict test or an unfairly loose one.
- Property tests over floating-point domains need NaN and infinity excluded explicitly, as done above, or handled as a separate deliberate case, since equality and tolerance comparisons involving NaN are not meaningful under IEEE 754 semantics.
Explain integer overflow and underflow and how behavior differs between C/C++ (wrap or UB), Java (wrap/defined?), and Python (big ints). As an SRE, how would you test for overflow in ingestion pipelines, telemetry aggregation, and logs where numbers may exceed expected ranges?
Sample Answer
Direct answer
Integer overflow happens when an arithmetic result exceeds the maximum value a fixed-width integer type can hold; C/C++ signed-integer overflow is undefined behavior (the compiler is allowed to assume it never happens, which can produce surprising results beyond simple wraparound), Java integers wrap around silently and deterministically (Integer.MAX_VALUE + 1 reliably becomes Integer.MIN_VALUE), and Python integers have no fixed width at all, transparently growing to arbitrary precision, so overflow in the C/Java sense simply cannot occur for plain Python ints.
Structured elaboration: the three-language comparison
| Language | Behavior on overflow | Practical implication |
|---|---|---|
| C/C++ | Undefined behavior (signed); unsigned integers wrap by the standard | A compiler MAY assume overflow never happens and optimize based on that assumption, which can eliminate intended overflow checks entirely, not just produce a 'wrong number' |
| Java | Silent, defined wraparound (two's complement) | Integer.MAX_VALUE + 1 == Integer.MIN_VALUE deterministically; no exception is thrown by default, so bugs pass silently unless explicitly checked (Math.addExact throws) |
| Python | No fixed-width overflow for int | Arbitrary-precision integers grow as needed; the practical overflow risk moves to fixed-width contexts INSIDE Python, such as numpy's int32/int64 arrays, which DO wrap like C |
Worked example: testing overflow in ingestion pipelines, telemetry, and logs, as an SRE
- Ingestion pipelines: if raw event counts are accumulated into a 32-bit counter column (common in a database schema or a numpy-backed aggregation) rather than Python's native arbitrary-precision int, a test should push the accumulator past 2^31-1 (2,147,483,647) with a controlled batch of synthetic events and assert the stored value is correct, not silently wrapped negative. This is a genuine, previously-seen production bug class: a counter that looks fine at low volume and becomes visibly wrong (negative counts) only once traffic crosses the 32-bit boundary.
- Telemetry aggregation: a metric like total-bytes-transferred summed across a long time window in a language/runtime using 32-bit floats or ints for the accumulator can silently wrap or lose precision; the test strategy is to seed a synthetic high-volume period and assert the aggregate against an independently-computed 64-bit or arbitrary-precision reference sum (an oracle-by-differential-computation, not by trusting the pipeline's own math).
- Logs: numeric fields parsed FROM log lines (e.g. a request-duration-in-microseconds field written by a system that itself overflowed) need tests confirming the LOG PARSER doesn't compound the problem by re-parsing an already-wrapped negative number as if it were valid, and ideally surfaces an anomaly flag (a negative duration is never physically meaningful) rather than silently accepting it.
The security-hardening angle
In C/C++ specifically, an integer overflow that controls a buffer-size calculation (e.g. malloc(count * size) where count * size overflows to a small positive number) can lead to a buffer that is allocated far smaller than intended, and subsequent writes based on the ORIGINAL, un-overflowed count then write past the buffer's real boundary; this is a well-documented memory-safety vulnerability class, not just a numeric-correctness bug, which is why overflow-prone size/length calculations in C/C++ warrant deliberate hardening (checked-arithmetic helpers, or unsigned-overflow-safe idioms) beyond what a Java or Python equivalent would need.
Trade-offs & pitfalls
A common mistake is assuming Python's arbitrary-precision integers make an SRE's pipeline immune to overflow entirely; in practice most high-throughput pipelines use numpy, pandas, or a database column with a FIXED width for performance reasons, reintroducing exactly the overflow risk that plain Python ints don't have, so "we use Python" is not itself a mitigation without checking every numeric boundary the pipeline actually touches.
Design property-based tests for a concurrent queue implementation to check invariants like FIFO ordering, element preservation, and absence of lost or duplicated items under interleavings. Describe how to model concurrent operations as histories, generate interleavings, shrink failing histories, and validate linearizability. What challenges arise and how would you address them?
Sample Answer
Direct answer
Property-based tests for a concurrent queue work by recording a history of concurrent operations (each with a start time, an end time, and a result), then checking whether SOME sequential reordering of that history is both consistent with real-time order and a valid execution of the sequential queue (FIFO ordering, nothing lost, nothing duplicated). If no such reordering exists, the history proves a linearizability violation, which is the formal correctness condition for a concurrent data structure: every concurrent execution must be equivalent to some valid sequential one.
Structured elaboration
Modeling concurrent operations as histories. Each operation is recorded as a tuple of (thread id, operation type, argument, result, invocation time, completion time). Two operations are said to "overlap" if their time intervals intersect; only overlapping operations are free to be reordered relative to each other in a candidate linearization, non-overlapping operations must keep their real-time order (an operation that fully completed before another started cannot be placed after it).
Generating interleavings. A brute-force checker enumerates every permutation of the recorded operations and, for each, checks two things: does the permutation respect real-time order (see above), and does replaying the operations in that order against a plain sequential reference queue produce the same results the concurrent run actually observed. If at least one permutation passes both checks, the history is linearizable.
Shrinking failing histories. Brute-force permutation checking is exponential, so a practical property-based framework generates random operation sequences with random interleavings, and when it finds one that is not linearizable, it "shrinks" it: repeatedly tries removing operations or simplifying arguments while re-checking that the reduced history still fails the linearizability check, converging on a minimal failing example a human can actually read (often 2-4 operations) instead of the original 50-operation randomly generated sequence.
Validating linearizability. The check itself is the two-part test above (real-time consistency plus sequential-queue replay agreement), applied over candidate orderings; for larger histories this is done with a more efficient algorithm than brute force (e.g. Wing and Gong's technique, or the widely used porcupine/Jepsen-style linearizability checkers use a decision-procedure approach rather than full permutation enumeration), but the definition being checked is the same.
Challenges and how to address them. The state space of interleavings grows factorially with operation count, so a checker either bounds the number of operations per generated history (trading thoroughness for tractability) or uses a smarter algorithm than brute force; wall-clock timestamps from a real concurrent run are noisy and a naive read of "start" and "end" times can be wrong near clock-resolution boundaries, so implementations usually instrument the operations directly (recording invocation/response events from inside the test rather than trusting external timestamps) instead of relying on OS-level timing; and a checker that is itself buggy will produce false negatives (missing a real bug) far more dangerously than false positives, so the checker's own logic (the sequential-replay reference implementation) needs to be the simplest, most obviously-correct code in the whole test, deliberately not sharing any code with the concurrent implementation under test.
Worked example (executed)
A minimal brute-force linearizability checker, applied to three small histories:
from itertools import permutations
def overlaps(a, b):
return a[4] < b[5] and b[4] < a[5]
def respects_realtime(order, history):
pos = {idx: i for i, idx in enumerate(order)}
for i in range(len(history)):
for j in range(len(history)):
if i != j and history[i][5] <= history[j][4] and not overlaps(history[i], history[j]):
if pos[i] > pos[j]:
return False
return True
def simulate_fifo_queue(order, history):
q = []
for idx in order:
_, op, arg, result, _, _ = history[idx]
if op == "enq":
q.append(arg)
else:
if not q:
if result is not None: return False
elif q.pop(0) != result:
return False
return True
def is_linearizable(history):
for order in permutations(range(len(history))):
if respects_realtime(order, history) and simulate_fifo_queue(order, history):
return True, order
return False, None
Three histories were checked. history_ok (thread T1 enqueues 1, then thread T2 enqueues 2, non-overlapping, then both dequeue in matching order) came back linearizable=True. history_overlap_ok (T1's enqueue of 1 overlaps T2's enqueue of 2 in real time, and the two dequeues return 2 then 1) also came back linearizable=True, with witness order (1, 0, 2, 3), i.e. enqueue-2-then-enqueue-1 is a valid linearization precisely because the enqueues genuinely overlapped. history_buggy (same overlapping enqueues, but BOTH dequeues return element 1, meaning element 2 vanished, the classic lost-update signature of an unsynchronized push/pop) came back linearizable=False, having exhaustively checked all 4!=24 possible orderings of the four operations and found none that is simultaneously real-time-consistent and a valid sequential FIFO execution.
Trade-offs and pitfalls
The exhaustive permutation approach used above does not scale (a history of n operations has n! candidate orderings), so it is only practical as a teaching example or for very small generated histories; production linearizability checkers use a polynomial or near-polynomial algorithm and this is a real engineering decision, not just an implementation detail, since a checker that times out on large histories effectively stops testing the interesting cases. A second pitfall is conflating "this specific run passed the linearizability check" with "the queue is linearizable": a single passing run only proves that one observed interleaving was fine, so the value comes from running many randomly generated concurrent histories (ideally under a scheduler that deliberately interleaves aggressively, since real hardware often does not exercise rare interleavings on its own) rather than from any single execution. Finally, the reference sequential implementation used inside the checker (simulate_fifo_queue above) must never share code with the concurrent implementation under test, because a shared bug in both would make the checker blind to it.
Explain state transition testing and produce a state diagram for a shopping-cart system with these states: empty, items-added, checkout-started, payment-pending, confirmed, failed, and canceled. From that diagram, list test cases that cover all transitions, including persistence across sessions and behavior on timeout during 'payment-pending'.
Sample Answer
Direct answer
State transition testing derives test cases from a state diagram rather than from input values: you enumerate the system's valid states, the events/transitions between them, and then design at least one test per transition (and, ideally, tests for the invalid transitions that should be rejected) rather than testing inputs in isolation.
Structured elaboration: the state diagram
stateDiagram-v2
[*] --> empty
empty --> items_added: add item
items_added --> items_added: add/remove item
items_added --> empty: remove last item
items_added --> checkout_started: begin checkout
checkout_started --> payment_pending: submit payment info
checkout_started --> items_added: abandon checkout
payment_pending --> confirmed: payment succeeds
payment_pending --> failed: payment declined
payment_pending --> canceled: timeout / user cancels
failed --> payment_pending: retry payment
failed --> items_added: abandon after failure
confirmed --> [*]
canceled --> [*]
Worked example: transition-coverage test cases
- empty -> items_added (add the first item): cart becomes non-empty, item count = 1.
- items_added -> items_added (add a second item, then remove one): confirms self-loop transitions don't corrupt state.
- items_added -> empty (remove the last remaining item): cart returns to empty, not to an undefined state.
- items_added -> checkout_started (begin checkout): checkout flow becomes available only from a non-empty cart; a companion NEGATIVE test confirms empty -> checkout_started is REJECTED (you cannot check out an empty cart).
- checkout_started -> payment_pending (submit payment info): cart is now locked from further item edits.
- checkout_started -> items_added (abandon checkout): confirms the user can back out before paying, and the cart contents are preserved, not cleared.
- payment_pending -> confirmed (payment succeeds): order is finalized.
- payment_pending -> failed (payment is declined): cart is NOT cleared, so the user can retry.
- failed -> payment_pending (retry with corrected payment info): confirms the retry loop actually re-enters payment processing rather than being a dead end.
- failed -> items_added (abandon after a failed payment): confirms items are still there to re-checkout later.
Persistence across sessions
A state-only diagram is not enough here: 'items_added' and 'checkout_started' must survive a browser refresh or a new session on the same account (persisted cart), while 'payment_pending' crossing a session boundary is a distinct, higher-risk case: if the user closes the tab mid-payment and reopens the site, the test must confirm the system does NOT silently resume 'payment_pending' as if nothing happened (which risks a double-charge or an orphaned pending order); it should either restore to 'payment_pending' with the SAME idempotent payment attempt, or transition to 'failed'/'canceled' based on the payment provider's actual status, never re-submit a fresh payment attempt implicitly.
Timeout during payment-pending
This is the transition most worth a dedicated test: payment_pending -> canceled after a defined timeout window (e.g. 15 minutes with no confirmation from the payment provider). The test needs to verify three things together: (a) the transition actually fires at the timeout boundary, not indefinitely later; (b) the cart's item state is preserved so the user isn't forced to rebuild it; (c) if the payment provider's confirmation arrives AFTER the local timeout has already fired the cancellation (a race the diagram doesn't show but the real system has), the system does not end up both 'canceled' locally and 'confirmed' at the payment provider, i.e. the reconciliation logic for a late-arriving webhook after a local timeout needs its own explicit test.
Trade-offs & pitfalls
A state diagram that omits the late-arriving-webhook race (as the given 7-state list does) will produce a test suite that looks complete against the diagram while missing the actual production risk (double payment / lost order). State-transition testing is only as good as the diagram; a common pitfall is drawing the diagram from the happy-path requirements document rather than from how the system's async dependencies (a payment gateway here) can genuinely desynchronize from it.
Unlock Full Question Bank
Get access to all Test Case Design and Edge Case Analysis interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.