diff --git a/CMakeLists.txt b/CMakeLists.txt index b9f893c..3b0d79c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -70,6 +70,8 @@ add_library(VoidBuild_Core STATIC src/Package/Resolver.cpp src/Package/Manifest.cpp src/Package/Audit.cpp + src/Test/Doctest.cpp + src/Test/Fuzz.cpp src/Sandbox/Linux/NamespaceSandbox.cpp src/Provider/PkgConfig.cpp src/Provider/Provider.cpp diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 19d6681..6fbb75d 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -401,6 +401,8 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B ## Remaining future scope +- **Wave 152 (Test depth and fuzzing, G8)**: `vbs doctest` extracts fenced C++ blocks from `///`, `//!` and Doxygen comment blocks, compiles each as the body of `main()` with `#line` mapping (so errors point at the header), links optional `--source` files and reports block pass/fail. The test runner gained `--shard I/N` (fixture-aware clustering, greedy balancing by the previous run's recorded timings in `/.vbs/test_timings.json`), `--rerun-failed` (reads `/.vbs/last_failed_tests.json` and re-runs only the failed closure), `--known-flaky FILE` (flaky failures are reported but do not fail the run) and coverage gates `--coverage-min PCT` / `--coverage-diff BASE` (lcov summary comparison). `vbs fuzz` builds a libFuzzer target with clang (`-fsanitize=fuzzer,address,undefined`), runs it over a corpus and reports crash artifacts. Verified by `doctest_extracts_compiles_and_runs_blocks`, `test_sharding_partitions_tests_and_records_timings`, `test_rerun_failed_and_known_flaky`, `coverage_gates_enforce_minimum_and_baseline` and `fuzz_builds_targets_and_reports_crashes`. + - **Wave 151 (Profiles and toolchain pinning, G3)**: `Dependency::profile(name, DependencyProfileOptions)` stores per-profile compile/link options, defines, LTO and sanitizers; the native provider applies the matching override to the dependency's own `ProfileContext` and includes the overrides in the provider input hash, so changing them invalidates cached dependency builds. `vbs-toolchain.toml` pins compiler, minimum version, C/C++ standards and sysroot (with a `strict` field); it is loaded once per build and checked after every toolchain probe, warning on drift or failing with `--locked-toolchain` (or `strict = true`). `vbs profile list|show|diff` lists declared profiles with parents, prints one resolved profile, or reports the fields that differ between two. Verified by `FullV1Tests.dependency_profile_overrides_apply_to_native_builds`, `toolchain_pin_detects_and_enforces_drift` and `profile_commands_list_show_and_diff`. - **Wave 150 (Real feature flags, G2)**: `Project::feature(name, default_on)` (or `FeatureDescription`), `Target::require_feature(name)` (renamed because `requires` is a C++20 keyword), and `Dependency::when(feature)` for optional dependencies. `--features a,b` / `--no-default-features` on build/test/run/explain/deps (or `VBS_FEATURE`-style CLI only) perform additive unification: defaults (unless disabled) + features required by targets + requested features; enabled features add `VBS_FEATURE_` compile definitions to every target (so action keys and the cache are feature-aware) and the descriptor JSON/`vbs metadata` expose declared features with their enabled state. Optional dependencies are filtered before resolution, so the lock contains only active ones; `vbs explain --show-features` prints the unified set with reasons (default/requested/required by target). Verified by `FullV1Tests.features_unify_defines_and_invalidate_action_keys` and `FullV1Tests.optional_dependencies_follow_feature_selection`. diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index ccbfa45..b09d656 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -151,4 +151,5 @@ Base HEAD: `fe0d1a6` | Wave 149 (Trust layer) | `vbs attest create\|verify` (DSSE + in-toto Statement v1 + SLSA provenance v1, Ed25519 over the PAE, trusted-key and subject-digest enforcement), `vbs audit --advisories OSV.json` (introduced/fixed/last_affected/limit ranges, severity threshold, JSON), signing availability in `vbs doctor` | COMPLETE & VERIFIED (GCC 16.2; `attest_create_and_verify_detects_tampering` and `audit_matches_osv_advisories_against_lock` pass; CLI contracts pass) | `include/Void/Build/Provenance/Attestation.hpp`, `src/Provenance/Attestation.cpp`, `include/Void/Build/Package/Audit.hpp`, `src/Package/Audit.cpp`, `src/Main.cpp`, `tests/{FullV1Tests,CliContracts}`, docs | | Wave 150 (Feature flags) | `Project::feature`, `Target::require_feature`, `Dependency::when`, additive unification, `--features`/`--no-default-features`, `VBS_FEATURE_*` defines, feature-aware action keys, optional dependency filtering, `explain --show-features`, metadata feature list | COMPLETE & VERIFIED (GCC 16.2; `features_unify_defines_and_invalidate_action_keys` and `optional_dependencies_follow_feature_selection` pass; CLI contracts pass) | `include/Void/Build.hpp`, `sdk/Build.cpp`, `include/Void/Build/Graph/Graph.hpp`, `src/Graph/Graph.cpp`, `src/Main.cpp`, `tests/{FullV1Tests,CliContracts}`, docs | | Wave 151 (Profiles + toolchain pinning) | `Dependency::profile` overrides for native dependency builds (hash-aware), `vbs-toolchain.toml` pin + drift detection (`--locked-toolchain`, `strict`), `vbs profile list\|show\|diff` | COMPLETE & VERIFIED (GCC 16.2; the three G3 tests pass; CLI contracts pass) | `include/Void/Build.hpp`, `sdk/Build.cpp`, `src/Graph/Graph.cpp`, `src/Provider/Provider.cpp`, `include/Void/Build/Toolchain/Pin.hpp`, `src/Toolchain/Pin.cpp`, `src/Main.cpp`, `tests/{FullV1Tests,CliContracts}`, docs | +| Wave 152 (Test depth + fuzzing) | `vbs doctest` (fenced blocks, `#line` diagnostics, `--source`), `--shard I/N` + timings, `--rerun-failed`, `--known-flaky`, `--coverage-min`/`--coverage-diff`, `vbs fuzz` (libFuzzer) | COMPLETE & VERIFIED (GCC 16.2; doctest/sharding/rerun/coverage tests pass; fuzz test passes under clang 23; CLI contracts pass) | `include/Void/Build/Test/Doctest.hpp`, `src/Test/Doctest.cpp`, `include/Void/Build/Test/Fuzz.hpp`, `src/Test/Fuzz.cpp`, `include/Void/Build/Report/Coverage.hpp`, `src/Report/Coverage.cpp`, `src/Main.cpp`, `tests/{FullV1Tests,CliContracts}`, docs | | Future (Plans 23–24) | Gap closure and superiority tracks | PLANNED (see the plans for per-track acceptance gates) | [23-remaining-upgrade-plan.md](../roadmap/23-remaining-upgrade-plan.md), [24-superiority-tracks.md](../roadmap/24-superiority-tracks.md) | diff --git a/docs/roadmap/24-superiority-tracks.md b/docs/roadmap/24-superiority-tracks.md index 58b134c..2a24e62 100644 --- a/docs/roadmap/24-superiority-tracks.md +++ b/docs/roadmap/24-superiority-tracks.md @@ -391,6 +391,12 @@ registry and lists the same action count; `cache stats` matches the report count ### G8 — Test and benchmark depth *(M)* +**Status: partially implemented (Wave 152).** Done: doctests (`vbs doctest`), sharding with +duration-aware partitioning (`vbs test --shard I/N`), `--rerun-failed`, `--known-flaky`, +coverage gates (`--coverage-min`, `--coverage-diff`) and `vbs fuzz` over libFuzzer targets. +Pending: benchmark regression gates (G1 `bench`), AFL support, coverage diff at line level +(currently summary-level), and benchmark result storage. + **Beats:** CTest (no doctests, no impact analysis), Cargo (no sharding in stable, no coverage gates), everyone (no benchmark regression gate built in). diff --git a/include/Void/Build/Report/Coverage.hpp b/include/Void/Build/Report/Coverage.hpp index d859096..e0a601e 100644 --- a/include/Void/Build/Report/Coverage.hpp +++ b/include/Void/Build/Report/Coverage.hpp @@ -29,4 +29,10 @@ write_coverage_report(const std::vector &gcda_files, const std::filesystem::path &source_root = {}, const std::string &gcov_executable = "gcov"); +// Reads the LF/LH totals from an lcov file (used for coverage gates and diffs). +[[nodiscard]] Void::Result::Result +read_lcov_summary(const std::filesystem::path &lcov_file); + +[[nodiscard]] double coverage_percent(const CoverageSummary &summary) noexcept; + } // namespace Void::Build::Report diff --git a/include/Void/Build/Test/Doctest.hpp b/include/Void/Build/Test/Doctest.hpp new file mode 100644 index 0000000..d7c168c --- /dev/null +++ b/include/Void/Build/Test/Doctest.hpp @@ -0,0 +1,49 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::Build::Test { + +// One fenced code block extracted from a header's documentation comments +// (``/// ```cpp`` ... ``/// ``` ``, `//!`, or Doxygen `*` lines). +struct DoctestBlock { + std::filesystem::path file; + std::size_t line{0}; + std::string code; + std::string language; +}; + +[[nodiscard]] Void::Result::Result, Void::Result::Error> +extract_doctest_blocks(const std::filesystem::path &header); + +struct DoctestOptions { + std::filesystem::path project_root; + std::filesystem::path build_dir; + std::vector headers; + std::vector include_dirs; + std::vector extra_sources; // linked into every doctest + std::filesystem::path compiler; // empty = resolve g++/clang++ + std::string cxx_standard{"c++26"}; + std::chrono::milliseconds timeout{std::chrono::seconds{120}}; +}; + +struct DoctestResult { + std::size_t blocks{0}; + std::size_t passed{0}; + std::size_t failed{0}; + std::vector diagnostics; +}; + +// Compiles and runs each block as the body of `main()` in a generated translation unit that +// includes the header (`#line` maps compiler errors back to the header). +[[nodiscard]] Void::Result::Result +run_doctests(const DoctestOptions &options); + +} // namespace Void::Build::Test diff --git a/include/Void/Build/Test/Fuzz.hpp b/include/Void/Build/Test/Fuzz.hpp new file mode 100644 index 0000000..406eb23 --- /dev/null +++ b/include/Void/Build/Test/Fuzz.hpp @@ -0,0 +1,38 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +namespace Void::Build::Test { + +struct FuzzOptions { + std::filesystem::path project_root; + std::filesystem::path build_dir; + std::vector sources; + std::vector include_dirs; + std::filesystem::path compiler; // empty = clang++ + std::string name{"fuzz"}; + std::size_t runs{10000}; + std::filesystem::path corpus; // default: /fuzz/corpus + std::chrono::milliseconds timeout{std::chrono::minutes{10}}; +}; + +struct FuzzResult { + std::filesystem::path binary; + int exit_code{-1}; + std::string output; + std::vector artifacts; +}; + +// Compiles a libFuzzer target (`-fsanitize=fuzzer,address,undefined`) and runs it over the +// corpus for `runs` iterations. A non-zero fuzzer exit (crash, sanitizer finding) is reported in +// the result; setup failures are errors. +[[nodiscard]] Void::Result::Result +run_fuzz(const FuzzOptions &options); + +} // namespace Void::Build::Test diff --git a/src/Main.cpp b/src/Main.cpp index 36a5139..2c68b40 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -38,6 +38,8 @@ #include #include #include +#include +#include #include #include #include @@ -465,6 +467,11 @@ struct BuildCmdOptions { bool no_default_features{false}; bool show_features{false}; bool locked_toolchain{false}; + std::optional shard_arg; + std::vector known_flaky_files; + bool rerun_failed{false}; + std::optional coverage_min_arg; + std::optional coverage_diff_arg; bool publish_editor_selection{true}; bool no_cache{false}; bool locked{false}; @@ -552,6 +559,106 @@ void filter_optional_dependencies(std::vector &de }); } +std::map read_test_timings(const std::filesystem::path &build_root) { + std::map timings; + auto text = Void::FileSystem::read_file(build_root / ".vbs" / "test_timings.json"); + if (!text) { + return timings; + } + auto parsed = Void::Json::Strict::parse(*text); + if (!parsed) { + return timings; + } + const auto *object = std::get_if(&parsed->value); + if (object == nullptr) { + return timings; + } + for (const auto &[key, value] : *object) { + if (const auto *number = std::get_if(&value.value)) { + timings[key] = *number; + } else if (const auto *integer = std::get_if(&value.value)) { + timings[key] = static_cast(*integer); + } + } + return timings; +} + +void write_test_timings(const std::filesystem::path &build_root, + const std::string &profile, + const std::vector &records) { + auto timings = read_test_timings(build_root); + for (const auto &record : records) { + timings[profile + ":" + record.name] = record.elapsed_ms; + } + using JsonValue = Void::Json::Strict::Value; + JsonValue::Object object; + for (const auto &[key, value] : timings) { + object[key] = JsonValue{value}; + } + JsonValue root; + root.value = std::move(object); + if (auto serialized = Void::Json::Strict::serialize(root); serialized) { + std::error_code ec; + std::filesystem::create_directories(build_root / ".vbs", ec); + (void)Platform::atomic_write_file(build_root / ".vbs" / "test_timings.json", *serialized, + false); + } +} + +std::set read_name_list(const std::filesystem::path &path) { + std::set names; + auto text = Void::FileSystem::read_file(path); + if (!text) { + return names; + } + auto parsed = Void::Json::Strict::parse(*text); + if (!parsed) { + return names; + } + const auto *array = std::get_if(&parsed->value); + if (array == nullptr) { + return names; + } + for (const auto &entry : *array) { + if (const auto *name = std::get_if(&entry.value)) { + names.insert(*name); + } + } + return names; +} + +void write_name_list(const std::filesystem::path &path, const std::set &names) { + using JsonValue = Void::Json::Strict::Value; + JsonValue::Array array; + for (const auto &name : names) { + array.push_back(JsonValue{name}); + } + JsonValue root; + root.value = std::move(array); + if (auto serialized = Void::Json::Strict::serialize(root); serialized) { + std::error_code ec; + std::filesystem::create_directories(path.parent_path(), ec); + (void)Platform::atomic_write_file(path, *serialized, false); + } +} + +std::set read_flaky_names(const std::vector &files) { + std::set names; + for (const auto &file : files) { + auto text = Void::FileSystem::read_file(file); + if (!text) { + continue; + } + for (const auto line : Void::Str::split(*text, '\n')) { + const std::string name = std::string{Void::Str::trim(line)}; + if (!name.empty() && !name.starts_with("#")) { + names.insert(name); + } + } + } + return names; +} + int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { const std::string cmd_name = run_tests ? "vbs test" : "vbs build"; if (opts.frozen) { @@ -647,8 +754,7 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { return 2; } std::optional shuffle_seed; - if (opts.shuffle && opts.shuffle_seed_arg && !opts.shuffle_seed_arg->empty()) { - std::uint64_t parsed_seed = 0; + if (opts.shuffle && opts.shuffle_seed_arg && !opts.shuffle_seed_arg->empty()) { std::uint64_t parsed_seed = 0; const auto &text = *opts.shuffle_seed_arg; const auto [ptr, ec] = std::from_chars(text.data(), text.data() + text.size(), parsed_seed); if (ec != std::errc{} || ptr != text.data() + text.size()) { @@ -659,6 +765,41 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { shuffle_seed = parsed_seed; } + int shard_index = 0; + int shard_count = 0; + if (opts.shard_arg) { + const auto slash = opts.shard_arg->find('/'); + if (slash == std::string::npos || + !Void::Str::to_int(opts.shard_arg->substr(0, slash), shard_index) || + !Void::Str::to_int(opts.shard_arg->substr(slash + 1), shard_count) || + shard_count < 1 || shard_count > 128 || shard_index < 1 || shard_index > shard_count) { + std::cerr << cmd_name << ": invalid --shard value '" << *opts.shard_arg + << "' (expected I/N with 1 <= I <= N <= 128)\n"; + return 2; + } + } + double coverage_min = -1.0; + if (opts.coverage_min_arg) { + char *end = nullptr; + coverage_min = std::strtod(opts.coverage_min_arg->c_str(), &end); + if (end == opts.coverage_min_arg->c_str() || *end != '\0' || coverage_min < 0.0 || + coverage_min > 100.0) { + std::cerr << cmd_name << ": invalid --coverage-min value '" << *opts.coverage_min_arg + << "' (expected 0..100)\n"; + return 2; + } + } + if ((opts.coverage_min_arg || opts.coverage_diff_arg) && !opts.coverage_arg) { + std::cerr << cmd_name << ": --coverage-min and --coverage-diff require --coverage DIR\n"; + return 2; + } + if (!run_tests && + (opts.shard_arg || opts.rerun_failed || !opts.known_flaky_files.empty() || + opts.coverage_min_arg || opts.coverage_diff_arg)) { + std::cerr << cmd_name << ": test-runner options require 'vbs test'\n"; + return 2; + } + std::vector test_records; const auto total_sw = Void::Time::Stopwatch::started(); @@ -881,6 +1022,7 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { Void::Str::to_lower_ascii(Toolchain::host_os_name()) != "windows"; bool all_ok = true; + std::set failed_test_names; // Native compiler cache (ccache/sccache): resolved once and injected into compile actions. std::optional native_cache; { @@ -1630,6 +1772,120 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { } } + // ---- Test selection: --rerun-failed, --shard and --known-flaky (Track G8) ---- + const auto test_timings = read_test_timings(build_root); + const auto known_flaky = read_flaky_names(opts.known_flaky_files); + const auto last_failed_path = build_root / ".vbs" / "last_failed_tests.json"; + std::error_code last_failed_ec; + const bool have_last_failed = + std::filesystem::is_regular_file(last_failed_path, last_failed_ec); + const auto last_failed_names = have_last_failed ? read_name_list(last_failed_path) + : std::set{}; + const auto apply_selection = [&](const std::vector &keep) { + std::vector kept; + std::vector remap(test_jobs.size(), std::string::npos); + for (std::size_t i = 0; i < test_jobs.size(); ++i) { + if (keep[i]) { + remap[i] = kept.size(); + kept.push_back(test_jobs[i]); + } + } + for (auto &job : kept) { + std::vector prerequisites; + for (const auto prerequisite : job.prerequisites) { + if (remap[prerequisite] != std::string::npos) { + prerequisites.push_back(remap[prerequisite]); + } + } + job.prerequisites = std::move(prerequisites); + } + test_jobs = std::move(kept); + }; + if (opts.rerun_failed) { + if (!have_last_failed || last_failed_names.empty()) { + Void::Log::warn("Test", + "--rerun-failed: no previous failures recorded; running all " + "tests"); + } else { + std::vector keep(test_jobs.size(), false); + std::function mark = [&](std::size_t index) { + if (keep[index]) { + return; + } + keep[index] = true; + for (const auto prerequisite : test_jobs[index].prerequisites) { + mark(prerequisite); + } + }; + for (std::size_t i = 0; i < test_jobs.size(); ++i) { + if (last_failed_names.contains(test_jobs[i].name)) { + mark(i); + } + } + apply_selection(keep); + Void::Log::info("Test", "[{}] --rerun-failed selected {} test(s)", prof_name, + test_jobs.size()); + } + } + if (shard_count > 0 && !test_jobs.empty()) { + // Group tests with their fixture prerequisites into clusters, then greedily + // balance clusters across shards using the previous run's timings. + std::vector parent(test_jobs.size()); + std::iota(parent.begin(), parent.end(), std::size_t{0}); + std::function find_root = [&](std::size_t index) { + return parent[index] == index ? index : parent[index] = find_root(parent[index]); + }; + for (std::size_t i = 0; i < test_jobs.size(); ++i) { + for (const auto prerequisite : test_jobs[i].prerequisites) { + const auto a = find_root(i); + const auto b = find_root(prerequisite); + if (a != b) { + parent[a] = b; + } + } + } + std::map> grouped; + for (std::size_t i = 0; i < test_jobs.size(); ++i) { + grouped[find_root(i)].push_back(i); + } + std::vector> clusters; + for (auto &[root, members] : grouped) { + (void)root; + clusters.push_back(std::move(members)); + } + const auto cluster_load = [&](const std::vector &cluster) { + double total = 0.0; + for (const auto index : cluster) { + const auto it = test_timings.find(prof_name + ":" + + test_jobs[index].name); + total += it == test_timings.end() ? 1.0 : it->second; + } + return total; + }; + std::ranges::sort(clusters, [&](const auto &a, const auto &b) { + return cluster_load(a) > cluster_load(b); + }); + std::vector> shards(static_cast(shard_count)); + std::vector shard_loads(static_cast(shard_count), 0.0); + for (auto &cluster : clusters) { + const auto target = static_cast( + std::distance(shard_loads.begin(), + std::ranges::min_element(shard_loads))); + shard_loads[target] += cluster_load(cluster); + for (const auto index : cluster) { + shards[target].push_back(index); + } + } + std::vector keep(test_jobs.size(), false); + for (const auto index : shards[static_cast(shard_index - 1)]) { + keep[index] = true; + } + apply_selection(keep); + Void::Log::info("Test", "[{}] shard {}/{} selected {} test(s) ({:.0f} ms of work)", + prof_name, shard_index, shard_count, test_jobs.size(), + shard_loads[static_cast(shard_index - 1)]); + } + // Tests run in parallel up to --jobs, except that tests sharing a resource are // serialized (a resource is held exclusively while its test runs) and fixture // prerequisites run first. @@ -1824,16 +2080,27 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { thread.join(); } } + std::vector timing_records; for (auto &record : records) { if (!record) { continue; } + timing_records.push_back(*record); + const bool flaky = known_flaky.contains(record->name) || + known_flaky.contains(record->profile + ":" + record->name); if (!record->passed) { - std::cerr << "vbs test: FAILED '" << record->name << "'\n"; - if (!record->output.empty()) { - std::cerr << record->output << '\n'; + failed_test_names.insert(record->name); + if (flaky) { + Void::Log::warn("Test", "[{}] FLAKY '{}' (known flaky failure)", + prof_name, record->name); + std::cout << "vbs test: FLAKY '" << record->name << "'\n"; + } else { + std::cerr << "vbs test: FAILED '" << record->name << "'\n"; + if (!record->output.empty()) { + std::cerr << record->output << '\n'; + } + all_ok = false; } - all_ok = false; } else { std::cout << "vbs test: PASSED '" << record->name << "'\n"; } @@ -1841,6 +2108,7 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { record->elapsed_ms); test_records.push_back(std::move(*record)); } + write_test_timings(build_root, prof_name, timing_records); } if (opts.stop_on_failure && !all_ok) { Void::Log::warn("Test", "--stop-on-failure: skipping the remaining profiles"); @@ -1866,6 +2134,32 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { Void::Log::info("Test", "Coverage {:.1f}% ({}/{} lines) across {} file(s) -> {}", percent, cov->lines_hit, cov->lines_found, cov->files, (std::filesystem::path{*opts.coverage_arg} / "coverage.info").string()); + if (coverage_min >= 0.0 && percent + 1e-9 < coverage_min) { + std::cerr << std::format( + "vbs test: coverage {:.2f}% is below --coverage-min {:.2f}%\n", percent, + coverage_min); + all_ok = false; + } + if (opts.coverage_diff_arg) { + auto baseline = Report::read_lcov_summary(*opts.coverage_diff_arg); + if (!baseline) { + std::cerr << "vbs test: cannot read the coverage baseline '" + << *opts.coverage_diff_arg << "': " << baseline.error().message() + << '\n'; + all_ok = false; + } else { + const double base_percent = Report::coverage_percent(*baseline); + if (percent + 1e-9 < base_percent) { + std::cerr << std::format( + "vbs test: coverage dropped from {:.2f}% to {:.2f}%\n", base_percent, + percent); + all_ok = false; + } else { + Void::Log::info("Test", "Coverage diff: +{:.2f}% vs baseline", + percent - base_percent); + } + } + } } } @@ -1998,6 +2292,9 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { } } + if (run_tests) { + write_name_list(build_root / ".vbs" / "last_failed_tests.json", failed_test_names); + } bep_emit("build_finished", project_root.filename().string(), all_ok ? "ok" : "failed", all_ok ? 0 : 1, total_sw.elapsed_ms()); flush_bep(); @@ -5443,6 +5740,143 @@ int execute_profile_command(std::string_view sub, const ProfileCmdOptions &opts) return 2; } +struct DoctestCmdOptions { + std::string project_arg{"."}; + std::optional build_arg; + std::vector header_args; + std::vector include_args; + std::vector source_args; + std::optional compiler_arg; +}; + +int execute_doctest_command(const DoctestCmdOptions &opts) { + const std::filesystem::path project_root = + std::filesystem::absolute(opts.project_arg).lexically_normal(); + const std::filesystem::path build_root = + opts.build_arg ? std::filesystem::path{*opts.build_arg} : (project_root / "build"); + std::vector headers; + for (const auto &header : opts.header_args) { + headers.emplace_back(header); + } + if (headers.empty()) { + std::error_code ec; + for (const char *dir : {"include", "src"}) { + const auto base = project_root / dir; + if (!std::filesystem::is_directory(base, ec)) { + continue; + } + for (std::filesystem::recursive_directory_iterator it{base, ec}, end; it != end; + it.increment(ec)) { + if (ec) { + break; + } + if (!it->is_regular_file(ec)) { + continue; + } + const std::string extension = it->path().extension().string(); + if (extension == ".hpp" || extension == ".h" || extension == ".hh" || + extension == ".hxx" || extension == ".ixx") { + headers.push_back(it->path()); + } + if (headers.size() >= 1000) { + break; + } + } + } + } + std::vector include_dirs; + for (const auto &include : opts.include_args) { + include_dirs.emplace_back(include); + } + std::filesystem::path compiler; + if (opts.compiler_arg) { + compiler = *opts.compiler_arg; + } else { + const auto ctx = default_profiles().resolve("debug", std::nullopt, + Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + if (auto toolchain = Toolchain::discover_and_probe(ctx, build_root / ".vbs" / "probes"); + toolchain) { + compiler = toolchain->cxx_compiler; + } + } + Test::DoctestOptions options; + options.project_root = project_root; + options.build_dir = build_root; + options.headers = std::move(headers); + options.include_dirs = std::move(include_dirs); + for (const auto &source : opts.source_args) { + options.extra_sources.emplace_back(source); + } + options.compiler = compiler; + auto result = Test::run_doctests(options); + if (!result) { + std::cerr << "vbs doctest: " << result.error().message() << '\n'; + return 1; + } + for (const auto &diagnostic : result->diagnostics) { + std::cerr << diagnostic << '\n'; + } + std::cout << "doctest: " << result->blocks << " block(s), " << result->passed << " passed, " + << result->failed << " failed\n"; + return result->failed == 0 ? 0 : 1; +} + +struct FuzzCmdOptions { + std::string project_arg{"."}; + std::optional build_arg; + std::vector sources; + std::vector include_args; + std::string name{"fuzz"}; + std::string runs_arg{"10000"}; + std::optional corpus_arg; + std::optional compiler_arg; +}; + +int execute_fuzz_command(const FuzzCmdOptions &opts) { + if (opts.sources.empty()) { + std::cerr << "vbs fuzz: at least one --source is required\n"; + return 2; + } + int runs = 0; + if (!Void::Str::to_int(opts.runs_arg, runs) || runs < 1 || runs > 10000000) { + std::cerr << "vbs fuzz: invalid --runs value '" << opts.runs_arg + << "' (expected 1..10000000)\n"; + return 2; + } + const std::filesystem::path project_root = + std::filesystem::absolute(opts.project_arg).lexically_normal(); + Test::FuzzOptions options; + options.project_root = project_root; + options.build_dir = opts.build_arg ? std::filesystem::path{*opts.build_arg} + : (project_root / "build"); + for (const auto &source : opts.sources) { + options.sources.emplace_back(source); + } + for (const auto &include : opts.include_args) { + options.include_dirs.emplace_back(include); + } + options.name = opts.name; + options.runs = static_cast(runs); + if (opts.corpus_arg) { + options.corpus = *opts.corpus_arg; + } + if (opts.compiler_arg) { + options.compiler = *opts.compiler_arg; + } + auto result = Test::run_fuzz(options); + if (!result) { + std::cerr << result.error().message() << '\n'; + return 1; + } + std::cout << result->output; + std::cout << "fuzz: " << result->binary.string() << " exited " << result->exit_code << '\n'; + for (const auto &artifact : result->artifacts) { + std::cout << "fuzz: artifact " << artifact.string() << '\n'; + } + return result->exit_code == 0 ? 0 : 1; +} + struct InitCmdOptions { std::string dir_arg; std::optional name_arg; @@ -6098,6 +6532,8 @@ int main(int argc, char **argv) { AttestCmdOptions attest_opts; AuditCmdOptions audit_opts; ProfileCmdOptions profile_opts; + DoctestCmdOptions doctest_opts; + FuzzCmdOptions fuzz_opts; CompletionsCmdOptions completions_opts; ManCmdOptions man_opts; IdeCmdOptions ide_opts; @@ -6131,6 +6567,19 @@ int main(int argc, char **argv) { build_opts.repeat_arg) .option_default("--retry", "", "Retry a failed test up to N times (0..10)", build_opts.retry_arg, "0") + .option("--shard", "", "Run only shard I/N (1-based, N <= 128)", + build_opts.shard_arg) + .option_many("--known-flaky", "", + "File listing known-flaky test names, one per line (repeatable)", + build_opts.known_flaky_files) + .flag("--rerun-failed", "", + "Re-run only tests that failed in the last run", build_opts.rerun_failed) + .option("--coverage-min", "", + "Fail when line coverage is below this percentage (0..100)", + build_opts.coverage_min_arg) + .option("--coverage-diff", "", + "Fail when coverage drops below this lcov baseline", + build_opts.coverage_diff_arg) .flag("--shuffle", "", "Run tests in a shuffled order", build_opts.shuffle) .option("--shuffle-seed", "", "Seed for --shuffle (default: random)", build_opts.shuffle_seed_arg) @@ -6757,6 +7206,38 @@ int main(int argc, char **argv) { configure_profile_common(profile_diff); profile_diff.positional_many("profiles", "Two profile names", profile_opts.diff_args, true); + auto &doctest_cmd = + root.subcommand("doctest", "Extract and run fenced C++ doctests from documentation comments"); + doctest_cmd + .option_default("--project", "-C", "Project directory", doctest_opts.project_arg, ".") + .option("--build-dir", "-B", "Build directory (default: /build)", + doctest_opts.build_arg) + .option_many("--header", "", "Header to scan (default: include/ and src/)", + doctest_opts.header_args) + .option_many("--include", "", "Additional include directory (repeatable)", + doctest_opts.include_args) + .option_many("--source", "", "Extra source file linked into every doctest", + doctest_opts.source_args) + .option("--compiler", "", "C++ compiler path (default: the probed host compiler)", + doctest_opts.compiler_arg); + add_log_flags(doctest_cmd); + + auto &fuzz_cmd = root.subcommand("fuzz", "Build and run a libFuzzer target over a corpus"); + fuzz_cmd + .option_default("--project", "-C", "Project directory", fuzz_opts.project_arg, ".") + .option("--build-dir", "-B", "Build directory (default: /build)", + fuzz_opts.build_arg) + .option_many("--source", "", "Fuzzer source file (repeatable)", fuzz_opts.sources) + .option_many("--include", "", "Additional include directory (repeatable)", + fuzz_opts.include_args) + .option_default("--name", "", "Fuzzer binary name", fuzz_opts.name, "fuzz") + .option_default("--runs", "", "Fuzzer iterations (1..10000000)", fuzz_opts.runs_arg, + "10000") + .option("--corpus", "", "Corpus directory (default: /fuzz/corpus)", + fuzz_opts.corpus_arg) + .option("--compiler", "", "clang++ path (libFuzzer)", fuzz_opts.compiler_arg); + add_log_flags(fuzz_cmd); + auto &ide_cmd = root.subcommand("ide", "Generate editor/IDE configs and query workspace metadata"); auto configure_ide_common = [&](Void::Argparse::Parser &p) { @@ -7164,6 +7645,12 @@ int main(int argc, char **argv) { if (cmd == "profile") { return execute_profile_command(parsed.matched_command_path.at(1), profile_opts); } + if (cmd == "doctest") { + return execute_doctest_command(doctest_opts); + } + if (cmd == "fuzz") { + return execute_fuzz_command(fuzz_opts); + } if (cmd == "ide") { return execute_ide_command(parsed.matched_command_path.at(1), ide_opts); } diff --git a/src/Report/Coverage.cpp b/src/Report/Coverage.cpp index 1a58b02..2aa67f9 100644 --- a/src/Report/Coverage.cpp +++ b/src/Report/Coverage.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -191,4 +192,40 @@ write_coverage_report(const std::vector &gcda_files, return summary; } -} // namespace Void::Build::Report +double coverage_percent(const CoverageSummary &summary) noexcept { + return summary.lines_found == 0 + ? 0.0 + : 100.0 * static_cast(summary.lines_hit) / + static_cast(summary.lines_found); +} + +Void::Result::Result +read_lcov_summary(const std::filesystem::path &lcov_file) { + auto text = Void::FileSystem::read_file(lcov_file); + if (!text) { + return std::unexpected{text.error()}; + } + CoverageSummary summary; + std::set files; + for (const auto line : Void::Str::split(*text, '\n')) { + if (Void::Str::starts_with(line, "SF:")) { + files.emplace(line.substr(3)); + } else if (Void::Str::starts_with(line, "LF:")) { + const auto value = std::string{Void::Str::trim(line.substr(3))}; + int parsed = 0; + if (Void::Str::to_int(value, parsed) && parsed >= 0) { + summary.lines_found += static_cast(parsed); + } + } else if (Void::Str::starts_with(line, "LH:")) { + const auto value = std::string{Void::Str::trim(line.substr(3))}; + int parsed = 0; + if (Void::Str::to_int(value, parsed) && parsed >= 0) { + summary.lines_hit += static_cast(parsed); + } + } + } + summary.files = files.size(); + return summary; +} + +} // namespace Void::Build::Report \ No newline at end of file diff --git a/src/Test/Doctest.cpp b/src/Test/Doctest.cpp new file mode 100644 index 0000000..01413f4 --- /dev/null +++ b/src/Test/Doctest.cpp @@ -0,0 +1,185 @@ +#include + +#include +#include +#include +#include +#include + +#include +#include + +namespace Void::Build::Test { +namespace { + +Void::Result::Error make_error(std::string message) { + return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument, + std::move(message)); +} + +std::string strip_comment_prefix(std::string_view line) { + std::string_view rest = Void::Str::trim_left(line); + for (const std::string_view prefix : {"///", "//!", "//"}) { + if (rest.starts_with(prefix)) { + rest = rest.substr(prefix.size()); + if (rest.starts_with(' ')) { + rest = rest.substr(1); + } + return std::string{rest}; + } + } + if (rest.starts_with('*')) { + rest = rest.substr(1); + if (rest.starts_with(' ')) { + rest = rest.substr(1); + } + return std::string{rest}; + } + return {}; +} + +bool block_language_supported(std::string_view language) { + return language.empty() || language == "cpp" || language == "c++" || language == "cxx" || + language == "cc"; +} + +std::string quote_include(const std::filesystem::path &path) { + std::string out; + for (const char c : path.string()) { + out.push_back(c == '\\' ? '/' : c); + } + return out; +} + +} // namespace + +Void::Result::Result, Void::Result::Error> +extract_doctest_blocks(const std::filesystem::path &header) { + auto text = Void::FileSystem::read_file(header); + if (!text) { + return std::unexpected{text.error()}; + } + std::vector blocks; + DoctestBlock current; + bool in_block = false; + std::size_t line_number = 0; + for (const auto raw_line : Void::Str::split(*text, '\n')) { + ++line_number; + std::string content = strip_comment_prefix(raw_line); + const std::string trimmed = std::string{Void::Str::trim(content)}; + if (!in_block) { + if (trimmed.starts_with("```")) { + current = DoctestBlock{}; + current.file = header; + current.line = line_number + 1; + current.language = std::string{Void::Str::trim(trimmed.substr(3))}; + in_block = true; + } + continue; + } + if (trimmed.starts_with("```")) { + if (block_language_supported(current.language) && !current.code.empty()) { + blocks.push_back(std::move(current)); + } else if (!block_language_supported(current.language)) { + // Non-C++ fences (text/sh) are documentation, not doctests. + } + current = DoctestBlock{}; + in_block = false; + continue; + } + current.code += content; + current.code += '\n'; + } + return blocks; +} + +Void::Result::Result +run_doctests(const DoctestOptions &options) { + auto compiler = options.compiler; + if (compiler.empty()) { + if (const auto found = Platform::resolve_executable("g++"); found) { + compiler = *found; + } else if (const auto found_clang = Platform::resolve_executable("clang++"); + found_clang) { + compiler = *found_clang; + } + } + if (compiler.empty()) { + return std::unexpected{make_error("doctest: no C++ compiler found in PATH")}; + } + std::error_code ec; + const auto work_dir = options.build_dir / "doctest"; + std::filesystem::create_directories(work_dir, ec); + if (ec) { + return std::unexpected{make_error("doctest: cannot create '" + work_dir.string() + "'")}; + } + + DoctestResult result; + for (const auto &header : options.headers) { + auto blocks = extract_doctest_blocks(header); + if (!blocks) { + return std::unexpected{blocks.error()}; + } + for (const auto &block : *blocks) { + ++result.blocks; + const std::string id = + Util::sha256_hex(block.file.string() + ":" + std::to_string(block.line)) + .substr(0, 16); + const auto source = work_dir / (id + ".cpp"); + const auto binary = work_dir / (id + ".bin"); + std::string code; + code += "#include <" + quote_include(block.file) + ">\n"; + code += "int main() {\n"; + code += "#line " + std::to_string(block.line) + " \"" + block.file.string() + "\"\n"; + code += block.code; + code += "\n}\n"; + if (auto written = Platform::atomic_write_file(source, code, false); !written) { + return std::unexpected{written.error()}; + } + Platform::ProcessRequest compile; + compile.executable = compiler; + compile.arguments = {"-std=" + options.cxx_standard}; + for (const auto &include : options.include_dirs) { + compile.arguments.push_back("-I"); + compile.arguments.push_back(include.string()); + } + compile.arguments.push_back("-I"); + compile.arguments.push_back((options.project_root / "include").string()); + compile.arguments.push_back("-I"); + compile.arguments.push_back(options.project_root.string()); + compile.arguments.push_back(source.string()); + for (const auto &extra : options.extra_sources) { + compile.arguments.push_back(extra.string()); + } + compile.arguments.push_back("-o"); + compile.arguments.push_back(binary.string()); + compile.working_directory = options.project_root; + compile.timeout = options.timeout; + auto compiled = Platform::run_supervised(compile); + if (!compiled || !compiled->succeeded()) { + ++result.failed; + result.diagnostics.push_back(std::format( + "{}:{}: doctest failed to compile:\n{}", block.file.string(), block.line, + compiled ? compiled->stderr_data : compiled.error().message())); + continue; + } + Platform::ProcessRequest run; + run.executable = binary; + run.working_directory = options.project_root; + run.timeout = options.timeout; + auto ran = Platform::run_supervised(run); + if (!ran || !ran->succeeded()) { + ++result.failed; + result.diagnostics.push_back(std::format( + "{}:{}: doctest failed (exit {}):\n{}{}", block.file.string(), block.line, + ran ? ran->exit_code : -1, ran ? ran->stdout_data : "", + ran ? ran->stderr_data : ran.error().message())); + continue; + } + ++result.passed; + } + } + return result; +} + +} // namespace Void::Build::Test diff --git a/src/Test/Fuzz.cpp b/src/Test/Fuzz.cpp new file mode 100644 index 0000000..ff7ca4d --- /dev/null +++ b/src/Test/Fuzz.cpp @@ -0,0 +1,95 @@ +#include + +#include +#include +#include + +#include + +namespace Void::Build::Test { +namespace { + +Void::Result::Error make_error(std::string message) { + return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument, + std::move(message)); +} + +} // namespace + +Void::Result::Result run_fuzz(const FuzzOptions &options) { + if (options.sources.empty()) { + return std::unexpected{make_error("fuzz: at least one --source is required")}; + } + auto compiler = options.compiler; + if (compiler.empty()) { + if (const auto found = Platform::resolve_executable("clang++"); found) { + compiler = *found; + } + } + if (compiler.empty()) { + return std::unexpected{ + make_error("fuzz: clang++ is required (libFuzzer); pass --compiler PATH")}; + } + std::error_code ec; + const auto out_dir = options.build_dir / "fuzz"; + std::filesystem::create_directories(out_dir, ec); + if (ec) { + return std::unexpected{make_error("fuzz: cannot create '" + out_dir.string() + "'")}; + } + const auto binary = out_dir / options.name; + + Platform::ProcessRequest compile; + compile.executable = compiler; + compile.arguments = {"-std=c++20", "-g", "-O1", "-fsanitize=fuzzer,address,undefined"}; + for (const auto &include : options.include_dirs) { + compile.arguments.push_back("-I"); + compile.arguments.push_back(include.string()); + } + compile.arguments.push_back("-I"); + compile.arguments.push_back((options.project_root / "include").string()); + compile.arguments.push_back("-I"); + compile.arguments.push_back(options.project_root.string()); + for (const auto &source : options.sources) { + compile.arguments.push_back(source.string()); + } + compile.arguments.push_back("-o"); + compile.arguments.push_back(binary.string()); + compile.working_directory = options.project_root; + compile.timeout = options.timeout; + auto compiled = Platform::run_supervised(compile); + if (!compiled || !compiled->succeeded()) { + return std::unexpected{make_error(std::format( + "fuzz: failed to build the fuzzer:\n{}", + compiled ? compiled->stderr_data : compiled.error().message()))}; + } + + const auto corpus = options.corpus.empty() ? (out_dir / "corpus") : options.corpus; + std::filesystem::create_directories(corpus, ec); + const auto artifact_prefix = out_dir.string() + "/"; + Platform::ProcessRequest run; + run.executable = binary; + run.arguments = {"-runs=" + std::to_string(options.runs), "-artifact_prefix=" + artifact_prefix, + corpus.string()}; + run.working_directory = options.project_root; + run.timeout = options.timeout; + run.environment.set_vars["ASAN_OPTIONS"] = "detect_leaks=0"; + auto executed = Platform::run_supervised(run); + if (!executed) { + return std::unexpected{executed.error()}; + } + + FuzzResult result; + result.binary = binary; + result.exit_code = executed->exit_code; + result.output = executed->stdout_data + executed->stderr_data; + for (const auto &entry : std::filesystem::directory_iterator(out_dir, ec)) { + const auto filename = entry.path().filename().string(); + if (filename.starts_with("crash-") || filename.starts_with("timeout-") || + filename.starts_with("leak-") || filename.starts_with("oom-")) { + result.artifacts.push_back(entry.path()); + } + } + return result; +} + +} // namespace Void::Build::Test diff --git a/tests/CliContracts.cmake b/tests/CliContracts.cmake index 79894a3..b562c09 100644 --- a/tests/CliContracts.cmake +++ b/tests/CliContracts.cmake @@ -70,6 +70,13 @@ check_process(0 "Usage: vbs profile list " "" profile list --help) check_process(0 "Usage: vbs profile show " "" profile show --help) check_process(0 "Usage: vbs profile diff " "" profile diff --help) check_process(2 "" "exactly two profile names" profile diff debug) +check_process(0 "Usage: vbs doctest " "" doctest --help) +check_process(0 "Usage: vbs fuzz " "" fuzz --help) +check_process(2 "" "at least one --source is required" fuzz) +check_process(2 "" "invalid --runs value" fuzz --source f.cpp --runs 0) +check_process(2 "" "--coverage-min and --coverage-diff require --coverage" test --coverage-min 80) +check_process(2 "" "invalid --shard value" test --shard 0/2) +check_process(2 "" "test-runner options require" build --rerun-failed) check_process(2 "" "invalid value 'bogus' for '--sandbox'" build --sandbox bogus) check_process(0 "Usage: vbs new " "" new --help) check_process(2 "" "unsupported --native-cache" build --native-cache bogus) diff --git a/tests/FullV1Tests.cpp b/tests/FullV1Tests.cpp index a8ec210..ef41c5c 100644 --- a/tests/FullV1Tests.cpp +++ b/tests/FullV1Tests.cpp @@ -5330,3 +5330,319 @@ void profiles(Void::Build::Profiles &p) { auto missing = run_vbs({"profile", "show", "nope", "--project", proj.string()}); Void::Testing::expect(missing.has_value() && missing->exit_code == 2); } + +// === G8: doctest extraction, compilation and execution === +VOID_TEST(FullV1Tests, doctest_extracts_compiles_and_runs_blocks) { + const auto vbs_bin = locate_vbs_binary(); + Void::Testing::expect(!vbs_bin.empty() && std::filesystem::exists(vbs_bin)); + if (vbs_bin.empty() || !std::filesystem::exists(vbs_bin)) { + return; + } + Void::FileSystem::TempDir tmp{"vbs_doctest_"}; + const auto proj = tmp / "proj"; + write_file(proj / "include" / "demo.hpp", R"cpp(#pragma once +/// Passing block. +/// ```cpp +/// if (2 + 2 != 4) return 1; +/// ``` +/// Failing block. +/// ```cpp +/// return 3; +/// ``` +/// Broken block. +/// ```cpp +/// this is not c++; +/// ``` +int demo(); +)cpp"); + write_file(proj / "src" / "demo.cpp", "int demo() { return 7; }\n"); + auto run_vbs = [&](std::vector args) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = std::move(args); + req.timeout = std::chrono::seconds{600}; + return Platform::run_supervised(req); + }; + auto failing = run_vbs({"doctest", "--project", proj.string(), "--build-dir", + (tmp / "build").string()}); + Void::Testing::expect(failing.has_value() && failing->exit_code == 1); + if (failing) { + Void::Testing::expect(failing->stdout_data.find("3 block(s), 1 passed, 2 failed") != + std::string::npos); + const std::string diagnostics = failing->stdout_data + failing->stderr_data; + Void::Testing::expect(diagnostics.find("demo.hpp:") != std::string::npos); + Void::Testing::expect(diagnostics.find("failed to compile") != std::string::npos); + } + // A passing block that calls into the project needs --source for linking. + write_file(proj / "include" / "demo.hpp", R"cpp(#pragma once +int demo(); +/// Uses the project implementation. +/// ```cpp +/// if (demo() != 7) return 1; +/// ``` +)cpp"); + auto linked = run_vbs({"doctest", "--project", proj.string(), "--build-dir", + (tmp / "build").string(), "--source", (proj / "src" / "demo.cpp").string()}); + Void::Testing::expect(linked.has_value() && linked->succeeded()); + if (linked) { + Void::Testing::expect(linked->stdout_data.find("1 block(s), 1 passed, 0 failed") != + std::string::npos); + } +} + +// === G8: libFuzzer targets === +VOID_TEST(FullV1Tests, fuzz_builds_targets_and_reports_crashes) { + const auto vbs_bin = locate_vbs_binary(); + Void::Testing::expect(!vbs_bin.empty() && std::filesystem::exists(vbs_bin)); + if (vbs_bin.empty() || !std::filesystem::exists(vbs_bin)) { + return; + } + if (!Platform::resolve_executable("clang++")) { + return; // libFuzzer requires clang. + } + Void::FileSystem::TempDir tmp{"vbs_fuzz_"}; + const auto proj = tmp / "proj"; + write_file(proj / "fuzz_ok.cpp", R"cpp(#include +#include +extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t *, std::size_t) { return 0; } +)cpp"); + write_file(proj / "fuzz_crash.cpp", R"cpp(#include +#include +extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t *, std::size_t size) { + if (size == 1) __builtin_trap(); + return 0; +} +)cpp"); + auto run_vbs = [&](std::vector args) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = std::move(args); + req.timeout = std::chrono::seconds{900}; + return Platform::run_supervised(req); + }; + auto stable = run_vbs({"fuzz", "--project", proj.string(), "--build-dir", + (tmp / "build").string(), "--source", + (proj / "fuzz_ok.cpp").string(), "--runs", "100"}); + Void::Testing::expect(stable.has_value() && stable->succeeded()); + if (stable && !stable->succeeded()) { + std::cerr << stable->stdout_data << stable->stderr_data << '\n'; + } + const auto corpus = tmp / "corpus"; + write_file(corpus / "seed", "A"); + auto crash = run_vbs({"fuzz", "--project", proj.string(), "--build-dir", + (tmp / "build").string(), "--source", + (proj / "fuzz_crash.cpp").string(), "--runs", "10", "--corpus", + corpus.string()}); + Void::Testing::expect(crash.has_value() && crash->exit_code == 1); + if (crash) { + const std::string output = crash->stdout_data + crash->stderr_data; + Void::Testing::expect(output.find("artifact") != std::string::npos || + output.find("crash-") != std::string::npos); + } +} + +// === G8: sharding with recorded timings === +VOID_TEST(FullV1Tests, test_sharding_partitions_tests_and_records_timings) { + const auto vbs_bin = locate_vbs_binary(); + Void::Testing::expect(!vbs_bin.empty() && std::filesystem::exists(vbs_bin)); + if (vbs_bin.empty() || !std::filesystem::exists(vbs_bin)) { + return; + } + Void::FileSystem::TempDir tmp{"vbs_shard_"}; + const auto proj = tmp / "proj"; + write_file(proj / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { + for (const char *name : {"s1", "s2", "s3", "s4"}) { + p.test(name).cxx_standard(Void::Build::CxxStandard::Cxx26) + .sources({std::string{"tests/"} + name + ".cpp"}); + } +} +)cpp"); + const int sleeps[] = {5, 10, 15, 20}; + int index = 0; + for (const char *name : {"s1", "s2", "s3", "s4"}) { + write_file(proj / "tests" / (std::string{name} + ".cpp"), + std::format("#include \nint main() {{ " + "std::this_thread::sleep_for(std::chrono::milliseconds({})); " + "return 0; }}\n", + sleeps[index++])); + } + auto run_vbs = [&](std::vector args) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = std::move(args); + req.timeout = std::chrono::seconds{600}; + return Platform::run_supervised(req); + }; + auto all = run_vbs({"test", "--project", proj.string(), "--build-dir", + (tmp / "build").string(), "--jobs", "2"}); + Void::Testing::expect(all.has_value() && all->succeeded()); + auto timings_text = Void::FileSystem::read_file(tmp / "build" / ".vbs" / "test_timings.json"); + Void::Testing::require(timings_text.has_value()); + auto timings = Void::Json::Strict::parse(*timings_text); + Void::Testing::require(timings.has_value()); + const auto *timings_object = std::get_if(&timings->value); + Void::Testing::require(timings_object != nullptr); + for (const char *name : {"s1", "s2", "s3", "s4"}) { + Void::Testing::expect(timings_object->contains(std::string{"debug:"} + name)); + } + const auto shard_names = [&](const std::string &shard) { + std::set names; + auto result = run_vbs({"test", "--project", proj.string(), "--build-dir", + (tmp / "build").string(), "--jobs", "2", "--shard", shard}); + if (!result || !result->succeeded()) { + std::cerr << "shard " << shard << " failed (exit " + << (result ? result->exit_code : -1) << "):\n" + << (result ? result->stdout_data + result->stderr_data : "") << '\n'; + return names; + } + for (const char *name : {"s1", "s2", "s3", "s4"}) { + if (result->stdout_data.find(std::string{"PASSED '"} + name + "'") != + std::string::npos) { + names.insert(name); + } + } + return names; + }; + const auto first = shard_names("1/2"); + const auto second = shard_names("2/2"); + if (first.size() + second.size() != 4) { + std::cerr << "shard 1: "; + for (const auto &name : first) { + std::cerr << name << ' '; + } + std::cerr << "\nshard 2: "; + for (const auto &name : second) { + std::cerr << name << ' '; + } + std::cerr << '\n'; + } + Void::Testing::expect_eq(first.size() + second.size(), std::size_t{4}); + for (const auto &name : first) { + Void::Testing::expect(!second.contains(name)); + } + auto invalid = run_vbs({"test", "--project", proj.string(), "--build-dir", + (tmp / "build").string(), "--shard", "3/2"}); + Void::Testing::expect(invalid.has_value() && invalid->exit_code == 2); +} + +// === G8: --rerun-failed and --known-flaky === +VOID_TEST(FullV1Tests, test_rerun_failed_and_known_flaky) { + const auto vbs_bin = locate_vbs_binary(); + Void::Testing::expect(!vbs_bin.empty() && std::filesystem::exists(vbs_bin)); + if (vbs_bin.empty() || !std::filesystem::exists(vbs_bin)) { + return; + } + Void::FileSystem::TempDir tmp{"vbs_rerun_"}; + const auto proj = tmp / "proj"; + write_file(proj / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { + p.test("stable").cxx_standard(Void::Build::CxxStandard::Cxx26).sources({"tests/stable.cpp"}); + p.test("flaky").cxx_standard(Void::Build::CxxStandard::Cxx26).sources({"tests/flaky.cpp"}); +} +)cpp"); + write_file(proj / "tests" / "stable.cpp", "int main() { return 0; }\n"); + write_file(proj / "tests" / "flaky.cpp", R"cpp(#include +#include +int main() { + int prior = 0; + { std::ifstream in{"flaky.count"}; std::string line; while (std::getline(in, line)) ++prior; } + { std::ofstream out{"flaky.count", std::ios::app}; out << "run\n"; } + return prior == 0 ? 1 : 0; +} +)cpp"); + auto run_vbs = [&](std::vector args) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = std::move(args); + req.timeout = std::chrono::seconds{600}; + return Platform::run_supervised(req); + }; + // First run: flaky fails and is recorded. + auto first = run_vbs({"test", "--project", proj.string(), "--build-dir", + (tmp / "build").string(), "--jobs", "2"}); + Void::Testing::expect(first.has_value() && first->exit_code == 1); + auto failed_text = Void::FileSystem::read_file(tmp / "build" / ".vbs" / + "last_failed_tests.json"); + Void::Testing::require(failed_text.has_value()); + Void::Testing::expect(failed_text->find("flaky") != std::string::npos); + // Rerun only the failed test (now passing because the counter exists). + auto rerun = run_vbs({"test", "--project", proj.string(), "--build-dir", + (tmp / "build").string(), "--jobs", "2", "--rerun-failed"}); + Void::Testing::expect(rerun.has_value() && rerun->succeeded()); + if (rerun) { + Void::Testing::expect(rerun->stdout_data.find("PASSED 'flaky'") != std::string::npos); + Void::Testing::expect(rerun->stdout_data.find("stable") == std::string::npos); + } + // Known-flaky: reset the counter so it fails again; the run still succeeds. + std::error_code ec; + std::filesystem::remove(proj / "flaky.count", ec); + const auto flaky_file = tmp / "flaky.txt"; + write_file(flaky_file, "flaky\n"); + auto known = run_vbs({"test", "--project", proj.string(), "--build-dir", + (tmp / "build").string(), "--jobs", "2", "--known-flaky", + flaky_file.string()}); + Void::Testing::expect(known.has_value() && known->succeeded()); + if (known) { + Void::Testing::expect(known->stdout_data.find("FLAKY 'flaky'") != std::string::npos); + } +} + +// === G8: coverage gates (minimum and baseline diff) === +VOID_TEST(FullV1Tests, coverage_gates_enforce_minimum_and_baseline) { + const auto vbs_bin = locate_vbs_binary(); + Void::Testing::expect(!vbs_bin.empty() && std::filesystem::exists(vbs_bin)); + if (vbs_bin.empty() || !std::filesystem::exists(vbs_bin)) { + return; + } + if (!Platform::resolve_executable("gcov")) { + return; + } + Void::FileSystem::TempDir tmp{"vbs_coverage_gate_"}; + const auto proj = tmp / "proj"; + write_file(proj / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { + auto lib = p.static_library("covlib").sources({"src/lib.cpp"}); + p.test("cov_test").cxx_standard(Void::Build::CxxStandard::Cxx26) + .sources({"tests/cov.cpp"}).link(lib); +} +)cpp"); + write_file(proj / "src" / "lib.cpp", "int covered() { return 1; }\n" + "int uncovered() { return 2; }\n"); + write_file(proj / "tests" / "cov.cpp", "int covered();\n" + "int main() { return covered() == 1 ? 0 : 1; }\n"); + auto run_vbs = [&](std::vector args) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = std::move(args); + req.timeout = std::chrono::seconds{600}; + return Platform::run_supervised(req); + }; + auto low_gate = run_vbs({"test", "--project", proj.string(), "--build-dir", + (tmp / "build").string(), "--jobs", "2", "--coverage", + (tmp / "cov").string(), "--coverage-min", "100"}); + Void::Testing::expect(low_gate.has_value() && low_gate->exit_code == 1); + if (low_gate) { + Void::Testing::expect(low_gate->stdout_data.find("Coverage") != std::string::npos || + low_gate->stderr_data.find("below --coverage-min") != + std::string::npos); + } + auto zero_gate = run_vbs({"test", "--project", proj.string(), "--build-dir", + (tmp / "build").string(), "--jobs", "2", "--coverage", + (tmp / "cov2").string(), "--coverage-min", "0"}); + Void::Testing::expect(zero_gate.has_value() && zero_gate->succeeded()); + // A 100% baseline fails the diff gate; a 0% baseline passes it. + const auto high_baseline = tmp / "high.info"; + write_file(high_baseline, "TN:\nSF:src/lib.cpp\nLF:1\nLH:1\nend_of_record\n"); + auto dropped = run_vbs({"test", "--project", proj.string(), "--build-dir", + (tmp / "build").string(), "--jobs", "2", "--coverage", + (tmp / "cov3").string(), "--coverage-diff", + high_baseline.string()}); + Void::Testing::expect(dropped.has_value() && dropped->exit_code == 1); + const auto low_baseline = tmp / "low.info"; + write_file(low_baseline, "TN:\nSF:src/lib.cpp\nLF:1\nLH:0\nend_of_record\n"); + auto kept = run_vbs({"test", "--project", proj.string(), "--build-dir", + (tmp / "build").string(), "--jobs", "2", "--coverage", + (tmp / "cov4").string(), "--coverage-diff", low_baseline.string()}); + Void::Testing::expect(kept.has_value() && kept->succeeded()); +}