CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
Loading...
Searching...
No Matches
UnitTestFramework.cpp
Go to the documentation of this file.
1
7// ============================================================================
8
9#include "UnitTestFramework.h"
10#include "PsyTime.h"
11#include "jsmn.h"
12
13#include <stdio.h>
14#include <stdarg.h>
15#include <stdlib.h>
16#include <string.h>
17#include <math.h>
18#include <set>
19#include <string>
20
21#ifdef WINDOWS
22 #include <io.h>
23 #define ISATTY(fd) _isatty(fd)
24 #define FILENO(f) _fileno(f)
25#else
26 #include <unistd.h>
27 #include <dirent.h>
28 #include <sys/stat.h>
29 #include <sys/wait.h>
30 #include <signal.h>
31 #include <execinfo.h>
32 #include <fcntl.h>
33 #define ISATTY(fd) isatty(fd)
34 #define FILENO(f) fileno(f)
35 #define UT_HAVE_FORK 1
36#endif
37
38// Hard per-test wall-clock cap when running each test in its own process. A
39// test that exceeds this is killed and reported as a timeout (rather than
40// hanging the whole suite). Scaled by UT_TIME_SCALE (UnitTestFramework.h) so
41// instrumented runs get slack while bare runs keep the tight 30 s ceiling:
42// builder_golden runs three node start/stop cycles, and under ASan each startup
43// costs ~11.8 s versus well under a second bare, so ~35 s of legitimate work was
44// hitting a 30 s cap on Linux.
45#define UT_TEST_TIMEOUT_US (30ULL * 1000000ULL * UT_TIME_SCALE)
46
47namespace cmlabs {
48
49// Best-effort removal of stale CMSDK shared-memory segments left behind by a
50// previous test process that was killed (kill -9) mid-operation. Such a process
51// can leave a PROCESS_SHARED pthread mutex locked inside a persisted segment,
52// which would deadlock the next run that re-opens it. Tests run under system id
53// 0, so clearing these test artifacts before a run makes the suite self-healing
54// and safely repeatable (e.g. for an agent looping to chase a perf target).
55// This assumes no live Psyclone node is using system id 0 on this machine while
56// tests run (which is already required by the "another node running" guard).
57static void ut_clearSegmentsIn(const char* dir, const char* prefix) {
58#ifndef WINDOWS
59 DIR* d = opendir(dir);
60 if (!d) return;
61 size_t plen = strlen(prefix);
62 struct dirent* e;
63 while ((e = readdir(d)) != NULL) {
64 if (strncmp(e->d_name, prefix, plen) == 0) {
65 std::string path = std::string(dir) + "/" + e->d_name;
66 unlink(path.c_str());
67 }
68 }
69 closedir(d);
70#endif
71}
72
74#ifndef WINDOWS
75 // ⚠️ A test that DELIBERATELY attaches to another process's segment must not run this.
76 // The cross-process ring fuzz (PSY_CONC_CHILD) re-execs this binary as a reader: with
77 // the cleanup enabled the child unlinked the PARENT's live segment before it could
78 // attach, connect() failed in 0.03 ms, and the tier reported "child produced NO read
79 // records". That looked like a cross-process defect and was purely this cleanup.
80 // Skipping it in the child is safe: the PARENT still clears stale segments on entry,
81 // and the child creates nothing of its own.
82 const char* attaching = getenv("PSY_CONC_CHILD");
83 if (attaching && *attaching)
84 return;
85 // macOS file-backed segments: /tmp/Psyclone_Shmem_<name>
86 ut_clearSegmentsIn("/tmp", "Psyclone_Shmem_");
87 // Linux / Cygwin POSIX shm: shm_open("/Shmem_<name>") -> /dev/shm/Shmem_<name>
88 ut_clearSegmentsIn("/dev/shm", "Shmem_");
89#endif
90}
91
92#ifdef UT_HAVE_FORK
93// ---- Timeout diagnostics for forked tests --------------------------------
94// When a test hangs, the parent's only signal is the wall-clock timeout, and
95// the child's buffered output is lost when it is killed. To make a hang
96// diagnosable we (a) have the child record its current phase to a file on every
97// progress() call (read back by the parent on timeout) and (b) on timeout ask
98// the child, via SIGUSR1, to dump a native stack trace of the stuck thread to a
99// file before we kill it. backtrace_symbols_fd() is async-signal-safe, so the
100// handler is safe to run from a signal.
101static int ut_traceFd = -1;
102static void ut_timeoutTraceHandler(int) {
103 if (ut_traceFd >= 0) {
104 void* frames[128];
105 int n = backtrace(frames, 128);
106 backtrace_symbols_fd(frames, n, ut_traceFd);
107 }
108 _exit(3);
109}
110static void ut_installTimeoutTraceHandler(const std::string& tracePath) {
111 ut_traceFd = open(tracePath.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
112 signal(SIGUSR1, ut_timeoutTraceHandler);
113}
114
115// Read back the child's last-recorded phase ("percent\taction") as a short
116// human-readable note for the status line.
117static std::string ut_readProgressNote(const std::string& path) {
118 FILE* f = fopen(path.c_str(), "r");
119 if (!f) return "";
120 char buf[512];
121 size_t r = fread(buf, 1, sizeof(buf) - 1, f);
122 fclose(f);
123 buf[r] = 0;
124 std::string s(buf);
125 std::string::size_type tab = s.find('\t');
126 if (tab == std::string::npos) return s;
127 return s.substr(0, tab) + "% \"" + s.substr(tab + 1) + "\"";
128}
129
130// Print the captured stack trace (if any) as indented diagnostic lines.
131static void ut_printTraceFile(const std::string& path) {
132 FILE* f = fopen(path.c_str(), "r");
133 if (!f) return;
134 char line[1024];
135 bool header = false;
136 while (fgets(line, sizeof(line), f)) {
137 if (!header) { printf(" stack trace where the test hung:\n"); header = true; }
138 printf(" %s", line);
139 }
140 if (header) { printf("\n"); fflush(stdout); }
141 fclose(f);
142}
143#endif
144
145// ----------------------------------------------------------------------------
146// Layout constants for consistent output
147// ----------------------------------------------------------------------------
148#define UT_NAME_WIDTH 28 // width of the test-name column on the status line
149#define UT_INDENT " " // 11 spaces, lines up after "[ PASS ] "
150#define UT_METRIC_WIDTH 26 // width of the metric-name column on a subline
151
152// ----------------------------------------------------------------------------
153// Singleton
154// ----------------------------------------------------------------------------
155UnitTestRunner& UnitTestRunner::instance() {
156 static UnitTestRunner theInstance;
157 return theInstance;
158}
159
160UnitTestRunner::UnitTestRunner()
161 : current(NULL), verboseFlag(false), writeJSONFlag(true),
162 forkPerTest(true), isTTY(false), lastProgressLen(0), outputDir("."),
163 compareLoaded(false) {
164 isTTY = ISATTY(FILENO(stdout)) ? true : false;
165}
166
167// ----------------------------------------------------------------------------
168// Registration & configuration
169// ----------------------------------------------------------------------------
170void UnitTestRunner::registerTest(const char* name, UnitTestFunc func,
171 const char* description, const char* category,
172 bool inDefaultRun, uint32 timeoutSec) {
173 if (!name || !func) return;
174 // Replace if a test with this name was already registered.
175 for (size_t i = 0; i < tests.size(); i++) {
176 if (tests[i].name == name) {
177 tests[i].func = func;
178 tests[i].description = description ? description : "";
179 tests[i].category = category ? category : "";
180 tests[i].inDefaultRun = inDefaultRun;
181 tests[i].timeoutSec = timeoutSec;
182 return;
183 }
184 }
185 UnitTestRecord rec;
186 rec.name = name;
187 rec.func = func;
188 rec.description = description ? description : "";
189 rec.category = category ? category : "";
190 rec.inDefaultRun = inDefaultRun;
191 rec.timeoutSec = timeoutSec;
192 tests.push_back(rec);
193}
194
195void UnitTestRunner::setVerbose(bool v) { verboseFlag = v; }
196void UnitTestRunner::setCompareFile(const char* p) { if (p) compareFile = p; }
197void UnitTestRunner::setOutputFile(const char* p) { if (p) outputFile = p; }
198void UnitTestRunner::setOutputDir(const char* d) { if (d) outputDir = d; }
199void UnitTestRunner::setWriteJSON(bool v) { writeJSONFlag = v; }
200void UnitTestRunner::setForkPerTest(bool v) { forkPerTest = v; }
201
202bool UnitTestRunner::hasTest(const char* name) const {
203 if (!name) return false;
204 for (size_t i = 0; i < tests.size(); i++)
205 if (stricmp(tests[i].name.c_str(), name) == 0) return true;
206 return false;
207}
208
209std::vector<std::string> UnitTestRunner::testNames() const {
210 std::vector<std::string> names;
211 for (size_t i = 0; i < tests.size(); i++) names.push_back(tests[i].name);
212 return names;
213}
214
216 printf("\nAvailable CMSDK unit tests (%u):\n\n", (uint32)tests.size());
217 std::string lastCat = "\x01";
218 for (size_t i = 0; i < tests.size(); i++) {
219 if (tests[i].category != lastCat) {
220 lastCat = tests[i].category;
221 printf(" [%s]\n", lastCat.empty() ? "general" : lastCat.c_str());
222 }
223 printf(" %-22s %s\n", tests[i].name.c_str(), tests[i].description.c_str());
224 }
225 printf("\nRun all with: test=cmsdk Run one with: test=<name>\n\n");
226}
227
228// ----------------------------------------------------------------------------
229// Hooks used by the unittest:: API for the currently running test
230// ----------------------------------------------------------------------------
231bool UnitTestRunner::hookVerbose() const { return verboseFlag; }
232
233void UnitTestRunner::hookProgress(int percent, const char* action) {
234 if (!current) return;
235 if (percent < 0) percent = 0;
236 if (percent > 100) percent = 100;
237
238 // Record the current phase to a file (forked child only) so that, if the test
239 // hangs and is killed by the timeout, the parent can still report which phase
240 // it was in. progress() is called only a handful of times per test, so this is
241 // cheap, and it happens regardless of whether stdout is a terminal.
242 if (!progressPath.empty()) {
243 FILE* pf = fopen(progressPath.c_str(), "w");
244 if (pf) { fprintf(pf, "%d\t%s", percent, action ? action : ""); fclose(pf); }
245 }
246
247 if (!isTTY) return; // keep piped/redirected logs clean
248
249 char buf[512];
250 int n = snprintf(buf, sizeof(buf), " [%3d%%] %-*.*s %s",
252 current->name.c_str(), action ? action : "");
253 if (n < 0) return;
254
255 // Pad to clear any longer text drawn previously.
256 int pad = lastProgressLen - n;
257 fputc('\r', stdout);
258 fputs(buf, stdout);
259 for (int i = 0; i < pad; i++) fputc(' ', stdout);
260 fputc('\r', stdout);
261 fflush(stdout);
262 lastProgressLen = (n > lastProgressLen) ? n : lastProgressLen;
263 // (we keep the max so the next pad clears the longest line)
264 lastProgressLen = n;
265}
266
267void UnitTestRunner::clearProgressLine() {
268 if (!isTTY || lastProgressLen <= 0) return;
269 fputc('\r', stdout);
270 for (int i = 0; i < lastProgressLen; i++) fputc(' ', stdout);
271 fputc('\r', stdout);
272 fflush(stdout);
273 lastProgressLen = 0;
274}
275
276void UnitTestRunner::hookMetric(const char* name, double value, const char* unit, bool higherIsBetter) {
277 if (!current || !name) return;
278 lock.enter();
280 m.name = name;
281 m.value = value;
282 m.unit = unit ? unit : "";
283 m.higherIsBetter = higherIsBetter;
284 current->metrics.push_back(m);
285 lock.leave();
286}
287
288void UnitTestRunner::hookDetail(const char* text) {
289 if (!current) return;
290 // ALWAYS record, even when not verbose: if this test goes on to fail we print the
291 // buffer with the reason (see hookFail). Previously detail() was discarded unless
292 // verbose was set, so a rare intermittent failure gave a one-line reason and no
293 // diagnostics at all - and you cannot re-run a 2%-rate flake on demand to get
294 // them. Bounded ring so a chatty passing test cannot grow without limit.
295 static const size_t UT_DETAIL_KEEP = 64;
296 current->detailLog.push_back(text ? text : "");
297 if (current->detailLog.size() > UT_DETAIL_KEEP)
298 current->detailLog.erase(current->detailLog.begin());
299 // Only ECHO live when verbose, so normal runs stay quiet.
300 if (!verboseFlag) return;
301 clearProgressLine();
302 printf(UT_INDENT "%s\n", text ? text : "");
303 fflush(stdout);
304}
305
306void UnitTestRunner::hookFail(const char* text) {
307 if (!current) return;
308 std::string reason = text ? text : "";
309 // Trim trailing whitespace/newlines so the reason renders on one line.
310 while (!reason.empty() &&
311 (reason[reason.size() - 1] == '\n' || reason[reason.size() - 1] == '\r' ||
312 reason[reason.size() - 1] == ' ' || reason[reason.size() - 1] == '\t'))
313 reason.erase(reason.size() - 1);
314 current->failReason = reason;
315
316 // Print the reason RIGHT NOW (always, regardless of verbose). The status
317 // line is printed later by the parent process, and if the test goes on to
318 // hang or crash before then, the per-test timeout/crash note would be all
319 // that survives - so emit the reason immediately while we still can.
320 if (!reason.empty()) {
321 clearProgressLine();
322 // Diagnostics FIRST, then the reason, so the reason stays the last line and
323 // existing log-scrapers that grep for "reason:" are unaffected. Only when not
324 // verbose - in verbose mode these were already echoed live and repeating them
325 // would just duplicate output.
326 if (!verboseFlag && !current->detailLog.empty()) {
327 printf(UT_INDENT "--- diagnostics (%u detail line(s) captured before failure) ---\n",
328 (uint32)current->detailLog.size());
329 for (size_t i = 0; i < current->detailLog.size(); i++)
330 printf(UT_INDENT " %s\n", current->detailLog[i].c_str());
331 }
332 printf(UT_INDENT "reason: %s\n", reason.c_str());
333 fflush(stdout);
334 }
335}
336
337// ----------------------------------------------------------------------------
338// Output of results
339// ----------------------------------------------------------------------------
340void UnitTestRunner::printStatusLine(const UnitTestRecord* rec) {
341 const char* tag = rec->passed ? "PASS" : "FAIL";
342 double ms = rec->durationUs / 1000.0;
343 // The test's own fail reason was already printed immediately by hookFail();
344 // here we only append the framework outcome note (timed out / crashed / no
345 // test function) so a hung or crashed test still shows why on the status line.
346 if (rec->passed || rec->endNote.empty())
347 printf("[ %s ] %-*s %10.2f ms\n", tag, UT_NAME_WIDTH, rec->name.c_str(), ms);
348 else
349 printf("[ %s ] %-*s %10.2f ms %s\n", tag, UT_NAME_WIDTH, rec->name.c_str(), ms,
350 rec->endNote.c_str());
351 fflush(stdout);
352}
353
354void UnitTestRunner::printMetricLines(const UnitTestRecord* rec) {
355 for (size_t i = 0; i < rec->metrics.size(); i++) {
356 const UnitTestMetric& m = rec->metrics[i];
357 char line[512];
358 snprintf(line, sizeof(line), UT_INDENT "%-*s %14.3f %-8s",
359 UT_METRIC_WIDTH, m.name.c_str(), m.value, m.unit.c_str());
360 printf("%s", line);
361
362 // Comparison against a previous run
363 double prev = 0.0;
364 std::string key = rec->name + "/" + m.name;
365 if (compareLoaded && comparisonValue(key, prev)) {
366 if (prev != 0.0) {
367 double pct = (m.value - prev) / prev * 100.0;
368 const char* dir;
369 bool improved = m.higherIsBetter ? (m.value > prev) : (m.value < prev);
370 bool worse = m.higherIsBetter ? (m.value < prev) : (m.value > prev);
371 dir = improved ? "better" : (worse ? "worse" : "same");
372 printf(" prev %.3f %+.1f%% (%s)", prev, pct, dir);
373 } else {
374 printf(" prev %.3f", prev);
375 }
376 }
377 printf("\n");
378 }
379 fflush(stdout);
380}
381
382// ----------------------------------------------------------------------------
383// Running
384// ----------------------------------------------------------------------------
385void UnitTestRunner::beginTest(UnitTestRecord* rec) {
386 current = rec;
387 lastProgressLen = 0;
388 rec->ran = true;
389 rec->passed = false;
390 rec->metrics.clear();
391 rec->failReason.clear();
392 rec->endNote.clear();
393}
394
395void UnitTestRunner::finishTest(UnitTestRecord* rec) {
396 clearProgressLine();
397 printStatusLine(rec);
398 printMetricLines(rec);
399 current = NULL;
400}
401
402// ---- child-result serialisation (used by the forked-execution path) --------
403// The child runs one test and records its metrics / fail reason into its own
404// copy of the record; it then serialises them to a small file the parent reads
405// back (fork copies memory, so the parent cannot see the child's heap directly).
406static std::string ut_escape_field(const std::string& s) {
407 std::string out;
408 for (size_t i = 0; i < s.size(); i++) {
409 char c = s[i];
410 if (c == '\n' || c == '\r' || c == '\t') out += ' ';
411 else out += c;
412 }
413 return out;
414}
415
416static void ut_writeChildResult(const std::string& path, const UnitTestRecord* rec) {
417 std::string s;
418 s += "fail\t" + ut_escape_field(rec->failReason) + "\n";
419 for (size_t i = 0; i < rec->metrics.size(); i++) {
420 const UnitTestMetric& m = rec->metrics[i];
421 char num[64];
422 snprintf(num, sizeof(num), "%.10g", m.value);
423 s += std::string("metric\t") + ut_escape_field(m.name) + "\t" + num + "\t" +
424 ut_escape_field(m.unit) + "\t" + (m.higherIsBetter ? "1" : "0") + "\n";
425 }
426 utils::WriteAFile(path.c_str(), s.c_str(), (uint32)s.size());
427}
428
429static void ut_readChildResult(const std::string& path, UnitTestRecord* rec) {
430 std::string data = utils::ReadAFileString(path);
431 if (data.empty()) return;
432 size_t pos = 0;
433 while (pos < data.size()) {
434 size_t eol = data.find('\n', pos);
435 if (eol == std::string::npos) eol = data.size();
436 std::string line = data.substr(pos, eol - pos);
437 pos = eol + 1;
438 if (line.empty()) continue;
439 // split on tabs
440 std::vector<std::string> f;
441 size_t p = 0;
442 while (true) {
443 size_t t = line.find('\t', p);
444 if (t == std::string::npos) { f.push_back(line.substr(p)); break; }
445 f.push_back(line.substr(p, t - p));
446 p = t + 1;
447 }
448 if (f[0] == "fail" && f.size() >= 2) {
449 rec->failReason = f[1];
450 } else if (f[0] == "metric" && f.size() >= 5) {
452 m.name = f[1];
453 m.value = utils::Ascii2Float64(f[2].c_str());
454 m.unit = f[3];
455 m.higherIsBetter = (f[4] == "1");
456 rec->metrics.push_back(m);
457 }
458 }
459}
460
461
462// What a test leaves behind (18 Nov 2026, Isaac): shared names that belong to a node are only removed by that node's
463// MemoryManager at shutdown, so tests that use the memory classes without one (processmemory, componentmemory_layout,
464// temporalmemory, memoryrequestserver, ...) left them; the PsyProbe tests left their psytest_* data dirs in the temp
465// dir. The runner now notes what exists when a test starts and removes what is new when it ends (the parent, after
466// the forked test process is gone). The machine-wide PsycloneIndex is kept, as a node would keep it.
467#ifndef WINDOWS
468static void ut_listDir(const char* dir, const char* prefix, bool dirsOnly, std::set<std::string>& out) {
469 DIR* d = opendir(dir);
470 if (!d) return;
471 size_t plen = strlen(prefix);
472 struct dirent* e;
473 while ((e = readdir(d)) != NULL) {
474 if (strncmp(e->d_name, prefix, plen) != 0)
475 continue;
476 std::string path = std::string(dir) + "/" + e->d_name;
477 if (dirsOnly) {
478 struct stat st;
479 if (lstat(path.c_str(), &st) != 0 || !S_ISDIR(st.st_mode))
480 continue;
481 }
482 out.insert(path);
483 }
484 closedir(d);
485}
486static void ut_listLeftovers(std::set<std::string>& names, std::set<std::string>& dirs) {
487 ut_listDir("/tmp", "Psyclone_Shmem_", false, names); // macOS segments (and named semaphores)
488 ut_listDir("/dev/shm", "Shmem_", false, names); // Linux segments
489 ut_listDir("/dev/shm", "sem.Semaphore_", false, names); // Linux named semaphores
490 ut_listDir("/tmp", "psytest_", true, dirs); // test data dirs
491}
493 std::set<std::string> names, dirs;
494 bool active;
496 const char* attaching = getenv("PSY_CONC_CHILD"); // a re-exec'd reader: the parent's names, not its own
497 active = !(attaching && *attaching);
498 if (active)
500 }
502 if (!active)
503 return;
504 std::set<std::string> n2, d2;
505 ut_listLeftovers(n2, d2);
506 for (std::set<std::string>::iterator i = n2.begin(); i != n2.end(); i++) {
507 if (names.count(*i) || (i->find("Shmem_PsycloneIndex") != std::string::npos))
508 continue;
509 unlink(i->c_str());
510 }
511 for (std::set<std::string>::iterator i = d2.begin(); i != d2.end(); i++)
512 if (!dirs.count(*i))
513 utils::DeleteADir(i->c_str(), true);
514 }
515};
516#else
517struct UTLeftoverSweep {};
518#endif
519
520// Run a single test in its own process so a crash or hang in the test cannot
521// take down the whole suite, and so global/shared state (thread manager,
522// shared memory, singletons) never leaks between tests. Returns true on pass.
523// On non-fork platforms falls back to running inline.
524bool UnitTestRunner::executeRecord(UnitTestRecord* rec) {
525 // Clean any stale shared-memory segments left by a previously crashed/killed
526 // test before starting this one, so it always begins from a clean slate.
528 UTLeftoverSweep sweep; // and remove what this test leaves behind, once it is over
529
530#ifdef UT_HAVE_FORK
531 if (forkPerTest) {
532 std::string dir = outputDir.size() ? outputDir : ".";
533 std::string resultPath = dir + "/.cmsdk_result_" + rec->name;
534 std::string progPath = resultPath + ".progress";
535 std::string tracePath = resultPath + ".trace";
536 unlink(resultPath.c_str());
537 unlink(progPath.c_str());
538 unlink(tracePath.c_str());
539
540 fflush(stdout);
541 fflush(stderr);
542 uint64 t0 = GetTimeNow();
543 pid_t pid = fork();
544 if (pid < 0) {
545 // fork failed - run inline as a fallback
546 bool ok = rec->func ? rec->func() : false;
547 rec->durationUs = GetTimeNow() - t0;
548 return ok;
549 }
550 if (pid == 0) {
551 // ---- child ----
552 current = rec;
553 progressPath = progPath; // record current phase for timeout diagnostics
554 ut_installTimeoutTraceHandler(tracePath); // SIGUSR1 -> dump stack trace, then exit
555 lastProgressLen = 0;
556 if (isTTY) hookProgress(0, "starting...");
557 bool ok = false;
558 if (rec->func) ok = rec->func();
559 else rec->failReason = "no test function registered";
560 clearProgressLine(); // erase our progress line so the parent's status line is clean
561 ut_writeChildResult(resultPath, rec);
562 fflush(stdout);
563 _exit(ok ? 0 : 1);
564 }
565
566 // ---- parent ----
567 int status = 0;
568 bool timedOut = false;
569 // a test may ask for a longer cap (registerTest timeoutSec), e.g. one that runs many node start/stop cycles
570 const uint64 limitUs = rec->timeoutSec ? (uint64)rec->timeoutSec * 1000000ULL * UT_TIME_SCALE : UT_TEST_TIMEOUT_US;
571 while (true) {
572 pid_t r = waitpid(pid, &status, WNOHANG);
573 if (r == pid) break;
574 if (r < 0) break;
575 if (GetTimeNow() - t0 > limitUs) {
576 // Ask the stuck child to dump a stack trace of where it hung, give
577 // it a brief grace period to do so, then force-kill if necessary.
578 kill(pid, SIGUSR1);
579 bool reaped = false;
580 uint64 graceStart = GetTimeNow();
581 while (GetTimeNow() - graceStart < 2000000ULL) { // up to 2s
582 pid_t rr = waitpid(pid, &status, WNOHANG);
583 if (rr == pid || rr < 0) { reaped = true; break; }
584 utils::Sleep(15);
585 }
586 if (!reaped) {
587 kill(pid, SIGKILL);
588 waitpid(pid, &status, 0);
589 }
590 timedOut = true;
591 break;
592 }
593 utils::Sleep(15);
594 }
595 rec->durationUs = GetTimeNow() - t0;
596
597 bool ok = false;
598 if (timedOut) {
599 // Report which phase the test was in when it hung, and print the stack
600 // trace the child captured (if any) so the hang is diagnosable.
601 std::string note = utils::StringFormat("timed out after %llus", limitUs / 1000000ULL);
602 std::string lastPhase = ut_readProgressNote(progPath);
603 if (!lastPhase.empty()) note += " (last phase: " + lastPhase + ")";
604 rec->endNote = note;
605 ut_readChildResult(resultPath, rec); // recover any reason/metrics gathered pre-hang
606 ut_printTraceFile(tracePath);
607 } else if (WIFSIGNALED(status)) {
608 rec->endNote = utils::StringFormat("crashed (signal %d)", WTERMSIG(status));
609 ut_readChildResult(resultPath, rec); // recover the reason/metrics gathered pre-crash
610 } else {
611 ut_readChildResult(resultPath, rec);
612 ok = (WIFEXITED(status) && WEXITSTATUS(status) == 0);
613 }
614 unlink(resultPath.c_str());
615 unlink(progPath.c_str());
616 unlink(tracePath.c_str());
617 return ok;
618 }
619#endif
620
621 // Inline fallback (no fork available, or fork disabled).
622 current = rec;
623 lastProgressLen = 0;
624 if (isTTY) hookProgress(0, "starting...");
625 uint64 t0 = GetTimeNow();
626 bool ok = rec->func ? rec->func() : false;
627 rec->durationUs = GetTimeNow() - t0;
628 if (!rec->func) rec->endNote = "no test function registered";
629 return ok;
630}
631
632bool UnitTestRunner::runRecords(std::vector<UnitTestRecord*>& records) {
633 // Start from a clean shared-memory slate so a previously killed run can't
634 // deadlock this one on a stale process-shared mutex.
636
637 if (compareFile.size() && !compareLoaded) loadComparison();
638
639 // In non-verbose mode, silence the logging system's console output so the
640 // only thing on stdout is the consistent status/metric lines. Tests still
641 // report failures via unittest::fail(). Verbose mode leaves logging on.
642 bool savedLogToStdOut = true;
643 if (!verboseFlag) {
644 LogSystem::SetLogReceiver(NULL); // ensures the singleton exists
646 savedLogToStdOut = LogSystem::LogSingleton->printToStdOut;
648 }
649 }
650
651 uint64 startAll = GetTimeNow();
652 int passed = 0, failed = 0;
653
654 for (size_t i = 0; i < records.size(); i++) {
655 UnitTestRecord* rec = records[i];
656 beginTest(rec);
657 bool ok = executeRecord(rec);
658 rec->passed = ok;
659 finishTest(rec);
660 if (ok) passed++; else failed++;
661 }
662
663 uint64 totalUs = GetTimeNow() - startAll;
664
665 printf("\n----------------------------------------------------------------\n");
666 printf("CMSDK tests: %d passed, %d failed, %d total in %.2f ms\n",
667 passed, failed, (int)records.size(), totalUs / 1000.0);
668
669 if (writeJSONFlag) writeResults(records, totalUs, passed, failed);
670 printf("\n");
671
672 if (!verboseFlag && LogSystem::LogSingleton)
673 LogSystem::LogSingleton->printToStdOut = savedLogToStdOut;
674
675 return failed == 0;
676}
677
679 std::vector<UnitTestRecord*> records;
680 int excluded = 0;
681 for (size_t i = 0; i < tests.size(); i++) {
682 if (tests[i].inDefaultRun) records.push_back(&tests[i]);
683 else excluded++;
684 }
685 if (records.empty()) {
686 printf("No CMSDK unit tests are registered.\n");
687 return false;
688 }
689 printf("\nRunning %u CMSDK unit tests", (uint32)records.size());
690 if (excluded)
691 printf(" (%d excluded from the default run; run them by name)", excluded);
692 printf("...\n\n");
693 return runRecords(records);
694}
695
696bool UnitTestRunner::runOne(const char* name) {
697 if (!name) return false;
698 UnitTestRecord* found = NULL;
699 for (size_t i = 0; i < tests.size(); i++) {
700 if (stricmp(tests[i].name.c_str(), name) == 0) { found = &tests[i]; break; }
701 }
702 if (!found) {
703 printf("No CMSDK unit test named '%s'.\n", name);
704 listTests();
705 return false;
706 }
707 std::vector<UnitTestRecord*> records;
708 records.push_back(found);
709 printf("\nRunning CMSDK unit test '%s'...\n\n", found->name.c_str());
710 return runRecords(records);
711}
712
713// ----------------------------------------------------------------------------
714// Comparison file loading
715// ----------------------------------------------------------------------------
716bool UnitTestRunner::comparisonValue(const std::string& key, double& out) const {
717 std::map<std::string, double>::const_iterator it = compareMetrics.find(key);
718 if (it == compareMetrics.end()) return false;
719 out = it->second;
720 return true;
721}
722
723void UnitTestRunner::loadComparison() {
724 compareLoaded = false;
725 compareMetrics.clear();
726
727 std::string json = utils::ReadAFileString(compareFile);
728 if (json.empty()) {
729 printf("Warning: could not read comparison file '%s'\n", compareFile.c_str());
730 return;
731 }
732
733 // Count tokens first, then parse.
734 jsmn_parser parser;
735 jsmn_init(&parser);
736 int needed = jsmn_parse(&parser, json.c_str(), json.size(), NULL, 0);
737 if (needed <= 0) {
738 printf("Warning: comparison file '%s' is not valid JSON\n", compareFile.c_str());
739 return;
740 }
741 jsmntok_t* tokens = new jsmntok_t[needed + 1];
742 jsmn_init(&parser);
743 int count = jsmn_parse(&parser, json.c_str(), json.size(), tokens, needed + 1);
744 if (count <= 0) {
745 delete[] tokens;
746 printf("Warning: failed to parse comparison file '%s'\n", compareFile.c_str());
747 return;
748 }
749
750 // Pull every "test/metric" -> number pair from the flat section. Flat keys
751 // are the only keys containing '/', so they are unambiguous.
752 for (int n = 0; n < count - 1; n++) {
753 if (tokens[n].type != JSMN_STRING) continue;
754 int klen = tokens[n].end - tokens[n].start;
755 if (klen <= 0) continue;
756 const char* kstart = json.c_str() + tokens[n].start;
757 bool hasSlash = false;
758 for (int c = 0; c < klen; c++) { if (kstart[c] == '/') { hasSlash = true; break; } }
759 if (!hasSlash) continue;
760 if (tokens[n + 1].type != JSMN_PRIMITIVE) continue;
761 std::string key(kstart, klen);
762 std::string val(json.c_str() + tokens[n + 1].start, tokens[n + 1].end - tokens[n + 1].start);
763 compareMetrics[key] = utils::Ascii2Float64(val.c_str());
764 }
765
766 delete[] tokens;
767 compareLoaded = true;
768 printf("Comparing against '%s' (%u recorded metrics)\n\n",
769 compareFile.c_str(), (uint32)compareMetrics.size());
770}
771
772// ----------------------------------------------------------------------------
773// Results JSON writing
774// ----------------------------------------------------------------------------
775static std::string jsonEscape(const std::string& s) {
776 std::string out;
777 for (size_t i = 0; i < s.size(); i++) {
778 char c = s[i];
779 switch (c) {
780 case '\"': out += "\\\""; break;
781 case '\\': out += "\\\\"; break;
782 case '\n': out += "\\n"; break;
783 case '\r': out += "\\r"; break;
784 case '\t': out += "\\t"; break;
785 default: out += c; break;
786 }
787 }
788 return out;
789}
790
791std::string UnitTestRunner::timestampForFilename(uint64 t) {
792 struct PsyDateAndTime d = GetDateAndTime(t);
793 char buf[40]; // worst-case uint16 fields (see writeResults) => keep truncation-warning-free
794 snprintf(buf, sizeof(buf), "%04u%02u%02u-%02u%02u%02u",
795 d.year, d.mon, d.day, d.hour, d.min, d.sec);
796 return std::string(buf);
797}
798
799void UnitTestRunner::writeResults(const std::vector<UnitTestRecord*>& records,
800 uint64 totalUs, int passed, int failed) {
801 uint64 now = GetTimeNow();
802 struct PsyDateAndTime d = GetDateAndTime(now);
803 // Sized for the theoretical worst case of the format below: the calendar
804 // fields are uint16, so the compiler must assume up to 5 digits each
805 // ("%04u-%02u-%02u %02u:%02u:%02u" => up to 35 chars + NUL). 40 keeps
806 // -Wformat-truncation quiet without relying on the values staying small.
807 char dt[40];
808 snprintf(dt, sizeof(dt), "%04u-%02u-%02u %02u:%02u:%02u",
809 d.year, d.mon, d.day, d.hour, d.min, d.sec);
810
811 const char* platform =
812#if defined(WINDOWS)
813 "win"
814#elif defined(DARWIN) || defined(OSX) || defined(__APPLE__)
815 "macosx"
816#elif defined(LINUX) || defined(__linux)
817 "linux"
818#else
819 "unknown"
820#endif
821#if defined(ARCH_64)
822 "64"
823#else
824 "32"
825#endif
826 ;
827
828 std::string json;
829 json += "{\n";
830 json += " \"meta\": {\n";
831 json += utils::StringFormat(" \"version\": 1,\n");
832 json += utils::StringFormat(" \"timestamp_us\": %llu,\n", (unsigned long long)now);
833 json += utils::StringFormat(" \"datetime\": \"%s\",\n", dt);
834 json += utils::StringFormat(" \"platform\": \"%s\",\n", platform);
835 json += utils::StringFormat(" \"total\": %d,\n", (int)records.size());
836 json += utils::StringFormat(" \"passed\": %d,\n", passed);
837 json += utils::StringFormat(" \"failed\": %d,\n", failed);
838 json += utils::StringFormat(" \"duration_us\": %llu\n", (unsigned long long)totalUs);
839 json += " },\n";
840
841 // Human-readable structured section
842 json += " \"tests\": {\n";
843 for (size_t i = 0; i < records.size(); i++) {
844 const UnitTestRecord* rec = records[i];
845 json += utils::StringFormat(" \"%s\": {\n", jsonEscape(rec->name).c_str());
846 json += utils::StringFormat(" \"status\": \"%s\",\n", rec->passed ? "pass" : "fail");
847 json += utils::StringFormat(" \"duration_us\": %llu,\n", (unsigned long long)rec->durationUs);
848 json += " \"metrics\": {\n";
849 for (size_t j = 0; j < rec->metrics.size(); j++) {
850 const UnitTestMetric& m = rec->metrics[j];
851 json += utils::StringFormat(
852 " \"%s\": { \"value\": %.6f, \"unit\": \"%s\", \"higher_is_better\": %s }%s\n",
853 jsonEscape(m.name).c_str(), m.value, jsonEscape(m.unit).c_str(),
854 m.higherIsBetter ? "true" : "false",
855 (j + 1 < rec->metrics.size()) ? "," : "");
856 }
857 json += " }\n";
858 json += utils::StringFormat(" }%s\n", (i + 1 < records.size()) ? "," : "");
859 }
860 json += " },\n";
861
862 // Flat machine-comparison section ("test/metric" -> number)
863 json += " \"flat\": {\n";
864 std::vector<std::string> flat;
865 for (size_t i = 0; i < records.size(); i++) {
866 const UnitTestRecord* rec = records[i];
867 flat.push_back(utils::StringFormat(" \"%s/__duration_us\": %llu",
868 jsonEscape(rec->name).c_str(), (unsigned long long)rec->durationUs));
869 for (size_t j = 0; j < rec->metrics.size(); j++) {
870 const UnitTestMetric& m = rec->metrics[j];
871 flat.push_back(utils::StringFormat(" \"%s/%s\": %.6f",
872 jsonEscape(rec->name).c_str(), jsonEscape(m.name).c_str(), m.value));
873 }
874 }
875 for (size_t i = 0; i < flat.size(); i++)
876 json += flat[i] + ((i + 1 < flat.size()) ? ",\n" : "\n");
877 json += " }\n";
878 json += "}\n";
879
880 // Decide output paths.
881 std::vector<std::string> paths;
882 if (outputFile.size()) {
883 paths.push_back(outputFile);
884 } else {
885 std::string dir = outputDir.size() ? outputDir : ".";
886 paths.push_back(dir + "/cmsdk_perf_" + timestampForFilename(now) + ".json");
887 paths.push_back(dir + "/cmsdk_perf_latest.json");
888 }
889
890 for (size_t i = 0; i < paths.size(); i++) {
891 if (utils::WriteAFile(paths[i].c_str(), json.c_str(), (uint32)json.size()))
892 printf("Performance data written to %s\n", paths[i].c_str());
893 else
894 printf("Warning: could not write performance data to %s\n", paths[i].c_str());
895 }
896}
897
898// ----------------------------------------------------------------------------
899// unittest:: free function API
900// ----------------------------------------------------------------------------
901namespace unittest {
902
903// Format a va_list into a std::string using CMSDK's portable formatter
904// (handles the snprintf/_vsnprintf_s differences across MSVC/Cygwin/POSIX).
905static std::string ut_vformat(const char* fmt, va_list args) {
906 uint32 sz = 0;
907 char* s = utils::StringFormatVA(sz, fmt, args);
908 std::string out = s ? s : "";
909 if (s) free(s);
910 return out;
911}
912
913void progress(int percent, const char* action) {
914 UnitTestRunner::instance().hookProgress(percent, action);
915}
916
917void progressf(int percent, const char* fmt, ...) {
918 va_list args;
919 va_start(args, fmt);
920 std::string s = ut_vformat(fmt, args);
921 va_end(args);
922 UnitTestRunner::instance().hookProgress(percent, s.c_str());
923}
924
925void metric(const char* name, double value, const char* unit, bool higherIsBetter) {
926 UnitTestRunner::instance().hookMetric(name, value, unit, higherIsBetter);
927}
928
929void detail(const char* fmt, ...) {
930 // NO verbose gate here any more: hookDetail() records unconditionally (so a
931 // failing test can print its diagnostics) and echoes live only when verbose.
932 va_list args;
933 va_start(args, fmt);
934 std::string s = ut_vformat(fmt, args);
935 va_end(args);
937}
938
939void fail(const char* fmt, ...) {
940 va_list args;
941 va_start(args, fmt);
942 std::string s = ut_vformat(fmt, args);
943 va_end(args);
945}
946
947bool verbose() {
949}
950
951} // namespace unittest
952
953} // namespace cmlabs
CMSDK time: µs-resolution 64-bit timestamps and the Time Mapping Constant (TMC).
#define FILENO(f)
#define UT_NAME_WIDTH
#define UT_TEST_TIMEOUT_US
#define UT_INDENT
#define UT_METRIC_WIDTH
#define ISATTY(fd)
Small, dependency-free unit test harness used by all CMSDK object tests.
#define UT_TIME_SCALE
#define stricmp
Definition Utils.h:132
static bool SetLogReceiver(LogReceiver *rec)
Register a receiver that gets every accepted LogEntry.
Definition Utils.cpp:209
bool printToStdOut
Definition Utils.h:327
static LogSystem * LogSingleton
Lazily-created global instance used by all static functions.
Definition Utils.h:295
std::vector< std::string > testNames() const
void hookDetail(const char *text)
Hook behind unittest::detail() for the current test.
void setForkPerTest(bool v)
Run each test in its own process (default: on where supported) so crashes/hangs are isolated.
void setWriteJSON(bool v)
Enable/disable writing the perf JSON file at all.
void listTests() const
Print the registered tests (name, category, description) to stdout.
void hookProgress(int percent, const char *action)
Hook behind unittest::progress()/progressf() for the current test.
void setOutputFile(const char *path)
Set an explicit perf JSON output path (overrides the timestamped default).
bool hasTest(const char *name) const
void hookMetric(const char *name, double value, const char *unit, bool higherIsBetter)
Hook behind unittest::metric() for the current test.
static UnitTestRunner & instance()
Access the singleton (created on first use).
void setVerbose(bool v)
Enable/disable verbose diagnostics (unittest::detail output).
void registerTest(const char *name, UnitTestFunc func, const char *description="", const char *category="", bool inDefaultRun=true, uint32 timeoutSec=0)
Register a test with the runner.
bool hookVerbose() const
Hook behind unittest::verbose().
void setCompareFile(const char *path)
Set a previous perf JSON file to compare metrics against.
bool runAll()
Run every test marked inDefaultRun.
bool runOne(const char *name)
Run a single named test in isolation.
void setOutputDir(const char *dir)
Set the directory for the default (timestamped + latest) output files.
void hookFail(const char *text)
Hook behind unittest::fail() for the current test.
uint64 GetTimeNow()
Return the current absolute time (µs since year 0) according to the TMC.
Definition PsyTime.cpp:69
struct PsyDateAndTime GetDateAndTime(uint64 t, bool local=true)
Break a timestamp into calendar fields.
Definition PsyTime.cpp:324
bool(* UnitTestFunc)()
Signature every unit test uses.
bool Sleep(uint32 ms)
Suspend the calling thread.
Definition Utils.cpp:4078
Third-party (vendored): jsmn minimalistic JSON tokenizer by Serge Zaitsev (MIT licence),...
@ JSMN_PRIMITIVE
Definition jsmn.h:33
@ JSMN_STRING
Definition jsmn.h:32
int jsmn_parse(jsmn_parser *parser, const char *js, size_t len, jsmntok_t *tokens, unsigned int num_tokens)
Run JSON parser.
Definition jsmn.cpp:156
void jsmn_init(jsmn_parser *parser)
Create JSON parser over an array of tokens.
Definition jsmn.cpp:311
API used by the body of a unit test.
void fail(const char *fmt,...)
Set an explanatory reason shown on the FAIL line.
void progressf(int percent, const char *fmt,...)
printf-style variant of progress().
void metric(const char *name, double value, const char *unit="", bool higherIsBetter=true)
Record a performance metric.
void detail(const char *fmt,...)
Verbose-only indented diagnostic line (shown only when verbose=1).
static std::string ut_vformat(const char *fmt, va_list args)
void progress(int percent, const char *action)
Report progress with a short description of the current action.
std::string ReadAFileString(std::string filename)
Read an entire file into a std::string.
Definition Utils.cpp:9232
char * StringFormatVA(uint32 &size, const char *format, va_list args)
va_list core used by the other StringFormat overloads.
Definition Utils.cpp:9001
bool WriteAFile(const char *filename, const char *data, uint32 length, bool binary=false)
Write (create/overwrite) a file.
Definition Utils.cpp:9312
std::string StringFormat(const char *format,...)
printf into a std::string.
Definition Utils.cpp:9061
bool DeleteADir(const char *dirname, bool force)
Delete a directory (recursively when force).
Definition Utils.cpp:9532
float64 Ascii2Float64(const char *ascii, uint32 start=0, uint32 end=0)
Parse a 64-bit float from a substring (decimal point, not locale dependent).
Definition Utils.cpp:9999
static void ClearStaleTestSegments()
struct dirent * readdir(DIR *)
static void ut_writeChildResult(const std::string &path, const UnitTestRecord *rec)
static std::string jsonEscape(const std::string &s)
DIR * opendir(const char *)
Definition direntwin.cpp:53
static void ut_listLeftovers(std::set< std::string > &names, std::set< std::string > &dirs)
static void ut_printTraceFile(const std::string &path)
static void ut_timeoutTraceHandler(int)
static void ut_listDir(const char *dir, const char *prefix, bool dirsOnly, std::set< std::string > &out)
static void ut_clearSegmentsIn(const char *dir, const char *prefix)
static std::string ut_escape_field(const std::string &s)
int closedir(DIR *)
Definition direntwin.cpp:95
static std::string ut_readProgressNote(const std::string &path)
static int ut_traceFd
static void ut_readChildResult(const std::string &path, UnitTestRecord *rec)
static void ut_installTimeoutTraceHandler(const std::string &tracePath)
std::set< std::string > dirs
std::set< std::string > names
One recorded performance metric of a test run.
bool higherIsBetter
Delta-direction hint for compare mode.
std::string unit
Unit label (e.g.
double value
Measured value.
std::string name
Metric name (unique within the test).
Registration and result record for a single unit test.
uint32 timeoutSec
Per-test wall-clock cap in seconds (forked runs), 0 = the default 30 s; scaled by UT_TIME_SCALE.
UnitTestFunc func
The test function itself.
bool passed
Outcome (only meaningful when ran).
std::vector< UnitTestMetric > metrics
Metrics recorded via unittest::metric().
std::string failReason
Reason set by the test via unittest::fail() (printed immediately).
bool inDefaultRun
Included when running the whole suite (test=cmsdk).
std::string description
One-line human description.
std::string name
Canonical name, used by test=<name>.
std::string endNote
Framework outcome note (timed out / crashed / no test function).
std::string category
Grouping label (e.g.
uint64 durationUs
Wall-clock duration in microseconds.
char * d_name
Definition direntwin.h:35
int start
Definition jsmn.h:53
int end
Definition jsmn.h:54