#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 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include 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 func; std::vector tagList() const { std::vector 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& registry(){ static std::vector 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 failures; int checks=0; bool skipped=false; std::string skipReason; // section state (persistent across passes) std::set completedSections; std::vector 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 "". Overloads: strings are quoted, * const char* is null-safe and quoted, bools print true/false. */ template std::string toStr(const T& v){ std::ostringstream o; if constexpr (requires{ o<"; } 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 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--` * (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 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(in)),std::istreambuf_iterator()); } /** @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/ (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< std::string screenText(const S& s){ return s.text(); } template 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"< 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 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 std::pair 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 std::string fullCellRect(const S& s,int x,int y,int w,int h){ std::string out; for(int row=0;row std::string fullCellText(const S& s){ auto sz=screenSize(s); return fullCellRect(s,0,0,sz.first,sz.second); } template 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 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 apply; long long tickMs=16; }; std::vector 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 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 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 seen; std::function 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 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 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 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& 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 results; int exitCode=0; if(opt.listOnly){ for(auto& c: cases) std::cout< 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(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(opt.timeoutSec))==std::future_status::timeout){ std::cout.flush(); std::cerr<<"TIMEOUT: "<> 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.."<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;istd::string{ if(i+1>=argc){ std::cerr<<"missing value for "<