#pragma once
// tttest.hpp - zero-dependency C++20 test framework (stdlib + POSIX only).
// Own framework for the ttgui suite (tests/): TEST_CASE/SECTION, CHECK vs
// REQUIRE with stringified expressions + file:line, tags, filters, repeat/
// shuffle-with-seed, per-case timeout, console/TAP/JSON reporters, golden
// screens (CHECK_GOLDEN/CHECK_CELLS/CHECK_SCREEN), FakeClock/SeededRng/
// SandboxDir determinism seams. Runner contract, tiers, and the
// requirement->test traceability table live in tests/README.md.
// Exit codes: 0 all pass, 1 failures, 2 usage error. SKIP is never a pass.
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <functional>
#include <future>
#include <iostream>
#include <map>
#include <memory>
#include <random>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include <unistd.h>
namespace tttest {
/** @brief One recorded assertion failure: source `file`/`line`, stringified `expr`, human `msg`, and `fatal` (REQUIRE) vs non-fatal (CHECK). */
struct Failure { std::string file; int line=0; std::string expr; std::string msg; bool fatal=false; };
/** @brief Thrown by SKIP_TEST; carries the mandatory skip `reason`. Caught by the runner and reported as SKIP, never PASS. */
struct SkipException { std::string reason; };
/** @brief Internal control-flow exception: a fatal REQUIRE aborts the current case only. */
struct RequireAbort {};
/** @brief Internal control-flow exception: a finished SECTION pass restarts the case body for the next section. */
struct SectionFinished {};
/**
* @brief One registered test case: `name`, raw `tags` string ("[a][b]"),
* registration `file`/`line`, and the case body `func`.
* @details `tagList()` parses the bracketed tags; `hasTag(t)` tests membership.
*/
struct TestCaseInfo {
std::string name; std::string tags; std::string file; int line=0;
std::function<void()> func;
std::vector<std::string> tagList() const {
std::vector<std::string> out; std::string cur;
for(char c: tags){ if(c=='['){cur.clear();} else if(c==']'){ if(!cur.empty()) out.push_back(cur); } else cur+=c; }
return out;
}
bool hasTag(const std::string& t) const { auto v=tagList(); return std::find(v.begin(),v.end(),t)!=v.end(); }
};
/** @brief The process-wide case registry (function-local static); Registrar appends, runAll() reads. Registration order is execution order unless shuffled. */
inline std::vector<TestCaseInfo>& registry(){ static std::vector<TestCaseInfo> r; return r; }
/**
* @brief Per-case mutable run state: recorded `failures`, `checks` count,
* skip state, and section bookkeeping (`completedSections`, `sectionStack`,
* `anySection`) that survives the section re-run passes of one case.
* `budgetSec` is reserved for per-case duration budgets.
*/
struct Context {
std::vector<Failure> failures; int checks=0; bool skipped=false; std::string skipReason;
// section state (persistent across passes)
std::set<std::string> completedSections;
std::vector<std::string> sectionStack;
bool anySection=false;
double budgetSec=0;
};
/** @brief Thread-local pointer to the running case's Context (null outside a case; set/cleared by runAll). */
inline Context*& currentCtx(){ static thread_local Context* p=nullptr; return p; }
/** @brief Runner-owned Context for the active case; counts checks made while a case temporarily swaps currentCtx() for a synthetic one. */
inline Context*& runnerCtx(){ static thread_local Context* p=nullptr; return p; }
/** @brief Thread-local pointer to the running case's name, for diagnostics. */
inline std::string*& currentCaseName(){ static thread_local std::string* p=nullptr; return p; }
/**
* @brief Record an assertion failure in the current case; throws
* RequireAbort when `fatal`. Outside a case it is a no-op (by design:
* framework self-tests exploit registries without a live Context).
*/
inline void recordFailure(const char* file,int line,const std::string& expr,const std::string& msg,bool fatal){
auto* c=currentCtx(); if(!c) return;
c->failures.push_back({file,line,expr,msg,fatal});
if(fatal) throw RequireAbort{};
}
/** @brief Count one executed assertion in the current case. */
inline void recordCheck(){ if(auto* c=currentCtx()) c->checks++; else if(auto* r=runnerCtx()) r->checks++; }
/**
* @brief Stringify a value for failure messages: streamable types via
* operator<<, others as "<unprintable>". Overloads: strings are quoted,
* const char* is null-safe and quoted, bools print true/false.
*/
template<typename T> std::string toStr(const T& v){ std::ostringstream o; if constexpr (requires{ o<<v; }) { o<<v; } else { o<<"<unprintable>"; } return o.str(); }
inline std::string toStr(const std::string& v){ return "\""+v+"\""; }
inline std::string toStr(const char* v){ return std::string("\"")+(v?v:"")+"\""; }
inline std::string toStr(bool v){ return v?"true":"false"; }
// --- Sections ---
/**
* @brief RAII guard behind SECTION: on construction it decides whether
* this section runs in the current pass (first uncompleted section path
* wins) and pushes the section name; `run` carries the decision.
* Sections are identified by their slash-joined nesting path, so nested
* sections re-run the case body once per leaf path.
*/
struct SectionScope {
std::string path; bool run=false;
explicit SectionScope(const std::string& name){
auto* c=currentCtx(); if(!c){ run=true; return; }
c->anySection=true;
std::string p; for(auto& s: c->sectionStack){ if(!p.empty()) p+="/"; p+=s; }
if(!p.empty()) p+="/";
p+=name; path=p;
if(c->completedSections.count(path)) { run=false; return; }
run=true; c->sectionStack.push_back(name);
}
};
/** @brief Marks the innermost section complete and throws SectionFinished to start the next pass. Called by the SECTION macro, not by users. */
inline void endSection(){
auto* c=currentCtx(); if(!c||c->sectionStack.empty()) return;
std::string p; for(auto& s: c->sectionStack){ if(!p.empty()) p+="/"; p+=s; }
c->sectionStack.pop_back();
c->completedSections.insert(p);
throw SectionFinished{};
}
// --- Determinism hooks ---
/**
* @brief Manual clock for tests: `advance(ms)` moves `nowMs`, `now()`
* reads it. `withinDoubleClick(a, b, dblMs)` reports |b-a| < dblMs — the
* exact boundary rule used for double-click timing tests. Nothing in the
* suite reads wall time for behaviour, only for reported durations.
*/
struct FakeClock {
long long nowMs=0;
void advance(long long ms){ nowMs+=ms; }
long long now() const { return nowMs; }
// double-click boundary helper
bool withinDoubleClick(long long a,long long b,int dblMs) const { (void)a;(void)b; return std::llabs(b-a) < dblMs; }
};
/**
* @brief Deterministic RNG (std::mt19937). `SeededRng(seed)`;
* `nextInt(lo, hi)` inclusive; `nextSize(hi)` returns an index in
* [0, hi) or 0 for hi == 0. Same seed, same stream, every run.
*/
struct SeededRng {
std::mt19937 rng;
explicit SeededRng(unsigned seed=42):rng(seed){}
int nextInt(int lo,int hi){ std::uniform_int_distribution<int> d(lo,hi); return d(rng); }
size_t nextSize(size_t hi){ return hi? (size_t)nextInt(0,(int)hi-1):0; }
};
// --- Temp sandbox ---
/**
* @brief Unique temporary directory, recursively removed on destruction.
* @details The constructor creates `$TMPDIR/tttest-sandbox-<pid>-<n>`
* (first free n; falls back to the temp dir itself). `path()` returns
* the directory; `file(name)` joins a child path. Tests must use this
* instead of $HOME or the working tree.
*/
struct SandboxDir {
std::filesystem::path dir; bool owns=false;
SandboxDir(){
auto base=std::filesystem::temp_directory_path();
for(int i=0;i<1000;i++){ auto p=base/("tttest-sandbox-"+std::to_string((long long)::getpid())+"-"+std::to_string(i));
std::error_code ec; if(std::filesystem::create_directory(p,ec)){ dir=p; owns=true; return; } }
throw std::runtime_error("SandboxDir: could not create unique sandbox under "+base.string());
}
~SandboxDir(){ if(owns){ std::error_code ec; std::filesystem::remove_all(dir,ec); } }
std::string path() const { return dir.string(); }
std::string file(const std::string& n) const { return (dir/n).string(); }
};
// --- Runner options ---
/**
* @brief Runner configuration parsed by tttest::main / set by embedders.
* @details `filter` (substring of case name), `tags`/`excludeTags`
* (parsed "[a][b]" lists; `explicitTags` records that the user asked for
* tags, which switches opt-in tiers [pty]/[fuzz]/[slow] on), `reporter`
* ("console"|"tap"|"json"), `repeat`, `shuffle` + `seed`, `failFast`,
* `listOnly`, `timeoutSec` (0 = no watchdog), `updateGolden`,
* `goldenDir`. `globalOptions()` is the process-wide instance the golden
* helpers read; `updateGoldenFlag()` mirrors --update-golden for helpers
* that receive options indirectly.
*/
struct Options {
std::string filter; std::vector<std::string> tags, excludeTags;
std::string reporter="console"; int repeat=1; bool shuffle=false; unsigned seed=42;
bool failFast=false; bool listOnly=false; double timeoutSec=0; bool updateGolden=false;
std::string goldenDir="tests/golden"; bool explicitTags=false;
};
/// @brief Process-wide Options instance used by golden/screen helpers.
inline Options& globalOptions(){ static Options o; return o; }
/// @brief Process-wide --update-golden mirror flag.
inline bool& updateGoldenFlag(){ static bool v=false; return v; }
// --- Golden ---
/** @brief Whole file as a string; "" when the file cannot be opened (a missing golden therefore fails with an empty "expected"). */
inline std::string readFileText(const std::string& p){ std::ifstream in(p); if(!in) return ""; return std::string((std::istreambuf_iterator<char>(in)),std::istreambuf_iterator<char>()); }
/** @brief Normalizes text for comparisons: strips trailing spaces/CR per line and trailing blank lines, so goldens are insensitive to padding. */
inline std::string trimRightLines(const std::string& s){
std::string out; std::istringstream iss(s); std::string line; bool first=true;
while(std::getline(iss,line)){ while(!line.empty()&&(line.back()==' '||line.back()=='\r')) line.pop_back(); if(!first) out+="\n"; first=false; out+=line; }
while(!out.empty()&&out.back()=='\n') out.pop_back();
return out;
}
/**
* @brief CHECK_GOLDEN implementation: compares `actual` with
* tests/golden/<name> (with golden/ and ../tests/golden fallbacks when
* run from tests/). With --update-golden it writes the file instead and
* always passes — a normal run never writes. Mismatches record a failure
* with expected, actual, and a per-line diff.
*/
inline bool checkGoldenImpl(const std::string& name,const std::string& actual,const char* file,int line){
recordCheck();
std::string dir=globalOptions().goldenDir;
// fallback if run from tests/ dir
if(!std::filesystem::exists(dir) && std::filesystem::exists("golden")) dir="golden";
if(!std::filesystem::exists(dir) && std::filesystem::exists("../tests/golden")) dir="../tests/golden";
std::string path=dir+"/"+name;
std::string act=trimRightLines(actual);
if(globalOptions().updateGolden || updateGoldenFlag()){
std::error_code ec; std::filesystem::create_directories(dir,ec);
std::ofstream out(path); out<<act<<"\n"; return true;
}
if(!std::filesystem::exists(path)){ recordFailure(file,line,"CHECK_GOLDEN("+name+")","missing golden file: "+path+" (regenerate with --update-golden)",false); return false; }
std::string exp=trimRightLines(readFileText(path));
if(exp!=act){
std::ostringstream msg; msg<<"golden mismatch: "<<path<<"\n--- expected ---\n"<<exp<<"\n--- actual ---\n"<<act<<"\n--- diff (E=expected A=actual) ---\n";
std::istringstream es(exp), as(act); std::string el,al; int ln=0;
while(true){ bool eok=bool(std::getline(es,el)); bool aok=bool(std::getline(as,al)); if(!eok&&!aok) break; ln++;
if(el!=al) msg<<"line "<<ln<<":\n E|"<<el<<"\n A|"<<al<<"\n"; }
recordFailure(file,line,"CHECK_GOLDEN("+name+")",msg.str(),false); return false;
}
return true;
}
// --- Screen helpers (duck-typed: .text(), .cellAt(x,y).ch, .line(y)) ---
/**
* @brief Helpers over any screen-like type (.text(), .cellAt(), .line()).
* @details `screenText(s)` is s.text(); `screenCount(s, glyph)` counts
* non-overlapping glyph occurrences in the text grid. `checkScreenImpl`
* (CHECK_SCREEN) compares trimmed grids and reports a side-by-side diff;
* `checkCellsImpl` (CHECK_CELLS) compares the glyph rectangle
* (x, y, w, h) against an expected multi-line string.
*/
template<typename S> std::string screenText(const S& s){ return s.text(); }
template<typename S> int screenCount(const S& s,const std::string& glyph){
std::string t=s.text(); int n=0; size_t pos=0; while(glyph.size() && (pos=t.find(glyph,pos))!=std::string::npos){ n++; pos+=glyph.size(); } return n;
}
/// @brief CHECK_SCREEN implementation (see the screen-helpers doc above).
inline bool checkScreenImpl(const std::string& actual,const std::string& expected,const char* file,int line){
recordCheck();
std::string a=trimRightLines(actual), e=trimRightLines(expected);
if(a!=e){
std::ostringstream msg; msg<<"screen mismatch\n--- expected ---\n"<<e<<"\n--- actual ---\n"<<a<<"\n--- side-by-side ---\n";
std::istringstream es(e), as(a); std::string el,al; int ln=0;
while(true){ bool eok=bool(std::getline(es,el)); bool aok=bool(std::getline(as,al)); if(!eok&&!aok) break; ln++;
msg<<(el==al?" ":"! ")<<ln<<": E|"<<el<<" A|"<<al<<"\n"; }
recordFailure(file,line,"CHECK_SCREEN",msg.str(),false); return false;
}
return true;
}
template<typename S>
bool checkCellsImpl(const S& s,int x,int y,int w,int h,const std::string& expected,const char* file,int line){
recordCheck();
std::string actual; for(int row=0;row<h;row++){ if(row) actual+="\n"; for(int col=0;col<w;col++) actual+=s.cellAt(x+col,y+row).ch; }
std::string a=trimRightLines(actual), e=trimRightLines(expected);
if(a!=e){ recordFailure(file,line,"CHECK_CELLS","cells mismatch in rect\n--- expected ---\n"+e+"\n--- actual ---\n"+a,false); return false; }
return true;
}
// --- Full-cell (glyph+colour+attrs) helpers ---
inline std::string colorStr(const auto& c){
std::ostringstream o; o<<"("<<c.r<<","<<c.g<<","<<c.b<<","<<c.idx<<")"; return o.str();
}
inline std::string cellStyleStr(const auto& st){
std::ostringstream o; o<<"fg"<<colorStr(st.fg)<<" bg"<<colorStr(st.bg);
if(st.bold) o<<" B";
if(st.dim) o<<" D";
if(st.underline) o<<" U";
if(st.reverse) o<<" R";
if(st.italic) o<<" I";
return o.str();
}
template<typename S> auto cellOf(const S& s,int x,int y){
if constexpr (requires{ s.cellAt(x,y); }) return s.cellAt(x,y); else return s.get(x,y);
}
template<typename S> std::pair<int,int> screenSize(const S& s){
if constexpr (requires{ s.cellAt(0,0); }) return {s.w, s.h}; else return {s.width(), s.height()};
}
// Serialize a rect as glyph rows then one style token per cell (row-major).
template<typename S> std::string fullCellRect(const S& s,int x,int y,int w,int h){
std::string out;
for(int row=0;row<h;row++){ if(row) out+="\n"; for(int col=0;col<w;col++) out+=cellOf(s,x+col,y+row).ch; }
out+="\n--styles--";
for(int row=0;row<h;row++) for(int col=0;col<w;col++){ out+="\n"; out+=cellStyleStr(cellOf(s,x+col,y+row).st); }
return out;
}
template<typename S> std::string fullCellText(const S& s){ auto sz=screenSize(s); return fullCellRect(s,0,0,sz.first,sz.second); }
template<typename S>
bool checkCellsFullImpl(const S& s,int x,int y,int w,int h,const std::string& expected,const char* file,int line){
recordCheck();
std::string a=trimRightLines(fullCellRect(s,x,y,w,h)), e=trimRightLines(expected);
if(a!=e){ recordFailure(file,line,"CHECK_CELLS_FULL","full-cell mismatch (glyph+colour+attrs)\n--- expected ---\n"+e+"\n--- actual ---\n"+a,false); return false; }
return true;
}
template<typename S>
bool checkGoldenCellsImpl(const std::string& name,const S& s,const char* file,int line){
return checkGoldenImpl(name, fullCellText(s), file, line);
}
// --- InputScript: declarative input replay through the real dispatch ---
// Steps are raw byte strings (fed via InputParser, exactly as run() does),
// synthetic Events, or ticks. Used so tests drive the same path as a TTY.
struct InputScript {
struct Step { enum Kind{Bytes, Ev, Tick} kind=Bytes; std::string bytes; int evType=0; std::function<void(void*)> apply; long long tickMs=16; };
std::vector<Step> steps;
InputScript& feed(const std::string& b){ Step s; s.kind=Step::Bytes; s.bytes=b; steps.push_back(std::move(s)); return *this; }
InputScript& key(const std::string& text){ return feed(text); }
InputScript& mouse(int btn,int x,int y,bool press){ return feed(std::string("\033[<")+std::to_string(btn)+";"+std::to_string(x+1)+";"+std::to_string(y+1)+(press?"M":"m")); }
InputScript& dragTo(int x,int y){ return feed(std::string("\033[<32;")+std::to_string(x+1)+";"+std::to_string(y+1)+"M"); }
InputScript& tick(long long ms=16){ Step s; s.kind=Step::Tick; s.tickMs=ms; steps.push_back(s); return *this; }
// Play against any app exposing parser.feed + dispatch + dispatchTick + tickMs (ttgui::Application).
template<typename App> int play(App& app){
int dispatched=0;
for(auto& st: steps){
if(st.kind==Step::Bytes){ for(auto& e: app.parser.feed(st.bytes)){ app.dispatch(e); dispatched++; } }
else if(st.kind==Step::Tick){ app.tickMs+=st.tickMs; app.bell.nowMs=app.tickMs; if constexpr (requires{ app.stepEffects(); }) app.stepEffects(); }
}
// flush a lone trailing ESC exactly as the poll-timeout path does
for(auto& e: app.parser.flushPending()){ app.dispatch(e); dispatched++; }
return dispatched;
}
};
// --- Invariant helpers (duck-typed widget tree) ---
/**
* @brief Structural widget-tree invariants: no cycles, every child's
* parent pointer points back at its owner, and no negative bounds.
* @param why optional out-string naming the first violated invariant.
* @return true when the whole tree satisfies all invariants.
*/
template<typename W> bool checkTreeInvariants(W* root,std::string* why=nullptr){
// Strengthened: cycles, duplicate child, self-parent, parent back-pointer,
// negative/zero-area-with-children bounds, parent-chain loop, sibling dup.
std::set<const void*> seen;
std::function<bool(W*)> rec=[&](W* w)->bool{
if(!w) return true;
if(w->parent==w){ if(why) *why="widget is its own parent"; return false; }
if(seen.count(w)){ if(why) *why="cycle or duplicate child in widget tree"; return false; }
seen.insert(w);
if(w->bounds.w<0||w->bounds.h<0){ if(why) *why="negative bounds"; return false; }
std::set<const void*> sibs;
for(auto& ch: w->children()){
if(!ch){ if(why) *why="null child"; return false; }
if(ch.get()==(void*)w){ if(why) *why="widget is its own child"; return false; }
if(sibs.count(ch.get())){ if(why) *why="duplicate child pointer"; return false; }
sibs.insert(ch.get());
if(ch->parent!=w){ if(why) *why="child parent pointer mismatch"; return false; }
// parent chain must terminate at root without looping
int depth=0; for(auto* p=ch->parent;p;p=p->parent){ if(++depth>10000){ if(why) *why="parent chain loop"; return false; } }
if(!rec(ch.get())) return false;
}
return true;
};
if(root&&root->parent){ /* root of a subtree may have a parent; only cycles checked */ }
return rec(root);
}
inline int runAll(const Options& optIn);
// Registry-sandbox: run synthetic cases in isolation and restore all runner
// state (registry, contexts, cout, global options). Returns captured output;
// results are parsed by callers from the console summary / per-case lines.
inline std::string runRegistrySandbox(std::vector<TestCaseInfo> cases, const Options& optIn){
auto savedRegistry=registry();
auto* savedCtx=currentCtx(); auto* savedRunner=runnerCtx(); auto* savedName=currentCaseName();
Options savedOpts=globalOptions(); bool savedGolden=updateGoldenFlag();
registry()=std::move(cases);
std::ostringstream captured; auto* oldBuf=std::cout.rdbuf(captured.rdbuf());
Options opt=optIn; opt.reporter="console";
runAll(opt);
std::cout.rdbuf(oldBuf);
registry()=savedRegistry; currentCtx()=savedCtx; runnerCtx()=savedRunner; currentCaseName()=savedName;
globalOptions()=savedOpts; updateGoldenFlag()=savedGolden;
// runAll's runOne nulls the thread-locals; restore the outer test context
currentCtx()=savedCtx; runnerCtx()=savedRunner;
return captured.str();
}
/** @brief Static-registration token: constructing one appends a TestCaseInfo to registry(). TEST_CASE creates it; users never do. */
struct Registrar { Registrar(const TestCaseInfo& tc){ registry().push_back(tc); } };
/// @brief Runs every selected case (defined below, after CaseResult).
inline int runAll(const Options& optIn);
} // namespace tttest
// ---------- Macros ----------
/**
* @brief Assertion and case macros (the user-facing API).
* @details TEST_CASE(name, tags) defines and statically registers a case;
* SECTION(name) runs its body in its own re-run pass (nesting composes).
* CHECK/REQUIRE(expr): REQUIRE is fatal. CHECK_TRUE/FALSE, REQUIRE_TRUE/
* FALSE. Binary comparisons with stringified values on failure:
* CHECK_EQ, REQUIRE_EQ, CHECK_NE, REQUIRE_NE, CHECK_LT, REQUIRE_LT,
* CHECK_LE, CHECK_GT, CHECK_GE. CHECK_NEAR(a, b, eps) for doubles.
* CHECK_THROWS_AS(expr, Ex), CHECK_NOTHROW(expr), REQUIRE_THROWS_AS.
* Screen assertions: CHECK_SCREEN(screen, expectedText),
* CHECK_CELLS(screen, x, y, w, h, expectedGlyphs),
* CHECK_GOLDEN(fileName, actualText). Control: SKIP_TEST(reason) (always
* reported, never a pass) and FAIL_TEST(msg) (fatal unconditional fail).
* Every CHECK/REQUIRE counts one check and records file:line automatically.
*/
#define TT_CONCAT2(a,b) a##b
#define TT_CONCAT(a,b) TT_CONCAT2(a,b)
#define TEST_CASE(name,tags) \
static void TT_CONCAT(tt_case_,__LINE__)(); \
static ::tttest::Registrar TT_CONCAT(tt_reg_,__LINE__)({name,tags,__FILE__,__LINE__,TT_CONCAT(tt_case_,__LINE__)}); \
static void TT_CONCAT(tt_case_,__LINE__)()
#define SECTION(name) if(::tttest::SectionScope _tt_sec{name}; _tt_sec.run) for(int _tt_once=0;_tt_once<1;++_tt_once, ::tttest::endSection())
#define CHECK(expr) do{ ::tttest::recordCheck(); if(!(expr)) ::tttest::recordFailure(__FILE__,__LINE__,#expr,"CHECK failed",false); }while(0)
#define REQUIRE(expr) do{ ::tttest::recordCheck(); if(!(expr)) ::tttest::recordFailure(__FILE__,__LINE__,#expr,"REQUIRE failed",true); }while(0)
#define CHECK_TRUE(expr) CHECK(expr)
#define CHECK_FALSE(expr) CHECK(!(expr))
#define REQUIRE_TRUE(expr) REQUIRE(expr)
#define REQUIRE_FALSE(expr) REQUIRE(!(expr))
#define TT_BINOP(a,b,op,NAME,fatal) do{ ::tttest::recordCheck(); auto&& _a=(a); auto&& _b=(b); if(!(_a op _b)){ std::ostringstream _o; _o<<"expected "<<::tttest::toStr(_a)<<" "#op" "<<::tttest::toStr(_b); ::tttest::recordFailure(__FILE__,__LINE__,#a" "#op" "#b,_o.str(),fatal); } }while(0)
#define CHECK_EQ(a,b) TT_BINOP(a,b,==,EQ,false)
#define REQUIRE_EQ(a,b) TT_BINOP(a,b,==,EQ,true)
#define CHECK_NE(a,b) TT_BINOP(a,b,!=,NE,false)
#define CHECK_LT(a,b) TT_BINOP(a,b,<,LT,false)
#define CHECK_LE(a,b) TT_BINOP(a,b,<=,LE,false)
#define CHECK_GT(a,b) TT_BINOP(a,b,>,GT,false)
#define CHECK_GE(a,b) TT_BINOP(a,b,>=,GE,false)
#define REQUIRE_NE(a,b) TT_BINOP(a,b,!=,NE,true)
#define REQUIRE_LT(a,b) TT_BINOP(a,b,<,LT,true)
#define CHECK_NEAR(a,b,eps) do{ ::tttest::recordCheck(); double _a=(a),_b=(b),_e=(eps); if(std::fabs(_a-_b)>_e){ std::ostringstream _o; _o<<"expected "<<_a<<" near "<<_b<<" eps "<<_e; ::tttest::recordFailure(__FILE__,__LINE__,#a" ~= "#b,_o.str(),false);} }while(0)
#define CHECK_THROWS_AS(expr,Ex) do{ ::tttest::recordCheck(); bool _ok=false; try{ (void)(expr); }catch(const Ex&){_ok=true;}catch(...){} if(!_ok) ::tttest::recordFailure(__FILE__,__LINE__,#expr,"expected throw "#Ex,false); }while(0)
#define CHECK_NOTHROW(expr) do{ ::tttest::recordCheck(); try{ (void)(expr); }catch(const std::exception& e){ ::tttest::recordFailure(__FILE__,__LINE__,#expr,std::string("unexpected throw: ")+e.what(),false);}catch(...){ ::tttest::recordFailure(__FILE__,__LINE__,#expr,"unexpected throw",false);} }while(0)
#define REQUIRE_THROWS_AS(expr,Ex) do{ ::tttest::recordCheck(); bool _ok=false; try{ (void)(expr); }catch(const Ex&){_ok=true;}catch(...){} if(!_ok) ::tttest::recordFailure(__FILE__,__LINE__,#expr,"expected throw "#Ex,true); }while(0)
#define CHECK_SCREEN(screen,expected) do{ ::tttest::checkScreenImpl((screen).text(),(expected),__FILE__,__LINE__); }while(0)
#define CHECK_CELLS(screen,x,y,w,h,expected) do{ ::tttest::checkCellsImpl((screen),(x),(y),(w),(h),(expected),__FILE__,__LINE__); }while(0)
#define CHECK_CELLS_FULL(screen,x,y,w,h,expected) do{ ::tttest::checkCellsFullImpl((screen),(x),(y),(w),(h),(expected),__FILE__,__LINE__); }while(0)
#define CHECK_GOLDEN(name,actual) do{ ::tttest::checkGoldenImpl((name),(actual),__FILE__,__LINE__); }while(0)
#define CHECK_GOLDEN_CELLS(name,screen) do{ ::tttest::checkGoldenCellsImpl((name),(screen),__FILE__,__LINE__); }while(0)
#define SKIP_TEST(reason) do{ throw ::tttest::SkipException{reason}; }while(0)
#define FAIL_TEST(msg) do{ ::tttest::recordFailure(__FILE__,__LINE__,"FAIL_TEST",msg,true); }while(0)
namespace tttest {
/** @brief Outcome of one case execution: info echo, status ("PASS"/"FAIL"/"SKIP"), check count, duration, failures, skip reason, repeat index. */
struct CaseResult { TestCaseInfo info; std::string status; int checks=0; double durSec=0; std::vector<Failure> failures; std::string skipReason; int repeatIdx=0; };
/** @brief Parses a tags CLI value ("[a][b]" or a bare "a") into tag names. Always returns true; empty segments are dropped. */
inline bool parseTagsArg(const std::string& s,std::vector<std::string>& out){
// "[a][b]" or "a"
if(s.find('[')==std::string::npos){ if(!s.empty()) out.push_back(s); return true; }
std::string cur; for(char c: s){ if(c=='[') cur.clear(); else if(c==']'){ if(!cur.empty()) out.push_back(cur); } else cur+=c; } return true;
}
/**
* @brief Execute the registry under `optIn` and report.
* @details Order is registration order, shuffled with a seeded RNG when
* requested; repeat executes the whole selection repeatedly. Without an
* explicit --tags, cases tagged [pty]/[fuzz]/[slow] are reported SKIP
* ("opt-in tier") — they never silently pass. Each case runs in section
* passes (a fresh pass per leaf SECTION), converts RequireAbort/
* SkipException/std::exception into FAIL/SKIP results, and honours
* timeoutSec by running the case on a worker thread (a timeout prints
* TIMEOUT and exits the process with 1, because a hung case cannot be
* safely resumed). failFast stops after the first failure's report.
* Reporters: console (coloured on a TTY), tap (v14), json; all end with
* run/passed/failed/skipped counts and (console/tap) a per-tag breakdown.
* @return 0 when nothing failed, 1 otherwise. (Usage errors return 2
* from main(), not here.)
*/
inline int runAll(const Options& optIn){
Options opt=optIn; globalOptions()=opt;
auto cases=registry();
// ordering: registration order; shuffle if asked
if(opt.shuffle){ std::mt19937 rng(opt.seed); std::shuffle(cases.begin(),cases.end(),rng); }
std::vector<CaseResult> results; int exitCode=0;
if(opt.listOnly){
for(auto& c: cases) std::cout<<c.name<<" "<<c.tags<<" "<<c.file<<":"<<c.line<<"\n";
return 0;
}
for(int rep=0;rep<opt.repeat;rep++){
for(auto& tc: cases){
if(!opt.filter.empty() && tc.name.find(opt.filter)==std::string::npos) continue;
if(opt.explicitTags){ bool ok=true; for(auto& t: opt.tags) if(!tc.hasTag(t)) ok=false; if(!ok) continue; }
else {
// default tier: skip pty/fuzz/slow
if(tc.hasTag("pty")||tc.hasTag("fuzz")||tc.hasTag("slow")){ CaseResult r; r.info=tc; r.status="SKIP"; r.skipReason="opt-in tier (use --tags)"; r.repeatIdx=rep; results.push_back(r); continue; }
}
bool excluded=false; for(auto& t: opt.excludeTags) if(tc.hasTag(t)) excluded=true;
if(excluded){ CaseResult r; r.info=tc; r.status="SKIP"; r.skipReason="excluded by --exclude-tags"; r.repeatIdx=rep; results.push_back(r); continue; }
CaseResult res; res.info=tc; res.repeatIdx=rep;
auto runOne=[&]() -> CaseResult {
CaseResult rr; rr.info=tc; rr.repeatIdx=rep;
Context ctx; currentCtx()=&ctx; runnerCtx()=&ctx; std::string nm=tc.name; currentCaseName()=&nm;
auto t0=std::chrono::steady_clock::now();
try{
// section rerun loop
for(int pass=0;pass<200;pass++){
ctx.sectionStack.clear(); bool finishedPass=false;
try{ tc.func(); finishedPass=true; }
catch(const SectionFinished&){ finishedPass=false; }
catch(const RequireAbort&){ break; }
catch(const SkipException& e){ ctx.skipped=true; ctx.skipReason=e.reason; break; }
if(finishedPass) break;
// if no section was completed this pass, avoid infinite loop
if(pass>0 && ctx.completedSections.empty()) break;
}
}catch(const RequireAbort&){}catch(const SkipException& e){ ctx.skipped=true; ctx.skipReason=e.reason; }
catch(const std::exception& e){ ctx.failures.push_back({tc.file,tc.line,tc.name,std::string("uncaught exception: ")+e.what(),false}); }
catch(...){ ctx.failures.push_back({tc.file,tc.line,tc.name,"uncaught unknown exception",false}); }
auto t1=std::chrono::steady_clock::now(); rr.durSec=std::chrono::duration<double>(t1-t0).count();
rr.checks=ctx.checks; rr.failures=ctx.failures;
if(ctx.skipped){ rr.status="SKIP"; rr.skipReason=ctx.skipReason; }
else if(!ctx.failures.empty()) rr.status="FAIL";
else if(ctx.checks==0){ rr.status="FAIL"; rr.failures.push_back({tc.file,tc.line,tc.name,"test case performed zero checks (NOCHECKS)",false}); }
else rr.status="PASS";
currentCtx()=nullptr; runnerCtx()=nullptr; currentCaseName()=nullptr;
return rr;
};
if(opt.timeoutSec>0){
auto fut=std::async(std::launch::async, runOne);
if(fut.wait_for(std::chrono::duration<double>(opt.timeoutSec))==std::future_status::timeout){
std::cout.flush(); std::cerr<<"TIMEOUT: "<<tc.name<<" exceeded "<<opt.timeoutSec<<"s (recorded as FAIL)\n"; std::cerr.flush();
if(opt.reporter=="tap") std::cout<<"not ok - "<<tc.name<<" # TIMEOUT "<<opt.timeoutSec<<"s\n";
else if(opt.reporter=="json") std::cout<<"{\"cases\":[{\"name\":\""<<tc.name<<"\",\"status\":\"FAIL\",\"checks\":0,\"failures\":[{\"message\":\"timeout\"}]}],\"run\":1,\"passed\":0,\"failed\":1,\"skipped\":0}\n";
else std::cout<<"FAIL "<<tc.name<<" [timeout "<<opt.timeoutSec<<"s]\n";
std::cout.flush(); std::quick_exit(1);
}
res=fut.get();
} else res=runOne();
results.push_back(res);
if(res.status=="FAIL" && opt.failFast) { /* report below then exit */ rep=opt.repeat; break; }
}
}
// summary counts
int passed=0,failed=0,skipped=0,runCnt=0; std::map<std::string,std::pair<int,int>> perTag; // tag -> [run,passed]
for(auto& r: results){ if(r.status=="PASS") passed++; else if(r.status=="FAIL") failed++; else if(r.status=="SKIP") skipped++; runCnt++;
for(auto& t: r.info.tagList()){ perTag[t].first++; if(r.status=="PASS") perTag[t].second++; } }
double totalDur=0; for(auto& r: results) totalDur+=r.durSec;
if(opt.reporter=="tap"){
std::cout<<"TAP version 14\n1.."<<results.size()<<"\n"; int idx=0;
for(auto& r: results){ idx++; if(r.status=="PASS") std::cout<<"ok "<<idx<<" - "<<r.info.name<<"\n"; else if(r.status=="SKIP") std::cout<<"ok "<<idx<<" - "<<r.info.name<<" # SKIP "<<r.skipReason<<"\n"; else { std::cout<<"not ok "<<idx<<" - "<<r.info.name<<"\n"; for(auto& f: r.failures) std::cout<<"# "<<f.file<<":"<<f.line<<" "<<f.expr<<" "<<f.msg<<"\n"; } }
} else if(opt.reporter=="json"){
std::cout<<"{\"cases\":[";
bool first=true; for(auto& r: results){ if(!first) std::cout<<","; first=false;
std::cout<<"{\"name\":\""<<r.info.name<<"\",\"tags\":\""<<r.info.tags<<"\",\"file\":\""<<r.info.file<<"\",\"line\":"<<r.info.line<<",\"status\":\""<<r.status<<"\",\"duration\":"<<r.durSec<<",\"checks\":"<<r.checks<<",\"failures\":[";
bool ff=true; for(auto& f: r.failures){ if(!ff) std::cout<<","; ff=false; std::cout<<"{\"file\":\""<<f.file<<"\",\"line\":"<<f.line<<",\"expr\":\""<<f.expr<<"\",\"message\":\""; for(char c: f.msg){ if(c=='"') std::cout<<"\\\""; else if(c=='\n') std::cout<<"\\n"; else if(c=='\\') std::cout<<"\\\\"; else std::cout<<c; } std::cout<<"\"}"; }
std::cout<<"]}"; }
std::cout<<"],\"run\":"<<runCnt<<",\"passed\":"<<passed<<",\"failed\":"<<failed<<",\"skipped\":"<<skipped<<",\"duration\":"<<totalDur<<"}\n";
} else {
bool useColor = ::isatty(STDOUT_FILENO);
for(auto& r: results){
std::string col = r.status=="PASS"?"\033[32m":(r.status=="FAIL"?"\033[31m":"\033[33m"); if(!useColor) col="";
std::string rst = useColor?"\033[0m":"";
if(r.status=="SKIP") std::cout<<col<<"SKIP"<<rst<<" "<<r.info.name<<" ("<<r.skipReason<<")\n";
else std::cout<<col<<r.status<<rst<<" "<<r.info.name<<" ["<<r.checks<<" checks, "<<(r.durSec*1000)<<"ms]\n";
for(auto& f: r.failures) std::cout<<" "<<f.file<<":"<<f.line<<": "<<f.expr<<" -- "<<f.msg<<"\n";
}
}
if(opt.reporter!="json" && opt.reporter!="tap"){
std::cout<<"== Summary: run="<<runCnt<<" passed="<<passed<<" failed="<<failed<<" skipped="<<skipped<<" wall="<<totalDur<<"s ==\n";
std::cout<<"Per-tag:";
for(auto& kv: perTag) std::cout<<" ["<<kv.first<<"] "<<kv.second.second<<"/"<<kv.first<<" passed;";
std::cout<<"\n";
} else if(opt.reporter=="tap"){
std::cout<<"# run="<<runCnt<<" passed="<<passed<<" failed="<<failed<<" skipped="<<skipped<<" wall="<<totalDur<<"s\n";
}
if(failed>0) exitCode=1;
return exitCode;
}
/**
* @brief CLI entry point used by test_main.cpp: parses
* --list/--filter/--tags/--exclude-tags/--repeat/--shuffle/--seed/
* --fail-fast/--timeout/--reporter/--update-golden/--golden-dir, then
* returns runAll(). Unknown options and bad reporters print to stderr
* and return 2; --help prints usage and returns 0.
*/
inline int main(int argc,char** argv){
Options opt;
for(int i=1;i<argc;i++){ std::string a=argv[i];
auto need=[&](const char* n)->std::string{ if(i+1>=argc){ std::cerr<<"missing value for "<<n<<"\n"; std::exit(2);} return argv[++i]; };
if(a=="--list") opt.listOnly=true;
else if(a=="--filter") opt.filter=need("--filter");
else if(a=="--tags"){ parseTagsArg(need("--tags"),opt.tags); opt.explicitTags=true; }
else if(a=="--exclude-tags") parseTagsArg(need("--exclude-tags"),opt.excludeTags);
else if(a=="--repeat") opt.repeat=std::max(1,atoi(need("--repeat").c_str()));
else if(a=="--shuffle") opt.shuffle=true;
else if(a=="--seed") opt.seed=(unsigned)atoi(need("--seed").c_str());
else if(a=="--fail-fast") opt.failFast=true;
else if(a=="--timeout") opt.timeoutSec=atof(need("--timeout").c_str());
else if(a=="--reporter") opt.reporter=need("--reporter");
else if(a=="--update-golden"){ opt.updateGolden=true; updateGoldenFlag()=true; }
else if(a=="--golden-dir") opt.goldenDir=need("--golden-dir");
else if(a=="--help"||a=="-h"){ std::cout<<"Usage: tests [--list] [--filter s] [--tags [a][b]] [--exclude-tags [x]] [--repeat N] [--shuffle --seed S] [--fail-fast] [--timeout s] [--reporter console|tap|json] [--update-golden]\n"; return 0; }
else { std::cerr<<"unknown option: "<<a<<"\n"; return 2; }
}
if(opt.reporter!="console"&&opt.reporter!="tap"&&opt.reporter!="json"){ std::cerr<<"bad reporter\n"; return 2; }
return runAll(opt);
}
} // namespace tttest