Skip to content
LeetQuant
QD09 Testing, Profiling and Debugging

QD09 · Testing, Profiling and Debugging · Lesson 1 of 5

Unit and Integration Testing

Structure tests as a pyramid, make event-driven trading components testable by injecting time and inputs, and lock down whole-system behaviour with deterministic replay and golden-file tests.

16 min

Objective

Developer interviews at trading firms ask "How would you test this?" about an order book, a throttle, a risk check or a strategy. A good answer names what each layer of tests is for, shows how to make time and market data controllable, and explains how to catch a behaviour change across the whole pipeline. This lesson is language-neutral with C++ and plain Python examples; pytest mechanics are covered in the Python engineering module.

The test pyramid

LayerScopeSpeedWhat it catches
Unitone function or class, no I/Omicrosecondslogic errors, edge cases, invariants
Integrationseveral real components wired together (parser + book + strategy), maybe a local socket or filemilliseconds to secondscontract mismatches between components, ordering and state bugs
End-to-end / replaythe whole system against recorded or simulated market dataseconds to minutesregressions in overall behaviour, performance cliffs

Most tests should be at the bottom: they are fast, precise about where the failure is, and cheap to keep. Integration and replay tests are fewer but catch what unit tests structurally cannot, for example a feed handler that emits prices in ticks while the book expects dollars.

What makes trading code hard to test

Trading components are event-driven and stateful: the output of on_quote depends on every earlier event. They also read wall-clock time (throttles, timeouts, session schedules) and receive input from the network. The cure is the same in every language:

  1. Inject the clock. Logic never calls now() itself; it receives a clock object or the event timestamp. In tests a fake clock advances only when told to, so "999 ms later" takes zero real time and is exactly reproducible.
  2. Separate decisions from I/O. The strategy is a pure-ish state machine: events in, actions (orders, cancels) out. The gateway that sends actions to an exchange is a thin adapter, replaced in tests by a recorder.
  3. Make randomness seeded and pass the generator in, so a failing run can be replayed.
  4. Test invariants, not just examples. For an order book: best bid < best ask after every event, total resting quantity equals adds − cancels − fills, no level with zero quantity. Check them after every event in a replay; one assertion covers millions of states.

Choosing unit-test cases

Interviewers listen for edge cases chosen deliberately: empty input, one element, boundaries (exactly at a limit, one either side), duplicates, extreme values, and invalid input. For a throttle "at most 3 orders per rolling second", the boundary is the instant the oldest order leaves the window. Is an order sent at t=0t = 0 still counted at t=1000t = 1000 ms? The specification must say, and a test must pin it.

Mocks, fakes and stubs

  • A stub returns canned answers (a reference-data service that always says the tick size is 0.01).
  • A fake is a working lightweight implementation (an in-memory exchange that matches orders, a fake clock).
  • A mock records calls so the test can assert on them ("exactly one cancel was sent for order 42").

Prefer fakes for collaborators with behaviour, and assert on outputs and state rather than on the exact sequence of internal calls; tests that mirror the implementation break on every refactor without catching bugs.

Worked example

testing a rolling-window throttle with a fake clock

Exchanges cap message rates, so a gateway has a throttle: at most 3 orders in any rolling 1-second window. Write the throttle so it can be tested without sleeping, and test the boundary where the oldest order leaves the window.

Show solution

Design. The throttle takes a Clock&; production passes a wrapper around std::chrono::steady_clock, tests pass a FakeClock. The throttle stores send times in a deque and expires those at or before now - window; that choice ("an order sent at t=0t=0 no longer counts at t=1000t = 1000 ms") is the specification, and the test pins it.

#include <cassert>
#include <cstdint>
#include <cstdio>
#include <deque>

// Time is injected, never read from the system inside the logic.
struct Clock {
    virtual std::int64_t now_ns() const = 0;
    virtual ~Clock() = default;
};

struct FakeClock : Clock {
    std::int64_t t = 0;
    std::int64_t now_ns() const override { return t; }
    void advance(std::int64_t ns) { t += ns; }
};

// Allow at most `limit` orders in any rolling window of `window_ns`.
class Throttle {
public:
    Throttle(const Clock& c, int limit, std::int64_t window_ns)
        : clock_(c), limit_(limit), window_(window_ns) {}

    bool try_send() {
        const std::int64_t now = clock_.now_ns();
        while (!sent_.empty() && sent_.front() <= now - window_) sent_.pop_front();
        if (static_cast<int>(sent_.size()) >= limit_) return false;
        sent_.push_back(now);
        return true;
    }

private:
    const Clock& clock_;
    int limit_;
    std::int64_t window_;
    std::deque<std::int64_t> sent_;
};

