From a1d0730124cec2bb062f41ea32c1f69fe5949371 Mon Sep 17 00:00:00 2001 From: Dejvino Date: Sat, 14 Nov 2026 13:02:35 +0100 Subject: [PATCH] =?UTF-8?q?NetDeck:=20headless=20test=20runner=20=E2=80=94?= =?UTF-8?q?=20unit=20+=20integration=20suites,=20E2E=20as=20separate=20bui?= =?UTF-8?q?ld?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - emulator/tests/: harness.h (TEST/EXPECT framework, input + serial + framebuffer helpers), shim_globals.cpp (shim externs for test binaries, replacing main.cpp ownership) - unit_tests.h (14): map/door/LOS/BFS/cover/link state machine/trace/ spike/reinforcement/win/loss/reset — deterministic fixed-seed, sim stepped tick by tick - integration_tests.h (7): keyboard->pollKeyboard->handleKey pipeline, beacon clicks -> squad movement, full network journey via clicks, hover-sever (incl. safe sever during trace), daemon gating - e2e_tests.cpp (separate NetDeck-e2e build): real setup()/loop() journeys with device-pipeline input injection (boot grace, 0x55 keyboard, GT911 tap, trackball ISRs), transcript + pixel assertions (HUD, freeze tint) - shim SerialSim: opt-in transcript ring for test assertions (off by default, interactive emulator unchanged) - make netdeck-test / -unit / -e2e (root) and make test / test-unit / test-e2e (emulator/); tests/README.md documents the structure - STATUS.md: test-structure note Verified: make netdeck-test -> 14 unit + 7 integration + 3 E2E, 0 failures --- .gitignore | 2 + Makefile | 21 ++- emulator/Makefile | 33 ++++- emulator/src/shim/Arduino.h | 26 +++- emulator/tests/README.md | 62 +++++++++ emulator/tests/e2e_tests.cpp | 182 +++++++++++++++++++++++++ emulator/tests/harness.h | 115 ++++++++++++++++ emulator/tests/integration_tests.h | 122 +++++++++++++++++ emulator/tests/shim_globals.cpp | 36 +++++ emulator/tests/sim_helpers.h | 42 ++++++ emulator/tests/test_main.cpp | 46 +++++++ emulator/tests/unit_tests.h | 206 +++++++++++++++++++++++++++++ src/netdeck/STATUS.md | 10 ++ 13 files changed, 894 insertions(+), 9 deletions(-) create mode 100644 emulator/tests/README.md create mode 100644 emulator/tests/e2e_tests.cpp create mode 100644 emulator/tests/harness.h create mode 100644 emulator/tests/integration_tests.h create mode 100644 emulator/tests/shim_globals.cpp create mode 100644 emulator/tests/sim_helpers.h create mode 100644 emulator/tests/test_main.cpp create mode 100644 emulator/tests/unit_tests.h diff --git a/.gitignore b/.gitignore index 6969f81..1dd4ede 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,5 @@ emulator/*-prefs.cfg emulator/m0_*.bmp emulator/m0_*.png emulator/smoke_frame.bmp +emulator/NetDeck-tests +emulator/NetDeck-e2e diff --git a/Makefile b/Makefile index e090ae5..8a716d7 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,13 @@ # targets (SDL2 emulator + ESP32-S3 firmware), so a change can never leave # one of them silently broken. # -# make netdeck build the NetDeck emulator AND the T-Deck firmware +# make netdeck build the NetDeck emulator AND the T-Deck firmware +# make netdeck-test run the full headless test suite: +# unit + integration (fast, deterministic) +# + E2E journeys (separate build, real loop(), +# ~1-2 min wall time) +# make netdeck-test-unit fast layer only +# make netdeck-test-e2e E2E layer only # # Firmware builds need platformio: either `pio` on PATH or the default # ~/.platformio/penv/bin/pio install. @@ -20,4 +26,15 @@ netdeck: $(MAKE) --no-print-directory -C emulator APP=NetDeck @echo "=== both NetDeck targets built OK ===" -.PHONY: netdeck +netdeck-test: + @echo "=== NetDeck tests: unit + integration + E2E ===" + $(MAKE) --no-print-directory -C emulator APP=NetDeck test + $(MAKE) --no-print-directory -C emulator APP=NetDeck test-e2e + +netdeck-test-unit: + $(MAKE) --no-print-directory -C emulator APP=NetDeck test + +netdeck-test-e2e: + $(MAKE) --no-print-directory -C emulator APP=NetDeck test-e2e + +.PHONY: netdeck netdeck-test netdeck-test-unit netdeck-test-e2e diff --git a/emulator/Makefile b/emulator/Makefile index 81a4e51..28418ec 100644 --- a/emulator/Makefile +++ b/emulator/Makefile @@ -45,10 +45,17 @@ LIBS := -lSDL2 -lSDL2_ttf DEFS += -DAPP_INO='"$(APP).ino"' -DAPP_NAME='"$(APP_TITLE)"' SHIMS := $(wildcard src/shim/*.h) $(wildcard src/shim/driver/*.h) +SKETCH_SRCS := $(APP_DIR)/$(APP).ino $(wildcard $(APP_DIR)/*.h) SOUND_SRC := $(wildcard $(APP_DIR)/sound_engine.cpp) EMU := $(APP)-emu -.PHONY: all run smoke clean +# Headless test binaries (tests/): same single-TU sketch inclusion as +# main.cpp, no window. Unit+integration share one fast binary; E2E is a +# separate build driving the real loop() through the device input pipeline. +TESTS := $(wildcard tests/*.h tests/*.cpp tests/e2e/*.cpp) +TESTS_INC := $(INC) -Itests + +.PHONY: all run smoke test test-unit test-e2e clean all: $(EMU) @@ -64,5 +71,27 @@ run: $(EMU) smoke: $(EMU) ./$(EMU) --frames 240 --dump smoke_frame.bmp +# --- tests ----------------------------------------------------------------- +# fast layer: unit + integration (deterministic, sim stepped directly) +$(APP)-tests: tests/test_main.cpp tests/shim_globals.cpp tests/harness.h \ + tests/sim_helpers.h tests/unit_tests.h tests/integration_tests.h \ + $(SHIMS) $(SKETCH_SRCS) + $(CXX) $(CXXFLAGS) $(SDLFLAGS) $(TESTS_INC) $(DEFS) \ + tests/shim_globals.cpp tests/test_main.cpp -o $@ $(LIBS) + +# slow layer: E2E journeys through the real loop() + input pipeline (own build) +$(APP)-e2e: tests/e2e_tests.cpp tests/shim_globals.cpp tests/harness.h \ + tests/sim_helpers.h $(SHIMS) $(SKETCH_SRCS) + $(CXX) $(CXXFLAGS) $(SDLFLAGS) $(TESTS_INC) $(DEFS) \ + tests/shim_globals.cpp tests/e2e_tests.cpp -o $@ $(LIBS) + +test-unit: $(APP)-tests + ./$(APP)-tests unit + +test: test-unit + ./$(APP)-tests integration +test-e2e: $(APP)-e2e + SDL_VIDEODRIVER=dummy ./$(APP)-e2e + clean: - rm -f $(EMU) smoke_frame.bmp \ No newline at end of file + rm -f $(EMU) $(APP)-tests $(APP)-e2e smoke_frame.bmp \ No newline at end of file diff --git a/emulator/src/shim/Arduino.h b/emulator/src/shim/Arduino.h index 9d88a24..1dd3a7f 100644 --- a/emulator/src/shim/Arduino.h +++ b/emulator/src/shim/Arduino.h @@ -232,11 +232,27 @@ inline int xTaskCreatePinnedToCore(void (*fn)(void *), const char *, unsigned, v // --------------------------------------------------------------------------- struct SerialSim { void begin(unsigned long) {} - template void printf(const char *fmt, A... a) { std::printf(fmt, a...); } - void println() { std::printf("\n"); } - void println(const char *s) { std::printf("%s\n", s); } - void println(const String &s) { std::printf("%s\n", s.c_str()); } - void println(int v) { std::printf("%d\n", v); } + // Test support: when sink is non-null, every printed chunk is ALSO + // captured there (bounded ring) so headless tests can assert on the + // transcript. The interactive emulator leaves it null — zero overhead. + std::deque *sink = nullptr; + void capture(const char *s) + { + if (!sink) return; + sink->push_back(s); + while (sink->size() > 512) sink->pop_front(); + } + template void printf(const char *fmt, A... a) + { + char buf[512]; + std::snprintf(buf, sizeof(buf), fmt, a...); + std::fputs(buf, stdout); + capture(buf); + } + void println() { std::printf("\n"); capture("\n"); } + void println(const char *s) { std::printf("%s\n", s); capture(s); capture("\n"); } + void println(const String &s) { std::printf("%s\n", s.c_str()); capture(s.c_str()); capture("\n"); } + void println(int v) { std::printf("%d\n", v); capture(std::to_string(v).c_str()); capture("\n"); } void setDebugOutput(bool) {} }; diff --git a/emulator/tests/README.md b/emulator/tests/README.md new file mode 100644 index 0000000..3e440d1 --- /dev/null +++ b/emulator/tests/README.md @@ -0,0 +1,62 @@ +# NetDeck headless tests + +Three layers, all running on the host (no device needed). The sketch is +compiled into each test binary as a **single translation unit** (the same +`#include APP_INO` trick `emulator/src/main.cpp` uses), which gives tests +direct access to the sketch's internal statics — no refactor required to +make the game testable. + +## Layers + +| Layer | Binary | Speed | What it drives | Assertions | +| --- | --- | --- | --- | --- | +| **Unit** | `NetDeck-tests` | ms | pure logic directly: `bfsPath`, `losClear`, `tryLink`, `severLink`, `stepSim` ticks | game state | +| **Integration** | `NetDeck-tests` | ms | subsystems through their entry points: `pollKeyboard` → `handleKey`, clicks → `registerClick`, multi-tick sim scenarios | state + serial transcript | +| **E2E** | `NetDeck-e2e` (separate build) | ~1–2 min | the real thing: `setup()` → `loop()` iterations, boot grace, inputs through the device pipeline (0x55 keyboard queue, GT911 touch state, trackball pin ISRs) | serial transcript + framebuffer pixels | + +E2E is a separate build because it is real-time paced (the scenario runs at +20 Hz wall time) and needs SDL/TTF runtime for text rendering; everything +else is deterministic and instant. + +## Running + +```sh +make netdeck-test # everything: unit + integration + E2E (from repo root) +make netdeck-test-unit # fast layer only +make netdeck-test-e2e # E2E only +``` + +From `emulator/` directly: `make test APP=NetDeck`, `make test-e2e APP=NetDeck`. +Both binaries accept a name-prefix filter: `./NetDeck-tests unit`, +`./NetDeck-tests integration/daemon`, `./NetDeck-e2e e2e/network`. + +## Adding tests + +- **Unit**: append a `TEST(unit/your_case)` block to `tests/unit_tests.h`. + Call `freshScenario()` first (fixed RNG seed + clean state). Step time with + `stepTicks(n)` — 20 ticks = 1 s of sim, no wall time. +- **Integration**: append `TEST(integration/your_case)` to + `tests/integration_tests.h`. Drive input via `test::typeKey()` + + `pollKeyboard()`, `clickNode()` / `clickTile()`, then `stepTicks()`. +- **E2E**: append `TEST(e2e/your_journey)` to `tests/e2e_tests.cpp`. Start + with `reboot()`, schedule inputs with `schedule(t, 'key')` / + `scheduleTap(t, x, y)` (seconds after journey start), pump with + `pumpUntil(deadline, donePredicate)`, assert with `test::serialHas()` and + `test::pixelIs565()`. + +## Conventions / gotchas + +- `freshScenario()` resets the scenario AND the view mode (`resetScenario` + deliberately keeps the view); `reboot()` additionally rewinds the boot + phase, which plain `setup()` does not do. +- The serial transcript is a 512-line ring (`Serial.sink`); clear it with + `test::serialClear()` before the stretch you assert on, or assert right + after the event (combat logs can flood it). +- Sim RNG is seeded (`0xC0FFEE`) — combat hit/miss rolls are reproducible + per seed, but not across libcs. Prefer structural assertions (someone took + damage / link dropped) over exact hit counts. +- Keypress timing in E2E must clear the 1.4 s boot grace (schedule keys at + t ≥ 2.0 s). +- The firmware build itself is exercised by `make netdeck` — the Arduino + preprocessor catches things the emulator TU does not (e.g. prototype + injection vs custom-type parameters). diff --git a/emulator/tests/e2e_tests.cpp b/emulator/tests/e2e_tests.cpp new file mode 100644 index 0000000..6877c7f --- /dev/null +++ b/emulator/tests/e2e_tests.cpp @@ -0,0 +1,182 @@ +/** + * @file e2e_tests.cpp + * @brief End-to-end tests — SEPARATE BUILD (NetDeck-e2e). + * + * Unlike the fast suites (test_main.cpp), E2E drives the sketch through its + * REAL entry points: setup() -> loop() iterations, with inputs injected + * through the actual device pipeline (0x55 keyboard queue, GT911 touch + * state, trackball pin ISRs) and wall-clock boot grace. Assertions read the + * serial transcript and the rendered framebuffer, like a player would. + * + * Slower by nature (~1-2 min: the scenario runs at 20 Hz real time), which + * is why it gets its own build and its own make target. + */ +#include "harness.h" + +#include +#include + +// pull in the whole sketch as a single translation unit (-DAPP_INO) +#include APP_INO +#include "sim_helpers.h" // stepTicks() etc. (needs sketch statics) + +// --------------------------------------------------------------------------- +// mini host: scheduled inputs by wall-clock time, loop() driven for real +// --------------------------------------------------------------------------- +struct Evt { + double at; // seconds after journey start + char key; // 0 = screen tap instead + int x, y; // tap coords + bool fired = false; + int holdIters = 0; +}; + +static std::vector g_evts; +static unsigned long g_iters = 0; + +static void schedule(double at, char key) { g_evts.push_back({at, key, 0, 0}); } +static void scheduleTap(double at, int x, int y) { g_evts.push_back({at, 0, x, y}); } + +static void pumpEvents(double el) +{ + for (auto &e : g_evts) { + if (!e.fired && el >= e.at) { + e.fired = true; + if (e.key) { + test::typeKey(e.key); + } else { + emu::touchDown = true; + emu::touchX = e.x; + emu::touchY = e.y; + e.holdIters = 60; // ~80 ms press, like main.cpp + } + } else if (e.fired && e.holdIters > 0 && --e.holdIters == 0) { + emu::touchDown = false; // release -> pollTouch edge + } + } +} + +// run loop() iterations until done() fires or the deadline expires. +// With a completion predicate: true = done() fired. Without one (plain +// timed run): true once the deadline elapses. +// Does NOT touch the schedule — journeys clear/schedule explicitly. +static bool pumpUntil(double deadlineSec, bool (*done)()) +{ + double t0 = millis() / 1000.0; + g_iters = 0; + for (;;) { + double el = millis() / 1000.0 - t0; + pumpEvents(el); + emu::dispatchIsrs(); + loop(); + g_iters++; + if (done && done()) return true; + if (millis() / 1000.0 - t0 > deadlineSec) return done == nullptr; + } +} +static bool pumpFor(double seconds) +{ + return pumpUntil(seconds, nullptr); +} + +// fresh boot for a journey: setup() does not rewind the app's own flow state, +// so the harness rewinds what a power-cycle would (boot phase + view baseline) +static void reboot() +{ + gameState = ST_BOOT; + viewMode = VM_CAMERAS; + test::resetInput(); + test::serialClear(); + g_evts.clear(); + setup(); +} + +// --------------------------------------------------------------------------- +// journeys +// --------------------------------------------------------------------------- +static bool bootDone() { return test::serialHas("[boot] encounter loaded"); } +static bool spikeSeen() { return test::serialHas("[net] FEEDBACK SPIKE"); } +static bool droidDown() { return test::serialHas("SECURITY DROID destroyed"); } + +TEST(e2e/boot_and_controls) +{ + reboot(); + EXPECT(pumpUntil(8.0, bootDone)); + + schedule(2.2, 'p'); // -> Network view + schedule(2.6, ' '); // freeze OFF + schedule(3.0, 'r'); // reset (re-pauses) + test::serialClear(); + EXPECT(pumpFor(4.5)); // run the inputs through loop() + EXPECT(test::serialHas("[key] view -> NETWORK")); + EXPECT(test::serialHas("[key] tactical freeze OFF")); + EXPECT(test::serialHas("[key] RESET")); + + // HUD separator rendered across the top of the HUD bar + EXPECT(test::pixelIs565(160, nd::HUD_Y, nd::C_BORDER)); + // paused -> freeze scanlines: every 3rd view row is black + EXPECT(test::pixelIs565(50, 0, 0x0000)); + EXPECT(test::pixelIs565(50, 3, 0x0000)); + EXPECT(!test::pixelIs565(50, 1, 0x0000)); +} + +TEST(e2e/network_journey) +{ + reboot(); + schedule(2.0, 'p'); // Network view + scheduleTap(2.4, 36, 164); // AIRLK + scheduleTap(2.8, 148, 52); // JUNC (route, 1.5 s) + schedule(3.1, ' '); // unpause -> build completes + scheduleTap(6.0, 284, 36); // HIVE (3 s ICE) + EXPECT(pumpUntil(30.0, spikeSeen)); // ... trace ... feedback spike + EXPECT(test::serialHas("[spawn] reinforcement droid")); + stepTicks(1); + EXPECT(units[6].alive); + EXPECT(heatT > 0); // OVERHEAT lockout engaged +} + +TEST(e2e/corridor_assault) +{ + reboot(); + schedule(2.0, 'r'); // clean re-arm (clears overheat) + scheduleTap(2.4, 164, 100); // beacon into the corridor + schedule(2.7, ' '); // unpause + EXPECT(pumpUntil(60.0, droidDown)); // squad engages the garrison + stepTicks(2); + bool garrisonHit = !units[2].alive || !units[3].alive; + EXPECT(garrisonHit || test::serialHas("[combat]")); +} + +int main(int argc, char **argv) +{ + // headless: no window needed — rendering goes into the shim framebuffer + SDL_setenv("SDL_VIDEODRIVER", "dummy", 1); + if (SDL_Init(SDL_INIT_VIDEO) != 0) { + std::printf("SDL_Init failed: %s\n", SDL_GetError()); + return 2; + } + TTF_Init(); // drawString needs real fonts + + const char *filter = argc > 1 ? argv[1] : nullptr; + test::captureSerial(); + test::g_group = "e2e"; + std::srand(0xC0FFEE); + + int run = 0; + for (const auto &c : test::cases()) { + if (filter && std::strncmp(c.name, filter, std::strlen(filter)) != 0) + continue; + test::g_current = c.name; + std::printf("RUN %s\n", c.name); + c.fn(); + run++; + } + + TTF_Quit(); + SDL_Quit(); + std::printf("\n%s: %d %s, %d failure%s\n", + run ? "DONE" : "NO TESTS MATCHED FILTER", + run, run == 1 ? "journey" : "journeys", + test::g_failures, test::g_failures == 1 ? "" : "s"); + return (run > 0 && test::g_failures == 0) ? 0 : 1; +} diff --git a/emulator/tests/harness.h b/emulator/tests/harness.h new file mode 100644 index 0000000..af4764b --- /dev/null +++ b/emulator/tests/harness.h @@ -0,0 +1,115 @@ +/** + * @file harness.h + * @brief Minimal headless test harness for the T-Deck emulator shims. + * + * Must be included BEFORE the sketch (it only depends on the shims, never on + * sketch internals). Sketch-level helpers (stepSim, units, ...) live in the + * test suites themselves, which are included AFTER the sketch. + * + * Framework: TEST(name) registers a case; EXPECT/EXPECT_EQ assert; the runner + * in test_main.cpp / e2e_tests.cpp reports failures and exits non-zero. + */ +#pragma once +#include "Arduino.h" +#include "TFT_eSPI.h" // rgb565to888 for pixel assertions +#include "emu_gfx.h" +#include +#include +#include +#include + +namespace test { + +struct Case { + const char *name; + void (*fn)(); +}; +inline std::vector &cases() +{ + static std::vector c; + return c; +} +struct Registrar { + Registrar(const char *name, void (*fn)()) { cases().push_back({name, fn}); } +}; + +inline int g_failures = 0; +inline std::string g_current; // full case name, e.g. "unit/map_queries" +inline std::string g_group; // prefix before the first '/' + +inline void fail(const char *file, int line, const std::string &what) +{ + std::printf(" FAIL [%s/%s] %s:%d %s\n", g_group.c_str(), g_current.c_str(), + file, line, what.c_str()); + g_failures++; +} + +// --- serial transcript helpers (Serial.sink is set by captureSerial()) --- +inline std::string serialJoined() +{ + std::string all; + if (Serial.sink) + for (const auto &l : *Serial.sink) all += l; + return all; +} +inline bool serialHas(const std::string &pat) +{ + return serialJoined().find(pat) != std::string::npos; +} +inline void serialClear() +{ + if (Serial.sink) Serial.sink->clear(); +} +inline void captureSerial() +{ + static std::deque ring; + Serial.sink = ˚ +} + +// --- input pipeline helpers (the same state the SDL host writes) --- +inline void resetInput() +{ + for (auto &p : emu::pinLevels) p = 1; // everything pulled up + while (!emu::keyboard.empty()) emu::keyboard.pop_front(); + emu::touchDown = false; + emu::touchX = emu::touchY = 0; +} +// queue a key on the fake 0x55 keyboard device (consumed by pollKeyboard()) +inline void typeKey(char c) { emu::keyboard.push_back((uint8_t)c); } + +// --- framebuffer helpers (E2E pixel assertions) --- +inline uint32_t pixel(int x, int y) +{ + if (x < 0 || y < 0 || x >= emuGfx::W || y >= emuGfx::H) return 0; + return emuGfx::fb[y * emuGfx::W + x]; +} +inline bool pixelIs565(int x, int y, uint16_t c565) +{ + return pixel(x, y) == rgb565to888(c565); +} + +} // namespace test + +// The display name may contain '/' (e.g. "unit/map_queries") — identifiers +// are generated from __LINE__, so the name string itself is never pasted. +#define TEST_CAT2(a, b) a##b +#define TEST_CAT(a, b) TEST_CAT2(a, b) +#define TEST(name) \ + static void TEST_CAT(test_case_, __LINE__)(); \ + static test::Registrar TEST_CAT(reg_case_, __LINE__)( \ + #name, TEST_CAT(test_case_, __LINE__)); \ + static void TEST_CAT(test_case_, __LINE__)() + +#define EXPECT(cond) \ + do { \ + if (!(cond)) test::fail(__FILE__, __LINE__, "expected " #cond); \ + } while (0) + +#define EXPECT_EQ(a, b) \ + do { \ + if (!((a) == (b))) \ + test::fail(__FILE__, __LINE__, \ + std::string(#a " == " #b) + " (got: " + \ + std::to_string((long long)(a)) + " vs " + \ + std::to_string((long long)(b)) + ")"); \ + } while (0) diff --git a/emulator/tests/integration_tests.h b/emulator/tests/integration_tests.h new file mode 100644 index 0000000..60b5b43 --- /dev/null +++ b/emulator/tests/integration_tests.h @@ -0,0 +1,122 @@ +/** + * @file integration_tests.h + * @brief Integration tests: several sketch subsystems cooperating — + * keyboard device -> pollKeyboard -> handleKey, cursor clicks -> + * registerClick -> beacon/node routing, sim ticks -> combat/objective + * flow. Still deterministic (fixed seed, direct tick stepping, no + * wall time, no rendering — pixels are the E2E layer's job). + * + * Included by test_main.cpp AFTER the sketch and unit_tests.h. + */ +#include "sim_helpers.h" + +TEST(integration/keyboard_device_pipeline) +{ + freshScenario(); + test::resetInput(); + test::typeKey('p'); // keyboard device @0x55 + pollKeyboard(); // -> handleKey + EXPECT_EQ(viewMode, VM_NETWORK); + test::typeKey(' '); + pollKeyboard(); + EXPECT(!paused); // freeze OFF + test::typeKey('p'); + pollKeyboard(); + EXPECT_EQ(viewMode, VM_CAMERAS); + test::typeKey('r'); + pollKeyboard(); + EXPECT(test::serialHas("[key] RESET")); + EXPECT(paused); // reset re-arms paused +} + +TEST(integration/beacon_click_paths_the_squad) +{ + freshScenario(); + clickTile(20, 12); // corridor floor + EXPECT_EQ(beaconTX, 20); + EXPECT_EQ(beaconTY, 12); + EXPECT(test::serialHas("[click] beacon -> tile 20,12")); + stepTicks(200); // marines march + engage + bool progressed = units[0].tx >= 6 || !units[2].alive; + EXPECT(progressed); // moving and/or fighting + EXPECT(test::serialHas("[combat]")); // contact was made + for (const auto &t : tracers) EXPECT(t.ttl >= 0 && t.ttl <= 2); +} + +TEST(integration/click_blocked_tile_keeps_beacon) +{ + freshScenario(); + clickTile(20, 12); // valid first + int bx = beaconTX, by = beaconTY; + clickTile(5, 0); // wall tile + EXPECT(test::serialHas("beacon ignored")); + EXPECT_EQ(beaconTX, bx); // unchanged + EXPECT_EQ(beaconTY, by); +} + +TEST(integration/full_network_journey) +{ + freshScenario(); + handleKey('p'); // Network view + clickNode(N_JUNC); // route AIRLK-JUNC + stepTicks(LINK_TICKS); + EXPECT(nodeOnline[N_JUNC]); + clickNode(N_DOOR); // route JUNC-DOOR + stepTicks(LINK_TICKS); + EXPECT(nodeOnline[N_DOOR]); + EXPECT(!doorOpen); + clickNode(N_DOOR); // online DOOR toggles + EXPECT(doorOpen); + clickNode(N_HIVE); // 3 s ICE + stepTicks(ICE_TICKS); + EXPECT(hiveCracked); + EXPECT(traceActive); + stepTicks(TRACE_TICKS); + EXPECT(heatT > 0); // feedback spike cooldown + EXPECT(units[6].alive); // reinforcement spawned + EXPECT(!nodeOnline[N_JUNC]); // spike dropped the net +} + +TEST(integration/sever_via_hovered_link) +{ + freshScenario(); + handleKey('p'); + clickNode(N_JUNC); + stepTicks(LINK_TICKS); + EXPECT(nodeOnline[N_JUNC]); + // midpoint of the AIRLK(36,164)-JUNC(148,52) segment + curX = (nodePx(N_AIRLK) + nodePx(N_JUNC)) / 2; + curY = (nodePy(N_AIRLK) + nodePy(N_JUNC)) / 2; + EXPECT_EQ(hoverLink(), linkIdx(0)); + handleKey('x'); + EXPECT(test::serialHas("[net] severed AIRLK-JUNC")); + EXPECT(!nodeOnline[N_JUNC]); +} + +TEST(integration/sever_during_trace_is_safe) +{ + freshScenario(); + handleKey('p'); + clickNode(N_JUNC); stepTicks(LINK_TICKS); + clickNode(N_HIVE); stepTicks(ICE_TICKS); + EXPECT(traceActive); // trace running + curX = (nodePx(N_JUNC) + nodePx(N_HIVE)) / 2; // hover the ICE link + curY = (nodePy(N_JUNC) + nodePy(N_HIVE)) / 2; + handleKey('x'); // sever before arrival + EXPECT(!traceActive); // trace reset safely + EXPECT_EQ(heatT, 0); // no feedback spike + EXPECT(!units[6].alive); // no reinforcement +} + +TEST(integration/daemon_gating_messages) +{ + freshScenario(); + handleKey('1'); // no HIVE link yet + EXPECT_EQ(strcmp(msgText, "NO HIVE LINK"), 0); + handleKey('p'); + clickNode(N_JUNC); stepTicks(LINK_TICKS); + clickNode(N_HIVE); stepTicks(ICE_TICKS); + handleKey('1'); // HIVE online -> armed + EXPECT_EQ(strcmp(msgText, "M4 PENDING"), 0); // payload lands in M4 + EXPECT(test::serialHas("daemon 1 armed")); +} diff --git a/emulator/tests/shim_globals.cpp b/emulator/tests/shim_globals.cpp new file mode 100644 index 0000000..5e2e182 --- /dev/null +++ b/emulator/tests/shim_globals.cpp @@ -0,0 +1,36 @@ +/** + * @file shim_globals.cpp + * @brief Definitions of the shim globals that src/main.cpp normally owns. + * + * Both test binaries (NetDeck-tests, NetDeck-e2e) link this instead of + * main.cpp, so they get the shim environment without the SDL window/event + * host loop. The sketch itself is included by each test's own TU (single-TU + * inclusion, same trick main.cpp uses). + */ +#include "Arduino.h" +#include "TFT_eSPI.h" +#include "Wire.h" +#include "SPI.h" + +namespace emu { +uint8_t pinLevels[64]; +bool touchDown = false; +int touchX = 0, touchY = 0; +std::deque keyboard; +bool quitRequested = false; +} // namespace emu + +namespace emuGfx { +uint32_t fb[320 * 240]; +SDL_Texture *tex = nullptr; +bool dirty = true; +} // namespace emuGfx + +SerialSim Serial; +TwoWire Wire; +SPIClass SPI; + +const FreeFontStub FreeSansBold24pt7b {0}; +const FreeFontStub FreeSansBold18pt7b {0}; +const FreeFontStub FreeSansOblique12pt7b {0}; +const FreeFontStub FreeSans12pt7b {0}; diff --git a/emulator/tests/sim_helpers.h b/emulator/tests/sim_helpers.h new file mode 100644 index 0000000..6ad7ec5 --- /dev/null +++ b/emulator/tests/sim_helpers.h @@ -0,0 +1,42 @@ +/** + * @file sim_helpers.h + * @brief Test helpers that touch sketch internals — include AFTER the + * sketch (single-TU inclusion gives the tests access to the + * sketch's statics, exactly like main.cpp gets them). + */ +#pragma once +#include "harness.h" + +// advance the deterministic 20 Hz simulation by n ticks (no wall time) +inline void stepTicks(int n) +{ + for (int i = 0; i < n; i++) stepSim(); +} + +// click exactly on a network node (Network view) — cursor + primary action +inline void clickNode(int node) +{ + curX = nodePx(node); + curY = nodePy(node); + registerClick(); +} + +// click the center of a map tile (Cameras view) — places the beacon +inline void clickTile(int tx, int ty) +{ + curX = tx * nd::TILE + nd::TILE / 2; + curY = ty * nd::TILE + nd::TILE / 2; + registerClick(); +} + +// find the active link on an edge, or -1 +inline int linkIdx(int edge) { return linkOnEdge(edge); } + +// fresh deterministic scenario state for a test +inline void freshScenario(unsigned seed = 0xC0FFEE) +{ + std::srand((unsigned)seed); + resetScenario(); + viewMode = VM_CAMERAS; // resetScenario deliberately keeps the view + test::serialClear(); +} diff --git a/emulator/tests/test_main.cpp b/emulator/tests/test_main.cpp new file mode 100644 index 0000000..8e9c2ec --- /dev/null +++ b/emulator/tests/test_main.cpp @@ -0,0 +1,46 @@ +/** + * @file test_main.cpp + * @brief Runner for the fast headless suites: unit + integration. + * + * The sketch is included as a single translation unit (the same trick the + * emulator host uses), which gives the tests direct access to the sketch's + * internal statics — no refactor needed to make the game testable. + * + * Deterministic: no wall-clock waits (tests step the 20 Hz sim tick by tick) + * and a fixed RNG seed. Rendering and pixel assertions belong to the E2E + * binary (e2e_tests.cpp). + */ +#include "harness.h" + +// pull in the whole sketch as a single translation unit (-DAPP_INO) +#include APP_INO + +#include "unit_tests.h" +#include "integration_tests.h" + +int main(int argc, char **argv) +{ + // optional filter: ./NetDeck-tests unit | ./NetDeck-tests int + const char *filter = argc > 1 ? argv[1] : nullptr; + + test::captureSerial(); + std::srand(0xC0FFEE); + + int run = 0; + for (const auto &c : test::cases()) { + if (filter && std::strncmp(c.name, filter, std::strlen(filter)) != 0) + continue; + test::g_current = c.name; + size_t slash = test::g_current.find('/'); + test::g_group = slash == std::string::npos ? "" : test::g_current.substr(0, slash); + std::printf("RUN %s\n", c.name); + c.fn(); + run++; + } + + std::printf("\n%s: %d test%s, %d failure%s\n", + run ? "DONE" : "NO TESTS MATCHED FILTER", + run, run == 1 ? "" : "s", + test::g_failures, test::g_failures == 1 ? "" : "s"); + return (run > 0 && test::g_failures == 0) ? 0 : 1; +} diff --git a/emulator/tests/unit_tests.h b/emulator/tests/unit_tests.h new file mode 100644 index 0000000..0cebf9f --- /dev/null +++ b/emulator/tests/unit_tests.h @@ -0,0 +1,206 @@ +/** + * @file unit_tests.h + * @brief Unit tests: pure sketch logic in isolation (map queries, LOS, + * pathfinding, cover, link state machine, combat rules, flow + * transitions). No rendering, no input pipeline, no wall time — + * determinism comes from freshScenario()'s fixed RNG seed. + * + * Included by test_main.cpp AFTER the sketch, so sketch statics are visible. + */ +#include "sim_helpers.h" + +// --- map queries ----------------------------------------------------------- + +TEST(unit/map_queries) +{ + freshScenario(); + EXPECT_EQ(tileAt(-1, 0), '#'); // out of bounds = wall + EXPECT_EQ(tileAt(40, 0), '#'); + EXPECT_EQ(tileAt(28, 12), '+'); // the blast door tile + EXPECT(!walkable(0, 0)); // '#' + EXPECT(walkable(20, 12)); // corridor floor + EXPECT(walkable(2, 21)); // airlock 'A' + EXPECT(walkable(34, 7)); // objective terminal 'T' + EXPECT(blocksSight(0, 0)); + EXPECT(!blocksSight(20, 12)); + EXPECT_EQ(DEMO_MAP[7][34], 'T'); // the win tile really is T +} + +TEST(unit/door_gates_movement_and_sight) +{ + freshScenario(); + EXPECT(!walkable(28, 12)); // closed door blocks movement + EXPECT(blocksSight(28, 12)); // ... and sight + doorOpen = true; + EXPECT(walkable(28, 12)); + EXPECT(!blocksSight(28, 12)); + doorOpen = false; + EXPECT(!walkable(28, 12)); +} + +// --- line of sight --------------------------------------------------------- + +TEST(unit/los_wall_and_door) +{ + freshScenario(); + EXPECT(losClear(1, 1, 9, 1)); // along open floor + EXPECT(!losClear(1, 1, 11, 1)); // wall at col 10 + EXPECT(!losClear(27, 12, 29, 12)); // through CLOSED door + doorOpen = true; + EXPECT(losClear(27, 12, 29, 12)); // through OPEN door + doorOpen = false; +} + +// --- pathfinding ----------------------------------------------------------- + +TEST(unit/bfs_door_gates_the_route) +{ + freshScenario(); + int path[64]; + EXPECT_EQ(bfsPath(2, 21, 34, 7, path, 64), -1); // no route, door closed + doorOpen = true; + int n = bfsPath(2, 21, 34, 7, path, 64); + EXPECT(n > 0); + for (int i = 0; i < n; i++) { // every step walkable + int t = path[i]; + EXPECT(walkable(t % nd::TILE_COLS, t / nd::TILE_COLS)); + } + EXPECT_EQ(bfsPath(2, 21, 0, 0, path, 64), -1); // wall target unreachable +} + +TEST(unit/bfs_respects_capacity) +{ + freshScenario(); + doorOpen = true; + int path[4]; // tiny buffer + EXPECT_EQ(bfsPath(2, 21, 34, 7, path, 4), -1); // longer than cap -> fail +} + +// --- cover ----------------------------------------------------------------- + +TEST(unit/cover_rule) +{ + freshScenario(); + spawnUnit(6, U_DROID, 4, 4); // beside the crate at (5,4) + EXPECT(inCover(6)); + spawnUnit(6, U_DROID, 20, 10); // open corridor floor + EXPECT(!inCover(6)); +} + +// --- link state machine ------------------------------------------------------ + +TEST(unit/link_routing_and_online) +{ + freshScenario(); + tryLink(N_JUNC); // AIRLK root is online + int l = linkIdx(0); // edge AIRLK-JUNC + EXPECT(l >= 0); + EXPECT(!nodeOnline[N_JUNC]); // offline while building + stepTicks(LINK_TICKS); + EXPECT(nodeOnline[N_JUNC]); // up after 1.5 s of ticks + tryLink(N_DOOR); + stepTicks(LINK_TICKS); + EXPECT(nodeOnline[N_DOOR]); +} + +TEST(unit/link_rejects_non_adjacent) +{ + freshScenario(); + tryLink(N_HIVE); // not adjacent to AIRLK + EXPECT_EQ(strcmp(msgText, "NO UPLINK"), 0); + EXPECT(linkIdx(2) < 0); // JUNC-HIVE not routed +} + +TEST(unit/sever_cascades_downstream) +{ + freshScenario(); + tryLink(N_JUNC); stepTicks(LINK_TICKS); + tryLink(N_DOOR); stepTicks(LINK_TICKS); + tryLink(N_HIVE); stepTicks(ICE_TICKS); + EXPECT(nodeOnline[N_HIVE]); + int door = linkIdx(1); // JUNC-DOOR + severLink(door); + EXPECT(!nodeOnline[N_DOOR]); + EXPECT(nodeOnline[N_JUNC]); // upstream survives + EXPECT(linkIdx(1) < 0); +} + +// --- trace / feedback / reinforcement --------------------------------------- + +TEST(unit/ice_trace_feedback_reinforcement) +{ + freshScenario(); + tryLink(N_JUNC); stepTicks(LINK_TICKS); + tryLink(N_HIVE); stepTicks(ICE_TICKS); + EXPECT(hiveCracked); + EXPECT(traceActive); // red trace inbound + stepTicks(TRACE_TICKS); // trace reaches AIRLK + EXPECT(!traceActive); + EXPECT(heatT > 0 && heatT <= HEAT_TICKS); // OVERHEAT lockout engaged + EXPECT(linkIdx(0) < 0 && linkIdx(1) < 0 && linkIdx(2) < 0); + EXPECT(!nodeOnline[N_JUNC]); // everything past root drops + EXPECT(nodeOnline[N_AIRLK]); + EXPECT(units[6].alive); // reinforcement droid spawned +} + +TEST(unit/overheat_gates_daemons_and_sever) +{ + freshScenario(); + heatT = HEAT_TICKS; + handleKey('1'); + EXPECT_EQ(strcmp(msgText, "OVERHEAT"), 0); + handleKey('x'); + EXPECT_EQ(strcmp(msgText, "OVERHEAT"), 0); + stepTicks(HEAT_TICKS); + EXPECT_EQ(heatT, 0); // lockout expires +} + +// --- combat rules ------------------------------------------------------------ + +TEST(unit/target_acquisition_needs_range_and_los) +{ + freshScenario(); + spawnUnit(6, U_MARINE, 5, 7); + spawnUnit(0, U_DROID, 20, 12); // far outside marine range + spawnUnit(1, U_DROID, 8, 7); // same room, clear LOS + EXPECT_EQ(acquireTarget(6), 1); + units[1].tx = 11; units[1].ty = 7; // still in range (6 tiles) + EXPECT_EQ(acquireTarget(6), -1); // but the col-10 wall at + // row 7 blocks sight +} + +TEST(unit/win_and_loss_transitions) +{ + freshScenario(); + for (int i = 2; i < 7; i++) // clear the terminal guards: + if (units[i].alive) unitKill(i); // no target -> marine walks + beaconTX = 34; beaconTY = 7; + units[0].tx = 33; units[0].ty = 7; // adjacent, path in + stepTicks(1); // arrive -> BREACH SUCCESS + EXPECT_EQ(scenario, SC_WIN); + + freshScenario(); + unitKill(0); + unitKill(1); + stepTicks(1); + EXPECT_EQ(scenario, SC_LOSS); +} + +TEST(unit/reset_rearms_everything) +{ + freshScenario(); + units[0].tx = 34; units[0].ty = 7; + stepTicks(1); // -> SC_WIN mess + resetScenario(); + EXPECT_EQ(scenario, SC_LIVE); + EXPECT(paused); + EXPECT(units[0].alive && units[1].alive); + EXPECT_EQ(units[0].tx, 2); // back in the airlock + EXPECT_EQ(units[0].hp, STATS[U_MARINE].maxHp); + EXPECT(!units[6].alive); // reinforcement slot cleared + EXPECT(!doorOpen); + EXPECT_EQ(heatT, 0); + EXPECT(linkIdx(0) < 0 && linkIdx(1) < 0 && linkIdx(2) < 0); + EXPECT(nodeOnline[N_AIRLK]); // the old root-online bug + EXPECT(!nodeOnline[N_JUNC] && !nodeOnline[N_DOOR] && !nodeOnline[N_HIVE]); +} diff --git a/src/netdeck/STATUS.md b/src/netdeck/STATUS.md index c7844e5..ac15976 100644 --- a/src/netdeck/STATUS.md +++ b/src/netdeck/STATUS.md @@ -134,6 +134,16 @@ squad through) completes in M4; until then the loss path + reset are the verifiable branches. On-device check still pending (inherits the M1 checklist in §M1 above). +### Headless test structure + +Tests live in `emulator/tests/` (see its README): **unit** + +**integration** suites share one fast deterministic binary +(`NetDeck-tests` — 21 tests, single-TU sketch inclusion, sim stepped tick by +tick), and **E2E** is a separate build (`NetDeck-e2e`) driving the real +`loop()` through the device input pipeline with transcript + pixel +assertions. One command from the repo root: `make netdeck-test` +(`make netdeck` builds both firmware + emulator). + ### Source layout (this commit) The sketch moved from `examples/NetDeck/NetDeck.ino` to