PeaBox Lab › PeaLang › Learn › Chapter 10 › Lesson 3

Part II — Intermediate Development · Chapter 10 · Lesson 3 of 6 · 8 min read

Lesson 3: Fixtures, Deterministic Tests, and Boundary Cases

Lesson level: Intermediate

Purpose: Build reliable test data, remove hidden sources of variation, and choose inputs that expose boundary and precedence defects.

Learning objectives

By the end of this lesson, you should be able to:

Release note: syntax and helper names in this lesson are illustrative. Verify them against the installed v0.63 release.

3.1 What a fixture is

A fixture is the known starting state a test needs: input data, configuration, or a prepared object. A good fixture makes the test’s intent obvious by containing only what matters to the behavior under test.

In the order-discount project, a fixture is usually a small map representing one order. All values are synthetic.

let gold_bulk_order = {"tier": "gold", "quantity": 10, "unit_price": 20}
let standard_small_order = {"tier": "standard", "quantity": 2, "unit_price": 20}

3.2 Principles for fixtures

3.3 Builders and variations

When many tests differ by one field, a small builder function creates a valid default and overrides only what the test cares about. This keeps the difference visible.

function make_order(overrides) {
    let order = {"tier": "standard", "quantity": 1, "unit_price": 20}
    for key in overrides {
        order[key] = overrides[key]
    }
    return order
}

test "gold tier at bulk threshold returns GOLD_BULK" {
    let order = make_order({"tier": "gold", "quantity": 10})
    assert rules.decide(order)["reason"] == "GOLD_BULK"
}

The test body now shows exactly which inputs matter. A reader does not need to compare two large literals to find the difference.

3.4 Shared state and isolation

Shared mutable state is the most common cause of order-dependent failures. A test that passes alone but fails in the full suite usually reads state that another test changed.

3.5 Sources of nondeterminism

SourceSymptomRemedy
Current timePasses today, fails at month endPass the time in as a parameter or use a fixed fake clock
RandomnessFails one run in twentyUse a fixed seed or inject a fake generator
Map or set iteration orderOutput order changesSort keys before comparing, or compare as sets
Floating-point arithmeticLast digit differsCompare within a stated tolerance
Files and environmentFails on another machineUse temporary data and inject paths; deny file capabilities by default
Network and HTTPSlow or intermittent failuresInject a fake transport; never call real services
Concurrency timingRace-dependent resultsUse deterministic scheduling or bounded waits

Deterministic tests give the same result on every run, on every machine, in any order. Without that property, a failure carries no information.

3.6 Inject, do not fetch

The cleanest remedy is dependency injection. The rule receives the value it needs rather than obtaining it itself. This follows the Chapter 9 design: pure rules, narrow adapters, and dependencies that point downward.

// Hard to test: reads the clock inside the rule
function is_promo_active() { return std.datetime.now() < promo_end }

// Easy to test: the caller supplies the instant
function is_promo_active(now, promo_end) { return now < promo_end }

The second form is a pure function. Its tests need no clock, no setup, and no cleanup.

3.7 Floating-point comparisons

Compare computed decimals with a tolerance, not exact equality. State the tolerance in the test so a reader understands the precision the rule guarantees.

let expected = 36.0
let actual = rules.total(order)
assert std.math.abs(actual - expected) < 0.0001

Where the domain allows it, prefer integer minor units such as cents. Integer arithmetic removes a whole class of precision questions.

3.8 Deriving boundary cases

Most rule defects live at thresholds. For every threshold, test the value just below, exactly at, and just above it. This three-point method is the core of boundary testing.

RuleBelowAtAbove
Bulk threshold: quantity >= 109 → no bulk10 → bulk11 → bulk
Quantity must be positive0 → VALIDATION_ERROR1 → valid2 → valid
Gold tier match"silver" → not gold"gold" → gold"Gold" → not gold (case-sensitive)

Also test the extremes of each domain: the smallest valid value, the largest permitted value, empty collections, missing fields, null, and values of the wrong type.

3.9 Precedence and overlap cases

When two rules can both apply, the order of evaluation decides the result. Write a case where several conditions are true at once and assert the documented winner. In the order-discount project, a gold customer at the bulk threshold satisfies both GOLD and BULK, and the expected reason is GOLD_BULK.

Then reverse the order of two rules on a scratch copy and confirm that exactly the overlap tests fail. If no test fails, precedence is untested.

3.10 Table-driven tests

When many cases share one assertion shape, put the cases in a table and loop over them. Each row should carry a name so a failure identifies the case.

let cases = [
    {"name": "A below bulk", "tier": "standard", "qty": 9, "reason": "NONE"},
    {"name": "B at bulk", "tier": "standard", "qty": 10, "reason": "BULK"},
    {"name": "C gold at bulk", "tier": "gold", "qty": 10, "reason": "GOLD_BULK"},
    {"name": "D zero quantity", "tier": "gold", "qty": 0, "reason": "VALIDATION_ERROR"}
]

test "discount reasons by case" {
    for c in cases {
        let result = rules.decide(make_order({"tier": c["tier"], "quantity": c["qty"]}))
        assert result["reason"] == c["reason"], c["name"]
    }
}

A table keeps the data separate from the logic. The risk is that a loop stops at the first failure, so keep each row independent and include the case name in every assertion message.

3.11 Diagnosing flaky tests

3.12 Common mistakes

MistakeConsequenceCorrection
Large shared fixture used by every testHidden coupling; one change breaks many testsUse small builders with explicit overrides
Reading the real clock in a ruleDate-dependent failuresInject the instant
Comparing floats with equalityIntermittent last-digit failuresCompare within a tolerance
Testing only the middle of a rangeBoundary defects surviveTest below, at, and above every threshold
Asserting on map print orderOrder-dependent failuresCompare fields, or sort first
Retrying a flaky test until greenReal defects hiddenFind the nondeterminism and remove it

3.13 Diagnostic workflow

3.14 Guided practice

3.15 Hands-on lab: Make the order-discount suite deterministic

Goal: Rebuild the fixtures for the Chapter 9 project and prove that the suite is deterministic and boundary-complete.

Deliverable: The updated tests, a boundary table for every threshold, a record of the repeated runs, and a short note describing the nondeterminism you introduced and how you removed it.

3.16 Review questions

3.17 Applied challenge

Choose a rule from your own domain that depends on the current time and a threshold. Redesign it so time is injected, write a fixture builder, list its boundary cases in a table, and write the table-driven test. Explain which failures your tests would detect if the time source changed.

Lesson summary

Reliable tests start from small, named, independent fixtures and remove hidden variation by injecting time, randomness, and external data. Boundary cases come directly from thresholds: below, at, and above. Table-driven tests keep many cases readable, and overlap tests protect rule precedence. A flaky test signals hidden nondeterminism that must be found and removed, not retried.

Transition to Lesson 4

The next lesson covers interpreter/VM differential testing, fuzzing, and conformance: running the same program on both execution engines, generating unexpected inputs, and checking behavior against the specification.

Lesson status: Ready for review.

← Previous Next →