int main() {
    constexpr std::int64_t ms = 1'000'000;
    FakeClock clk;
    Throttle th(clk, 3, 1000 * ms);  // 3 orders per second

    assert(th.try_send());           // t = 0
    clk.advance(100 * ms);
    assert(th.try_send());           // t = 100 ms
    assert(th.try_send());           // t = 100 ms
    assert(!th.try_send());          // 4th inside the window: rejected

    clk.advance(899 * ms);           // t = 999 ms: first order still inside
    assert(!th.try_send());
    clk.advance(1 * ms);             // t = 1000 ms: first order expires exactly now
    assert(th.try_send());
    assert(!th.try_send());

    std::puts("throttle tests passed");
}

Built with c++ -std=c++20 -O1 -g -fsanitize=undefined and run, it prints:

throttle tests passed

Why these cases. The fourth order at 100 ms tests the limit itself. The tests at 999 ms and 1000 ms bracket the boundary: an off-by-one (< instead of <= in the expiry loop) fails the 1000 ms assertion. The final rejection checks that only one slot was freed, since two orders were sent at 100 ms. The whole test takes microseconds; a version that called sleep would take a second and still be flaky under load.

Deterministic replay and golden files

A replay test feeds recorded market data (a capture of the real feed, or a synthetic scenario) through the real parser, book and strategy, with the clock driven by the recorded timestamps. Because nothing reads wall-clock time or unseeded randomness, the output is a deterministic function of the input file.

A golden-file test stores that output (orders, signals, P&L per event, or a hash of them) and fails on any difference. It answers "did my refactor change behaviour?" for the whole system at once. Rules that keep golden tests useful:

  • Canonical, diffable output. One event per line, fixed field order, fixed float formatting (or integer ticks). Never print pointer addresses, unordered-map iteration order or wall-clock times.
  • Review every update. When behaviour should change, regenerate the golden file and review the diff in code review like code. A golden file updated without reading the diff tests nothing.
  • Keep the cause findable. A small scenario file per feature (gap open, crossed book, halt) localises failures better than one giant day of data.
  • Determinism is a feature to test. Run the same replay twice, or on two threads counts, and require identical output. Non-determinism found here is far cheaper than in production.

Worked example

a golden replay test catches a silent change

A simple signal emits a line whenever the mid moves more than a threshold from the mid at the last signal. Write a replay test against a golden output, then show what happens when someone changes the default threshold from 0.05 to 0.04.

Show solution
import difflib

TICKS = [  # (ts_ms, bid, ask) as recorded from the feed
    (0, 99.98, 100.02), (5, 99.99, 100.03), (9, 100.04, 100.08),
    (14, 100.10, 100.14), (20, 100.06, 100.10), (27, 99.95, 99.99),
]

def replay(ticks, threshold=0.05):
    """Emit a signal line whenever mid moves more than `threshold` from the last signal."""
    out, anchor = [], None
    for ts, bid, ask in ticks:
        mid = (bid + ask) / 2
        if anchor is None or abs(mid - anchor) > threshold:
            side = "INIT" if anchor is None else ("BUY" if mid > anchor else "SELL")
            out.append(f"{ts} {side} mid={mid:.3f}")
            anchor = mid
    return out

GOLDEN = """0 INIT mid=100.000
9 BUY mid=100.060
14 BUY mid=100.120
27 SELL mid=99.970""".splitlines()

def check(actual):
    diff = list(difflib.unified_diff(GOLDEN, actual, "golden", "actual", lineterm=""))
    print("PASS" if not diff else "\n".join(diff))

check(replay(TICKS))
check(replay(TICKS, threshold=0.04))   # someone "tunes" the default

Output:

PASS
--- golden
+++ actual
@@ -1,4 +1,5 @@
 0 INIT mid=100.000
 9 BUY mid=100.060
 14 BUY mid=100.120
+20 SELL mid=100.080
 27 SELL mid=99.970

Reading the result. The mids are 100.00, 100.01, 100.06, 100.12, 100.08 and 99.97. With threshold 0.05 the tick at 20 ms is 0.04 from the anchor 100.12, so no signal. With threshold 0.04 a signal fires, and the diff shows exactly which event changed.

The hidden lesson. In decimal, ∣100.08−100.12∣=0.04|100.08 - 100.12| = 0.04 exactly, so > 0.04 "should" be false. In binary floating point the computed difference is 0.04000000000000625, so the comparison is true. A golden test exposes this; the fix in production code is to hold prices as integer ticks so boundary comparisons are exact.

Knowledge check

A session-close handler should flatten positions at 15:59:30. What is the best way to unit test it?

Knowledge check

A golden-file replay test fails after a refactor that was meant to be behaviour-neutral, but only on some runs. What is the most likely cause?

Knowledge check

Which statement best describes the role of integration tests relative to unit tests?

Key takeaways

  • Pyramid: many fast unit tests, fewer integration tests, a small set of replay or end-to-end tests.
  • Inject the clock, the random generator and the I/O boundary; trading logic becomes a deterministic state machine.
  • Choose edge cases deliberately, especially exact boundaries, and test invariants after every event.
  • Golden-file replay tests catch any behaviour change across the whole system, provided the output is canonical and every golden update is reviewed.
  • Floating-point boundaries are a classic source of golden diffs; integer ticks make comparisons exact.

Practice problems

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).