дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +02:00
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 <[email protected]>
302 рядки
11 KiB
TypeScript
302 рядки
11 KiB
TypeScript
/**
|
|
* 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<string> = new Set<CppFramework>(["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<typeof at> => !!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 `<seconds> s: <name>` once it ends.
|
|
* Without durations, the tests seen are reported when the run ends.
|
|
*/
|
|
export function doctestParser(): TestOutputParser {
|
|
const paths = new Map<string, string[]>();
|
|
const failed = new Set<string>();
|
|
const finished = new Set<string>();
|
|
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 [];
|
|
}
|
|
}
|