Test a Callback Exception Without Starting a Session
Reproducing a paper strategy failure usually means re-running a session and reading logs. But a large class of failures lives entirely in your callback logic: a bad price comparison, a Decimal that cannot be constructed, a missing quote that your code assumed was present. You do not need a hosted worker, live ticks, or simulated orders to catch those. You need a pure function and a fixture.
This post builds two offline fixtures around a strategy callback: a positive case that asserts the expected decision, and an error case that asserts the expected exception. It pairs them with a sanitized expected error record you can store next to the test. This extends the reproduction workflow in /blog/reproduce-a-paper-strategy-failure without repeating its general explanation.
Why an offline fixture beats re-running a session
A hosted paper run couples three things: your decision logic, the data feed, and the fill and fee model. When a run throws, you cannot immediately tell whether the strategy math was wrong or the environment handed you something unexpected. A unit test around the pure decision isolates the first from the second. It runs in milliseconds, needs no account, and produces a deterministic pass or fail.
The trick is to separate your decision from the framework callback. In Banger, the strategy entry point is on_market_tick(self, market, tick, ctx), with an optional on_start(ctx). Tick prices are Decimal, bid and ask can be absent, and the timestamp is a datetime. That is a lot of surface area to simulate. So do not simulate it. Extract the part you actually want to test into a plain function that takes simple inputs and returns a decision, then call that function from both your real callback and your test.
Step 1: extract a pure decision function
A pure function has no I/O, no network, no clock, and no hidden state. Given the same inputs it returns the same output or raises the same exception. Here is a conceptual decision helper. It is standalone illustrative code, not a shipped SDK symbol, and it has not been executed against a live venue.
# decision.py (conceptual, offline, no SDK required)
from decimal import Decimal
def decide_side(yes_price: Decimal, threshold: Decimal) -> str | None:
"""Return 'yes' when the YES price is below threshold, else None.
Pure: no network, no clock, no framework objects."""
if yes_price is None:
raise ValueError("missing yes_price")
return "yes" if yes_price < threshold else NoneYour real callback stays thin. It reads fields off the tick, converts or validates them, calls decide_side, and only then asks the context to act. Keeping the framework-facing shell small means almost all of your logic is testable without the framework.
Step 2: write the positive fixture
The positive case pins expected behavior. Pass known inputs, assert the returned decision. Use Decimal literals built from strings so you are testing the same type the runtime uses, not a float that happens to look similar.
# test_decision.py
from decimal import Decimal
import pytest
from decision import decide_side
def test_opens_when_below_threshold():
assert decide_side(Decimal("0.44"), Decimal("0.45")) == "yes"
def test_holds_when_at_or_above_threshold():
assert decide_side(Decimal("0.45"), Decimal("0.45")) is NoneStep 3: write the error fixture
The error case is the point of this post. You want a test that asserts a specific exception, from a specific cause, so a regression that changes the failure mode is caught. There are two useful error sources here. The first is your own validation, the missing-quote branch that raises ValueError. The second comes from the number type itself.
Prediction-market code leans on Decimal because cent-level prices and fees need exact arithmetic. Decimal construction and arithmetic can raise. The module's signals include InvalidOperation among others.
The default context matters: the decimal module enables traps for Overflow, DivisionByZero, and InvalidOperation by default, so those conditions raise rather than silently returning NaN. One concrete sharp edge: the docs note that comparing Decimals with the ordering operators raises the InvalidOperation signal if either operand is NaN. That is exactly the kind of thing a less-than check inside a tick handler can hit if a NaN slips in from upstream.
# test_decision_errors.py
from decimal import Decimal, InvalidOperation
import pytest
from decision import decide_side
def test_missing_price_raises_value_error():
with pytest.raises(ValueError, match="missing yes_price"):
decide_side(None, Decimal("0.45"))
def test_nan_comparison_raises_invalid_operation():
# Comparing against NaN with < raises InvalidOperation under the
# default trapping context.
with pytest.raises(InvalidOperation):
decide_side(Decimal("NaN"), Decimal("0.45"))The second test documents a real failure mode rather than a contrived one. If a future refactor wraps the comparison in a try/except that swallows InvalidOperation, this test turns red and tells you the failure mode changed.
Step 4: store a sanitized expected error record
When you reproduce a failure, capture what you expect so the next person does not re-derive it. Keep the record sanitized: no account identifiers, no keys, no raw venue payloads, no secrets. A no-order observer does not need trading credentials, so none should ever appear in a fixture. Record the exception type, the triggering input class, and the assertion, not live data.
# expected_error.json (sanitized, checked into the repo)
{
"fixture": "nan_comparison",
"callable": "decide_side",
"input_class": "decimal.Decimal('NaN') vs threshold",
"expected_exception": "decimal.InvalidOperation",
"cause": "ordering comparison with a NaN operand under the default trapping context",
"notes": "offline unit fixture; no session, no orders, no venue keys"
}This record is evidence about your code's behavior under chosen inputs. It is not a claim about fills, settlement, or venue execution. Those depend on a data, fill, fee and valuation model that a unit test deliberately excludes.
What this does and does not prove
- It proves your decision logic returns the expected side and raises the expected exception for the inputs you chose.
- It does not prove a market will ever present those inputs, that an order would fill, or that a paper or live run would reproduce any P&L.
- It does not exercise the Banger runtime, the universe resolver, the risk envelope, or the paper fill model. Those need an actual run to observe.
- It is reproducible only because the inputs are fixed literals. A test that pulls a live ticker or the first discovery result is not deterministic.
Keep these fast offline fixtures as your first line of defense, then use a bounded paper run when you genuinely need to observe data and the fill model together. When you do run one, select and preserve an exact current market ticker so the run is reproducible, bound its output, and stop a local supervised check with Ctrl+C when you have seen enough.
Next steps
For the current callback signatures and CLI behavior, start at the Banger docs at https://www.bangertrades.com/docs and reverify before you wire the pure function into a real strategy. For the exception semantics used above, the Python decimal reference is the primary source.
If you want to move from an offline fixture to a bounded observation, you can explore paper research at /sign-up. Paper results are evidence under a particular model, not a promise of fills or returns.