feat(Testing): add per-run owned reporters, strict config validation, FailureCapture, subprocess isolation, and deterministic property/schedule harness (M-TESTING-02, M-TESTING-03)
This commit is contained in:
1 parent
1b3331e3a8
commit
de8a981893
11 files changed
+1712
-55
No files matched your search
+55
-13
@@ -1,17 +1,59 @@
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
namespace Void::Testing::Detail {
|
||||
void handle_assertion(AssertionResult result) {
|
||||
|
||||
#include <atomic>
|
||||
|
||||
namespace Void::Testing::Detail
|
||||
{
|
||||
namespace
|
||||
{
|
||||
std::atomic<std::size_t> g_stray_assertions{0};
|
||||
} // namespace
|
||||
|
||||
std::size_t stray_assertion_count() noexcept
|
||||
{
|
||||
return g_stray_assertions.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
void reset_stray_assertion_count() noexcept
|
||||
{
|
||||
g_stray_assertions.store(0, std::memory_order_release);
|
||||
}
|
||||
|
||||
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};
|
||||
}
|
||||
}
|
||||
if (!ctx.current_result) {
|
||||
g_stray_assertions.fetch_add(1, std::memory_order_acq_rel);
|
||||
return;
|
||||
}
|
||||
|
||||
TestResult* tr = ctx.current_result;
|
||||
const bool passed = result.passed;
|
||||
const AssertKind kind = result.kind;
|
||||
std::string abort_msg = result.message;
|
||||
|
||||
if (!passed) {
|
||||
tr->state = TestState::Failed;
|
||||
}
|
||||
|
||||
const std::size_t entry_bytes =
|
||||
result.expression.size() +
|
||||
result.expected_repr.size() +
|
||||
result.actual_repr.size() +
|
||||
result.message.size() + 64;
|
||||
|
||||
if (tr->assertions.size() < kMaxRetainedAssertionsPerTest &&
|
||||
tr->diagnostic_bytes + entry_bytes <= kMaxDiagnosticBytesPerTest) {
|
||||
tr->diagnostic_bytes += entry_bytes;
|
||||
tr->assertions.push_back(std::move(result));
|
||||
} else {
|
||||
tr->assertions_truncated = true;
|
||||
tr->dropped_assertions += 1;
|
||||
}
|
||||
|
||||
if (!passed && (kind == AssertKind::Require || kind == AssertKind::Assert)) {
|
||||
ctx.should_abort = true;
|
||||
throw RequireFailure{abort_msg};
|
||||
}
|
||||
}
|
||||
} // namespace Void::Testing::Detail
|
||||
} // namespace Void::Testing::Detail
|
||||
+271
-42
@@ -37,50 +37,146 @@
|
||||
#endif
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <csignal>
|
||||
#include <cstdlib>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <random>
|
||||
#include <regex>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace Void::Testing
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
class OwningJUnitReporter final : public Reporter
|
||||
{
|
||||
public:
|
||||
OwningJUnitReporter(std::unique_ptr<std::ofstream> stream,
|
||||
std::string* write_err_out)
|
||||
: stream_(std::move(stream))
|
||||
, inner_(*stream_)
|
||||
, write_err_out_(write_err_out)
|
||||
{
|
||||
}
|
||||
|
||||
void on_run_start(const RunConfig& c, int n) override { inner_.on_run_start(c, n); }
|
||||
void on_suite_start(const std::string& s, int n) override { inner_.on_suite_start(s, n); }
|
||||
void on_test_start(const TestCase& t) override { inner_.on_test_start(t); }
|
||||
void on_test_end(const TestResult& r) override { inner_.on_test_end(r); }
|
||||
void on_suite_end(const SuiteResult& s) override { inner_.on_suite_end(s); }
|
||||
void on_run_end(const RunResult& r) override
|
||||
{
|
||||
inner_.on_run_end(r);
|
||||
if (stream_) {
|
||||
stream_->flush();
|
||||
if (!stream_->good() && write_err_out_ != nullptr &&
|
||||
write_err_out_->empty()) {
|
||||
*write_err_out_ = "Failed while writing JUnit report";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
std::unique_ptr<std::ofstream> stream_;
|
||||
JUnitReporter inner_;
|
||||
std::string* write_err_out_{nullptr};
|
||||
};
|
||||
|
||||
struct ContextRestorer {
|
||||
Detail::TestContext saved;
|
||||
ContextRestorer() : saved(Detail::TestContext::current()) {}
|
||||
~ContextRestorer() { Detail::TestContext::current() = saved; }
|
||||
ContextRestorer(const ContextRestorer&) = delete;
|
||||
ContextRestorer& operator=(const ContextRestorer&) = delete;
|
||||
};
|
||||
|
||||
[[nodiscard]] bool parse_unsigned_strict(const std::string& text,
|
||||
unsigned& out) noexcept
|
||||
{
|
||||
if (text.empty() || text[0] == '-') {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
std::size_t pos = 0;
|
||||
const unsigned long val = std::stoul(text, &pos, 10);
|
||||
if (pos != text.size() || val > std::numeric_limits<unsigned>::max()) {
|
||||
return false;
|
||||
}
|
||||
out = static_cast<unsigned>(val);
|
||||
return true;
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
RunConfig Runner::parse_args(int argc, char** argv)
|
||||
{
|
||||
RunConfig config;
|
||||
auto need_val = [&](const std::string& flag, int& i, std::string& out) -> bool {
|
||||
if (i + 1 >= argc) {
|
||||
if (config.parse_error.empty()) {
|
||||
config.parse_error = std::format("Missing value for option {}", flag);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
out = argv[++i];
|
||||
return true;
|
||||
};
|
||||
|
||||
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" ||
|
||||
arg == "--log-file" || arg == "--parallel") &&
|
||||
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 == "--log-file") {
|
||||
config.log_file = 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 == "--parallel") {
|
||||
config.parallel_threads =
|
||||
static_cast<unsigned>(std::stoul(val));
|
||||
if (arg == "--filter") {
|
||||
(void)need_val(arg, i, config.filter_pattern);
|
||||
} else if (arg == "--suite") {
|
||||
(void)need_val(arg, i, config.suite_filter);
|
||||
} else if (arg == "--reporter") {
|
||||
(void)need_val(arg, i, config.reporter);
|
||||
} else if (arg == "--output") {
|
||||
(void)need_val(arg, i, config.output_file);
|
||||
} else if (arg == "--tag") {
|
||||
(void)need_val(arg, i, config.tag_filter);
|
||||
} else if (arg == "--log-file") {
|
||||
(void)need_val(arg, i, config.log_file);
|
||||
} else if (arg == "--selftest-child") {
|
||||
(void)need_val(arg, i, config.selftest_child);
|
||||
} else if (arg == "--seed") {
|
||||
std::string val;
|
||||
if (need_val(arg, i, val)) {
|
||||
unsigned parsed = 0;
|
||||
if (!parse_unsigned_strict(val, parsed)) {
|
||||
config.parse_error = std::format("Invalid --seed value: {}", val);
|
||||
} else {
|
||||
config.shuffle = true;
|
||||
config.random_seed = parsed;
|
||||
}
|
||||
}
|
||||
} else if (arg == "--repeat") {
|
||||
std::string val;
|
||||
if (need_val(arg, i, val)) {
|
||||
unsigned parsed = 0;
|
||||
if (!parse_unsigned_strict(val, parsed)) {
|
||||
config.parse_error = std::format("Invalid --repeat value: {}", val);
|
||||
} else {
|
||||
config.repeat = parsed;
|
||||
}
|
||||
}
|
||||
} else if (arg == "--parallel") {
|
||||
std::string val;
|
||||
if (need_val(arg, i, val)) {
|
||||
unsigned parsed = 0;
|
||||
if (!parse_unsigned_strict(val, parsed)) {
|
||||
config.parse_error = std::format("Invalid --parallel value: {}", val);
|
||||
} else {
|
||||
config.parallel_threads = parsed;
|
||||
}
|
||||
}
|
||||
} else if (arg == "--help") {
|
||||
config.show_help = true;
|
||||
@@ -90,10 +186,16 @@ namespace Void::Testing
|
||||
config.verbose = true;
|
||||
} else if (arg == "--no-color") {
|
||||
config.no_color = true;
|
||||
} else if (arg == "--allow-empty") {
|
||||
config.allow_empty = true;
|
||||
} else if (arg == "--shuffle") {
|
||||
config.shuffle = true;
|
||||
std::random_device rd;
|
||||
config.random_seed = rd();
|
||||
} else if (!arg.empty() && arg[0] == '-') {
|
||||
if (config.parse_error.empty()) {
|
||||
config.parse_error = std::format("Unknown option: {}", arg);
|
||||
}
|
||||
}
|
||||
}
|
||||
return config;
|
||||
@@ -142,14 +244,19 @@ namespace Void::Testing
|
||||
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);
|
||||
const std::string path =
|
||||
config.output_file.empty() ? "test_results.xml" : config.output_file;
|
||||
auto file = std::make_unique<std::ofstream>(path, std::ios::out | std::ios::trunc);
|
||||
return std::make_unique<OwningJUnitReporter>(std::move(file), nullptr);
|
||||
}
|
||||
return std::make_unique<ConsoleReporter>(std::cout, !config.no_color);
|
||||
}
|
||||
|
||||
TestResult Runner::execute_case(TestCase& test_case)
|
||||
{
|
||||
return execute_test(test_case);
|
||||
}
|
||||
|
||||
TestResult Runner::execute_test(TestCase& test_case)
|
||||
{
|
||||
TestResult result;
|
||||
@@ -163,6 +270,7 @@ namespace Void::Testing
|
||||
: test_case.skip_reason;
|
||||
return result;
|
||||
}
|
||||
ContextRestorer ctx_restorer;
|
||||
Detail::TestContext::current().current_result = &result;
|
||||
Detail::TestContext::current().should_abort = false;
|
||||
|
||||
@@ -214,7 +322,6 @@ namespace Void::Testing
|
||||
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) {
|
||||
@@ -223,7 +330,7 @@ namespace Void::Testing
|
||||
[](const auto& a) { return !a.passed; });
|
||||
// An exception that escaped the body fails it too, with no failed
|
||||
// assertion recorded.
|
||||
const bool unhandled = !result.crash_info.empty();
|
||||
const bool unhandled = !result.crash_info.empty() || !result.cleanup_error.empty();
|
||||
result.state =
|
||||
any || unhandled ? TestState::Failed : TestState::Passed;
|
||||
}
|
||||
@@ -245,6 +352,7 @@ namespace Void::Testing
|
||||
: test_case.skip_reason;
|
||||
return result;
|
||||
}
|
||||
ContextRestorer ctx_restorer;
|
||||
Detail::TestContext::current().current_result = &result;
|
||||
Detail::TestContext::current().should_abort = false;
|
||||
|
||||
@@ -265,7 +373,6 @@ namespace Void::Testing
|
||||
}
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
result.duration = end - start;
|
||||
Detail::TestContext::current().current_result = nullptr;
|
||||
|
||||
if (result.state != TestState::Skipped &&
|
||||
result.state != TestState::Crashed) {
|
||||
@@ -274,29 +381,58 @@ namespace Void::Testing
|
||||
[](const auto& a) { return !a.passed; });
|
||||
// An exception that escaped the body fails it too, with no failed
|
||||
// assertion recorded.
|
||||
const bool unhandled = !result.crash_info.empty();
|
||||
const bool unhandled = !result.crash_info.empty() || !result.cleanup_error.empty();
|
||||
result.state =
|
||||
any || unhandled ? TestState::Failed : TestState::Passed;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void Runner::run_test_body(TestCase& test_case, TestResult&)
|
||||
void Runner::run_test_body(TestCase& test_case, TestResult& result)
|
||||
{
|
||||
if (test_case.fixture_create) {
|
||||
void* fixture = test_case.fixture_create();
|
||||
Detail::TestContext::current().fixture = fixture;
|
||||
bool teardown_attempted = false;
|
||||
auto run_teardown_once = [&]() {
|
||||
if (teardown_attempted) {
|
||||
return;
|
||||
}
|
||||
teardown_attempted = true;
|
||||
try {
|
||||
if (test_case.fixture_teardown) {
|
||||
test_case.fixture_teardown(fixture);
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
result.cleanup_error =
|
||||
std::format("Fixture teardown error: {}", e.what());
|
||||
if (result.state == TestState::Passed) {
|
||||
result.state = TestState::Failed;
|
||||
}
|
||||
} catch (...) {
|
||||
result.cleanup_error = "Fixture teardown unknown exception";
|
||||
if (result.state == TestState::Passed) {
|
||||
result.state = TestState::Failed;
|
||||
}
|
||||
}
|
||||
};
|
||||
try {
|
||||
test_case.fixture_setup(fixture);
|
||||
if (test_case.fixture_setup) {
|
||||
test_case.fixture_setup(fixture);
|
||||
}
|
||||
test_case.run();
|
||||
test_case.fixture_teardown(fixture);
|
||||
run_teardown_once();
|
||||
} catch (...) {
|
||||
test_case.fixture_teardown(fixture);
|
||||
test_case.fixture_destroy(fixture);
|
||||
run_teardown_once();
|
||||
if (test_case.fixture_destroy) {
|
||||
test_case.fixture_destroy(fixture);
|
||||
}
|
||||
Detail::TestContext::current().fixture = nullptr;
|
||||
throw;
|
||||
}
|
||||
test_case.fixture_destroy(fixture);
|
||||
if (test_case.fixture_destroy) {
|
||||
test_case.fixture_destroy(fixture);
|
||||
}
|
||||
Detail::TestContext::current().fixture = nullptr;
|
||||
} else {
|
||||
test_case.run();
|
||||
@@ -401,6 +537,8 @@ namespace Void::Testing
|
||||
<< apply(dim, "Enable verbose output") << "\n"
|
||||
<< " " << opt("--no-color")
|
||||
<< apply(dim, "Disable colored console output") << "\n"
|
||||
<< " " << opt("--allow-empty")
|
||||
<< apply(dim, "Do not fail when selection matches zero tests") << "\n"
|
||||
<< " " << opt("--help")
|
||||
<< apply(dim, "Show this help message") << "\n"
|
||||
<< "\n"
|
||||
@@ -417,9 +555,72 @@ namespace Void::Testing
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
if (!config.parse_error.empty()) {
|
||||
RunResult err_res;
|
||||
err_res.config_error = config.parse_error;
|
||||
std::cerr << "error: " << err_res.config_error << "\n";
|
||||
return err_res;
|
||||
}
|
||||
if (config.reporter != "console" && config.reporter != "junit") {
|
||||
RunResult err_res;
|
||||
err_res.config_error =
|
||||
std::format("Unknown reporter: {}", config.reporter);
|
||||
std::cerr << "error: " << err_res.config_error << "\n";
|
||||
return err_res;
|
||||
}
|
||||
if (config.repeat == 0) {
|
||||
RunResult err_res;
|
||||
err_res.config_error = "--repeat must be >= 1";
|
||||
std::cerr << "error: " << err_res.config_error << "\n";
|
||||
return err_res;
|
||||
}
|
||||
if (!config.filter_pattern.empty()) {
|
||||
try {
|
||||
(void)std::regex{config.filter_pattern};
|
||||
} catch (const std::regex_error& e) {
|
||||
RunResult err_res;
|
||||
err_res.config_error = std::format(
|
||||
"Invalid --filter regex '{}': {}", config.filter_pattern, e.what());
|
||||
std::cerr << "error: " << err_res.config_error << "\n";
|
||||
return err_res;
|
||||
}
|
||||
}
|
||||
|
||||
auto all_tests = Detail::Registry::instance().tests();
|
||||
auto tests = filter_tests(all_tests, config);
|
||||
auto reporter = create_reporter(config);
|
||||
const bool has_explicit_selection =
|
||||
!config.filter_pattern.empty() ||
|
||||
!config.suite_filter.empty() ||
|
||||
!config.tag_filter.empty();
|
||||
if (!config.list_only && has_explicit_selection &&
|
||||
tests.empty() && !config.allow_empty) {
|
||||
RunResult err_res;
|
||||
err_res.config_error =
|
||||
"Test selection matched 0 tests (pass --allow-empty to permit empty selection)";
|
||||
std::cerr << "error: " << err_res.config_error << "\n";
|
||||
return err_res;
|
||||
}
|
||||
|
||||
std::string report_write_error;
|
||||
std::unique_ptr<Reporter> reporter;
|
||||
if (config.reporter == "junit") {
|
||||
const std::string path =
|
||||
config.output_file.empty() ? "test_results.xml" : config.output_file;
|
||||
auto file = std::make_unique<std::ofstream>(
|
||||
path, std::ios::out | std::ios::trunc);
|
||||
if (!file->is_open()) {
|
||||
RunResult err_res;
|
||||
err_res.config_error =
|
||||
std::format("Failed to open JUnit output file: {}", path);
|
||||
std::cerr << "error: " << err_res.config_error << "\n";
|
||||
return err_res;
|
||||
}
|
||||
reporter = std::make_unique<OwningJUnitReporter>(
|
||||
std::move(file), &report_write_error);
|
||||
} else {
|
||||
reporter = create_reporter(config);
|
||||
}
|
||||
|
||||
// ── Optional: file logger sink (requires Void::Logging) ──────────────────
|
||||
#ifdef VOID_HAS_LOG
|
||||
@@ -661,6 +862,11 @@ namespace Void::Testing
|
||||
}
|
||||
run_result.total_duration = end_time - start_time;
|
||||
reporter->on_run_end(run_result);
|
||||
reporter.reset();
|
||||
if (!report_write_error.empty()) {
|
||||
run_result.config_error = std::move(report_write_error);
|
||||
std::cerr << "error: " << run_result.config_error << "\n";
|
||||
}
|
||||
#ifdef VOID_HAS_LOG
|
||||
if (log_sink) {
|
||||
log_sink->info(
|
||||
@@ -680,7 +886,30 @@ namespace Void::Testing
|
||||
int Runner::main(int argc, char** argv)
|
||||
{
|
||||
auto config = parse_args(argc, argv);
|
||||
if (!config.selftest_child.empty()) {
|
||||
if (config.selftest_child == "abort") {
|
||||
std::signal(SIGSEGV, SIG_DFL);
|
||||
std::signal(SIGABRT, SIG_DFL);
|
||||
std::abort();
|
||||
}
|
||||
if (config.selftest_child == "hang") {
|
||||
std::this_thread::sleep_for(std::chrono::seconds{5});
|
||||
return 0;
|
||||
}
|
||||
if (config.selftest_child == "flood") {
|
||||
const std::string out_chunk(131072, 'O');
|
||||
const std::string err_chunk(131072, 'E');
|
||||
std::cout << out_chunk << std::flush;
|
||||
std::cerr << err_chunk << std::flush;
|
||||
return 0;
|
||||
}
|
||||
std::cerr << "Unknown --selftest-child mode: " << config.selftest_child << "\n";
|
||||
return 2;
|
||||
}
|
||||
auto result = run(config);
|
||||
if (!result.config_error.empty()) {
|
||||
return 2;
|
||||
}
|
||||
return (result.failed + result.crashed > 0) ? 1 : 0;
|
||||
}
|
||||
} // namespace Void::Testing
|
||||
@@ -0,0 +1,307 @@
|
||||
#include <Void/Testing/Subprocess.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
#include <csignal>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <system_error>
|
||||
#include <vector>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <fcntl.h>
|
||||
#include <poll.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace Void::Testing
|
||||
{
|
||||
|
||||
std::string current_executable_path()
|
||||
{
|
||||
#ifdef __linux__
|
||||
std::error_code ec;
|
||||
const auto p = std::filesystem::read_symlink("/proc/self/exe", ec);
|
||||
if (!ec) {
|
||||
return p.string();
|
||||
}
|
||||
#endif
|
||||
return {};
|
||||
}
|
||||
|
||||
#ifndef _WIN32
|
||||
namespace
|
||||
{
|
||||
|
||||
void close_fd_safe(int& fd) noexcept
|
||||
{
|
||||
if (fd >= 0) {
|
||||
::close(fd);
|
||||
fd = -1;
|
||||
}
|
||||
}
|
||||
|
||||
bool create_cloexec_pipe(int fds[2]) noexcept
|
||||
{
|
||||
#ifdef __linux__
|
||||
if (::pipe2(fds, O_CLOEXEC) == 0) {
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
if (::pipe(fds) != 0) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
const int fl = ::fcntl(fds[i], F_GETFD, 0);
|
||||
if (fl >= 0) {
|
||||
(void)::fcntl(fds[i], F_SETFD, fl | FD_CLOEXEC);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void drain_fd_chunk(int& fd,
|
||||
std::string& dst,
|
||||
bool& truncated,
|
||||
std::size_t limit) noexcept
|
||||
{
|
||||
std::array<char, 4096> buf{};
|
||||
for (;;) {
|
||||
const ssize_t n = ::read(fd, buf.data(), buf.size());
|
||||
if (n > 0) {
|
||||
const std::size_t got = static_cast<std::size_t>(n);
|
||||
if (dst.size() < limit) {
|
||||
const std::size_t take = std::min(got, limit - dst.size());
|
||||
dst.append(buf.data(), take);
|
||||
if (take < got) {
|
||||
truncated = true;
|
||||
}
|
||||
} else {
|
||||
truncated = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (n == 0) {
|
||||
close_fd_safe(fd);
|
||||
return;
|
||||
}
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
if (errno == EAGAIN || errno == EWOULDBLOCK) {
|
||||
return;
|
||||
}
|
||||
close_fd_safe(fd);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
ProcessTestResult run_isolated_subprocess(
|
||||
std::string_view executable,
|
||||
std::span<const std::string> args,
|
||||
ProcessTestOptions options)
|
||||
{
|
||||
ProcessTestResult res;
|
||||
if (executable.empty()) {
|
||||
res.diagnostic = "Subprocess executable path is empty";
|
||||
return res;
|
||||
}
|
||||
|
||||
int out_pipe[2]{-1, -1};
|
||||
int err_pipe[2]{-1, -1};
|
||||
if (!create_cloexec_pipe(out_pipe) || !create_cloexec_pipe(err_pipe)) {
|
||||
res.diagnostic = std::string{"pipe failed: "} + std::strerror(errno);
|
||||
close_fd_safe(out_pipe[0]);
|
||||
close_fd_safe(out_pipe[1]);
|
||||
close_fd_safe(err_pipe[0]);
|
||||
close_fd_safe(err_pipe[1]);
|
||||
return res;
|
||||
}
|
||||
|
||||
// Build execv arguments before fork so child stays async-signal-safe.
|
||||
std::string exe_str{executable};
|
||||
std::vector<std::string> arg_storage;
|
||||
arg_storage.reserve(args.size() + 1);
|
||||
arg_storage.push_back(exe_str);
|
||||
for (const auto& a : args) {
|
||||
arg_storage.push_back(a);
|
||||
}
|
||||
std::vector<char*> argv_ptrs;
|
||||
argv_ptrs.reserve(arg_storage.size() + 1);
|
||||
for (auto& s : arg_storage) {
|
||||
argv_ptrs.push_back(s.data());
|
||||
}
|
||||
argv_ptrs.push_back(nullptr);
|
||||
|
||||
const pid_t pid = ::fork();
|
||||
if (pid < 0) {
|
||||
res.diagnostic = std::string{"fork failed: "} + std::strerror(errno);
|
||||
close_fd_safe(out_pipe[0]);
|
||||
close_fd_safe(out_pipe[1]);
|
||||
close_fd_safe(err_pipe[0]);
|
||||
close_fd_safe(err_pipe[1]);
|
||||
return res;
|
||||
}
|
||||
|
||||
if (pid == 0) {
|
||||
close_fd_safe(out_pipe[0]);
|
||||
close_fd_safe(err_pipe[0]);
|
||||
(void)::dup2(out_pipe[1], STDOUT_FILENO);
|
||||
(void)::dup2(err_pipe[1], STDERR_FILENO);
|
||||
close_fd_safe(out_pipe[1]);
|
||||
close_fd_safe(err_pipe[1]);
|
||||
::execv(exe_str.c_str(), argv_ptrs.data());
|
||||
::_exit(127);
|
||||
}
|
||||
|
||||
close_fd_safe(out_pipe[1]);
|
||||
close_fd_safe(err_pipe[1]);
|
||||
|
||||
for (int fd : {out_pipe[0], err_pipe[0]}) {
|
||||
const int fl = ::fcntl(fd, F_GETFL, 0);
|
||||
if (fl >= 0) {
|
||||
(void)::fcntl(fd, F_SETFL, fl | O_NONBLOCK);
|
||||
}
|
||||
}
|
||||
|
||||
const auto start = std::chrono::steady_clock::now();
|
||||
const auto deadline = start + std::max(options.timeout, std::chrono::milliseconds{1});
|
||||
bool timed_out = false;
|
||||
bool child_reaped = false;
|
||||
int wait_status = 0;
|
||||
|
||||
while (out_pipe[0] >= 0 || err_pipe[0] >= 0 || !child_reaped) {
|
||||
if (!child_reaped) {
|
||||
const pid_t wr = ::waitpid(pid, &wait_status, WNOHANG);
|
||||
if (wr == pid) {
|
||||
child_reaped = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (out_pipe[0] < 0 && err_pipe[0] < 0) {
|
||||
if (child_reaped) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (now >= deadline && !timed_out) {
|
||||
timed_out = true;
|
||||
(void)::kill(pid, SIGKILL);
|
||||
}
|
||||
|
||||
if (out_pipe[0] >= 0 || err_pipe[0] >= 0) {
|
||||
std::array<pollfd, 2> pfds{};
|
||||
nfds_t nfds = 0;
|
||||
if (out_pipe[0] >= 0) {
|
||||
pfds[nfds++] = pollfd{out_pipe[0], POLLIN | POLLHUP | POLLERR, 0};
|
||||
}
|
||||
if (err_pipe[0] >= 0) {
|
||||
pfds[nfds++] = pollfd{err_pipe[0], POLLIN | POLLHUP | POLLERR, 0};
|
||||
}
|
||||
int wait_ms = 5;
|
||||
if (!timed_out) {
|
||||
const auto rem_ms =
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now).count();
|
||||
wait_ms = static_cast<int>(std::clamp<long long>(rem_ms, 1, 20));
|
||||
}
|
||||
const int pr = ::poll(pfds.data(), nfds, wait_ms);
|
||||
if (pr < 0 && errno != EINTR) {
|
||||
break;
|
||||
}
|
||||
if (out_pipe[0] >= 0) {
|
||||
drain_fd_chunk(out_pipe[0], res.stdout_captured, res.stdout_truncated, options.max_output_bytes);
|
||||
}
|
||||
if (err_pipe[0] >= 0) {
|
||||
drain_fd_chunk(err_pipe[0], res.stderr_captured, res.stderr_truncated, options.max_output_bytes);
|
||||
}
|
||||
if (timed_out) {
|
||||
// Reap killed child and finish draining pipes cleanly.
|
||||
if (!child_reaped) {
|
||||
for (;;) {
|
||||
const pid_t wr = ::waitpid(pid, &wait_status, 0);
|
||||
if (wr == pid) {
|
||||
child_reaped = true;
|
||||
break;
|
||||
}
|
||||
if (wr < 0 && errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (out_pipe[0] >= 0) {
|
||||
drain_fd_chunk(out_pipe[0], res.stdout_captured, res.stdout_truncated, options.max_output_bytes);
|
||||
}
|
||||
if (err_pipe[0] >= 0) {
|
||||
drain_fd_chunk(err_pipe[0], res.stderr_captured, res.stderr_truncated, options.max_output_bytes);
|
||||
}
|
||||
break;
|
||||
}
|
||||
} else if (!child_reaped) {
|
||||
::poll(nullptr, 0, 2);
|
||||
}
|
||||
}
|
||||
|
||||
close_fd_safe(out_pipe[0]);
|
||||
close_fd_safe(err_pipe[0]);
|
||||
|
||||
if (!child_reaped) {
|
||||
for (;;) {
|
||||
const pid_t wr = ::waitpid(pid, &wait_status, 0);
|
||||
if (wr == pid) {
|
||||
child_reaped = true;
|
||||
break;
|
||||
}
|
||||
if (wr < 0 && errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (timed_out) {
|
||||
res.outcome = ProcessOutcome::timed_out;
|
||||
res.diagnostic = "Subprocess exceeded timeout";
|
||||
return res;
|
||||
}
|
||||
if (!child_reaped) {
|
||||
res.outcome = ProcessOutcome::infrastructure_error;
|
||||
res.diagnostic = "Failed to waitpid on subprocess";
|
||||
return res;
|
||||
}
|
||||
if (WIFSIGNALED(wait_status)) {
|
||||
res.outcome = ProcessOutcome::crashed;
|
||||
res.term_signal = WTERMSIG(wait_status);
|
||||
return res;
|
||||
}
|
||||
if (WIFEXITED(wait_status)) {
|
||||
res.exit_code = WEXITSTATUS(wait_status);
|
||||
res.outcome = (res.exit_code == 0) ? ProcessOutcome::passed : ProcessOutcome::failed;
|
||||
return res;
|
||||
}
|
||||
|
||||
res.outcome = ProcessOutcome::infrastructure_error;
|
||||
res.diagnostic = "Subprocess exited in unexpected state";
|
||||
return res;
|
||||
}
|
||||
#else
|
||||
ProcessTestResult run_isolated_subprocess(
|
||||
std::string_view,
|
||||
std::span<const std::string>,
|
||||
ProcessTestOptions)
|
||||
{
|
||||
ProcessTestResult res;
|
||||
res.outcome = ProcessOutcome::infrastructure_error;
|
||||
res.diagnostic = "Subprocess isolation not implemented on Windows";
|
||||
return res;
|
||||
}
|
||||
#endif
|
||||
|
||||
} // namespace Void::Testing
|
||||
Reference in new issue
Block a user