feat(cucumber): cucumber-jvm step definitions in Java and Kotlin (#3690)

Step navigation, the Undefined step inspection and Create step definition cover cucumber-jvm: @Given("…") annotations and Java 8 lambdas in .java / .kt files are scanned and matched, and string patterns anchored with ^ or $ read as regular expressions. Created definitions in Java / Kotlin are annotated methods in the class with {int} / {double} / {string} parameters, cucumber-jvm method names and the keyword's io.cucumber.java.en import.

Refs #797
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-11-16 14:16:50 +08:00
1 джерело f4469a2f53
коміт efc1e607b8
8 files changed
+272 -40

No files matched your search

+29 -14
Переглянути файл
@@ -1,9 +1,10 @@
/**
* Cucumber steps: Go to Declaration (⌘-click, ⌘B) on a `.feature` step opens its JavaScript /
* TypeScript step definitions, and on a definition's pattern lists the feature steps it
* Cucumber steps: Go to Declaration (⌘-click, ⌘B) on a `.feature` step opens its step
* definitions (JavaScript / TypeScript, and cucumber-jvm's Java / Kotlin), and on a definition's pattern lists the feature steps it
* matches. Steps no definition matches are reported (Undefined step), with a quick fix that
* writes a pending definition into the project's step file.
*/
import { Text } from "@codemirror/state";
import { ViewPlugin, type EditorView } from "@codemirror/view";
import {
intentionProviders,
@@ -22,7 +23,15 @@ import { tx } from "@/platform/i18n";
import { CUCUMBER_UNDEFINED_STEP_PRODUCER } from "@/platform/inspections";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { editorService, notifications } from "@/workbench/contributions";
import { definingKeyword, featureSteps, stepDefinitions, stepSnippet, type FeatureStep } from "./steps";
import {
definingKeyword,
definitionInsertions,
featureSteps,
snippetStyle,
stepDefinitions,
stepSnippet,
type FeatureStep,
} from "./steps";
import {
clearStepIndex,
definitionFileFor,
@@ -32,7 +41,7 @@ import {
usagesOf,
} from "./stepIndex";
const SCRIPT = /\.[cm]?[jt]sx?$/i;
const SCRIPT = /\.(?:[cm]?[jt]sx?|java|kt)$/i;
const FEATURE = /\.feature$/i;
const DELAY_MS = 300;
@@ -62,21 +71,27 @@ async function createDefinition(featurePath: string, all: readonly FeatureStep[]
cursor?.path === target
? (await call(commands.docSnapshot(cursor.doc))).text
: await call(commands.fsReadText(target));
const lines = text.split("\n");
const end = { line: lines.length - 1, col: lines[lines.length - 1]!.length };
const lead = text.length === 0 ? "" : text.endsWith("\n\n") ? "" : text.endsWith("\n") ? "\n" : "\n\n";
const style = /\bcreateBdd\s*\(/.test(text) ? "playwright-bdd" : "cucumber";
const snippet = stepSnippet(definingKeyword(all, step), step.matchText, style);
const style = snippetStyle(target, text);
const keyword = definingKeyword(all, step);
const snippet = stepSnippet(keyword, step.matchText, style);
const { insertions, select } = definitionInsertions(text, keyword, snippet, style);
const lines = Text.of(text.split("\n"));
await whenAllSynced();
await call(
commands.applyWorkspaceEdit({
files: [{ kind: "edit", path: target, edits: [{ range: { start: end, end }, new_text: lead + snippet.text }] }],
files: [
{
kind: "edit",
path: target,
edits: insertions.map((i) => ({ range: offsetsToRange(lines, i.at, i.at), new_text: i.text })),
},
],
}),
);
// The body line (the pending return, or the comment) is selected.
const line = end.line + lead.split("\n").length - 1 + snippet.body;
const body = snippet.text.split("\n")[snippet.body]!;
await editorService().openFile(target, { selection: { line, col: 2, endLine: line, endCol: body.length } });
// The body line (the pending return or exception, or the comment) is selected.
await editorService().openFile(target, {
selection: { line: select.line, col: select.from, endLine: select.line, endCol: select.to },
});
} catch (e) {
notifications().notify({
group: "cucumber",
+8 -2
Переглянути файл
@@ -18,7 +18,7 @@ let cached: Promise<StepIndex> | null = null;
/** Whether a change to `path` can change the index: a feature or script file. */
export function isCucumberSource(path: string): boolean {
return /\.(feature|[cm]?[jt]sx?)$/i.test(path);
return /\.(feature|[cm]?[jt]sx?|java|kt)$/i.test(path);
}
/** Forgets the index, so the next lookup rescans the project. */
@@ -93,7 +93,13 @@ export async function undefinedSteps(steps: readonly FeatureStep[]): Promise<Fea
/** The file a new definition for a step of `featurePath` goes to: the step file named like the feature, else the one with the most definitions. */
export async function definitionFileFor(featurePath: string): Promise<string | null> {
const { definitions } = await stepIndex();
const stem = (path: string) => (path.split("/").pop() ?? "").split(".")[0]!.toLowerCase();
// `cart.steps.ts`, `CartSteps.java` and `cart_stepdefs.kt` all name the `cart` feature's steps.
const stem = (path: string) =>
(path.split("/").pop() ?? "")
.split(".")[0]!
.toLowerCase()
.replace(/[^a-z0-9]/g, "")
.replace(/(?:stepdefinitions|stepdefs|steps)$/, "");
const feature = stem(featurePath);
const named = definitions.find((file) => stem(file.path) === feature);
if (named) return named.path;
+70 -1
Переглянути файл
@@ -1,5 +1,14 @@
import { describe, expect, it } from "vitest";
import { definingKeyword, expressionRegExp, featureSteps, matchesStep, stepDefinitions, stepSnippet } from "./steps";
import {
definingKeyword,
definitionInsertions,
expressionRegExp,
featureSteps,
matchesStep,
snippetStyle,
stepDefinitions,
stepSnippet,
} from "./steps";
const STEPS = `import { Given, When, Then } from "@cucumber/cucumber";
import { createBdd } from "playwright-bdd";
@@ -135,3 +144,63 @@ describe("definingKeyword", () => {
expect(steps.map((s) => definingKeyword(steps, s))).toEqual(["Given", "Given", "When", "When", "Then", "Then"]);
});
});
describe("cucumber-jvm", () => {
const step = (text: string) => featureSteps(`Feature: f\n Scenario: s\n Given ${text}\n`)[0]!;
const JAVA = `package shop;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
public class CartSteps {
@Given("an empty cart")
public void emptyCart() {}
@Then("^the total is (\\\\d+\\\\.\\\\d+) EUR$")
public void total(String amount) {}
}
`;
it("reads annotation patterns, anchored strings as regular expressions", () => {
const definitions = stepDefinitions(JAVA);
expect(definitions.map((d) => d.source)).toEqual(["an empty cart", "^the total is (\\d+\\.\\d+) EUR$"]);
expect(matchesStep(definitions[1]!, step("the total is 3.50 EUR"))).toBe(true);
expect(matchesStep(definitions[0]!, step("an empty cart"))).toBe(true);
});
it("writes a Java method into the class with the keyword's import", () => {
const snippet = stepSnippet("When", `I pay 12 "EUR" for 2.5 kg (net)`, "java");
expect(snippet.text).toBe(
[
' @When("I pay {int} {string} for {double} kg \\\\(net\\\\)")',
" public void i_pay_for_kg_net(Integer int1, String string, Double double1) {",
" // Write code here that turns the phrase above into concrete actions",
" throw new io.cucumber.java.PendingException();",
" }",
"",
].join("\n"),
);
const { insertions, select } = definitionInsertions(JAVA, "When", snippet, "java");
let out = JAVA;
for (const i of [...insertions].sort((a, b) => b.at - a.at)) out = out.slice(0, i.at) + i.text + out.slice(i.at);
expect(out).toContain("import io.cucumber.java.en.Then;\nimport io.cucumber.java.en.When;\n");
expect(
out.endsWith(" public void total(String amount) {}\n\n" + snippet.text.replace(/\n$/, "") + "\n}\n"),
).toBe(true);
expect(out.split("\n")[select.line]!.slice(select.from, select.to)).toBe(
"throw new io.cucumber.java.PendingException();",
);
const created = stepDefinitions(out).find((d) => d.source.startsWith("I pay"))!;
expect(matchesStep(created, step(`I pay 12 "EUR" for 2.5 kg (net)`))).toBe(true);
});
it("writes Kotlin in camel case and escapes $", () => {
const snippet = stepSnippet("Given", "a $5 coupon", "kotlin");
expect(snippet.text.split("\n").slice(0, 2)).toEqual([
' @Given("a \\${int} coupon")',
" fun aCoupon(int1: Int) {",
]);
expect(snippetStyle("src/test/kotlin/CartSteps.kt", "")).toBe("kotlin");
expect(snippetStyle("steps/cart.steps.ts", "createBdd()")).toBe("playwright-bdd");
});
});
+153 -14
Переглянути файл
@@ -5,7 +5,10 @@
* expression matching between them.
*/
/** A step definition: the pattern literal of a `Given` / `When` / `Then` / `Step` call. */
/**
* A step definition: the pattern literal of a `Given` / `When` / `Then` / `Step` call, or of a
* cucumber-jvm `@Given("…")` annotation.
*/
export interface StepDefinition {
/** Offsets of the literal (quotes or slashes included) in its file. */
from: number;
@@ -36,12 +39,26 @@ export function stepDefinitions(text: string): StepDefinition[] {
const at = m.index + m[0].length;
const literal = readLiteral(text, at);
if (!literal) continue;
const regexp = literal.regexp ?? expressionRegExp(literal.value);
const regexp = literal.regexp ?? stringPattern(literal.value);
if (regexp) out.push({ from: at, to: literal.end, source: literal.value, regexp });
}
return out;
}
/**
* The pattern of a string: a regular expression when it is anchored with `^` or `$` (how
* Cucumber's expression factory tells them apart, and how cucumber-jvm annotations write them),
* else a Cucumber expression.
*/
function stringPattern(value: string): RegExp | null {
if (!value.startsWith("^") && !value.endsWith("$")) return expressionRegExp(value);
try {
return new RegExp(value);
} catch {
return null;
}
}
/** A string, template (without substitutions) or regular expression literal at `at`. */
function readLiteral(text: string, at: number): { value: string; end: number; regexp?: RegExp } | null {
const quote = text[at];
@@ -218,47 +235,118 @@ export function definingKeyword(steps: readonly FeatureStep[], step: FeatureStep
/** Strings and numbers of a step's text, as Cucumber's snippets turn them into parameters. */
const SNIPPET_PARAMETER = /(^|[^\w.-])("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|-?\d+\.\d+|-?\d+)(?![\w.])/g;
/** `text` as a Cucumber expression inside a single-quoted JavaScript string. */
const expressionText = (text: string) => text.replace(/[\\(){}/]/g, "\\\\$&").replace(/'/g, "\\'");
export type SnippetStyle = "cucumber" | "playwright-bdd" | "java" | "kotlin";
/** The snippet style of a step definition file. */
export function snippetStyle(path: string, text: string): SnippetStyle {
if (/\.java$/i.test(path)) return "java";
if (/\.kts?$/i.test(path)) return "kotlin";
return /\bcreateBdd\s*\(/.test(text) ? "playwright-bdd" : "cucumber";
}
/** `text` as a Cucumber expression inside a string literal of the snippet's language. */
function expressionText(text: string, style: SnippetStyle): string {
const escaped = text.replace(/[\\(){}/]/g, "\\\\$&");
if (style === "java") return escaped.replace(/"/g, '\\"');
if (style === "kotlin") return escaped.replace(/"/g, '\\"').replace(/\$/g, "\\$");
return escaped.replace(/'/g, "\\'");
}
/** cucumber-jvm's method name for a step: its words without the parameters, in snake case (camel case in Kotlin). */
function methodName(words: string, style: "java" | "kotlin"): string {
const parts = words
.toLowerCase()
.split(/[^a-z0-9]+/)
.filter(Boolean);
if (!parts.length) return "step";
const name =
style === "java"
? parts.join("_")
: parts[0]! +
parts
.slice(1)
.map((p) => p[0]!.toUpperCase() + p.slice(1))
.join("");
return /^\d/.test(name) ? `_${name}` : name;
}
const COMMENT = "// Write code here that turns the phrase above into concrete actions";
/**
* The step definition Cucumber suggests for an undefined step: its strings and numbers become
* `{string}`, `{float}` and `{int}` parameters of a pending step. `playwright-bdd` steps take
* the fixtures first. `body` is the line (0-based) of the snippet the caret goes to.
* `{string}`, `{float}` (`{double}` on the JVM) and `{int}` parameters of a pending step.
* `playwright-bdd` steps take the fixtures first; Java and Kotlin ones are annotated methods,
* indented for a class body. `body` is the line (0-based) of the snippet the caret goes to.
*/
export function stepSnippet(
keyword: string,
text: string,
style: "cucumber" | "playwright-bdd" = "cucumber",
style: SnippetStyle = "cucumber",
): { text: string; body: number } {
const jvm = style === "java" || style === "kotlin";
const types: string[] = [];
let expression = "";
let words = "";
let last = 0;
for (const m of text.matchAll(SNIPPET_PARAMETER)) {
const start = m.index + m[1]!.length;
const value = m[2]!;
const type = /^["']/.test(value) ? "string" : value.includes(".") ? "float" : "int";
expression += `${expressionText(text.slice(last, start))}{${type}}`;
const type = /^["']/.test(value) ? "string" : value.includes(".") ? (jvm ? "double" : "float") : "int";
expression += `${expressionText(text.slice(last, start), style)}{${type}}`;
words += ` ${text.slice(last, start)}`;
types.push(type);
last = start + value.length;
}
expression += expressionText(text.slice(last));
expression += expressionText(text.slice(last), style);
words += ` ${text.slice(last)}`;
const seen = new Map<string, number>();
const names = types.map((type) => {
const n = (seen.get(type) ?? 0) + 1;
seen.set(type, n);
return n === 1 ? type : `${type}${n}`;
// cucumber-jvm numbers its int and double parameters from 1.
return type === "string" ? (n === 1 ? type : `${type}${n}`) : jvm ? `${type}${n}` : n === 1 ? type : `${type}${n}`;
});
const comment = " // Write code here that turns the phrase above into concrete actions";
if (style === "java") {
const javaType: Record<string, string> = { int: "Integer", double: "Double", string: "String" };
const params = types.map((t, i) => `${javaType[t]} ${names[i]}`).join(", ");
return {
text: [
` @${keyword}("${expression}")`,
` public void ${methodName(words, "java")}(${params}) {`,
` ${COMMENT}`,
" throw new io.cucumber.java.PendingException();",
" }",
"",
].join("\n"),
body: 3,
};
}
if (style === "kotlin") {
const kotlinType: Record<string, string> = { int: "Int", double: "Double", string: "String" };
const params = types.map((t, i) => `${names[i]}: ${kotlinType[t]}`).join(", ");
return {
text: [
` @${keyword}("${expression}")`,
` fun ${methodName(words, "kotlin")}(${params}) {`,
` ${COMMENT}`,
" throw io.cucumber.java.PendingException()",
" }",
"",
].join("\n"),
body: 3,
};
}
if (style === "playwright-bdd")
return {
text: [`${keyword}('${expression}', async (${["{}", ...names].join(", ")}) => {`, comment, "});", ""].join("\n"),
text: [`${keyword}('${expression}', async (${["{}", ...names].join(", ")}) => {`, ` ${COMMENT}`, "});", ""].join(
"\n",
),
body: 1,
};
return {
text: [
`${keyword}('${expression}', async function (${names.join(", ")}) {`,
comment,
` ${COMMENT}`,
" return 'pending';",
"});",
"",
@@ -266,3 +354,54 @@ export function stepSnippet(
body: 2,
};
}
/** A text insertion at an offset of the file. */
export interface Insertion {
at: number;
text: string;
}
/**
* Where a definition goes in a step file: at its end, or before the closing brace of its class
* for Java and Kotlin, which also get the keyword's `io.cucumber.java.en` import when the file
* imports others from there. `select` is the body line's range in the file after the insertions.
*/
export function definitionInsertions(
fileText: string,
keyword: string,
snippet: { text: string; body: number },
style: SnippetStyle,
): { insertions: Insertion[]; select: { line: number; from: number; to: number } } {
const insertions: Insertion[] = [];
let at: number;
let insert: string;
if (style === "java" || style === "kotlin") {
const close = fileText.lastIndexOf("}");
at = close < 0 ? fileText.length : fileText.slice(0, close).trimEnd().length;
insert = `\n\n${snippet.text.replace(/\n$/, "")}`;
if (close >= 0 && !fileText.slice(at, close).includes("\n")) insert += "\n";
const imports = [...fileText.matchAll(/^import\s+io\.cucumber\.java\.en\.(\w+);?[ \t]*$/gm)];
if (imports.length && !imports.some((m) => m[1] === keyword || m[1] === "*")) {
const lastImport = imports[imports.length - 1]!;
const end = lastImport.index + lastImport[0].length;
const statement = ["import io.cucumber.java.en.", keyword, style === "java" ? ";" : ""].join("");
insertions.push({ at: end, text: `\n${statement}` });
}
} else {
at = fileText.length;
const lead = !fileText ? "" : fileText.endsWith("\n\n") ? "" : fileText.endsWith("\n") ? "\n" : "\n\n";
insert = lead + snippet.text;
}
insertions.push({ at, text: insert });
// The snippet's first line, counted in the file after every insertion before it.
const before = insertions.filter((i) => i.at < at).reduce((n, i) => n + (i.text.split("\n").length - 1), 0);
const snippetStart = insert.length - insert.trimStart().length;
const firstLine =
fileText.slice(0, at).split("\n").length - 1 + before + (insert.slice(0, snippetStart).split("\n").length - 1);
const bodyText = snippet.text.split("\n")[snippet.body]!;
const indent = bodyText.length - bodyText.trimStart().length;
return {
insertions,
select: { line: firstLine + snippet.body, from: indent, to: bodyText.length },
};
}