23 #define ISATTY(fd) _isatty(fd)
24 #define FILENO(f) _fileno(f)
33 #define ISATTY(fd) isatty(fd)
34 #define FILENO(f) fileno(f)
35 #define UT_HAVE_FORK 1
45#define UT_TEST_TIMEOUT_US (30ULL * 1000000ULL * UT_TIME_SCALE)
61 size_t plen = strlen(prefix);
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;
82 const char* attaching = getenv(
"PSY_CONC_CHILD");
83 if (attaching && *attaching)
105 int n = backtrace(frames, 128);
111 ut_traceFd = open(tracePath.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
118 FILE* f = fopen(path.c_str(),
"r");
121 size_t r = fread(buf, 1,
sizeof(buf) - 1, f);
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) +
"\"";
132 FILE* f = fopen(path.c_str(),
"r");
136 while (fgets(line,
sizeof(line), f)) {
137 if (!header) { printf(
" stack trace where the test hung:\n"); header =
true; }
140 if (header) { printf(
"\n"); fflush(stdout); }
148#define UT_NAME_WIDTH 28
150#define UT_METRIC_WIDTH 26
156 static UnitTestRunner theInstance;
160UnitTestRunner::UnitTestRunner()
161 : current(NULL), verboseFlag(false), writeJSONFlag(true),
162 forkPerTest(true), isTTY(false), lastProgressLen(0), outputDir(
"."),
163 compareLoaded(false) {
171 const char* description,
const char* category,
172 bool inDefaultRun, uint32 timeoutSec) {
173 if (!name || !func)
return;
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;
189 rec.
category = category ? category :
"";
192 tests.push_back(rec);
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;
210 std::vector<std::string> names;
211 for (
size_t i = 0; i < tests.size(); i++) names.push_back(tests[i].name);
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());
223 printf(
" %-22s %s\n", tests[i].name.c_str(), tests[i].description.c_str());
225 printf(
"\nRun all with: test=cmsdk Run one with: test=<name>\n\n");
234 if (!current)
return;
235 if (percent < 0) percent = 0;
236 if (percent > 100) percent = 100;
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); }
250 int n = snprintf(buf,
sizeof(buf),
" [%3d%%] %-*.*s %s",
252 current->name.c_str(), action ? action :
"");
256 int pad = lastProgressLen - n;
259 for (
int i = 0; i < pad; i++) fputc(
' ', stdout);
262 lastProgressLen = (n > lastProgressLen) ? n : lastProgressLen;
267void UnitTestRunner::clearProgressLine() {
268 if (!isTTY || lastProgressLen <= 0)
return;
270 for (
int i = 0; i < lastProgressLen; i++) fputc(
' ', stdout);
277 if (!current || !name)
return;
282 m.
unit = unit ? unit :
"";
284 current->metrics.push_back(m);
289 if (!current)
return;
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());
300 if (!verboseFlag)
return;
302 printf(
UT_INDENT "%s\n", text ? text :
"");
307 if (!current)
return;
308 std::string reason = text ? text :
"";
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;
320 if (!reason.empty()) {
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());
332 printf(
UT_INDENT "reason: %s\n", reason.c_str());
341 const char* tag = rec->
passed ?
"PASS" :
"FAIL";
354void UnitTestRunner::printMetricLines(
const UnitTestRecord* rec) {
355 for (
size_t i = 0; i < rec->metrics.size(); i++) {
356 const UnitTestMetric& m = rec->metrics[i];
358 snprintf(line,
sizeof(line),
UT_INDENT "%-*s %14.3f %-8s",
364 std::string key = rec->name +
"/" + m.name;
365 if (compareLoaded && comparisonValue(key, prev)) {
367 double pct = (m.value - prev) / prev * 100.0;
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);
374 printf(
" prev %.3f", prev);
390 rec->metrics.clear();
391 rec->failReason.clear();
392 rec->endNote.clear();
397 printStatusLine(rec);
398 printMetricLines(rec);
408 for (
size_t i = 0; i < s.size(); i++) {
410 if (c ==
'\n' || c ==
'\r' || c ==
'\t') out +=
' ';
419 for (
size_t i = 0; i < rec->
metrics.size(); i++) {
422 snprintf(num,
sizeof(num),
"%.10g", m.
value);
431 if (data.empty())
return;
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);
438 if (line.empty())
continue;
440 std::vector<std::string> f;
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));
448 if (f[0] ==
"fail" && f.size() >= 2) {
450 }
else if (f[0] ==
"metric" && f.size() >= 5) {
468static void ut_listDir(
const char* dir,
const char* prefix,
bool dirsOnly, std::set<std::string>& out) {
471 size_t plen = strlen(prefix);
473 while ((e =
readdir(d)) != NULL) {
474 if (strncmp(e->
d_name, prefix, plen) != 0)
476 std::string path = std::string(dir) +
"/" + e->
d_name;
479 if (lstat(path.c_str(), &st) != 0 || !S_ISDIR(st.st_mode))
487 ut_listDir(
"/tmp",
"Psyclone_Shmem_",
false, names);
488 ut_listDir(
"/dev/shm",
"Shmem_",
false, names);
489 ut_listDir(
"/dev/shm",
"sem.Semaphore_",
false, names);
496 const char* attaching = getenv(
"PSY_CONC_CHILD");
497 active = !(attaching && *attaching);
504 std::set<std::string> 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))
511 for (std::set<std::string>::iterator i = d2.begin(); i != d2.end(); i++)
517struct UTLeftoverSweep {};
528 UTLeftoverSweep sweep;
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());
546 bool ok = rec->func ? rec->func() :
false;
553 progressPath = progPath;
558 if (rec->func) ok = rec->func();
559 else rec->failReason =
"no test function registered";
568 bool timedOut =
false;
572 pid_t r = waitpid(pid, &status, WNOHANG);
581 while (
GetTimeNow() - graceStart < 2000000ULL) {
582 pid_t rr = waitpid(pid, &status, WNOHANG);
583 if (rr == pid || rr < 0) { reaped =
true;
break; }
588 waitpid(pid, &status, 0);
603 if (!lastPhase.empty()) note +=
" (last phase: " + lastPhase +
")";
607 }
else if (WIFSIGNALED(status)) {
612 ok = (WIFEXITED(status) && WEXITSTATUS(status) == 0);
614 unlink(resultPath.c_str());
615 unlink(progPath.c_str());
616 unlink(tracePath.c_str());
626 bool ok = rec->func ? rec->func() :
false;
628 if (!rec->func) rec->endNote =
"no test function registered";
632bool UnitTestRunner::runRecords(std::vector<UnitTestRecord*>& records) {
637 if (compareFile.size() && !compareLoaded) loadComparison();
642 bool savedLogToStdOut =
true;
652 int passed = 0, failed = 0;
654 for (
size_t i = 0; i < records.size(); i++) {
655 UnitTestRecord* rec = records[i];
657 bool ok = executeRecord(rec);
660 if (ok) passed++;
else failed++;
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);
669 if (writeJSONFlag) writeResults(records, totalUs, passed, failed);
679 std::vector<UnitTestRecord*> records;
681 for (
size_t i = 0; i < tests.size(); i++) {
682 if (tests[i].inDefaultRun) records.push_back(&tests[i]);
685 if (records.empty()) {
686 printf(
"No CMSDK unit tests are registered.\n");
689 printf(
"\nRunning %u CMSDK unit tests", (uint32)records.size());
691 printf(
" (%d excluded from the default run; run them by name)", excluded);
693 return runRecords(records);
697 if (!name)
return false;
699 for (
size_t i = 0; i < tests.size(); i++) {
700 if (
stricmp(tests[i].name.c_str(), name) == 0) { found = &tests[i];
break; }
703 printf(
"No CMSDK unit test named '%s'.\n", name);
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);
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;
723void UnitTestRunner::loadComparison() {
724 compareLoaded =
false;
725 compareMetrics.clear();
729 printf(
"Warning: could not read comparison file '%s'\n", compareFile.c_str());
736 int needed =
jsmn_parse(&parser, json.c_str(), json.size(), NULL, 0);
738 printf(
"Warning: comparison file '%s' is not valid JSON\n", compareFile.c_str());
741 jsmntok_t* tokens =
new jsmntok_t[needed + 1];
743 int count =
jsmn_parse(&parser, json.c_str(), json.size(), tokens, needed + 1);
746 printf(
"Warning: failed to parse comparison file '%s'\n", compareFile.c_str());
752 for (
int n = 0; n < count - 1; n++) {
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;
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);
767 compareLoaded =
true;
768 printf(
"Comparing against '%s' (%u recorded metrics)\n\n",
769 compareFile.c_str(), (uint32)compareMetrics.size());
777 for (
size_t i = 0; i < s.size(); i++) {
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;
791std::string UnitTestRunner::timestampForFilename(uint64 t) {
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);
799void UnitTestRunner::writeResults(
const std::vector<UnitTestRecord*>& records,
800 uint64 totalUs,
int passed,
int failed) {
808 snprintf(dt,
sizeof(dt),
"%04u-%02u-%02u %02u:%02u:%02u",
809 d.year, d.mon, d.day, d.hour, d.min, d.sec);
811 const char* platform =
814#elif defined(DARWIN) || defined(OSX) || defined(__APPLE__)
816#elif defined(LINUX) || defined(__linux)
830 json +=
" \"meta\": {\n";
842 json +=
" \"tests\": {\n";
843 for (
size_t i = 0; i < records.size(); i++) {
844 const UnitTestRecord* rec = records[i];
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];
852 " \"%s\": { \"value\": %.6f, \"unit\": \"%s\", \"higher_is_better\": %s }%s\n",
854 m.higherIsBetter ?
"true" :
"false",
855 (j + 1 < rec->metrics.size()) ?
"," :
"");
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];
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];
875 for (
size_t i = 0; i < flat.size(); i++)
876 json += flat[i] + ((i + 1 < flat.size()) ?
",\n" :
"\n");
881 std::vector<std::string> paths;
882 if (outputFile.size()) {
883 paths.push_back(outputFile);
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");
890 for (
size_t i = 0; i < paths.size(); i++) {
892 printf(
"Performance data written to %s\n", paths[i].c_str());
894 printf(
"Warning: could not write performance data to %s\n", paths[i].c_str());
905static std::string
ut_vformat(
const char* fmt, va_list args) {
908 std::string out = s ? s :
"";
925void metric(
const char* name,
double value,
const char* unit,
bool higherIsBetter) {
939void fail(
const char* fmt, ...) {
CMSDK time: µs-resolution 64-bit timestamps and the Time Mapping Constant (TMC).
#define UT_TEST_TIMEOUT_US
Small, dependency-free unit test harness used by all CMSDK object tests.
static bool SetLogReceiver(LogReceiver *rec)
Register a receiver that gets every accepted LogEntry.
static LogSystem * LogSingleton
Lazily-created global instance used by all static functions.
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.
struct PsyDateAndTime GetDateAndTime(uint64 t, bool local=true)
Break a timestamp into calendar fields.
bool(* UnitTestFunc)()
Signature every unit test uses.
bool Sleep(uint32 ms)
Suspend the calling thread.
Third-party (vendored): jsmn minimalistic JSON tokenizer by Serge Zaitsev (MIT licence),...
int jsmn_parse(jsmn_parser *parser, const char *js, size_t len, jsmntok_t *tokens, unsigned int num_tokens)
Run JSON parser.
void jsmn_init(jsmn_parser *parser)
Create JSON parser over an array of tokens.
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.
char * StringFormatVA(uint32 &size, const char *format, va_list args)
va_list core used by the other StringFormat overloads.
bool WriteAFile(const char *filename, const char *data, uint32 length, bool binary=false)
Write (create/overwrite) a file.
std::string StringFormat(const char *format,...)
printf into a std::string.
bool DeleteADir(const char *dirname, bool force)
Delete a directory (recursively when force).
float64 Ascii2Float64(const char *ascii, uint32 start=0, uint32 end=0)
Parse a 64-bit float from a substring (decimal point, not locale dependent).
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 *)
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)
static std::string ut_readProgressNote(const std::string &path)
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.