From 92c4be92737140ddd7493a0e73921e50b9ebc6a4 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Sat, 5 Dec 2026 14:50:44 +0300 Subject: [PATCH] feat(test): write lcov coverage reports --- CMakeLists.txt | 1 + docs/agent-workflow/STATE.md | 2 + docs/agent-workflow/TASKS.md | 1 + docs/agent-workflow/VERIFICATION.md | 9 ++ docs/roadmap/22-superiority-and-gaps.md | 2 +- include/Void/Build/Report/Coverage.hpp | 32 ++++ src/Main.cpp | 31 ++++ src/Report/Coverage.cpp | 194 ++++++++++++++++++++++++ tests/FullV1Tests.cpp | 55 +++++++ 9 files changed, 326 insertions(+), 1 deletion(-) create mode 100644 include/Void/Build/Report/Coverage.hpp create mode 100644 src/Report/Coverage.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 251370e..46f153f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -51,6 +51,7 @@ add_library(VoidBuild_Core STATIC src/Config/Scaffold.cpp src/Daemon/Daemon.cpp src/Report/Cdash.cpp + src/Report/Coverage.cpp src/Editor/CompDb.cpp src/Watch/Linux/Watcher.cpp src/Package/Toml.cpp diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 4ec83ba..f693e5e 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -381,6 +381,8 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B - **Wave 144 (NuGet Package Generator)**: `vbs install --archive FILE --archive-format nuget` writes a `.nupkg` - an OPC ZIP with the `.nuspec` manifest, `[Content_Types].xml`, `_rels/.rels` and the installed files mapped to `runtimes//native/**` (headers under `build/native/include`). The RID comes from the profile (e.g. `linux-x64`). Python `zipfile` + ElementTree validate the generated package (id/version/authors parse, CRCs clean); the install test asserts the manifest, layout and native asset paths. +- **Wave 145 (Coverage Reporting)**: `vbs test --coverage DIR` instruments every compile and link with `--coverage`, runs the tests, and converts the gcov JSON data into `DIR/coverage.info` (lcov) and `DIR/summary.txt`. System headers outside the project root are filtered out. `FullV1Tests.test_coverage_writes_lcov_and_summary` builds a library with a covered and an uncovered function and asserts `DA:1,1`, `DA:2,0` and the summary. A fresh-tree bug (a transient filesystem error aborting the .gcda walk) was found and fixed. + ## Remaining future scope - **Superiority plan ([22-superiority-and-gaps.md](../roadmap/22-superiority-and-gaps.md), 2026-12-05)**: revised platform strategy - **macOS deferred**, **Windows via MinGW-w64 cross-compilation + Wine execution** (`dev cpp-gcc -p pkgsCross.mingwW64.stdenv.cc`, `dev cpp-gcc -p wine64`), native MSVC deferred; plus packaging parity (ZIP/DEB/RPM), IDE ecosystem, migration tooling, test-runner parity, benchmarks, CI runners, and remote execution in prioritized order. diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index fe45b9a..b7aed06 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -144,4 +144,5 @@ Base HEAD: `fe0d1a6` | Wave 141 (ASM + shader languages) | `.s`/`.S` assembly; `shader_bundle`/`.shader()` lowered to SPIR-V (glslang/slangc/dxc) | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; both E2Es pass, GLSL/Slang/HLSL produce SPIR-V, full CTest 8/8) | `src/Graph/Graph.cpp`, `src/Toolchain/Driver.cpp`, `include/Void/Build.hpp`, `sdk/Build.cpp`, `tests/FullV1Tests.cpp`, docs | | Wave 142 (Gitea CI + release workflow) | Gitea-hosted CI with artifacts; tag-driven release workflow with asset upload | COMPLETE (YAML-validated; unexecuted without a runner) | `.gitea/workflows/ci.yml`, `.gitea/workflows/release.yml`, docs | | Wave 144 (NuGet generator) | `--archive-format nuget`: `.nupkg` with nuspec, OPC parts and `runtimes//native` assets | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Python validates the package, install test passes, full CTest 8/8) | `src/Install/Installer.cpp`, `src/Main.cpp`, `tests/FullV1Tests.cpp`, docs | +| Wave 145 (Coverage reporting) | `vbs test --coverage DIR`; gcov JSON -> lcov + summary | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; E2E passes, full CTest 8/8) | `include/Void/Build/Report/Coverage.hpp`, `src/Report/Coverage.cpp`, `src/Main.cpp`, `tests/FullV1Tests.cpp`, docs | | Future (Plan 20 Slice 3 / Tracks C, E3 editor extensions) |"}] Live `conan` CLI verification; macOS/Windows/cross-compile; binary-variant signing and key distribution; daemon-side dependency materialization and editor plugins; `Void::Net`/`Void::Sqlite` alignment | PLANNED (unimplemented) | [21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md), [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md) | diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index 203370f..eecd8c2 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -1860,6 +1860,15 @@ VOID_INCLUDE_DIR=/tmp/opencode/vl-pin/include dev cpp -c bash fuzz/run.sh 30 magic, the nuspec id/version, the OPC parts and the runtime asset paths (**passed**, 6.36 s). - Full CTest: **8 / 8 passed** in 337.44 s. +## Coverage Reporting (GCC 16.2, pin `0002e74`) + +- `vbs test --coverage DIR` adds `--coverage` to the profile compile and link options, runs the + tests, and writes `DIR/coverage.info` (lcov) plus `DIR/summary.txt` from gcov's JSON output. +- `FullV1Tests.test_coverage_writes_lcov_and_summary` **passed** (2.66 s): the report contains + `SF:` records for both sources, `DA:1,1` (executed function) and `DA:2,0` (uncovered + function), `end_of_record`, and a summary starting with `Coverage: ` and containing `%`. +- Full CTest: **8 / 8 passed** in 352.77 s. + ## Limits and Unrun Checks 1. **HTTPS git fetch**: the host shell is proxy-restricted, but the Docker container could clone `https://git.faumaray.com/Void/VoidLibrary.git`; the pinned commit `3e254055e081a104f08df68dde39711bc7813518` was fetched directly for the verification above. A separate configure against the local `/home/faumaray/Projects/Library` checkout via `VBS_VOID_SOURCE_DIR` also succeeded (development-only override, checkout unmodified). diff --git a/docs/roadmap/22-superiority-and-gaps.md b/docs/roadmap/22-superiority-and-gaps.md index 312f4ee..46eac7f 100644 --- a/docs/roadmap/22-superiority-and-gaps.md +++ b/docs/roadmap/22-superiority-and-gaps.md @@ -127,7 +127,7 @@ first, then what makes VBS *better* rather than merely equal. ### 8.2 Developer experience and IDE integration -6. **Coverage reporting.** `vbs test --coverage` producing lcov XML (gcov for GCC, +6. **Coverage reporting - done (Wave 145).** `vbs test --coverage` produces lcov (gcov for GCC, llvm-cov for Clang) alongside JUnit. CMake has `CTestCoverageCollectGCOV`; Meson has the `b_coverage` option. 7. **Test repetition controls.** CTest offers `--repeat until-fail|after-timeout|until-pass`, diff --git a/include/Void/Build/Report/Coverage.hpp b/include/Void/Build/Report/Coverage.hpp new file mode 100644 index 0000000..d859096 --- /dev/null +++ b/include/Void/Build/Report/Coverage.hpp @@ -0,0 +1,32 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +namespace Void::Build::Report { + +struct CoverageSummary { + std::size_t files{0}; + std::size_t lines_found{0}; + std::size_t lines_hit{0}; +}; + +// Every `.gcda` profile data file under `root` (e.g. a profile build directory). +[[nodiscard]] std::vector +collect_gcda_files(const std::filesystem::path &root); + +// Converts gcov data into `output_dir/coverage.info` (lcov) and `output_dir/summary.txt`. +// Requires the `gcov` executable (part of the GCC/Clang toolchain); when `source_root` is +// non-empty only sources below it are reported (system headers are dropped). +[[nodiscard]] Void::Result::Result +write_coverage_report(const std::vector &gcda_files, + const std::filesystem::path &output_dir, + const std::filesystem::path &source_root = {}, + const std::string &gcov_executable = "gcov"); + +} // namespace Void::Build::Report diff --git a/src/Main.cpp b/src/Main.cpp index 7af397c..e3e98e6 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -395,6 +396,7 @@ struct BuildCmdOptions { std::optional target_os_arg; std::optional target_arch_arg; std::optional junit_arg; + std::optional coverage_arg; std::optional cdash_arg; std::optional cdash_project_arg; std::optional cdash_build_arg; @@ -543,6 +545,12 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { std::cerr << "vbs: " << ex.what() << '\n'; return 2; } + if (opts.coverage_arg) { + // Instrument every compile and link so gcov data is produced when tests run. + // (GCC and Clang both accept --coverage.) + ctx.compile_options.push_back("--coverage"); + ctx.link_options.push_back("--coverage"); + } auto tc = Toolchain::discover_and_probe(ctx, build_root / ".vbs" / "probes"); if (!tc) { @@ -1102,6 +1110,27 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { } } + // lcov coverage report from the gcov data produced by the instrumented test binaries. + if (run_tests && opts.coverage_arg) { + const auto gcda = Report::collect_gcda_files(build_root); + std::error_code cov_ec; + const auto source_root = std::filesystem::weakly_canonical(project_root, cov_ec); + auto cov = Report::write_coverage_report(gcda, *opts.coverage_arg, source_root); + if (!cov) { + std::cerr << "vbs test: " << cov.error().message() << '\n'; + all_ok = false; + } else { + const double percent = + cov->lines_found == 0 + ? 0.0 + : 100.0 * static_cast(cov->lines_hit) / + static_cast(cov->lines_found); + 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()); + } + } + // JUnit XML report for CI systems (aggregated across selected profiles). if (opts.junit_arg && !opts.junit_arg->empty() && !test_records.empty()) { const auto xml_escape = [](std::string_view text) { @@ -3636,6 +3665,8 @@ int main(int argc, char **argv) { .option_default("--test-timeout", "", "Per-test timeout in seconds (1..86400)", build_opts.test_timeout_arg, "300") .option("--junit", "", "Write a JUnit XML report of test results", build_opts.junit_arg) + .option("--coverage", "", "Build with --coverage and write an lcov report to this directory", + build_opts.coverage_arg) .option("--cdash", "", "Upload a CDash test report to this base URL", build_opts.cdash_arg) .option("--cdash-project", "", "CDash project name (default: project directory name)", diff --git a/src/Report/Coverage.cpp b/src/Report/Coverage.cpp new file mode 100644 index 0000000..1a58b02 --- /dev/null +++ b/src/Report/Coverage.cpp @@ -0,0 +1,194 @@ +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace Void::Build::Report { +namespace { + +using JsonVal = Void::Json::Strict::Value; + +Void::Result::Error make_error(std::string msg) { + return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument, + std::move(msg)); +} + +const JsonVal *find_key(const JsonVal::Object &object, std::string_view key) { + const auto it = object.find(std::string{key}); + return it == object.end() ? nullptr : &it->second; +} + +} // namespace + +std::vector collect_gcda_files(const std::filesystem::path &root) { + std::vector files; + std::error_code ec; + if (!std::filesystem::is_directory(root, ec)) { + return files; + } + // Per-entry errors (dangling symlinks, unreadable dirs) must not abort the walk: a fresh + // build tree can contain them while it is still being populated. + try { + for (const auto &entry : std::filesystem::recursive_directory_iterator( + root, std::filesystem::directory_options::skip_permission_denied)) { + std::error_code entry_ec; + if (entry.is_regular_file(entry_ec) && !entry_ec && + entry.path().extension() == ".gcda") { + files.push_back(entry.path()); + } + } + } catch (const std::filesystem::filesystem_error &) { + // Keep whatever was collected before the unreadable subtree. + } + std::ranges::sort(files); + return files; +} + +Void::Result::Result +write_coverage_report(const std::vector &gcda_files, + const std::filesystem::path &output_dir, + const std::filesystem::path &source_root, + const std::string &gcov_executable) { + std::error_code ec; + std::filesystem::create_directories(output_dir, ec); + if (ec) { + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(ec.value()), + std::format("cannot create coverage directory '{}': {}", output_dir.string(), + ec.message()), + ec.value())}; + } + if (gcda_files.empty()) { + return std::unexpected{make_error("no .gcda coverage data was produced")}; + } + + // Source path -> line -> execution count (max across translation units that include it). + std::map, std::less<>> coverage; + for (const auto &gcda : gcda_files) { + Platform::ProcessRequest req; + req.executable = gcov_executable; + req.arguments = {"--json-format", "--stdout", gcda.filename().string()}; + req.working_directory = gcda.parent_path(); + req.timeout = std::chrono::seconds{60}; + auto res = Platform::run_supervised(req); + if (!res || !res->succeeded()) { + return std::unexpected{make_error(std::format( + "gcov failed for '{}': {}", gcda.string(), + res ? res->stderr_data : res.error().message()))}; + } + auto parsed = Void::Json::Strict::parse(res->stdout_data); + if (!parsed) { + return std::unexpected{make_error( + std::format("gcov produced invalid JSON for '{}'", gcda.string()))}; + } + const auto *root = std::get_if(&parsed->value); + if (root == nullptr) { + continue; + } + std::filesystem::path cwd; + if (const auto *cwd_v = find_key(*root, "current_working_directory")) { + if (const auto *text = std::get_if(&cwd_v->value)) { + cwd = *text; + } + } + const auto *files_v = find_key(*root, "files"); + const auto *files = files_v ? std::get_if(&files_v->value) : nullptr; + if (files == nullptr) { + continue; + } + for (const auto &file_entry : *files) { + const auto *file_obj = std::get_if(&file_entry.value); + if (file_obj == nullptr) { + continue; + } + const auto *path_v = find_key(*file_obj, "file"); + const auto *path_text = path_v ? std::get_if(&path_v->value) : nullptr; + if (path_text == nullptr) { + continue; + } + std::filesystem::path source{*path_text}; + if (source.is_relative()) { + source = (cwd / source).lexically_normal(); + } + if (!source_root.empty() && !Platform::path_is_within(source_root, source)) { + continue; + } + const auto *lines_v = find_key(*file_obj, "lines"); + const auto *lines = lines_v ? std::get_if(&lines_v->value) : nullptr; + if (lines == nullptr) { + continue; + } + auto &entry = coverage[source.string()]; + for (const auto &line_entry : *lines) { + const auto *line_obj = std::get_if(&line_entry.value); + if (line_obj == nullptr) { + continue; + } + std::int64_t number = 0; + std::int64_t count = 0; + if (const auto *number_v = find_key(*line_obj, "line_number")) { + if (const auto *value = std::get_if(&number_v->value)) { + number = *value; + } + } + if (const auto *count_v = find_key(*line_obj, "count")) { + if (const auto *value = std::get_if(&count_v->value)) { + count = *value; + } + } + if (number <= 0) { + continue; + } + auto &slot = entry[number]; + slot = std::max(slot, count); + } + } + } + + CoverageSummary summary; + std::string lcov; + for (auto &[path, lines] : coverage) { + if (lines.empty()) { + continue; + } + ++summary.files; + std::size_t hit = 0; + lcov += "TN:\nSF:" + path + '\n'; + for (const auto &[number, count] : lines) { + lcov += std::format("DA:{},{}\n", number, count); + if (count > 0) { + ++hit; + } + } + lcov += std::format("LF:{}\nLH:{}\nend_of_record\n", lines.size(), hit); + summary.lines_found += lines.size(); + summary.lines_hit += hit; + } + + if (auto written = Platform::atomic_write_file(output_dir / "coverage.info", lcov, true); + !written) { + return std::unexpected{written.error()}; + } + const double percent = + summary.lines_found == 0 + ? 0.0 + : 100.0 * static_cast(summary.lines_hit) / + static_cast(summary.lines_found); + const std::string summary_text = + std::format("Coverage: {:.1f}% ({}/{} lines) across {} file(s)\n", percent, + summary.lines_hit, summary.lines_found, summary.files); + if (auto written = Platform::atomic_write_file(output_dir / "summary.txt", summary_text, true); + !written) { + return std::unexpected{written.error()}; + } + return summary; +} + +} // namespace Void::Build::Report diff --git a/tests/FullV1Tests.cpp b/tests/FullV1Tests.cpp index 032599c..d8fa1bb 100644 --- a/tests/FullV1Tests.cpp +++ b/tests/FullV1Tests.cpp @@ -2719,6 +2719,61 @@ void build(Void::Build::Project &p) { } } +// === Coverage reporting (vbs test --coverage) === +VOID_TEST(FullV1Tests, test_coverage_writes_lcov_and_summary) { + if (!Platform::resolve_executable("gcov")) { + return; // gcov ships with GCC/Clang; skip if the toolchain lacks it. + } + 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_coverage_"}; + const auto proj = tmp / "proj"; + const auto bdir = tmp / "build"; + const auto report = tmp / "coverage"; + write_file(proj / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { + auto lib = p.static_library("covlib"); + lib.cxx_standard(Void::Build::CxxStandard::Cxx26).sources({"src/calc.cpp"}); + p.test("cov_tests") + .cxx_standard(Void::Build::CxxStandard::Cxx26) + .sources({"tests/main.cpp"}) + .link(lib); +} +)cpp"); + write_file(proj / "src" / "calc.cpp", + "int add(int a, int b) { return a + b; }\n" + "int never_called(int a) { return a * 2; }\n"); + write_file(proj / "tests" / "main.cpp", + "int add(int, int);\nint main() { return add(1, 2) == 3 ? 0 : 1; }\n"); + + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = {"test", "--project", proj.string(), "--build-dir", bdir.string(), + "--coverage", report.string()}; + req.timeout = std::chrono::seconds{300}; + auto res = Platform::run_supervised(req); + Void::Testing::expect(res.has_value() && res->succeeded()); + if (res && !res->succeeded()) { + std::fprintf(stderr, "%s\n", (res->stdout_data + res->stderr_data).c_str()); + } + auto info = Void::FileSystem::read_file(report / "coverage.info"); + Void::Testing::require(info.has_value()); + Void::Testing::expect(info->find("SF:") != std::string::npos); + Void::Testing::expect(info->find("calc.cpp") != std::string::npos); + Void::Testing::expect(info->find("main.cpp") != std::string::npos); + // add() is executed, never_called() is not. + Void::Testing::expect(info->find("DA:1,1") != std::string::npos); + Void::Testing::expect(info->find("DA:2,0") != std::string::npos); + Void::Testing::expect(info->find("end_of_record") != std::string::npos); + auto summary = Void::FileSystem::read_file(report / "summary.txt"); + Void::Testing::require(summary.has_value()); + Void::Testing::expect(summary->starts_with("Coverage: ")); + Void::Testing::expect(summary->find("%") != std::string::npos); +} + // === Track A1: Native VBS subproject dependency (builder == "native", zero CMake!) === VOID_TEST(FullV1Tests, native_vbs_subproject_dependency_builds_without_cmake) { const auto vbs_bin = locate_vbs_binary();