Testing module

Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-04-29 22:49:33 +03:00
1 parent 4fc129fb7e
commit e7186f17f0
42 files changed
+1816 -413

No files matched your search

+18
View File
@@ -0,0 +1,18 @@
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Detail/Stacktrace.hpp>
namespace Void::Testing::Detail {
void handle_assertion(AssertionResult result) {
auto& ctx = TestContext::current();
if (ctx.current_result) {
ctx.current_result->assertions.push_back(std::move(result));
const auto& last = ctx.current_result->assertions.back();
if (!last.passed) {
ctx.current_result->state = TestState::Failed;
if (last.kind == AssertKind::Require || last.kind == AssertKind::Assert) {
ctx.should_abort = true;
throw RequireFailure{last.message};
}
}
}
}
} // namespace Void::Testing::Detail
+71
View File
@@ -0,0 +1,71 @@
#include <Void/Testing/ConsoleReporter.hpp>
#include <Void/Testing/Detail/Color.hpp>
#include <Void/Testing/Detail/SignalHandler.hpp>
#include <format>
#include <chrono>
#include <algorithm>
namespace Void::Testing {
using namespace Detail::Color;
void ConsoleReporter::on_run_start(const RunConfig&, int total_tests) {
os_ << "\n" << apply(bold_blue, "╭──────────────────────────────────────────────╮") << "\n"
<< apply(bold_blue, "│") << apply(bold_white, " Void Testing") << apply(dim, " v1.0") << std::string(31, ' ') << apply(bold_blue, "│") << "\n"
<< std::format("{}│{} Discovered {} test{}{}│\n", apply(bold_blue, "╰"), apply(dim, ""), apply(bold_white, std::to_string(total_tests)), total_tests != 1 ? "s" : "", std::string(total_tests < 10 ? 33 : 28, ' '))
<< apply(bold_blue, "╰──────────────────────────────────────────────╯") << "\n\n";
}
void ConsoleReporter::on_suite_start(const std::string& suite_name, int test_count) {
os_ << std::format(" {} {} [{} test{}]\n", apply(bold_blue, "◆"), apply(bold_white, suite_name), apply(dim, std::to_string(test_count)), test_count != 1 ? "s" : "");
}
void ConsoleReporter::on_test_start(const TestCase&) {}
void ConsoleReporter::on_suite_end(const SuiteResult&) {}
void ConsoleReporter::on_test_end(const TestResult& result) {
double ms = std::chrono::duration<double, std::milli>(result.duration).count();
std::string time_str = ms < 1.0 ? std::format("{:.3f}ms", ms) : std::format("{:.1f}ms", ms);
std::string tags_str;
if (!result.tags.empty()) { for(const auto& t : result.tags) tags_str += "[" + t + "]"; tags_str = " " + apply(dim, tags_str); }
switch (result.state) {
case TestState::Passed: os_ << std::format(" {} {:<40s}{}{}\n", apply(bold_green, "✔"), apply(green, result.name), tags_str, apply(dim, time_str)); break;
case TestState::Failed:
os_ << std::format(" {} {:<40s}{}{}\n", apply(bold_red, "✘"), apply(red, result.name), tags_str, apply(dim, time_str));
for (const auto& ar : result.assertions) if (!ar.passed) print_assertion_failure(ar);
if (!result.crash_info.empty()) print_crash_info(result);
break;
case TestState::Skipped: os_ << std::format(" {} {:<40s}{}\n", apply(bold_yellow, "⊘"), apply(yellow, result.name), apply(dim, std::format("[SKIPPED: {}]", result.skip_reason.empty() ? "no reason" : result.skip_reason))); break;
case TestState::Crashed: os_ << std::format(" {} {:<40s}{}\n", apply(bold_red, "⚡"), apply(red, result.name), apply(dim, time_str)); print_crash_info(result); break;
}
}
void ConsoleReporter::print_assertion_failure(const AssertionResult& ar) {
os_ << apply(red, " ╭─── Assertion Failed") << apply(dim, " ──────────────────────╮") << "\n";
std::filesystem::path p{ar.location.file_name()};
os_ << std::format(" │ {}:{}\n", apply(bold_white, p.filename().string()), ar.location.line());
if (!ar.expression.empty()) os_ << std::format(" │ {}\n", apply(cyan, ar.expression));
if (!ar.expected_repr.empty()) os_ << std::format(" │ {} {}\n", apply(bold_white, "expected:"), apply(green, ar.expected_repr));
if (!ar.actual_repr.empty()) os_ << std::format(" │ {} {}\n", apply(bold_white, "actual: "), apply(red, ar.actual_repr));
if (!ar.message.empty()) os_ << std::format(" │ {}\n", ar.message);
os_ << apply(red, " ╰────────────────────────────────────────────╯") << "\n";
}
void ConsoleReporter::print_crash_info(const TestResult& result) {
os_ << apply(bold_red, " ╭─── Crash") << apply(dim, " ───────────────────────────╮") << "\n";
if (!result.crash_info.empty()) os_ << std::format(" │ {}\n", apply(red, result.crash_info));
os_ << apply(bold_red, " ╰────────────────────────────────────────────╯") << "\n";
if (!result.stacktrace.empty()) os_ << apply(dim, " Stacktrace:\n") << result.stacktrace << "\n";
}
void ConsoleReporter::on_run_end(const RunResult& result) {
os_ << "\n" << apply(dim, "╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍") << "\n"
<< std::format(" {} tests: ", apply(bold_white, std::to_string(result.total)));
if (result.passed > 0) os_ << std::format("{} {} ", apply(bold_green, std::to_string(result.passed)), apply(green, "✔"));
if (result.failed + result.crashed > 0) os_ << std::format("{} {} ", apply(bold_red, std::to_string(result.failed + result.crashed)), apply(red, "✘"));
if (result.skipped > 0) os_ << std::format("{} {} ", apply(bold_yellow, std::to_string(result.skipped)), apply(yellow, "⊘"));
double total_ms = std::chrono::duration<double, std::milli>(result.total_duration).count();
os_ << std::format(" {} {}\n", apply(dim, "in"), apply(bold_cyan, total_ms < 1000 ? std::format("{:.1f}ms", total_ms) : std::format("{:.2f}s", total_ms / 1000.0)))
<< apply(dim, "╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍") << "\n\n";
}
} // namespace Void::Testing
+35
View File
@@ -0,0 +1,35 @@
#include <Void/Testing/JUnitReporter.hpp>
#include <format>
#include <chrono>
namespace Void::Testing {
void JUnitReporter::on_run_start(const RunConfig&, int) {}
void JUnitReporter::on_suite_start(const std::string&, int) {}
void JUnitReporter::on_test_start(const TestCase&) {}
void JUnitReporter::on_test_end(const TestResult&) {}
void JUnitReporter::on_suite_end(const SuiteResult& result) { suite_results_.push_back(result); }
void JUnitReporter::on_run_end(const RunResult& result) {
double total_seconds = std::chrono::duration<double>(result.total_duration).count();
os_ << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<testsuites tests=\"" << result.total << "\" failures=\"" << result.failed << "\" errors=\"" << result.crashed << "\" time=\"" << std::format("{:.3f}", total_seconds) << "\">\n";
for (const auto& suite : suite_results_) {
int sf=0, se=0, ss=0; for (const auto& t : suite.tests) { if(t.state==TestState::Failed) sf++; if(t.state==TestState::Crashed) se++; if(t.state==TestState::Skipped) ss++; }
double st=0; for (const auto& t : suite.tests) st += std::chrono::duration<double>(t.duration).count();
os_ << " <testsuite name=\"" << xml_escape(suite.name) << "\" tests=\"" << suite.tests.size() << "\" failures=\"" << sf << "\" errors=\"" << se << "\" skipped=\"" << ss << "\" time=\"" << std::format("{:.3f}", st) << "\">\n";
for (const auto& test : suite.tests) {
double tt = std::chrono::duration<double>(test.duration).count();
os_ << " <testcase name=\"" << xml_escape(test.name) << "\" classname=\"" << xml_escape(test.suite) << "\" time=\"" << std::format("{:.3f}", tt) << "\"";
if (test.state == TestState::Skipped) os_ << ">\n <skipped message=\"" << xml_escape(test.skip_reason) << "\"/>\n </testcase>\n";
else if (test.state == TestState::Failed) { os_ << ">\n"; for (const auto& ar : test.assertions) if(!ar.passed) os_ << " <failure message=\"" << xml_escape(ar.message) << "\"/>\n"; os_ << " </testcase>\n"; }
else if (test.state == TestState::Crashed) os_ << ">\n <error message=\"" << xml_escape(test.crash_info) << "\"/>\n </testcase>\n";
else os_ << "/>\n";
}
os_ << " </testsuite>\n";
}
os_ << "</testsuites>\n";
}
std::string JUnitReporter::xml_escape(std::string_view s) {
std::string r; r.reserve(s.size()); for(char c : s) { switch(c) { case '&': r+="&amp;"; break; case '<': r+="&lt;"; break; case '>': r+="&gt;"; break; case '"': r+="&quot;"; break; case '\'': r+="&apos;"; break; default: r+=c; } } return r;
}
} // namespace Void::Testing
+2
View File
@@ -0,0 +1,2 @@
#include <Void/Testing/Runner.hpp>
int main(int argc, char** argv) { return Void::Testing::Runner::instance().main(argc, argv); }
+2
View File
@@ -0,0 +1,2 @@
#include <Void/Testing/Detail/Registry.hpp>
namespace Void::Testing::Detail {}
+355
View File
@@ -0,0 +1,355 @@
#include <Void/Testing/Runner.hpp>
#include "Void/Testing/Config.hpp"
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/ConsoleReporter.hpp>
#include <Void/Testing/Detail/Color.hpp>
#include <Void/Testing/Detail/Registry.hpp>
#include <Void/Testing/Detail/SignalHandler.hpp>
#include <Void/Testing/Detail/Stacktrace.hpp>
#include <Void/Testing/JUnitReporter.hpp>
#include <algorithm>
#include <csignal>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <random>
#include <regex>
#include <unordered_map>
namespace Void::Testing
{
RunConfig Runner::parse_args(int argc, char** argv)
{
RunConfig config;
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if ((arg == "--filter" || arg == "--suite" || arg == "--reporter" ||
arg == "--output" || arg == "--tag" || arg == "--seed" ||
arg == "--repeat") &&
i + 1 < argc) {
std::string val = argv[++i];
if (arg == "--filter") {
config.filter_pattern = val;
} else if (arg == "--suite") {
config.suite_filter = val;
} else if (arg == "--reporter") {
config.reporter = val;
} else if (arg == "--output") {
config.output_file = val;
} else if (arg == "--tag") {
config.tag_filter = val;
} else if (arg == "--seed") {
config.shuffle = true;
config.random_seed = static_cast<unsigned>(std::stoul(val));
} else if (arg == "--repeat") {
config.repeat = static_cast<unsigned>(std::stoul(val));
}
} else if (arg == "--help") {
config.show_help = true;
} else if (arg == "--list") {
config.list_only = true;
} else if (arg == "--verbose") {
config.verbose = true;
} else if (arg == "--no-color") {
config.no_color = true;
} else if (arg == "--shuffle") {
config.shuffle = true;
std::random_device rd;
config.random_seed = rd();
}
}
return config;
}
std::vector<TestCase>
Runner::filter_tests(const std::vector<TestCase>& tests,
const RunConfig& config)
{
std::vector<TestCase> result;
std::regex filter_regex{".*"};
if (!config.filter_pattern.empty()) {
try {
filter_regex = std::regex{config.filter_pattern};
} catch (...) {
return {};
}
}
for (const auto& test : tests) {
if (!config.suite_filter.empty() &&
test.suite != config.suite_filter) {
continue;
}
if (!std::regex_search(test.name, filter_regex) &&
!std::regex_search(test.suite + "." + test.name,
filter_regex)) {
continue;
}
if (!config.tag_filter.empty()) {
bool has = false;
for (const auto& t : test.tags) {
if (t == config.tag_filter) {
has = true;
break;
}
}
if (!has) {
continue;
}
}
result.push_back(test);
}
return result;
}
std::unique_ptr<Reporter> Runner::create_reporter(const RunConfig& config)
{
if (config.reporter == "junit") {
static std::ofstream file{config.output_file.empty()
? "test_results.xml"
: config.output_file};
return std::make_unique<JUnitReporter>(file);
}
return std::make_unique<ConsoleReporter>(std::cout, !config.no_color);
}
TestResult Runner::execute_test(TestCase& test_case)
{
TestResult result;
result.name = test_case.name;
result.suite = test_case.suite;
result.tags = test_case.tags;
if (test_case.disabled) {
result.state = TestState::Skipped;
result.skip_reason = test_case.skip_reason.empty()
? "disabled"
: test_case.skip_reason;
return result;
}
Detail::TestContext::current().current_result = &result;
Detail::TestContext::current().should_abort = false;
int crash_signal = 0;
std::string crash_stacktrace;
Detail::install_signal_handlers([&](int sig, const std::string& trace) {
crash_signal = sig;
crash_stacktrace = trace;
});
auto start = std::chrono::high_resolution_clock::now();
try {
#ifndef _WIN32
if (sigsetjmp(Detail::get_jump_buffer(), 1) == 0) {
Detail::set_jump_ready(true);
run_test_body(test_case, result);
} else {
result.state = TestState::Crashed;
result.crash_info = std::format(
"Signal: {}", Detail::signal_name(crash_signal));
result.stacktrace = crash_stacktrace;
}
Detail::set_jump_ready(false);
#else
run_test_body(test_case, result);
#endif
} catch (const Detail::RequireFailure&) {
if (result.state != TestState::Skipped) {
result.state = TestState::Failed;
}
} catch (const std::exception& e) {
result.state = TestState::Failed;
result.crash_info =
std::format("Unhandled exception: {}", e.what());
result.stacktrace =
Detail::format_stacktrace(Detail::capture_stacktrace(1, 8));
} catch (...) {
result.state = TestState::Failed;
result.crash_info = "Unhandled unknown exception";
result.stacktrace =
Detail::format_stacktrace(Detail::capture_stacktrace(1, 8));
}
auto end = std::chrono::high_resolution_clock::now();
result.duration = end - start;
Detail::uninstall_signal_handlers();
Detail::TestContext::current().current_result = nullptr;
if (result.state != TestState::Skipped &&
result.state != TestState::Crashed) {
bool any =
std::any_of(result.assertions.begin(), result.assertions.end(),
[](const auto& a) { return !a.passed; });
result.state = any ? TestState::Failed : TestState::Passed;
}
return result;
}
void Runner::run_test_body(TestCase& test_case, TestResult&)
{
if (test_case.fixture_create) {
void* fixture = test_case.fixture_create();
Detail::TestContext::current().fixture = fixture;
try {
test_case.fixture_setup(fixture);
test_case.run();
test_case.fixture_teardown(fixture);
} catch (...) {
test_case.fixture_teardown(fixture);
test_case.fixture_destroy(fixture);
Detail::TestContext::current().fixture = nullptr;
throw;
}
test_case.fixture_destroy(fixture);
Detail::TestContext::current().fixture = nullptr;
} else {
test_case.run();
}
}
RunResult Runner::run(const RunConfig& config)
{
Detail::Color::g_color_enabled = !config.no_color;
if (config.show_help) {
using namespace Detail::Color;
std::cout
<< "\n"
<< apply(bold_blue, "╭─────────────────────────────────────────"
"─────────────────────────╮")
<< "\n"
<< apply(bold_blue, "│") << apply(bold_white, " Void Testing")
<< apply(dim, " — Command Line Interface")
<< std::string(28, ' ') << apply(bold_blue, "│") << "\n"
<< apply(bold_blue, "╰─────────────────────────────────────────"
"─────────────────────────╯")
<< "\n"
<< "\n"
<< " " << apply(bold_white, "USAGE:") << "\n"
<< " " << apply(cyan, "<executable>") << " "
<< apply(dim, "[options]") << "\n"
<< "\n"
<< " " << apply(bold_white, "OPTIONS:") << "\n"
<< " " << apply(green, "--filter <pattern> ")
<< apply(dim, "Run tests matching the regex pattern") << "\n"
<< " " << apply(green, "--suite <name> ")
<< apply(dim, "Run only tests in the specified suite") << "\n"
<< " " << apply(green, "--tag <name> ")
<< apply(dim, "Run only tests with the specified tag") << "\n"
<< " " << apply(green, "--list ")
<< apply(dim, "List discovered tests without running them")
<< "\n"
<< " " << apply(green, "--shuffle ")
<< apply(dim, "Randomize the order of test execution") << "\n"
<< " " << apply(green, "--seed <n> ")
<< apply(dim, "Set the random seed (implies --shuffle)") << "\n"
<< " " << apply(green, "--repeat <n> ")
<< apply(dim, "Repeat the test run n times") << "\n"
<< " " << apply(green, "--reporter <type> ")
<< apply(dim, "Choose the output reporter: console, junit")
<< "\n"
<< " " << apply(green, "--output <file> ")
<< apply(dim, "Write reporter output to a file") << "\n"
<< " " << apply(green, "--verbose ")
<< apply(dim, "Enable verbose output") << "\n"
<< " " << apply(green, "--no-color ")
<< apply(dim, "Disable colored console output") << "\n"
<< " " << apply(green, "--help ")
<< apply(dim, "Show this help message") << "\n"
<< "\n"
<< " " << apply(bold_white, "EXAMPLES:") << "\n"
<< " " << apply(cyan, "./run_tests") << " "
<< apply(yellow, "--filter") << " \"math_tests.*\"" << "\n"
<< " " << apply(cyan, "./run_tests") << " "
<< apply(yellow, "--tag") << " integration "
<< apply(yellow, "--shuffle") << "\n"
<< " " << apply(cyan, "./run_tests") << " "
<< apply(yellow, "--reporter") << " junit "
<< apply(yellow, "--output") << " results.xml" << "\n"
<< "\n";
return {};
}
auto all_tests = Detail::Registry::instance().tests();
auto tests = filter_tests(all_tests, config);
auto reporter = create_reporter(config);
if (config.list_only) {
for (const auto& t : tests) {
std::cout << t.suite << "." << t.name
<< (t.disabled ? " [DISABLED]" : "") << "\n";
}
return {};
}
RunResult run_result;
reporter->on_run_start(config, static_cast<int>(tests.size()));
if (config.shuffle) {
std::shuffle(tests.begin(), tests.end(),
std::mt19937{config.random_seed});
}
std::vector<SuiteResult> suite_results;
std::unordered_map<std::string, size_t> suite_index;
for (auto& test : tests) {
if (suite_index.find(test.suite) == suite_index.end()) {
suite_index[test.suite] = suite_results.size();
suite_results.push_back({.name = test.suite});
}
}
auto start_time = std::chrono::high_resolution_clock::now();
for (unsigned rep = 0; rep < config.repeat; ++rep) {
for (auto& test : tests) {
auto& suite = suite_results[suite_index[test.suite]];
if (rep == 0) {
reporter->on_suite_start(
suite.name, std::count_if(tests.begin(), tests.end(),
[&](const auto& t) {
return t.suite ==
suite.name;
}));
}
reporter->on_test_start(test);
auto result = execute_test(test);
reporter->on_test_end(result);
if (rep == config.repeat - 1) {
suite.tests.push_back(std::move(result));
}
}
}
auto end_time = std::chrono::high_resolution_clock::now();
for (auto& suite : suite_results) {
for (const auto& test : suite.tests) {
switch (test.state) {
case TestState::Passed:
run_result.passed++;
break;
case TestState::Failed:
run_result.failed++;
break;
case TestState::Skipped:
run_result.skipped++;
break;
case TestState::Crashed:
run_result.crashed++;
break;
}
run_result.total++;
}
reporter->on_suite_end(suite);
run_result.suites.push_back(std::move(suite));
}
run_result.total_duration = end_time - start_time;
reporter->on_run_end(run_result);
return run_result;
}
int Runner::main(int argc, char** argv)
{
auto config = parse_args(argc, argv);
auto result = run(config);
return (result.failed + result.crashed > 0) ? 1 : 0;
}
} // namespace Void::Testing
+59
View File
@@ -0,0 +1,59 @@
#include <Void/Testing/Detail/SignalHandler.hpp>
#include <Void/Testing/Detail/Stacktrace.hpp>
#include <csignal>
#include <cstring>
#include <cstdlib>
namespace Void::Testing::Detail {
static CrashCallback g_crash_callback;
static int g_last_signal{0};
#ifndef _WIN32
static sigjmp_buf g_jump_buffer;
static bool g_jump_ready{false};
sigjmp_buf& get_jump_buffer() { return g_jump_buffer; }
void set_jump_ready(bool ready) { g_jump_ready = ready; }
#endif
const char* signal_name(int sig) {
switch (sig) {
case SIGSEGV: return "SIGSEGV (segmentation fault)";
case SIGABRT: return "SIGABRT (abort)";
case SIGFPE: return "SIGFPE (floating point exception)";
case SIGILL: return "SIGILL (illegal instruction)";
#ifdef SIGBUS
case SIGBUS: return "SIGBUS (bus error)";
#endif
default: return "UNKNOWN SIGNAL";
}
}
static void crash_handler(int sig) {
g_last_signal = sig;
auto frames = capture_stacktrace(1, 16);
auto trace = format_stacktrace(frames);
if (g_crash_callback) g_crash_callback(sig, trace);
#ifndef _WIN32
if (g_jump_ready) { g_jump_ready = false; siglongjmp(g_jump_buffer, sig); }
#endif
std::_Exit(128 + sig);
}
void install_signal_handlers(CrashCallback on_crash) {
g_crash_callback = std::move(on_crash);
struct sigaction sa{}; sa.sa_handler = crash_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0;
sigaction(SIGSEGV, &sa, nullptr); sigaction(SIGABRT, &sa, nullptr); sigaction(SIGFPE, &sa, nullptr); sigaction(SIGILL, &sa, nullptr);
#ifdef SIGBUS
sigaction(SIGBUS, &sa, nullptr);
#endif
}
void uninstall_signal_handlers() {
struct sigaction sa{}; sa.sa_handler = SIG_DFL;
sigaction(SIGSEGV, &sa, nullptr); sigaction(SIGABRT, &sa, nullptr); sigaction(SIGFPE, &sa, nullptr); sigaction(SIGILL, &sa, nullptr);
#ifdef SIGBUS
sigaction(SIGBUS, &sa, nullptr);
#endif
g_crash_callback = nullptr;
}
} // namespace Void::Testing::Detail
+64
View File
@@ -0,0 +1,64 @@
#include <Void/Testing/Detail/Stacktrace.hpp>
#include <Void/Testing/Detail/Color.hpp>
#include <fstream>
#include <sstream>
#include <format>
#include <algorithm>
#include <filesystem>
#define BOOST_STACKTRACE_USE_BACKTRACE
#include <boost/stacktrace.hpp>
#include <boost/core/demangle.hpp>
namespace Void::Testing::Detail {
std::vector<StackFrame> capture_stacktrace(unsigned skip_frames, unsigned max_frames) {
std::vector<StackFrame> result;
try {
boost::stacktrace::stacktrace bt(skip_frames + 1, max_frames);
for (auto it = bt.begin(); it != bt.end(); ++it) {
StackFrame frame;
std::string name = it->name();
if (!name.empty()) frame.function_name = boost::core::demangle(name.c_str());
frame.source_file = it->source_file(); frame.source_line = it->source_line();
if (!frame.source_file.empty() && frame.source_line > 0) frame.source_snippet = read_source_snippet(frame.source_file, frame.source_line, 2);
result.push_back(std::move(frame));
}
} catch (...) {}
return result;
}
std::string read_source_snippet(const std::string& file, int line, int context_lines) {
std::ifstream ifs{file}; if (!ifs.is_open()) return {};
std::ostringstream result; std::string current_line; int line_num = 1;
int start = std::max(1, line - context_lines); int end = line + context_lines;
while (std::getline(ifs, current_line)) {
if (line_num >= start && line_num <= end) {
std::string prefix = (line_num == line) ? " >>> " : " ";
result << std::format("{:>4}{}{}\n", line_num, prefix, current_line);
}
if (line_num > end) break; ++line_num;
}
return result.str();
}
std::string format_stacktrace(const std::vector<StackFrame>& frames) {
if (frames.empty()) return " <no stacktrace available>\n";
std::ostringstream oss;
for (size_t i = 0; i < frames.size(); ++i) {
const auto& frame = frames[i];
oss << std::format(" #{:02} ", i);
if (!frame.function_name.empty()) oss << (Color::g_color_enabled ? Color::apply(Color::bold_cyan, frame.function_name) : frame.function_name);
else oss << "<unknown>";
if (!frame.source_file.empty() && frame.source_line > 0) {
std::filesystem::path p{frame.source_file};
oss << "\n at " << (Color::g_color_enabled ? Color::apply(Color::dim, p.filename().string()) : p.filename().string()) << ":" << frame.source_line;
}
oss << "\n";
if (!frame.source_snippet.empty() && i < 5) oss << " " << (Color::g_color_enabled ? Color::apply(Color::dim, frame.source_snippet) : frame.source_snippet);
}
return oss.str();
}
void print_stacktrace(std::ostream& os, const std::vector<StackFrame>& frames) { os << format_stacktrace(frames); }
} // namespace Void::Testing::Detail
+63
View File
@@ -0,0 +1,63 @@
#include <Void/Testing/Detail/Symbol.hpp>
#include <filesystem>
#include <algorithm>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <dbghelp.h>
#pragma comment(lib, "dbghelp.lib")
#else
#include <dlfcn.h>
#ifdef __GNUC__
#include <cxxabi.h>
#endif
#endif
namespace Void::Testing::Detail {
std::string resolve_symbol_name(const void* address) {
#ifdef _WIN32
static bool sym_initialized = false;
if (!sym_initialized) { SymInitialize(GetCurrentProcess(), nullptr, TRUE); sym_initialized = true; }
char buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)];
auto* symbol = reinterpret_cast<SYMBOL_INFO*>(buffer);
symbol->SizeOfStruct = sizeof(SYMBOL_INFO); symbol->MaxNameLen = MAX_SYM_NAME;
DWORD64 displacement = 0;
if (SymFromAddr(GetCurrentProcess(), reinterpret_cast<DWORD64>(address), &displacement, symbol)) return symbol->Name;
return {};
#else
Dl_info info{}; if (dladdr(address, &info) && info.dli_sname) return info.dli_sname; return {};
#endif
}
std::string demangle(std::string_view mangled) {
if (mangled.empty()) return {};
#ifdef _WIN32
return std::string{mangled};
#else
#ifdef __GNUC__
int status = 0; char* demangled = abi::__cxa_demangle(mangled.data(), nullptr, nullptr, &status);
if (status == 0 && demangled) { std::string result{demangled}; std::free(demangled); return result; }
return std::string{mangled};
#else
return std::string{mangled};
#endif
#endif
}
std::string pretty_name(const void* address) { auto m = resolve_symbol_name(address); return m.empty() ? "" : demangle(m); }
std::string extract_test_name(std::string_view pretty_symbol) {
if (pretty_symbol.empty()) return "<unnamed>";
auto paren = pretty_symbol.find('(');
std::string_view name_part = (paren != std::string_view::npos) ? pretty_symbol.substr(0, paren) : pretty_symbol;
auto last_colon = name_part.rfind("::");
if (last_colon != std::string_view::npos) name_part = name_part.substr(last_colon + 2);
while (!name_part.empty() && name_part.front() == ' ') name_part.remove_prefix(1);
while (!name_part.empty() && name_part.back() == ' ') name_part.remove_suffix(1);
return std::string{name_part};
}
std::string suite_from_file(std::string_view file_path) { return std::filesystem::path{file_path}.stem().string(); }
} // namespace Void::Testing::Detail
+8
View File
@@ -0,0 +1,8 @@
void_add_module(Testing EXTERNAL_DEPS Boost::stacktrace_backtrace)
if(WIN32)
target_link_libraries(Void_Testing PUBLIC dbghelp)
else()
target_link_libraries(Void_Testing PUBLIC dl)
target_compile_options(Void_Testing PRIVATE -g -fno-omit-frame-pointer)
endif()