From d2699c430ed1245967bc828a7d127c210cb542e4 Mon Sep 17 00:00:00 2001 From: Yohann CATHERINE Date: Wed, 2 Dec 2026 16:59:15 +0100 Subject: [PATCH] feat(cpp): GoogleTest, Catch2, doctest and CTest results in the test tree (#7538) C++ test executables ran as plain applications and CTest as one block of console output, so no test appeared in the test tree. CMake detection now marks an executable whose sources include GoogleTest, Catch2 v3 or doctest as a test configuration, and CTest as one too. Their output fills the test tree with each failure's message and location. GoogleTest, Catch2 and doctest test declarations get gutter icons that run one test through the framework's filter. Co-authored-by: yohannlog <8901733+yohannlog@users.noreply.github.com> --- crates/ide-run/src/detect/cmake/mod.rs | 78 +++++++ docs/en/languages/cpp.mdx | 11 +- docs/zh/languages/cpp.mdx | 11 +- src/features/run/producers.test.ts | 29 +++ src/features/run/producers.ts | 42 +++- src/features/run/store.ts | 2 +- src/features/run/testing/cpp.test.ts | 290 ++++++++++++++++++++++++ src/features/run/testing/cpp.ts | 301 +++++++++++++++++++++++++ src/features/run/testing/index.ts | 15 +- 9 files changed, 770 insertions(+), 9 deletions(-) create mode 100644 src/features/run/testing/cpp.test.ts create mode 100644 src/features/run/testing/cpp.ts diff --git a/crates/ide-run/src/detect/cmake/mod.rs b/crates/ide-run/src/detect/cmake/mod.rs index c889f4f44..222375c0d 100644 --- a/crates/ide-run/src/detect/cmake/mod.rs +++ b/crates/ide-run/src/detect/cmake/mod.rs @@ -141,6 +141,7 @@ fn detect_configs(root: &Path, profiles: Option<&[CMakeProfile]>, out: &mut Vec< &["--test-dir", &dir, "-C", &configuration, "--output-on-failure"], ); before(&mut test, &build_id); + mark_ctest(&mut test); names.push(out, test, &dir, ""); targets(root, &build, &dir, &prefix, None, out, names); } @@ -202,6 +203,7 @@ fn detect_profile(root: &Path, profile: &CMakeProfile, out: &mut Vec, }; test.args.push("--output-on-failure".into()); before(&mut test, &build_id); + mark_ctest(&mut test); names.push(out, test, &dir, &profile.name); targets(root, &build, &dir, prefix, Some(profile), out, names); for config in &mut out[start..] { @@ -370,6 +372,11 @@ fn targets( before(&mut run, &target_build_id); let sources: Vec = target.sources.iter().map(|s| canonical_root.join(s).to_string_lossy().replace('\\', "/")).collect(); + // CLion's Google Test / Catch / Doctest configurations: a test executable's results fill the test tree. + if let Some(framework) = test_framework(&canonical_root, &target.sources) { + run = run.test(); + run.extras.test_runner = Some(framework.into()); + } run.extras.params.insert("cmakeSources".into(), sources.join("\n")); if let Some(recorded) = &model.source { run.extras.params.insert("cmakeSourceRoot".into(), recorded.to_string_lossy().into_owned()); @@ -382,6 +389,54 @@ fn targets( } } +/// CTest reports each test it runs: its results fill the test tree. +fn mark_ctest(config: &mut RunConfig) { + config.is_test = true; + config.extras.test_runner = Some("ctest".into()); +} + +/// Bytes of each source read to find its test framework (the includes come first). +const TEST_SCAN_BYTES: u64 = 16 * 1024; + +/// The test framework a C++ executable is written with, from the headers its sources include: +/// `gtest` (GoogleTest / GoogleMock), `catch2` (Catch2 v3, whose TeamCity reporter the IDE +/// reads), `doctest`. Catch2 v2 (`catch.hpp`) has no reporter the IDE can read, so its tests +/// run as a plain application. +pub fn test_framework(root: &Path, sources: &[String]) -> Option<&'static str> { + use std::io::Read; + for source in sources { + if !source.rsplit_once('.').is_some_and(|(_, ext)| matches!(ext, "cpp" | "cc" | "cxx" | "c++" | "cu")) { + continue; + } + let Ok(file) = fs::File::open(root.join(source)) else { continue }; + let mut head = Vec::new(); + if file.take(TEST_SCAN_BYTES).read_to_end(&mut head).is_err() { + continue; + } + for line in String::from_utf8_lossy(&head).lines() { + let Some(include) = line.trim_start().strip_prefix('#').map(str::trim_start) else { continue }; + let Some(header) = include.strip_prefix("include") else { continue }; + // The name between `<>` or `""`, without a trailing comment. + let header = header.trim_start(); + let header = match header.chars().next() { + Some('<') => header[1..].split('>').next().unwrap_or_default(), + Some('"') => header[1..].split('"').next().unwrap_or_default(), + _ => continue, + }; + if header.starts_with("gtest/") || header.starts_with("gmock/") { + return Some("gtest"); + } + if header.starts_with("catch2/catch_") { + return Some("catch2"); + } + if header.ends_with("doctest.h") || header.ends_with("doctest.hpp") { + return Some("doctest"); + } + } + } + None +} + /// Ordered configure/build commands for a CMake build configuration. Executables and CTest /// are never executed by Build; only their explicit build prerequisites are accepted. pub fn build_configs(configs: &[RunConfig], id: &str) -> crate::IdeResult> { @@ -723,4 +778,27 @@ mod tests { assert_eq!(core.extras.params["cmakeTargetKind"], "STATIC_LIBRARY"); assert_eq!(build_configs(&configs, &core.id).unwrap().last().unwrap().id, core.id); } + + #[test] + fn test_executables_are_recognised_by_the_headers_their_sources_include() { + let root = tempfile::tempdir().unwrap(); + let write = |name: &str, text: &str| fs::write(root.path().join(name), text).unwrap(); + write("gt.cpp", "// tests\n#include \n# include \"gtest/gtest.h\"\nTEST(A, B) {}\n"); + write("mock.cc", "#include \n"); + write("c3.cpp", "#include \n"); + write("c2.cpp", "#include \"catch2/catch.hpp\"\n"); + write("dt.cpp", "#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN\n#include \"doctest.h\" // single header\n"); + write("app.cpp", "#include \nint main() {}\n"); + write("gtest.h", "#include \n"); + let found = |sources: &[&str]| { + test_framework(root.path(), &sources.iter().map(|s| (*s).to_owned()).collect::>()) + }; + assert_eq!(found(&["app.cpp", "gt.cpp"]), Some("gtest")); + assert_eq!(found(&["mock.cc"]), Some("gtest")); + assert_eq!(found(&["c3.cpp"]), Some("catch2")); + assert_eq!(found(&["c2.cpp"]), None, "Catch2 v2 has no reporter the IDE reads"); + assert_eq!(found(&["dt.cpp"]), Some("doctest")); + assert_eq!(found(&["app.cpp", "missing.cpp"]), None); + assert_eq!(found(&["gtest.h"]), None, "headers are not compiled sources"); + } } diff --git a/docs/en/languages/cpp.mdx b/docs/en/languages/cpp.mdx index 087275ea5..eeb67c99d 100644 --- a/docs/en/languages/cpp.mdx +++ b/docs/en/languages/cpp.mdx @@ -77,7 +77,7 @@ For every `CMakeLists.txt` project, OpenIDEA creates run configurations: - **CMake Configure**: `cmake -S . -B -DCMAKE_EXPORT_COMPILE_COMMANDS=ON` (plus `-DCMAKE_BUILD_TYPE=Debug` for a new build directory). - **CMake Build**: `cmake --build `. It runs the configure step first when the build directory is not configured yet. -- **CTest**: `ctest --test-dir --output-on-failure`, after a build. +- **CTest**: `ctest --test-dir --output-on-failure`, after a build. Each test CTest runs is listed in the test tree, with the output of a failed test. - **Build <target>** for every executable and library target (static, shared, module or object), and one run configuration per executable target. Running a target builds it first. The targets come from CMake's File API, so they appear after the first configure. Interface libraries, utility targets (such as Qt's `*_autogen`) and the targets CMake adds itself (`ZERO_CHECK`, `ALL_BUILD`) get no configuration. Nested CMake projects (for example in a folder that holds several repositories) get their own set of configurations. @@ -124,6 +124,12 @@ The IDE follows `include`, `inherits` and conditions (`equals`, `inList`, `match Each tool can be set: **CMake** (configure, build, and the `ctest` next to it), **Build Tool** (`CMAKE_MAKE_PROGRAM`), **C Compiler** and **C++ Compiler** (`CMAKE_C_COMPILER`, `CMAKE_CXX_COMPILER`), and **Debugger** (preferred over lldb-dap for the profile's run configurations). Under each one the page shows the executable it resolves to and its version. A toolchain never overrides what the profile sets itself: a variable among its CMake options or its preset's `cacheVariables`, the compilers and build tool when it names a toolchain file, and the build tool when its generator cannot use it (Visual Studio, Xcode, or Ninja with a make). +#### Test executables + +An executable target whose sources include GoogleTest (`gtest/…`, `gmock/…`), Catch2 v3 (`catch2/catch_…`) or doctest is a test configuration: running it lists its tests in the test tree, with each failure's message and location. Catch2 runs with `--reporter teamcity` and doctest with `--duration=true` so each test is reported, unless the configuration chooses its own reporter or duration option. + +In a source of a test executable, `TEST`, `TEST_F`, `TEST_P`, `TYPED_TEST`, `TEST_CASE`, `SCENARIO` and `TEST_CASE_METHOD` get a gutter run icon. It runs that test only (`--gtest_filter`, a Catch2 test spec, doctest's `--test-case`) and turns green or red with its last result. + ### Makefiles A `Makefile`, `makefile` or `GNUmakefile` gives one `make ` configuration per target. `test` and `check` targets are marked as tests. @@ -158,6 +164,5 @@ There are no upload or serial monitor actions for Arduino. - C and C++ code intelligence is only as good as clangd's compile flags. Without a `compile_commands.json` or `compile_flags.txt`, expect false errors. - The IDE does not generate a compilation database for Make, Meson or other build systems. -- CTest runs as a single configuration and shows its console output; individual tests are not listed in a test tree. -- There are no gutter run icons for C and C++ test frameworks (GoogleTest, Catch2 and so on). +- Catch2 v2 (`catch.hpp`) and Boost.Test executables run as plain applications: their tests are not listed in a test tree. - lldb-dap and GDB are not installed by the IDE. diff --git a/docs/zh/languages/cpp.mdx b/docs/zh/languages/cpp.mdx index 404004c2b..e204ed9b3 100644 --- a/docs/zh/languages/cpp.mdx +++ b/docs/zh/languages/cpp.mdx @@ -77,7 +77,7 @@ Xcode 和 Command Line Tools 自带的 `clangd` 不运行 clang-tidy。如果项 - **CMake Configure**:`cmake -S . -B <构建目录> -DCMAKE_EXPORT_COMPILE_COMMANDS=ON`(新构建目录还会加上 `-DCMAKE_BUILD_TYPE=Debug`)。 - **CMake Build**:`cmake --build <构建目录>`,构建目录尚未配置时会先执行配置步骤。 -- **CTest**:先构建,再执行 `ctest --test-dir <构建目录> --output-on-failure`。 +- **CTest**:先构建,再执行 `ctest --test-dir <构建目录> --output-on-failure`。CTest 运行的每个测试都会列在测试树中,失败的测试附带其输出。 - **Build <目标>**:每个可执行目标和库目标(静态库、共享库、模块库、对象库)各一个;另外每个可执行目标还有一个运行配置。运行目标前会先构建它。 目标来自 CMake 的 File API,因此要在第一次配置之后才会出现。接口库、工具目标(例如 Qt 的 `*_autogen`)以及 CMake 自己添加的目标(`ZERO_CHECK`、`ALL_BUILD`)不会生成配置。嵌套的 CMake 项目(例如一个文件夹里放了多个仓库)各自生成一套配置。 @@ -124,6 +124,12 @@ IDE 支持 `include`、`inherits` 和各种条件(`equals`、`inList`、`match 每个工具都可以单独设置:**CMake**(用于配置、构建,以及同目录下的 `ctest`)、**构建工具**(`CMAKE_MAKE_PROGRAM`)、**C 编译器**和 **C++ 编译器**(`CMAKE_C_COMPILER`、`CMAKE_CXX_COMPILER`),以及**调试器**(该配置的运行配置会优先使用它,而不是 lldb-dap)。页面会在每个工具下方显示解析到的可执行文件及其版本。工具链不会覆盖配置自身设置的内容:其 CMake 选项或预设 `cacheVariables` 中的变量;配置指定了工具链文件时的编译器和构建工具;以及生成器无法使用该构建工具时的构建工具(Visual Studio、Xcode,或 Ninja 搭配 make)。 +#### 测试可执行文件 + +源文件包含 GoogleTest(`gtest/…`、`gmock/…`)、Catch2 v3(`catch2/catch_…`)或 doctest 的可执行目标会作为测试配置:运行后在测试树中列出其中的测试,附带每个失败的消息和位置。Catch2 以 `--reporter teamcity` 运行,doctest 以 `--duration=true` 运行,以便逐个报告测试;配置自己指定了报告器或 duration 选项时除外。 + +在测试可执行文件的源文件中,`TEST`、`TEST_F`、`TEST_P`、`TYPED_TEST`、`TEST_CASE`、`SCENARIO` 和 `TEST_CASE_METHOD` 旁边会显示行号栏运行图标,只运行该测试(`--gtest_filter`、Catch2 测试规格、doctest 的 `--test-case`),并按最近一次结果显示为绿色或红色。 + ### Makefile `Makefile`、`makefile` 或 `GNUmakefile` 中的每个目标都会生成一个 `make <目标>` 配置,其中 `test` 和 `check` 目标标记为测试。 @@ -158,6 +164,5 @@ IDE 支持 `include`、`inherits` 和各种条件(`equals`、`inList`、`match - C/C++ 代码智能的质量取决于 clangd 拿到的编译参数。没有 `compile_commands.json` 或 `compile_flags.txt` 时会有误报。 - IDE 不会为 Make、Meson 等构建系统生成编译数据库。 -- CTest 作为一个整体配置运行,只显示控制台输出,不会在测试树中列出单个测试。 -- 没有针对 C/C++ 测试框架(GoogleTest、Catch2 等)的行号栏运行图标。 +- Catch2 v2(`catch.hpp`)和 Boost.Test 的可执行文件按普通应用运行,其中的测试不会列在测试树中。 - lldb-dap 和 GDB 不由 IDE 安装。 diff --git a/src/features/run/producers.test.ts b/src/features/run/producers.test.ts index 8a3800c88..94806799e 100644 --- a/src/features/run/producers.test.ts +++ b/src/features/run/producers.test.ts @@ -1565,6 +1565,35 @@ describe("CMake file context", () => { produceContextChoices({ ...input, configs: [configure, native, second] }, OPTIMISTIC).map((p) => p.config?.id), ).toEqual([native.id, second.id]); }); + it("puts gutter tests on a test executable's sources and runs one test with its filter", () => { + const tests = cfg({ + ...native, + id: "cmake:profile:target:unit", + name: "unit", + isTest: true, + testRunner: "gtest", + params: { cmakeSources: "test/math_test.cpp" }, + }); + const content = "#include \n\nTEST(Math, Adds) {\n EXPECT_EQ(2, 1 + 1);\n}\n"; + const testInput = { ...input, path: "/p/test/math_test.cpp", configs: [configure, native, tests], content }; + expect(fileTargets(testInput, content)).toEqual([ + { line: 2, kind: "test", name: "Math.Adds", path: ["Math", "Adds"] }, + ]); + // Not built into a test executable: no test icons. + expect(fileTargets({ ...testInput, configs: [configure, native] }, content)).toEqual([]); + const p = produceContext({ ...testInput, line: 3 }, OPTIMISTIC); + expect(p?.scope).toBe("element"); + expect(p?.config).toMatchObject({ + id: "context:target:cmake:profile:target:unit:test/math_test.cpp:Math/Adds", + name: "Math.Adds", + command: "/p/build/app", + args: ["--gtest_filter=Math.Adds"], + testRunner: "gtest", + isTest: true, + }); + // The whole file: the executable with every test. + expect(produceFile({ ...testInput, line: undefined }, OPTIMISTIC)?.config).toEqual(tests); + }); it("never compiles a CMake source as a standalone file when the target is unknown", () => { const p = produceContext({ ...input, configs: [configure] }, OPTIMISTIC); expect(p?.config).toBeUndefined(); diff --git a/src/features/run/producers.ts b/src/features/run/producers.ts index f7babc877..480ed7153 100644 --- a/src/features/run/producers.ts +++ b/src/features/run/producers.ts @@ -38,6 +38,7 @@ import { isWindows } from "./jvmTypes"; import { inheritedRunTargets } from "./inheritedMain"; import { withMavenTests } from "./mavenTests"; import { escapeRegExp } from "./testing/rerun"; +import { CPP_FRAMEWORKS, cppTestDeclarations, cppTestFilter, type CppFramework } from "./testing/cpp"; import { detectRunTargets, goFuzzConfig, @@ -1183,7 +1184,14 @@ export function fileTargets( input = scopedInput(input); const s = { inProject: isProjectPath(input), rel: relTo(input.path, input.root) }; const rust = /\.rs$/.test(input.path); - if (/\.(c|cpp|cc|cxx)$/.test(input.path)) return standaloneTargets(content, input.path); + if (/\.(c|cpp|cc|cxx)$/.test(input.path)) { + // Tests of a CMake test executable built from this file (GoogleTest, Catch2, doctest). + const tests = s.inProject && cppTestExecutable(input) ? cppTestDeclarations(content) : []; + return [ + ...standaloneTargets(content, input.path), + ...tests.map((t): RunTarget => ({ line: t.line, kind: "test", name: t.path.join("."), path: t.path })), + ]; + } if (/\.zig$/.test(input.path)) return zigTargets(content); if (/\.swift$/.test(input.path)) return s.inProject && swiftPackageDir(s.rel) !== null ? swiftTargets(content) : []; const cargo = @@ -1238,6 +1246,7 @@ function elementProduction(input: ContextInput, env: ToolEnv, target: RunTarget) return compiled(input, env, s, "rust", { name, filter }); } if (!s.inProject) return null; + if (/\.(c|cpp|cc|cxx)$/.test(input.path)) return cppTestProduction(input, rel, target); const found = targetConfig(target, rel, [...input.configs], input.content); const config = found && goTestNamed(found, input, target.name); return config ? { name: config.name, scope: "element", config } : null; @@ -1305,6 +1314,37 @@ export function produceContextChoices(input: ContextInput, env: ToolEnv): Produc return out.length > 1 ? out : [produced]; } +/** The CMake test executable (GoogleTest, Catch2, doctest) built from the file of `input`. */ +function cppTestExecutable(input: Pick): RunConfig | null { + if (!isProjectPath(input)) return null; + const rel = relTo(input.path, input.root); + return ( + input.configs.find( + (c) => + c.testRunner && + c.testRunner !== "ctest" && + CPP_FRAMEWORKS.has(c.testRunner) && + c.params?.cmakeSources?.split("\n").some((p) => p === rel || p === input.path), + ) ?? null + ); +} + +/** One test (gutter, ⌃⇧R) of a C / C++ test executable: the executable with its framework's filter. */ +function cppTestProduction(input: ContextInput, rel: string, target: RunTarget): Produced | null { + const exe = cppTestExecutable(input); + const test = exe && cppTestDeclarations(input.content ?? "").find((t) => t.line === target.line); + if (!exe || !test) return null; + const config: RunConfig = { + ...exe, + id: `context:target:${exe.id}:${rel}:${test.path.join("/")}`, + name: target.name, + args: [...exe.args, ...cppTestFilter(exe.testRunner as CppFramework, test)], + env: { ...exe.env }, + detected: true, + }; + return { name: config.name, scope: "element", config }; +} + function cmakeTargets(input: ContextInput): RunConfig[] { if (!isProjectPath(input)) return []; const lang = scriptLanguage(input.path, input.content); diff --git a/src/features/run/store.ts b/src/features/run/store.ts index c4b036918..970341895 100644 --- a/src/features/run/store.ts +++ b/src/features/run/store.ts @@ -832,7 +832,7 @@ function newRuntime(config: RunConfig): SessionRuntime { const stdout = framework === "go" ? new GoTestOutput(feed) - : framework === "phpunit" || framework === "jvm" || framework === "cypress" // Cypress: its `teamcity` reporter + : framework === "phpunit" || framework === "jvm" || framework === "cypress" || framework === "catch2" // Cypress, Catch2: their `teamcity` reporter ? new TeamcityOutput(feed, framework !== "phpunit") : framework === "ruby" && config.kind !== "rspec" ? new RubyTestOutput(feed) diff --git a/src/features/run/testing/cpp.test.ts b/src/features/run/testing/cpp.test.ts new file mode 100644 index 000000000..b2ac89eb7 --- /dev/null +++ b/src/features/run/testing/cpp.test.ts @@ -0,0 +1,290 @@ +import { describe, expect, it } from "vitest"; +import { TestResults, nodeStatus } from "./results"; +import { createTestParser, frameworkFor, parseAll, withTestReporting } from "./index"; +import { cppTestDeclarations, cppTestFilter, type CppFramework } from "./cpp"; +import type { TestEvent } from "./types"; + +// Output captured from GoogleTest 1.15, Catch2 3.7 and doctest 2.4 test executables, and CTest 3.28. +const GTEST = `Running main() from /tmp/cpptests/build/_deps/googletest-src/googletest/src/gtest_main.cc +[==========] Running 6 tests from 3 test suites. +[----------] Global test environment set-up. +[----------] 3 tests from Math +[ RUN ] Math.Adds +[ OK ] Math.Adds (0 ms) +[ RUN ] Math.Fails +/tmp/cpptests/gt.cpp:3: Failure +Expected equality of these values: + 1 + 1 + Which is: 2 + 3 +custom message + +[ FAILED ] Math.Fails (0 ms) +[ RUN ] Math.Skips +/tmp/cpptests/gt.cpp:4: Skipped +not now + +[ SKIPPED ] Math.Skips (0 ms) +[----------] 3 tests from Math (0 ms total) + +[----------] 1 test from Fix +[ RUN ] Fix.Works +[ OK ] Fix.Works (12 ms) +[----------] 1 test from Fix (0 ms total) + +[----------] 2 tests from Nums/P +[ RUN ] Nums/P.Even/0 +[ OK ] Nums/P.Even/0 (0 ms) +[ RUN ] Nums/P.Even/1 +/tmp/cpptests/gt.cpp:8: Failure +Expected equality of these values: + GetParam() % 2 + Which is: 1 + 0 + +[ FAILED ] Nums/P.Even/1, where GetParam() = 3 (0 ms) +[----------] 2 tests from Nums/P (0 ms total) + +[----------] Global test environment tear-down +[==========] 6 tests from 3 test suites ran. (0 ms total) +[ PASSED ] 3 tests. +[ SKIPPED ] 1 test, listed below: +[ SKIPPED ] Math.Skips +[ FAILED ] 2 tests, listed below: +[ FAILED ] Math.Fails +[ FAILED ] Nums/P.Even/1, where GetParam() = 3 + + 2 FAILED TESTS`; + +const CATCH2 = `##teamcity[testSuiteStarted name='c2'] +##teamcity[testStarted name='adds numbers'] +##teamcity[testFinished name='adds numbers' duration='0'] +##teamcity[testStarted name='fails here'] +##teamcity[testFailed name='fails here' message='/tmp/cpptests/c2.cpp:4|n...............................................................................|n|n/tmp/cpptests/c2.cpp:4|nexpression failed|n CHECK( a == 2 )|nwith expansion:|n 1 == 2|n'] +##teamcity[testFinished name='fails here' duration='0'] +##teamcity[testStarted name='with sections'] +##teamcity[testFailed name='with sections' message='-------------------------------------------------------------------------------|nsecond|n-------------------------------------------------------------------------------|n/tmp/cpptests/c2.cpp:5|n...............................................................................|n|n/tmp/cpptests/c2.cpp:7|nexpression failed|n REQUIRE( false )|nwith expansion:|n false|n'] +##teamcity[testStdOut name='with sections' out='hello|n'] +##teamcity[testFinished name='with sections' duration='0'] +##teamcity[testStarted name='skipped'] +##teamcity[testIgnored name='skipped' message='/tmp/cpptests/c2.cpp:9|n...............................................................................|n|n/tmp/cpptests/c2.cpp:9|nexplicit skip with message:|n "later"'] +##teamcity[testFinished name='skipped' duration='0'] +##teamcity[testSuiteFinished name='c2']`; + +const DOCTEST = `[doctest] doctest version is "2.4.11" +[doctest] run with "--help" for options +=============================================================================== +/tmp/cpptests/dt.cpp:3: +TEST CASE: dt adds + +0.000006 s: dt adds +=============================================================================== +/tmp/cpptests/dt.cpp:4: +TEST CASE: dt fails + +/tmp/cpptests/dt.cpp:4: ERROR: CHECK( 1 + 1 == 3 ) is NOT correct! + values: CHECK( 2 == 3 ) + +0.000074 s: dt fails +=============================================================================== +/tmp/cpptests/dt.cpp:5: +TEST SUITE: suite +TEST CASE: inner + +0.000003 s: inner +=============================================================================== +/tmp/cpptests/dt.cpp:6: +TEST CASE: dt sub + b + +/tmp/cpptests/dt.cpp:6: ERROR: CHECK( false ) is NOT correct! + values: CHECK( false ) + +=============================================================================== +/tmp/cpptests/dt.cpp:6: +TEST CASE: dt sub + +DEEPEST SUBCASE STACK REACHED (DIFFERENT FROM THE CURRENT ONE): + b + +0.000025 s: dt sub +=============================================================================== +[doctest] test cases: 4 | 2 passed | 2 failed | 1 skipped +[doctest] assertions: 5 | 3 passed | 2 failed | +[doctest] Status: FAILURE!`; + +const CTEST = `Test project /tmp/cpptests/build + Start 1: gt +1/3 Test #1: gt ...............................***Failed 0.00 sec +[ FAILED ] Math.Fails + Start 2: c2 +2/3 Test #2: c2 ............................... Passed 0.25 sec + Start 3: dt disabled +3/3 Test #3: dt disabled ......................***Not Run (Disabled) 0.00 sec + +67% tests passed, 1 tests failed out of 3 + +Total Test time (real) = 0.01 sec`; + +const run = (testRunner: CppFramework, text: string) => { + const parser = createTestParser({ kind: "cmake-application", command: "/b/t", args: [], testRunner }); + const events = parseAll(parser, text); + const results = new TestResults(); + results.apply(events); + return { events, results }; +}; + +const statuses = (results: TestResults) => { + const out: Record = {}; + const visit = (n: (typeof results.roots)[number]) => { + if (!n.children.length) out[n.path.join(" > ")] = nodeStatus(n) ?? "none"; + n.children.forEach(visit); + }; + results.roots.forEach(visit); + return out; +}; + +const locations = (events: TestEvent[]) => + events.flatMap((e) => + e.type === "location" ? [`${e.path.join(" > ")} @ ${e.location.path}:${e.location.line}`] : [], + ); + +describe("C++ test output", () => { + it("reads GoogleTest's console, leaving out the summary", () => { + const { events, results } = run("gtest", GTEST); + expect(statuses(results)).toEqual({ + "Math > Adds": "passed", + "Math > Fails": "failed", + "Math > Skips": "skipped", + "Fix > Works": "passed", + "Nums/P > Even/0": "passed", + "Nums/P > Even/1": "failed", + }); + expect(locations(events)).toEqual([ + "Math > Fails @ /tmp/cpptests/gt.cpp:3", + "Math > Skips @ /tmp/cpptests/gt.cpp:4", + "Nums/P > Even/1 @ /tmp/cpptests/gt.cpp:8", + ]); + const output = events.filter((e) => e.type === "output" && e.path.join(".") === "Math.Fails"); + expect(output.map((e) => (e.type === "output" ? e.line : ""))).toContain("custom message"); + expect(events).toContainEqual({ type: "result", path: ["Fix", "Works"], status: "passed", durationMs: 12 }); + }); + + it("fails a GoogleTest test the executable crashed in", () => { + const { results } = run("gtest", "[ RUN ] A.Crash\nSegmentation fault"); + expect(statuses(results)).toEqual({ "A > Crash": "failed" }); + }); + + it("reads Catch2's TeamCity reporter, at the failed assertion", () => { + const { events, results } = run("catch2", CATCH2); + expect(statuses(results)).toEqual({ + "c2 > adds numbers": "passed", + "c2 > fails here": "failed", + "c2 > with sections": "failed", + "c2 > skipped": "skipped", + }); + expect(locations(events)).toEqual([ + "c2 > fails here @ /tmp/cpptests/c2.cpp:4", + "c2 > with sections @ /tmp/cpptests/c2.cpp:7", + "c2 > skipped @ /tmp/cpptests/c2.cpp:9", + ]); + }); + + it("reads doctest's console with durations, a subcase failure failing its test case", () => { + const { events, results } = run("doctest", DOCTEST); + expect(statuses(results)).toEqual({ + "dt adds": "passed", + "dt fails": "failed", + "suite > inner": "passed", + "dt sub": "failed", + }); + expect(locations(events)).toEqual([ + "dt adds @ /tmp/cpptests/dt.cpp:3", + "dt fails @ /tmp/cpptests/dt.cpp:4", + "dt fails @ /tmp/cpptests/dt.cpp:4", + "suite > inner @ /tmp/cpptests/dt.cpp:5", + "dt sub @ /tmp/cpptests/dt.cpp:6", + "dt sub @ /tmp/cpptests/dt.cpp:6", + ]); + expect(events).toContainEqual({ type: "result", path: ["dt fails"], status: "failed", durationMs: 0.074 }); + }); + + it("reports doctest's tests at the end when durations are off", () => { + const text = DOCTEST.split("\n") + .filter((l) => !/^\d+(\.\d+)? s: /.test(l)) + .join("\n"); + expect(statuses(run("doctest", text).results)).toEqual({ + "dt adds": "passed", + "dt fails": "failed", + "suite > inner": "passed", + "dt sub": "failed", + }); + }); + + it("reads CTest's progress lines, with a failed test's output", () => { + const { events, results } = run("ctest", CTEST); + expect(statuses(results)).toEqual({ gt: "failed", c2: "passed", "dt disabled": "skipped" }); + expect(events).toContainEqual({ type: "output", path: ["gt"], line: "[ FAILED ] Math.Fails" }); + expect(events).toContainEqual({ type: "result", path: ["c2"], status: "passed", durationMs: 250 }); + }); +}); + +describe("C++ test launches", () => { + const config = (testRunner: string, args: string[] = []) => ({ + kind: "cmake-application", + command: "/b/t", + args, + testRunner, + }); + + it("takes the framework CMake detection recorded", () => { + for (const f of ["gtest", "catch2", "doctest", "ctest"]) expect(frameworkFor(config(f))).toBe(f); + expect(frameworkFor({ kind: "cmake-application", command: "/b/app", args: [] })).toBe("auto"); + }); + + it("asks Catch2 for its TeamCity reporter and doctest for durations, unless chosen", () => { + expect(withTestReporting(config("catch2")).args).toEqual(["--reporter", "teamcity"]); + expect(withTestReporting(config("catch2", ["-r", "junit"])).args).toEqual(["-r", "junit"]); + expect(withTestReporting(config("doctest", ["-tc=x"])).args).toEqual(["-tc=x", "--duration=true"]); + expect(withTestReporting(config("doctest", ["--duration=false"])).args).toEqual(["--duration=false"]); + expect(withTestReporting(config("gtest")).args).toEqual([]); + }); + + it("finds test declarations and filters a run to one of them", () => { + const src = [ + "#include ", + "TEST(Math, Adds) {}", + "TEST_F(Fix, Works) {", + "TEST_P(P, Even) {}", + "TYPED_TEST(Typed, Sorts) {}", + 'TEST_CASE("adds, numbers [fast]", "[math]") {}', + 'SCENARIO("vectors grow") {}', + 'TEST_CASE_METHOD(Fixture, "uses fixture") {}', + "// TEST(Not, Code) is still matched by line, like other languages' gutters", + ].join("\n"); + const decls = cppTestDeclarations(src); + expect(decls.map((d) => `${d.line}:${d.path.join(".")}`)).toEqual([ + "1:Math.Adds", + "2:Fix.Works", + "3:P.Even", + "4:Typed.Sorts", + "5:adds, numbers [fast]", + "6:Scenario: vectors grow", + "7:uses fixture", + ]); + const filter = (f: CppFramework, line: number) => + cppTestFilter( + f, + decls.find((d) => d.line === line)!, + ); + expect(filter("gtest", 1)).toEqual(["--gtest_filter=Math.Adds"]); + expect(filter("gtest", 3)).toEqual(["--gtest_filter=*P.Even/*"]); + expect(filter("gtest", 4)).toEqual(["--gtest_filter=Typed/*.Sorts"]); + expect(filter("catch2", 5)).toEqual(["adds\\, numbers \\[fast\\]"]); + expect(filter("doctest", 5)).toEqual(["--test-case=adds\\, numbers [fast]"]); + const more = cppTestDeclarations('TYPED_TEST_P(Stack, Push) {}\nTEMPLATE_TEST_CASE("vec", "[t]", int, float) {}'); + // Instances: `My/Stack/0.Push`, `vec - int`. + expect(cppTestFilter("gtest", more[0]!)).toEqual(["--gtest_filter=*/Stack/*.Push"]); + expect(cppTestFilter("catch2", more[1]!)).toEqual(["vec - *"]); + }); +}); diff --git a/src/features/run/testing/cpp.ts b/src/features/run/testing/cpp.ts new file mode 100644 index 000000000..61f230397 --- /dev/null +++ b/src/features/run/testing/cpp.ts @@ -0,0 +1,301 @@ +/** + * C / C++ test runners, as CLion's Google Test, Catch and Doctest configurations, and CTest: + * their console output (Catch2 v3: its TeamCity reporter) turned into test tree events. + */ +import { phpunitParser } from "./phpunit"; +import { serviceMessage } from "./teamcity"; +import type { TestEvent, TestLocation, TestOutputParser } from "./types"; + +export type CppFramework = "gtest" | "catch2" | "doctest" | "ctest"; + +export const CPP_FRAMEWORKS: ReadonlySet = new Set(["gtest", "catch2", "doctest", "ctest"]); + +/** `path:line` (GCC, Clang) or `path(line)` (MSVC) at the start of a line, then `rest`. */ +const SOURCE_AT = + /^((?:[A-Za-z]:)?[^:()]*?\.(?:c|cc|cpp|cxx|c\+\+|h|hh|hpp|hxx|ipp|tpp|inl|cu|m|mm))(?::(\d+)|\((\d+)\))/; + +function sourceAt(line: string): { path: string; line: number; rest: string } | null { + const m = SOURCE_AT.exec(line.trim()); + if (!m) return null; + return { path: m[1]!, line: Number(m[2] ?? m[3]), rest: line.trim().slice(m[0].length) }; +} + +const location = (path: string[], at: { path: string; line: number }): TestEvent => ({ + type: "location", + path, + location: { path: at.path, line: at.line, resolve: "path" } satisfies TestLocation, +}); + +// ----------------------------------------------------------------- GoogleTest + +const GTEST_RUN = /^\[ RUN {6}\] (.+)$/; +const GTEST_DONE = /^\[\s*(OK|FAILED|SKIPPED)\s*\] (.+?)(?:, where .*?)?(?: \((\d+) ms\))?$/; + +/** `Suite.Name` (`Prefix/Suite.Name/0` for value-parameterized tests) → `[Suite, Name]`. */ +function gtestPath(full: string): string[] { + const dot = full.indexOf("."); + return dot > 0 ? [full.slice(0, dot), full.slice(dot + 1)] : [full]; +} + +/** + * GoogleTest's console output: `[ RUN ] Suite.Name`, its output, then `[ OK ]`, + * `[ FAILED ]` or `[ SKIPPED ]`. The summary that lists the failed tests again is left out. + */ +export function gtestParser(): TestOutputParser { + let current: { name: string; path: string[]; located: boolean } | null = null; + return { + feed(line) { + const run = GTEST_RUN.exec(line); + if (run) { + current = { name: run[1]!, path: gtestPath(run[1]!), located: false }; + return [{ type: "start", path: current.path }]; + } + if (!current) return []; + const done = GTEST_DONE.exec(line); + if (done && done[2] === current.name) { + const status = done[1] === "FAILED" ? "failed" : done[1] === "SKIPPED" ? "skipped" : "passed"; + const path = current.path; + current = null; + return [{ type: "result", path, status, ...(done[3] ? { durationMs: Number(done[3]) } : {}) }]; + } + const events: TestEvent[] = [{ type: "output", path: current.path, line }]; + const at = sourceAt(line); + if (at && !current.located && /^:\s*(error: )?(Failure|Skipped|error)\b/.test(at.rest)) { + current.located = true; + events.push(location(current.path, at)); + } + return events; + }, + end() { + // A crash ends the test without a verdict. + if (!current) return []; + const path = current.path; + current = null; + return [{ type: "result", path, status: "failed" }]; + }, + }; +} + +// ----------------------------------------------------------------- Catch2 + +/** Catch2 v3's `--reporter teamcity`: the failure message carries the assertion's `file:line`. */ +export function catch2Parser(): TestOutputParser { + const inner = phpunitParser(); + return { + feed(line) { + const events = inner.feed(line); + const message = serviceMessage(line); + if (message?.kind !== "testFailed" && message?.kind !== "testIgnored") return events; + const result = events.find((e) => e.type === "result"); + if (!result || events.some((e) => e.type === "location")) return events; + // The test case's own line comes first, the failed assertion's last. + const places = (message.attrs.message ?? "") + .split("\n") + .map((l) => sourceAt(l)) + .filter((at): at is NonNullable => !!at && !at.rest.trim()); + const at = places.at(-1); + if (!at) return events; + const index = events.indexOf(result); + return [...events.slice(0, index), location(result.path, at), ...events.slice(index)]; + }, + }; +} + +// ----------------------------------------------------------------- doctest + +const DOCTEST_RULE = /^={20,}$/; +const DOCTEST_DURATION = /^(\d+(?:\.\d+)?) s: (.+)$/; + +/** + * doctest's console output with `--duration=true`: a block per test case (`TEST SUITE:`, + * `TEST CASE:`) holding its failed assertions, then ` s: ` once it ends. + * Without durations, the tests seen are reported when the run ends. + */ +export function doctestParser(): TestOutputParser { + const paths = new Map(); + const failed = new Set(); + const finished = new Set(); + let block: { at: { path: string; line: number } | null; suite: string | null; name: string | null } | null = null; + + const result = (name: string, durationMs?: number): TestEvent[] => { + const path = paths.get(name); + if (!path || finished.has(name)) return []; + finished.add(name); + const status = failed.has(name) ? "failed" : "passed"; + return [{ type: "result", path, status, ...(durationMs !== undefined ? { durationMs } : {}) }]; + }; + + return { + feed(line) { + if (DOCTEST_RULE.test(line)) { + block = { at: null, suite: null, name: null }; + return []; + } + if (line.startsWith("[doctest]")) { + block = null; + return []; + } + const duration = DOCTEST_DURATION.exec(line); + if (duration) { + block = null; + return result(duration[2]!, Math.round(Number(duration[1]) * 1_000_000) / 1000); + } + if (!block) return []; + if (!block.name) { + const at = sourceAt(line); + if (at && /^:?\s*$/.test(at.rest)) block.at = at; + else if (line.startsWith("TEST SUITE: ")) block.suite = line.slice("TEST SUITE: ".length).trim(); + else if (line.startsWith("TEST CASE:")) { + const name = line.slice("TEST CASE:".length).trim(); + block.name = name; + if (!paths.has(name)) { + const path = block.suite ? [block.suite, name] : [name]; + paths.set(name, path); + return [{ type: "start", path }, ...(block.at ? [location(path, block.at)] : [])]; + } + } + return []; + } + const path = paths.get(block.name)!; + if (!line.trim()) return []; + const events: TestEvent[] = [{ type: "output", path, line }]; + const at = sourceAt(line); + if (at && /^:\s*(FATAL )?ERROR:/.test(at.rest)) { + if (!failed.has(block.name)) events.push(location(path, at)); + failed.add(block.name); + } + return events; + }, + end() { + return [...paths.keys()].flatMap((name) => result(name)); + }, + }; +} + +// ----------------------------------------------------------------- CTest + +const CTEST_START = /^\s*Start\s+\d+: (.+?)\s*$/; +const CTEST_RESULT = /^\s*\d+\/\d+ Test\s+#\d+: (.+?) \.+\s*(\**)\s*(.+?)\s+(\d+(?:\.\d+)?) sec\s*$/; + +/** + * CTest's progress lines (`1/3 Test #1: name .... Passed 0.01 sec`), each test a leaf; with + * `--output-on-failure`, the output printed after a failed test goes to that test. + */ +export function ctestParser(): TestOutputParser { + let failedOutput: string[] | null = null; + return { + feed(line) { + const start = CTEST_START.exec(line); + if (start) { + failedOutput = null; + return [{ type: "start", path: [start[1]!] }]; + } + const done = CTEST_RESULT.exec(line); + if (done) { + const path = [done[1]!]; + const verdict = done[3]!; + // `Not Run (Disabled)` and `Skipped` (`SKIP_RETURN_CODE`) are skips; `Not Run` alone is a missing executable. + const status = /^Passed\b/.test(verdict) + ? "passed" + : /^(Skipped|Not Run \(Disabled\))/.test(verdict) + ? "skipped" + : "failed"; + failedOutput = status === "failed" ? path : null; + return [ + ...(status === "failed" ? [{ type: "output" as const, path, line: verdict }] : []), + { type: "result", path, status, durationMs: Math.round(Number(done[4]) * 1000) }, + ]; + } + if (/^\d+% tests passed/.test(line) || /^Total Test time/.test(line)) failedOutput = null; + return failedOutput ? [{ type: "output", path: failedOutput, line }] : []; + }, + }; +} + +export function cppTestParser(framework: CppFramework): TestOutputParser { + switch (framework) { + case "gtest": + return gtestParser(); + case "catch2": + return catch2Parser(); + case "doctest": + return doctestParser(); + case "ctest": + return ctestParser(); + } +} + +// ----------------------------------------------------------------- launching + +/** Arguments that make a test executable report what the parser reads. */ +export function cppReportingArgs(framework: CppFramework, args: readonly string[]): string[] { + if (framework === "catch2" && !args.some((a) => a === "-r" || a === "--reporter" || a.startsWith("--reporter="))) + return [...args, "--reporter", "teamcity"]; + if (framework === "doctest" && !args.some((a) => /^--?(dt-)?(d|duration)(=|$)/.test(a))) + return [...args, "--duration=true"]; + return [...args]; +} + +/** A test declared in C / C++ source, as the gutter shows it. */ +export interface CppTestDeclaration { + /** 0-based line. */ + line: number; + /** `[Suite, Name]` (GoogleTest), `[name]` (Catch2, doctest). */ + path: string[]; + macro: string; +} + +const GTEST_DECL = /^\s*(TEST|TEST_F|TEST_P|TYPED_TEST|TYPED_TEST_P|FRIEND_TEST)\s*\(\s*(\w+)\s*,\s*(\w+)\s*\)/; +const CASE_DECL = + /^\s*(TEST_CASE|SCENARIO|TEST_CASE_METHOD|TEMPLATE_TEST_CASE|DOCTEST_TEST_CASE)\s*\(\s*(?:[\w:]+\s*,\s*)?"((?:[^"\\]|\\.)*)"/; + +/** `TEST(Suite, Name)` and the like, and `TEST_CASE("name")`, in `content`. */ +export function cppTestDeclarations(content: string): CppTestDeclaration[] { + const out: CppTestDeclaration[] = []; + content.split("\n").forEach((text, line) => { + const g = GTEST_DECL.exec(text); + if (g && g[1] !== "FRIEND_TEST") { + out.push({ line, path: [g[2]!, g[3]!], macro: g[1]! }); + return; + } + const c = CASE_DECL.exec(text); + if (c) { + const name = c[2]!.replace(/\\(.)/g, "$1"); + out.push({ line, path: [c[1] === "SCENARIO" ? `Scenario: ${name}` : name], macro: c[1]! }); + } + }); + return out; +} + +/** Escapes the characters a Catch2 test spec or a doctest filter would read as syntax. */ +const escapeSpec = (name: string, special: RegExp) => name.replace(special, "\\$&"); + +/** Arguments that run only `test` of a `framework` executable. */ +export function cppTestFilter(framework: CppFramework, test: CppTestDeclaration): string[] { + const [first, second] = test.path; + switch (framework) { + case "gtest": { + if (!second) return []; + // Value-parameterized: `Prefix/Suite.Name/Param`; typed: `Suite/Type.Name`; type-parameterized: + // `Prefix/Suite/Type.Name`. + const pattern = + test.macro === "TEST_P" + ? `*${first}.${second}/*` + : test.macro === "TYPED_TEST_P" + ? `*/${first}/*.${second}` + : test.macro === "TYPED_TEST" + ? `${first}/*.${second}` + : `${first}.${second}`; + return [`--gtest_filter=${pattern}`]; + } + case "catch2": { + const spec = escapeSpec(first!, /[\\,[\]*"~]/g); + // TEMPLATE_TEST_CASE("name", …, int, float) registers `name - int`, `name - float`. + return [test.macro === "TEMPLATE_TEST_CASE" ? `${spec} - *` : spec]; + } + case "doctest": + return [`--test-case=${escapeSpec(first!, /[\\,*?]/g)}`]; + case "ctest": + return []; + } +} diff --git a/src/features/run/testing/index.ts b/src/features/run/testing/index.ts index 861125d2b..00251ed4f 100644 --- a/src/features/run/testing/index.ts +++ b/src/features/run/testing/index.ts @@ -2,6 +2,7 @@ import type { RunConfig } from "@/platform/ipc"; import { isJunitRunner } from "../application"; import { cargoParser } from "./cargo"; +import { CPP_FRAMEWORKS, cppReportingArgs, cppTestParser, type CppFramework } from "./cpp"; import { cypressParser, cypressSpecs } from "./cypress"; import { goParser } from "./go"; import { jsParser } from "./js"; @@ -73,6 +74,8 @@ export type Framework = /** `swift test`: XCTest and Swift Testing. */ | "swift" | "xcode" + /** C / C++ test executables (CMake), and CTest. */ + | CppFramework | "auto"; type FrameworkConfig = Pick & @@ -88,6 +91,8 @@ export function frameworkFor(config: FrameworkConfig): Framework { if (config.testRunner === "mocha" || /(^|[\s/\\])_?mocha(\.cmd|\.js)?(\s|$)/.test(cmd)) return "mocha"; if (config.testRunner === "jasmine" || /(^|[\s/\\])jasmine(\.cmd|\.js)?(\s|$)/.test(cmd)) return "jasmine"; if (config.testRunner === "jvm" || isJunitRunner(config)) return "jvm"; + // Set by CMake detection on test executables and CTest. + if (config.testRunner && CPP_FRAMEWORKS.has(config.testRunner)) return config.testRunner as CppFramework; switch (config.kind) { case "dotnet-test": return "dotnet"; @@ -160,7 +165,10 @@ function rubyVerbose>(con * IDEA's runner) unless the user chose a verbosity already. */ export function withTestReporting(config: T): T { - if (frameworkFor(config) === "node-test") return { ...config, env: withNodeTestReporter(config.env ?? {}) }; + const framework = frameworkFor(config); + if (framework === "catch2" || framework === "doctest") + return { ...config, args: cppReportingArgs(framework, config.args) }; + if (framework === "node-test") return { ...config, env: withNodeTestReporter(config.env ?? {}) }; if (frameworkFor(config) === "mocha") return { ...config, env: withMochaHook(config.env ?? {}) }; if (frameworkFor(config) === "jasmine") return { ...config, env: withJasmineHook(config.env ?? {}) }; if (frameworkFor(config) === "python-unittest") return withUnittestReporter(config); @@ -240,6 +248,11 @@ export function createTestParser(config: FrameworkConfig): TestOutputParser { return zigParser(); case "swift": return swiftParser(); + case "gtest": + case "catch2": + case "doctest": + case "ctest": + return cppTestParser(frameworkFor(config) as CppFramework); default: return combinedParser([ cargoParser(),