diff --git a/crates/ide-run/src/config.rs b/crates/ide-run/src/config.rs index cf40ffc93..8a306f0b2 100644 --- a/crates/ide-run/src/config.rs +++ b/crates/ide-run/src/config.rs @@ -118,6 +118,8 @@ struct FileConfig { #[serde(alias = "stopCommand")] stop_command: Option, target: Option, + #[serde(alias = "testRunner")] + test_runner: Option, } pub(crate) fn slug(s: &str) -> String { @@ -183,6 +185,7 @@ fn convert(configs: Vec, local: bool) -> Vec { emulate_terminal: c.emulate_terminal, stop_command: non_empty(c.stop_command), target: non_empty(c.target), + test_runner: non_empty(c.test_runner), }, }); } @@ -298,6 +301,9 @@ fn to_table(c: &RunConfig) -> Table { if let Some(target) = &x.target { t.insert("target", value(target)); } + if let Some(runner) = &x.test_runner { + t.insert("test-runner", value(runner)); + } t } diff --git a/crates/ide-run/src/detect.rs b/crates/ide-run/src/detect.rs index f53738bc1..d009a14ad 100644 --- a/crates/ide-run/src/detect.rs +++ b/crates/ide-run/src/detect.rs @@ -243,8 +243,32 @@ pub(crate) fn is_test_script(name: &str) -> bool { matches!(name, "test" | "vitest" | "jest") || name.starts_with("test:") } -fn push_scripts(pkg: &Json, pm: &str, prefix: Option<&str>, cwd: Option, out: &mut Vec) { - let Some(scripts) = pkg.get("scripts").and_then(Json::as_object) else { return }; +/// The test runner a `package.json` script starts, when its output and test selection differ +/// from Jest / Vitest's: `playwright test`. +fn script_test_runner(script: &str) -> Option<&'static str> { + let tokens: Vec<&str> = script.split(|c: char| c.is_whitespace() || matches!(c, '&' | '|' | ';')).collect(); + tokens.windows(2).any(|w| w[0] == "playwright" && w[1] == "test").then_some("playwright") +} + +const PLAYWRIGHT_CONFIGS: &[&str] = &[ + "playwright.config.ts", + "playwright.config.js", + "playwright.config.mts", + "playwright.config.mjs", + "playwright.config.cts", + "playwright.config.cjs", +]; + +/// Pushes the package's scripts; returns the test runners they start. +fn push_scripts( + pkg: &Json, + pm: &str, + prefix: Option<&str>, + cwd: Option, + out: &mut Vec, +) -> HashSet<&'static str> { + let mut runners = HashSet::new(); + let Some(scripts) = pkg.get("scripts").and_then(Json::as_object) else { return runners }; let mut names: Vec<&String> = scripts.keys().collect(); names.sort(); for script in names { @@ -254,11 +278,39 @@ fn push_scripts(pkg: &Json, pm: &str, prefix: Option<&str>, cwd: Option }; let mut c = config(id, name, "npm", pm, &["run", script]).in_dir(cwd.clone()).debug("js-debug"); c.extras.module = cwd.as_deref().map(ide_core::ipc_path::to_ipc); - if is_test_script(script) { + let runner = scripts[script].as_str().and_then(script_test_runner); + if is_test_script(script) || runner.is_some() { c = c.test(); } + if let Some(runner) = runner { + c.extras.test_runner = Some(runner.to_owned()); + runners.insert(runner); + } out.push(c); } + runners +} + +/// `npx playwright test` for a package with a Playwright configuration that no script runs +/// (`npm init playwright` adds none). +fn push_playwright( + dir: &Path, + runners: &HashSet<&str>, + prefix: Option<&str>, + cwd: Option, + out: &mut Vec, +) { + if runners.contains("playwright") || first_existing(dir, PLAYWRIGHT_CONFIGS).is_none() { + return; + } + let (id, name) = match prefix { + Some(p) => (format!("playwright:{p}"), format!("{p}: playwright test")), + None => ("playwright".to_owned(), "playwright test".to_owned()), + }; + let mut c = config(id, name, "node", "npx", &["playwright", "test"]).in_dir(cwd.clone()).debug("js-debug").test(); + c.extras.module = cwd.as_deref().map(ide_core::ipc_path::to_ipc); + c.extras.test_runner = Some("playwright".to_owned()); + out.push(c); } fn detect_node(root: &Path, out: &mut Vec) { @@ -275,7 +327,10 @@ fn detect_node(root: &Path, out: &mut Vec) { let pm = package_manager(&dir, &pkg); let rel = relative(root, &dir); let label = ide_core::ipc_path::to_ipc(&rel); - push_scripts(&pkg, pm, (dir != root).then_some(label.as_str()), (dir != root).then_some(rel), out); + let prefix = (dir != root).then_some(label.as_str()); + let cwd = (dir != root).then_some(rel); + let runners = push_scripts(&pkg, pm, prefix, cwd.clone(), out); + push_playwright(&dir, &runners, prefix, cwd, out); for member_dir in ide_core::project_roots::node_workspace_members(&dir) { if !covered.insert(member_dir.clone()) { continue; @@ -288,7 +343,8 @@ fn detect_node(root: &Path, out: &mut Vec) { .map(str::to_owned) .unwrap_or_else(|| ide_core::ipc_path::to_ipc(&rel)); let name = if dir == root { name } else { format!("{label}:{name}") }; - push_scripts(&member, pm, Some(&name), Some(rel), out); + let runners = push_scripts(&member, pm, Some(&name), Some(rel.clone()), out); + push_playwright(&member_dir, &runners, Some(&name), Some(rel), out); } } } diff --git a/crates/ide-run/src/lib.rs b/crates/ide-run/src/lib.rs index e1a0807c0..3278f7dbb 100644 --- a/crates/ide-run/src/lib.rs +++ b/crates/ide-run/src/lib.rs @@ -182,6 +182,12 @@ pub struct RunExtras { #[serde(default, skip_serializing_if = "Option::is_none")] #[specta(optional)] pub target: Option, + /// The test framework a test configuration runs when detection recognised one that the + /// command line doesn't name (a `package.json` script running `playwright test`): picks the + /// test output parser and how a single test is selected. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[specta(optional)] + pub test_runner: Option, } impl Default for RunExtras { @@ -205,6 +211,7 @@ impl Default for RunExtras { emulate_terminal: false, stop_command: None, target: None, + test_runner: None, } } } diff --git a/crates/ide-run/tests/detect.rs b/crates/ide-run/tests/detect.rs index 86ecaaf27..9a964c923 100644 --- a/crates/ide-run/tests/detect.rs +++ b/crates/ide-run/tests/detect.rs @@ -51,6 +51,31 @@ fn npm_scripts_with_lockfile_package_manager() { assert!(find(&c, "npm:test:e2e").is_test); } +#[test] +fn playwright_scripts_and_configs() { + let dir = project(&[ + ("package.json", r#"{"scripts":{"e2e":"cross-env CI=1 playwright test --project=chromium","test":"vitest"}}"#), + ("playwright.config.ts", ""), + ("site/package.json", r#"{"devDependencies":{"@playwright/test":"^1.56.0"}}"#), + ("site/playwright.config.ts", ""), + ]); + let c = detect(dir.path()); + let e2e = find(&c, "npm:e2e"); + assert!(e2e.is_test); + assert_eq!(e2e.extras.test_runner.as_deref(), Some("playwright")); + assert_eq!(find(&c, "npm:test").extras.test_runner, None); + // The root's script runs Playwright already; the nested package has none. + assert!(!ids(&c).contains(&"playwright")); + let site = find(&c, "playwright:site"); + assert_eq!(cmdline(site), "npx playwright test"); + assert_eq!(site.name, "site: playwright test"); + assert!(site.is_test && site.detected); + assert_eq!(site.kind, "node"); + assert_eq!(site.cwd.as_deref(), Some(Path::new("site"))); + assert_eq!(site.extras.test_runner.as_deref(), Some("playwright")); + assert_eq!(site.debug_adapter.as_deref(), Some("js-debug")); +} + #[test] fn package_manager_selection() { for (lock, pm) in [("yarn.lock", "yarn"), ("bun.lockb", "bun"), ("bun.lock", "bun"), ("package-lock.json", "npm")] { diff --git a/docs/en/guide/run.mdx b/docs/en/guide/run.mdx index fa64aca9b..63436ce87 100644 --- a/docs/en/guide/run.mdx +++ b/docs/en/guide/run.mdx @@ -19,6 +19,7 @@ When a project opens, OpenIDEA scans its build files (also in nested projects of | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `package.json` | One per `scripts` entry, run with the package manager of the lock file (npm, pnpm, yarn or bun). `test`, `test:*`, `jest` and `vitest` scripts are marked as tests. | | `deno.json` / `deno.jsonc` | Deno tasks | +| `playwright.config.*` | Scripts that run `playwright test` are tests; without one, `npx playwright test` | | `Cargo.toml` | `cargo run` for each binary, `cargo test`, `cargo build`; workspace members are included | | `build.gradle(.kts)` / `pom.xml` | Gradle and Maven run configurations | | `go.mod` / `go.work` | Go programs and tests | diff --git a/docs/en/guide/testing.mdx b/docs/en/guide/testing.mdx index 2972a79bf..9f6b9ebff 100644 --- a/docs/en/guide/testing.mdx +++ b/docs/en/guide/testing.mdx @@ -32,7 +32,7 @@ Running a single test creates a temporary run configuration based on the project | Language | Gutter icons on | Runs with | | --------------------------- | --------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | | Rust | `#[test]` functions, `mod tests` | `cargo test`, `cargo nextest` | -| JavaScript / TypeScript | `test`, `it`, `describe`, `suite`, `context` (also `.each`, `.only`, `.skip`) | Jest or Vitest through the project's test script; Deno and Bun | +| JavaScript / TypeScript | `test`, `it`, `describe`, `suite`, `context` (also `.each`, `.only`, `.skip`) | Jest or Vitest via the test script; Playwright Test; Deno, Bun | | Python | pytest `def test_*` and `class Test*`, unittest `TestCase` subclasses | pytest, Django `manage.py test` | | Go | `func TestX(t *testing.T)`, benchmarks | `go test` | | Java, Kotlin, Scala, Groovy | JUnit `@Test`, `@ParameterizedTest`, `@RepeatedTest`, `@TestFactory`, `@TestTemplate`; TestNG | Maven Surefire (`-Dtest=`) or Gradle (`--tests`) | @@ -66,7 +66,7 @@ Detected test configurations show results in the tree automatically. For your ow | **Rerun** (in the Run tool window) | `⌘R` | `Ctrl+F5` | | **Rerun Failed Tests** | — | — | -**Rerun Failed Tests** (in the Run tool window toolbar and Find Action) runs only the tests that failed in the last run, using each tool's filter syntax. It works for Cargo, Jest / Vitest, pytest, Django, PHPUnit, Go, Maven / Gradle and .NET runs, and for plugin test frameworks. +**Rerun Failed Tests** (in the Run tool window toolbar and Find Action) runs only the tests that failed in the last run, using each tool's filter syntax. It works for Cargo, Jest / Vitest, Playwright, pytest, Django, PHPUnit, Go, Maven / Gradle and .NET runs, and for plugin test frameworks. ## Navigate between code and tests diff --git a/docs/en/languages/javascript.mdx b/docs/en/languages/javascript.mdx index 087f68aaa..1443e314b 100644 --- a/docs/en/languages/javascript.mdx +++ b/docs/en/languages/javascript.mdx @@ -74,7 +74,8 @@ On both pages, **Formatting provider** chooses between **Automatic (language ser OpenIDEA detects run configurations when the project opens: -- One configuration per `package.json` script (`npm run build`, `pnpm run dev`, …), for the root package, nested packages and workspace members. Scripts named `test`, `jest`, `vitest` or `test:*` are test configurations. +- One configuration per `package.json` script (`npm run build`, `pnpm run dev`, …), for the root package, nested packages and workspace members. Scripts named `test`, `jest`, `vitest` or `test:*`, and scripts that run `playwright test`, are test configurations. +- `playwright test` (through `npx`) for a package with a `playwright.config.*` that no script runs. - One per task in `deno.json` / `deno.jsonc` (`deno task `). In `package.json`, the gutter shows run icons on each `scripts` entry to run or debug it. @@ -85,7 +86,7 @@ In `package.json`, the gutter shows run icons on each `scripts` entry to run or - Any other `.js` file runs with `node` (with `deno run` or `bun run` in a project with `deno.json` or `bun.lock`). - A `.ts` file runs with Node.js directly on 22.18+ / 23.6+, with `--experimental-strip-types` on 22.6–22.17 and 23.0–23.5, else through `tsx` or `ts-node`. -Jest and Vitest output is turned into the test tree, with **Rerun Failed Tests**. **Run with Coverage** works for scripts that run `vitest` or `jest` (Vitest needs a coverage provider such as `@vitest/coverage-v8`; the IDE offers to add it) and for `node` / `tsx` / `ts-node` runs through `c8`. See [Testing](/en/guide/testing) and [Coverage](/en/guide/coverage). +Jest, Vitest and Playwright Test output is turned into the test tree, with **Rerun Failed Tests**. Playwright runs report through its `list` reporter unless the configuration names another; a test in the gutter runs by its line (`file:line`), and runs with several projects show each project under its file. **Run with Coverage** works for scripts that run `vitest` or `jest` (Vitest needs a coverage provider such as `@vitest/coverage-v8`; the IDE offers to add it) and for `node` / `tsx` / `ts-node` runs through `c8`. See [Testing](/en/guide/testing) and [Coverage](/en/guide/coverage). ## Debugging diff --git a/docs/zh/guide/run.mdx b/docs/zh/guide/run.mdx index 08673a511..38b36fa52 100644 --- a/docs/zh/guide/run.mdx +++ b/docs/zh/guide/run.mdx @@ -19,6 +19,7 @@ description: "创建、编辑和启动运行配置,从装订区运行代码, | ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `package.json` | 每个 `scripts` 条目一个,使用锁文件对应的包管理器(npm、pnpm、yarn 或 bun)。`test`、`test:*`、`jest`、`vitest` 脚本会标记为测试。 | | `deno.json` / `deno.jsonc` | Deno task | +| `playwright.config.*` | 运行 `playwright test` 的脚本是测试配置;没有这样的脚本时为 `npx playwright test` | | `Cargo.toml` | 每个二进制一个 `cargo run`,以及 `cargo test`、`cargo build`;包含 workspace 成员 | | `build.gradle(.kts)` / `pom.xml` | Gradle、Maven 运行配置 | | `go.mod` / `go.work` | Go 程序和测试 | diff --git a/docs/zh/guide/testing.mdx b/docs/zh/guide/testing.mdx index 200a7af95..8300f3b0e 100644 --- a/docs/zh/guide/testing.mdx +++ b/docs/zh/guide/testing.mdx @@ -28,7 +28,7 @@ OpenIDEA 直接使用项目自己的测试工具(Cargo、Jest、pytest、Maven | 语言 | 装订区图标位置 | 运行方式 | | --------------------------- | --------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | Rust | `#[test]` 函数、`mod tests` | `cargo test`、`cargo nextest` | -| JavaScript / TypeScript | `test`、`it`、`describe`、`suite`、`context`(含 `.each`、`.only`、`.skip`) | 通过项目的测试脚本运行 Jest 或 Vitest;Deno、Bun | +| JavaScript / TypeScript | `test`、`it`、`describe`、`suite`、`context`(含 `.each`、`.only`、`.skip`) | 用测试脚本运行 Jest 或 Vitest;Playwright;Deno、Bun | | Python | pytest 的 `def test_*`、`class Test*`,unittest 的 `TestCase` 子类 | pytest、Django `manage.py test` | | Go | `func TestX(t *testing.T)`、基准测试 | `go test` | | Java、Kotlin、Scala、Groovy | JUnit `@Test`、`@ParameterizedTest`、`@RepeatedTest`、`@TestFactory`、`@TestTemplate`;TestNG | Maven Surefire(`-Dtest=`)或 Gradle(`--tests`) | @@ -62,7 +62,7 @@ RSpec 有自己的配置类型(**RSpec 测试**)和检测到的 `rspec` 配 | **重新运行**(在“运行”工具窗口中) | `⌘R` | `Ctrl+F5` | | **重新运行失败的测试** | — | — | -**重新运行失败的测试**(在“运行”工具窗口工具栏和“查找操作”中)只运行上一次失败的测试,会按各个工具自己的过滤语法生成命令。支持 Cargo、Jest / Vitest、pytest、Django、PHPUnit、Go、Maven / Gradle 和 .NET,以及插件接入的测试框架。 +**重新运行失败的测试**(在“运行”工具窗口工具栏和“查找操作”中)只运行上一次失败的测试,会按各个工具自己的过滤语法生成命令。支持 Cargo、Jest / Vitest、Playwright、pytest、Django、PHPUnit、Go、Maven / Gradle 和 .NET,以及插件接入的测试框架。 ## 在代码和测试之间跳转 diff --git a/docs/zh/languages/javascript.mdx b/docs/zh/languages/javascript.mdx index 912cbaa6f..80a318d85 100644 --- a/docs/zh/languages/javascript.mdx +++ b/docs/zh/languages/javascript.mdx @@ -74,7 +74,8 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript 打开项目时,OpenIDEA 会自动检测运行配置: -- 每个 `package.json` 脚本一个配置(`npm run build`、`pnpm run dev` 等),覆盖根包、嵌套包和 workspace 成员。名为 `test`、`jest`、`vitest` 或 `test:*` 的脚本是测试配置。 +- 每个 `package.json` 脚本一个配置(`npm run build`、`pnpm run dev` 等),覆盖根包、嵌套包和 workspace 成员。名为 `test`、`jest`、`vitest` 或 `test:*` 的脚本,以及运行 `playwright test` 的脚本,是测试配置。 +- 有 `playwright.config.*` 但没有脚本运行它的包:通过 `npx` 运行的 `playwright test`。 - `deno.json` / `deno.jsonc` 中每个 task 一个配置(`deno task `)。 在 `package.json` 中,每个 `scripts` 条目旁的边栏图标可以直接运行或调试该脚本。 @@ -85,7 +86,7 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript - 其他 `.js` 文件用 `node` 运行(项目含 `deno.json` 或 `bun.lock` 时改用 `deno run` 或 `bun run`)。 - `.ts` 文件在 Node.js 22.18+ / 23.6+ 上直接运行,在 22.6–22.17 和 23.0–23.5 上加 `--experimental-strip-types`,更早的版本则通过 `tsx` 或 `ts-node` 运行。 -Jest 和 Vitest 的输出会解析成测试树,支持 **重新运行失败的测试**。**使用覆盖率运行** 支持调用 `vitest` 或 `jest` 的脚本(Vitest 需要 `@vitest/coverage-v8` 之类的覆盖率 provider,缺失时 IDE 会提示添加),以及通过 `c8` 运行的 `node` / `tsx` / `ts-node`。详见[测试](/zh/guide/testing)和[覆盖率](/zh/guide/coverage)。 +Jest、Vitest 和 Playwright Test 的输出会解析成测试树,支持 **重新运行失败的测试**。Playwright 运行时使用它的 `list` 报告器(配置里指定了其他报告器时除外);从行号栏运行单个测试时按行号选择(`file:line`),有多个 project 的运行会在文件下按 project 分组。**使用覆盖率运行** 支持调用 `vitest` 或 `jest` 的脚本(Vitest 需要 `@vitest/coverage-v8` 之类的覆盖率 provider,缺失时 IDE 会提示添加),以及通过 `c8` 运行的 `node` / `tsx` / `ts-node`。详见[测试](/zh/guide/testing)和[覆盖率](/zh/guide/coverage)。 ## 调试 diff --git a/fixtures/README.md b/fixtures/README.md index b15ecc6a4..61c56b910 100644 --- a/fixtures/README.md +++ b/fixtures/README.md @@ -9,6 +9,7 @@ something to show. | ---------------- | --------------------------------------------------------------- | ----------------------------------- | -------------------- | ------------------------------------- | -------------------------------------------------------- | | `rust-app/` | cargo | `cargo run` | `cargo test` | `cargo test --features failing-tests` | unused variable in `src/parser.rs` | | `ts-app/` | Node 22+, pnpm/npm | `pnpm start` | `pnpm test` (vitest) | `OPENIDEA_FAIL=1 pnpm test` | unused function in `src/index.ts` | +| `playwright-app/` | Node 22+, npm (Playwright Test, no browser needed) | — | `npm test` | `OPENIDEA_FAIL=1 npm test` | unused function in `src/checkout.ts` | | `python-app/` | Python 3.10+, pytest | `python -m tasks.cli` (from `src/`) | `pytest` | `OPENIDEA_FAIL=1 pytest` | unused imports in `models.py` | | `go-app/` | Go 1.22+ | `go run ./cmd/server` | `go test ./...` | `OPENIDEA_FAIL=1 go test ./...` | unused `fmt.Sprintf` result in `internal/store/store.go` | | `kotlin-gradle/` | JDK 21, Gradle 8 (no wrapper) | `gradle run` | `gradle test` | `gradle test -PopenideaFail` | unused variable in `App.kt` | @@ -39,7 +40,7 @@ git init -q && git add -A && git commit -qm "initial" # for the VCS checks ``` Then open the folder with **File › Open…** (`⌘⇧⌥O`) or from the Welcome screen. -For `ts-app` / `polyglot/web` run `pnpm install` first; for `python-app` create a +For `ts-app` / `playwright-app` / `polyglot/web` run `pnpm install` first; for `python-app` create a venv (`python3 -m venv .venv && .venv/bin/pip install -e '.[dev]'`); for `php-app` run `composer install` (debugging it needs Xdebug in the PHP on `PATH`). diff --git a/fixtures/playwright-app/.gitignore b/fixtures/playwright-app/.gitignore new file mode 100644 index 000000000..456957827 --- /dev/null +++ b/fixtures/playwright-app/.gitignore @@ -0,0 +1,3 @@ +node_modules +test-results +playwright-report diff --git a/fixtures/playwright-app/package.json b/fixtures/playwright-app/package.json new file mode 100644 index 000000000..35d1d4a69 --- /dev/null +++ b/fixtures/playwright-app/package.json @@ -0,0 +1,15 @@ +{ + "name": "openidea-fixture-checkout", + "version": "0.1.0", + "private": true, + "description": "OpenIDEA QA fixture: Playwright Test specs for a checkout module (no browser needed)", + "type": "module", + "scripts": { + "test": "playwright test", + "lint": "tsc -p . --noEmit" + }, + "devDependencies": { + "@playwright/test": "^1.56.0", + "typescript": "^5.6.0" + } +} diff --git a/fixtures/playwright-app/playwright.config.ts b/fixtures/playwright-app/playwright.config.ts new file mode 100644 index 000000000..99313f18c --- /dev/null +++ b/fixtures/playwright-app/playwright.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from "@playwright/test"; + +// The IDE replaces the reporter with `list` for its test tree; `dot` is what a terminal shows. +export default defineConfig({ + testDir: "tests", + reporter: "dot", +}); diff --git a/fixtures/playwright-app/src/checkout.ts b/fixtures/playwright-app/src/checkout.ts new file mode 100644 index 000000000..a213a6593 --- /dev/null +++ b/fixtures/playwright-app/src/checkout.ts @@ -0,0 +1,27 @@ +export interface Line { + sku: string; + price: number; + quantity: number; +} + +const FREE_SHIPPING_FROM = 50; + +export function subtotal(lines: Line[]): number { + return lines.reduce((sum, l) => sum + l.price * l.quantity, 0); +} + +export function shipping(lines: Line[]): number { + // TODO: shipping by weight instead of a flat rate + return subtotal(lines) >= FREE_SHIPPING_FROM ? 0 : 4.99; +} + +export function applyCoupon(total: number, code: string): number { + if (code === "HALF") return Math.round(total * 50) / 100; + if (code === "TENOFF") return Math.max(0, total - 10); + throw new Error(`unknown coupon: ${code}`); +} + +// An intentional warning: never used. +function roundUp(value: number): number { + return Math.ceil(value); +} diff --git a/fixtures/playwright-app/tests/checkout.spec.ts b/fixtures/playwright-app/tests/checkout.spec.ts new file mode 100644 index 000000000..315ce0703 --- /dev/null +++ b/fixtures/playwright-app/tests/checkout.spec.ts @@ -0,0 +1,36 @@ +import { expect, test } from "@playwright/test"; +import { applyCoupon, shipping, subtotal, type Line } from "../src/checkout.ts"; + +const mug: Line = { sku: "mug", price: 12, quantity: 2 }; +const lamp: Line = { sku: "lamp", price: 40, quantity: 1 }; + +test.describe("checkout", () => { + test("adds up the lines", () => { + expect(subtotal([mug, lamp])).toBe(64); + }); + + test.describe("shipping", () => { + test("is free from 50", () => { + expect(shipping([mug, lamp])).toBe(0); + }); + + test("is a flat rate below 50", () => { + expect(shipping([mug])).toBe(4.99); + }); + }); + + test("intentionally fails (set OPENIDEA_FAIL=1)", () => { + test.skip(!process.env.OPENIDEA_FAIL, "set OPENIDEA_FAIL=1"); + expect(shipping([lamp])).toBe(0); + }); +}); + +test.describe("coupons", () => { + test("halves the total", () => { + expect(applyCoupon(64, "HALF")).toBe(32); + }); + + test("rejects unknown codes", () => { + expect(() => applyCoupon(64, "NOPE")).toThrow("unknown coupon"); + }); +}); diff --git a/fixtures/playwright-app/tsconfig.json b/fixtures/playwright-app/tsconfig.json new file mode 100644 index 000000000..9e626e1e5 --- /dev/null +++ b/fixtures/playwright-app/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "noUnusedLocals": true, + "allowImportingTsExtensions": true, + "noEmit": true, + "skipLibCheck": true + }, + "include": ["src", "tests", "playwright.config.ts"] +} diff --git a/smoke/run.test.ts b/smoke/run.test.ts index 6be950dca..f5a3bf5dd 100644 --- a/smoke/run.test.ts +++ b/smoke/run.test.ts @@ -1,5 +1,5 @@ /** - * Running and testing each language's `fixtures/` project the way the Run tool window does: + * Running and testing each language's `fixtures/` projects the way the Run tool window does: * the backend detects the configurations, the run store starts them (with its test * reporting), parses the output into the test tree, and reruns the failed tests. */ @@ -50,19 +50,36 @@ const env = (config: RunConfig, vars: Record): RunConfig => ({ }); const args = (config: RunConfig, extra: string[]): RunConfig => ({ ...config, args: [...config.args, ...extra] }); -const CASES: Record = { - typescript: { - fixture: "ts-app", - setup: (root) => execFileSync("npm", ["install", "--no-audit", "--no-fund"], { cwd: root, stdio: "ignore" }), - run: { config: "npm:start", prints: "Total: $134.97" }, - tests: { - config: "npm:test", - failing: (c) => env(c, { OPENIDEA_FAIL: "1" }), - passed: 4, - failed: "intentionally fails (set OPENIDEA_FAIL=1)", - file: "tests/cart.test.ts", +const npmInstall = (root: string) => + execFileSync("npm", ["install", "--no-audit", "--no-fund"], { cwd: root, stdio: "ignore" }); + +/** Each language's fixtures, run one after the other (the JavaScript test runners' in the TypeScript job). */ +const CASES: Record = { + typescript: [ + { + fixture: "ts-app", + setup: npmInstall, + run: { config: "npm:start", prints: "Total: $134.97" }, + tests: { + config: "npm:test", + failing: (c) => env(c, { OPENIDEA_FAIL: "1" }), + passed: 4, + failed: "intentionally fails (set OPENIDEA_FAIL=1)", + file: "tests/cart.test.ts", + }, }, - }, + { + fixture: "playwright-app", + setup: npmInstall, + tests: { + config: "npm:test", + failing: (c) => env(c, { OPENIDEA_FAIL: "1" }), + passed: 5, + failed: "intentionally fails (set OPENIDEA_FAIL=1)", + file: "tests/checkout.spec.ts", + }, + }, + ], python: { fixture: "python-app", // A project venv with pytest, as the fixture's README sets it up. @@ -154,15 +171,20 @@ let server: Server | null = null; let disconnect: (() => void) | null = null; let base = ""; -afterEach(async () => { +async function close() { // As switching projects does: run ids restart with each server. resetRuns(); disconnect?.(); + disconnect = null; await server?.close(); + server = null; // A language server's own process (jdtls's JVM) can outlive the server's for a moment: // deleting its data directory has to wait for it. if (base) rmSync(base, { recursive: true, force: true, maxRetries: 10, retryDelay: 1000 }); -}); + base = ""; +} + +afterEach(close); async function open(c: Case): Promise { base = realpathSync(mkdtempSync(join(tmpdir(), "openidea-smoke-"))); @@ -208,8 +230,7 @@ async function runToEnd(config: RunConfig, timeoutMs = 8 * 60_000): Promise<{ id return { id: session.id, output }; } -async function smoke(language: string) { - const c = CASES[language]!; +async function smoke(c: Case) { await open(c); if (c.run) { @@ -258,6 +279,11 @@ async function smoke(language: string) { expect(again.firstFailure()?.name).toBe(c.tests.failed); } -for (const language of Object.keys(CASES)) { - test(language, () => smoke(language)); +for (const [language, cases] of Object.entries(CASES)) { + test(language, async () => { + for (const [i, c] of [cases].flat().entries()) { + if (i > 0) await close(); + await smoke(c); + } + }); } diff --git a/src/bindings.ts b/src/bindings.ts index 63d52c4c6..5953c313c 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -11146,6 +11146,12 @@ export type RunExtras_Deserialize = { stopCommand?: string | null, /** Settings › Run Targets id the process runs on (over SSH); `None` = this machine. */ target?: string | null, + /** + * The test framework a test configuration runs when detection recognised one that the + * command line doesn't name (a `package.json` script running `playwright test`): picks the + * test output parser and how a single test is selected. + */ + testRunner?: string | null, }; export type RunExtras_Serialize = { @@ -11190,6 +11196,12 @@ export type RunExtras_Serialize = { stopCommand?: string | null, /** Settings › Run Targets id the process runs on (over SSH); `None` = this machine. */ target?: string | null, + /** + * The test framework a test configuration runs when detection recognised one that the + * command line doesn't name (a `package.json` script running `playwright test`): picks the + * test output parser and how a single test is selected. + */ + testRunner?: string | null, }; /** A process started from a run configuration. */ diff --git a/src/features/run/context.ts b/src/features/run/context.ts index 8d9b597ef..9f227a8be 100644 --- a/src/features/run/context.ts +++ b/src/features/run/context.ts @@ -9,6 +9,7 @@ import { djangoLabel, djangoTestsOf, hasDjangoTests } from "./djangoTypes"; import { inGradleModule } from "./gradleModuleTests"; import { systemPython } from "./pythonTypes"; import { phpunitArgs } from "./testing/phpunit"; +import { frameworkFor } from "./testing"; import { goTestParts } from "./goArguments"; import { goBuildType } from "./goTypes"; import { isWindows } from "./jvmTypes"; @@ -54,7 +55,7 @@ const stem = (p: string) => (p.split("/").pop() ?? p).replace(/\.[^.]+$/, ""); /** Kinds whose test configs can run a file of this extension. */ function testKinds(relPath: string): string[] { if (/\.cs$/i.test(relPath)) return ["dotnet-test"]; - if (/\.[cm]?[jt]sx?$/.test(relPath)) return ["npm", "deno", "bun"]; + if (/\.[cm]?[jt]sx?$/.test(relPath)) return ["npm", "deno", "bun", "node"]; if (/\.py$/.test(relPath)) return ["pytest", "python", "django-test"]; if (/\.php$/.test(relPath)) return ["phpunit"]; if (/_spec\.rb$/.test(relPath)) return ["rspec", "rake", "ruby"]; @@ -198,18 +199,31 @@ function applyPytestTemplate(config: RunConfig): RunConfig { return { ...config, command: line.command, args: line.args }; } +/** A Playwright spec: it imports Playwright Test, or uses its `test.describe` / `test.step` / `test.use`. */ +export function isPlaywrightSpec(content: string): boolean { + return /['"]@playwright\/test['"]|\btest\.(?:describe|step|use)\s*[.(]/.test(content); +} + +/** A project with Playwright and another JS runner: specs run on Playwright's configurations, other tests on the rest. */ +function byRunner(bases: RunConfig[], content: string): RunConfig[] { + const playwright = bases.filter((c) => frameworkFor(c) === "playwright"); + if (!playwright.length || playwright.length === bases.length) return bases; + return isPlaywrightSpec(content) ? playwright : bases.filter((c) => !playwright.includes(c)); +} + /** * Test configurations that can run `relPath` equally well (same, closest working * directory: `npm run test` and `npm run test:unit`…); the default one first. + * `content` (the file's text) tells a Playwright spec from other JS tests. */ -export function testBasesFor(relPath: string, configs: RunConfig[]): RunConfig[] { +export function testBasesFor(relPath: string, configs: RunConfig[], content?: string): RunConfig[] { const kinds = testKinds(relPath); // Configurations produced from a test or file are results of narrowing, never bases for it. const candidates = configs .filter((c) => c.isTest && kinds.includes(c.kind) && !c.id.startsWith("context:")) .sort((a, b) => kinds.indexOf(a.kind) - kinds.indexOf(b.kind)); const best = allClosest(candidates, relPath); - if (best.length) return best; + if (best.length) return content === undefined ? best : byRunner(best, content); const fallback = implicitPytest(relPath, configs); return fallback ? [fallback] : []; } @@ -224,7 +238,7 @@ export function testConfigFor( base?: RunConfig, content?: string, ): RunConfig | null { - base ??= testBasesFor(relPath, configs)[0]; + base ??= testBasesFor(relPath, configs, content)[0]; if (!base) return null; const file = relToCwd(relPath, base); switch (base.kind) { @@ -244,6 +258,7 @@ export function testConfigFor( return derived(base, relPath, { args }); } case "deno": + case "node": return derived(base, relPath, { args: [...base.args, file] }); case "pytest": case "python": diff --git a/src/features/run/producers.ts b/src/features/run/producers.ts index fad5a5dae..0953785fe 100644 --- a/src/features/run/producers.ts +++ b/src/features/run/producers.ts @@ -1216,7 +1216,7 @@ export function produceContextChoices(input: ContextInput, env: ToolEnv): Produc const rel = relTo(input.path, input.root); const cmake = cmakeTargets(input); if (cmake.length > 1) return cmake.map((config) => ({ name: config.name, scope: produced.scope, config })); - const bases = testBasesFor(rel, [...input.configs]); + const bases = testBasesFor(rel, [...input.configs], input.content); if (bases.length < 2) return [produced]; let element: RunTarget | null = null; if (produced.scope === "element") { diff --git a/src/features/run/targets.ts b/src/features/run/targets.ts index 4335e0f2a..bbb89df13 100644 --- a/src/features/run/targets.ts +++ b/src/features/run/targets.ts @@ -17,6 +17,7 @@ import { djangoLabel, djangoTestsOf } from "./djangoTypes"; import { scanJvmTargets, simpleClassName } from "./jvmTargets"; import { escapeRegExp } from "./testing/rerun"; import { pestFilter, phpunitArgs, phpunitFilter } from "./testing/phpunit"; +import { frameworkFor } from "./testing"; export type TargetKind = "main" | "test" | "suite" | "generate"; @@ -132,8 +133,9 @@ function rustTargets(lines: string[], relPath: string): RunTarget[] { ); } +/** Jest / Vitest `describe` / `test` / `it`, and Playwright's `test.describe` and modifiers. */ const JS_RE = - /^(\s*)(describe|suite|context|test|it)\b(?:\.(?:only|skip|todo|concurrent|failing|sequential))*(\.each\s*(?:\(.*?\)|`[^`]*`))?\s*\(\s*(['"`])((?:\\.|(?!\4).)*)\4/; + /^(\s*)(test\.describe|describe|suite|context|test|it)\b(?:\.(?:only|skip|todo|concurrent|failing|sequential|fixme|fail|serial|parallel))*(\.each\s*(?:\(.*?\)|`[^`]*`))?\s*\(\s*(['"`])((?:\\.|(?!\4).)*)\4/; function jsTargets(lines: string[]): RunTarget[] { const out: RunTarget[] = []; @@ -146,7 +148,7 @@ function jsTargets(lines: string[]): RunTarget[] { const name = m[5]!.replace(/\\(.)/g, "$1"); const parameterized = !!m[3] || (m[4] === "`" && name.includes("${")) || /%[sdifjo#%p]|\$\w+/.test(name); const path = [...stack.map((s) => s.name), name]; - const isSuite = m[2] === "describe" || m[2] === "suite" || m[2] === "context"; + const isSuite = m[2] === "test.describe" || m[2] === "describe" || m[2] === "suite" || m[2] === "context"; out.push({ line: i, kind: isSuite ? "suite" : "test", name: path.join(" > "), path, parameterized }); if (isSuite) stack.push({ indent, name }); } @@ -469,6 +471,8 @@ export function targetConfig( env: { ...file.env }, detected: true, }); + // Playwright selects by declaration line (`file:line`), which also covers a describe block. + if (frameworkFor(file) === "playwright") return named(withLast(file.args, (f) => `${f}:${target.line + 1}`)); switch (file.kind) { case "dotnet-test": { const methods = @@ -482,6 +486,7 @@ export function targetConfig( case "npm": case "bun": case "deno": + case "node": return named([...file.args, "-t", jsNamePattern(target)]); case "pytest": case "python": diff --git a/src/features/run/testing/index.ts b/src/features/run/testing/index.ts index 901020c92..1695d8e62 100644 --- a/src/features/run/testing/index.ts +++ b/src/features/run/testing/index.ts @@ -5,11 +5,13 @@ import { goParser } from "./go"; import { jsParser } from "./js"; import { jvmParser } from "./jvm"; import { phpunitParser, withTeamcity } from "./phpunit"; +import { playwrightParser } from "./playwright"; import { pytestParser } from "./pytest"; import { rubyParser } from "./ruby"; import { unittestParser } from "./unittest"; import { zigParser } from "./zig"; import type { TestEvent, TestOutputParser } from "./types"; +import { appendScriptArgs } from "../scriptArgs"; export type { TestEvent, TestOutputParser, TestStatus } from "./types"; export { formatDuration, parseDuration } from "./types"; @@ -20,6 +22,7 @@ export { jsParser, jvmParser, phpunitParser, + playwrightParser, pytestParser, rubyParser, unittestParser, @@ -37,6 +40,7 @@ export function combinedParser(parsers: TestOutputParser[]): TestOutputParser { export type Framework = | "cargo" | "js" + | "playwright" | "pytest" | "unittest" | "phpunit" @@ -47,8 +51,12 @@ export type Framework = | "zig" | "auto"; -export function frameworkFor(config: Pick): Framework { +type FrameworkConfig = Pick & Partial>; + +export function frameworkFor(config: FrameworkConfig): Framework { const cmd = [config.command, ...config.args].join(" "); + // A `package.json` script names its runner only in package.json: detection records it. + if (config.testRunner === "playwright" || /\bplaywright\s+test\b/.test(cmd)) return "playwright"; switch (config.kind) { case "dotnet-test": return "dotnet"; @@ -111,7 +119,12 @@ function rubyVerbose>(con * reach the tree. `-v` (Django: `-v 2`) adds one line per test (live, like * IDEA's runner) unless the user chose a verbosity already. */ -export function withTestReporting>(config: T): T { +export function withTestReporting(config: T): T { + if (frameworkFor(config) === "playwright") { + // The list reporter prints a line per test; a project's own (`html`, `dot` on CI) may print none. + const chosen = config.args.some((a) => a === "--reporter" || a.startsWith("--reporter=")); + return chosen ? config : { ...config, args: appendScriptArgs(config.command, config.args, ["--reporter=list"]) }; + } if (frameworkFor(config) === "go" && config.args[0] === "test") { const boundary = config.args.findIndex((a) => a === "-args" || a === "--"); const tool = boundary < 0 ? config.args : config.args.slice(0, boundary); @@ -139,7 +152,7 @@ export function withTestReporting): TestOutputParser { +export function createTestParser(config: FrameworkConfig): TestOutputParser { switch (frameworkFor(config)) { case "dotnet": return { feed: () => [] }; @@ -147,6 +160,8 @@ export function createTestParser(config: Pick & { id: string; kind: string }): RunConfig => ({ + name: over.id, + command: over.kind, + args: [], + cwd: null, + env: {}, + detected: true, + isTest: true, + debugAdapter: "js-debug", + ...over, +}); + +/** `npm run e2e` whose script is `playwright test` (detection records the runner). */ +const script = cfg({ id: "npm:e2e", kind: "npm", command: "npm", args: ["run", "e2e"], testRunner: "playwright" }); +/** The configuration detected for a `playwright.config.ts` no script runs. */ +const npx = cfg({ id: "playwright", kind: "node", command: "npx", args: ["playwright", "test"] }); + +function results(text: string, config: RunConfig = script) { + const r = new TestResults(); + r.apply(parseAll(createTestParser(config), text)); + return r; +} + +const key = (...path: string[]) => path.join("\u0000"); + +// `npx playwright test --reporter=list` in a Windows console (no UTF-8 marks), as printed. +const WINDOWS = ` +Running 5 tests using 1 worker + + ok 1 tests\\cart.spec.ts:4:3 › cart › adds items (2ms) + ok 2 tests\\cart.spec.ts:8:5 › cart › totals › sums (0ms) + x 3 tests\\cart.spec.ts:12:3 › cart › fails (1ms) + - 4 tests\\cart.spec.ts:15:8 › cart › skipped one +hello from test + ok 5 tests\\cart.spec.ts:18:1 › top level (0ms) + + + 1) tests\\cart.spec.ts:12:3 › cart › fails ─────────────────────────────────────── + + Error: expect(received).toBe(expected) // Object.is equality + + Expected: 2 + Received: 1 + + 11 | }); + 12 | test("fails", () => { + > 13 | expect(1).toBe(2); + | ^ + 14 | }); + at C:\\work\\shop\\tests\\cart.spec.ts:13:15 + + 1 failed + tests\\cart.spec.ts:12:3 › cart › fails ─────────────────────────────────────── + 1 skipped + 3 passed (563ms) +`; + +// macOS / Linux, with projects and a retried test. +const PROJECTS = ` +Running 4 tests using 2 workers + + ✓ 1 [chromium] › e2e/home.spec.ts:3:5 › home › has title (1.2s) + ✘ 2 [firefox] › e2e/home.spec.ts:3:5 › home › has title (5.0s) + ✓ 3 [firefox] › e2e/home.spec.ts:3:5 › home › has title (retry #1) (980ms) + ✘ 4 [chromium] › e2e/home.spec.ts:9:5 › home › links @smoke (1.0m) + + 1) [chromium] › e2e/home.spec.ts:9:5 › home › links @smoke ────────────────────── + + Error: Timed out 5000ms waiting for expect(locator).toBeVisible() + + 1 failed + [chromium] › e2e/home.spec.ts:9:5 › home › links @smoke ──────────────────────── + 1 flaky + [firefox] › e2e/home.spec.ts:3:5 › home › has title ──────────────────────────── + 1 passed (1.1m) +`; + +describe("Playwright list reporter", () => { + it("builds the tree from file, describe chain and title, with durations and locations", () => { + const r = results(WINDOWS); + expect(r.counts()).toMatchObject({ passed: 3, failed: 1, skipped: 1 }); + expect(r.roots.map((n) => n.name)).toEqual(["tests/cart.spec.ts"]); + const sums = r.get(key("tests/cart.spec.ts", "cart", "totals", "sums"))!; + expect(sums.own).toBe("passed"); + expect(sums.durationMs).toBe(0); + expect(sums.location).toEqual({ path: "tests/cart.spec.ts", line: 8, col: 5, resolve: "path" }); + expect(r.get(key("tests/cart.spec.ts", "cart", "skipped one"))?.own).toBe("skipped"); + expect(r.get(key("tests/cart.spec.ts", "top level"))?.own).toBe("passed"); + expect(r.summary).toMatchObject({ passed: 3, failed: 1, skipped: 1, durationMs: 563 }); + }); + + it("keeps a failure's details, up to the summary", () => { + const r = results(WINDOWS); + const failure = r.firstFailure()!; + expect(failure.path).toEqual(["tests/cart.spec.ts", "cart", "fails"]); + expect(failure.location).toMatchObject({ path: "tests/cart.spec.ts", line: 12 }); + const output = nodeOutput(failure).join("\n"); + expect(output).toContain("Expected: 2"); + expect(output).toContain("at C:\\work\\shop\\tests\\cart.spec.ts:13:15"); + expect(output).not.toContain("1 skipped"); + }); + + it("groups by project; a test that passed only on a retry (flaky) stays failed", () => { + const r = results(PROJECTS); + expect(r.get(key("e2e/home.spec.ts", "[chromium]", "home", "has title"))?.own).toBe("passed"); + const firefox = r.get(key("e2e/home.spec.ts", "[firefox]", "home", "has title"))!; + expect(firefox.own).toBe("failed"); + expect(firefox.durationMs).toBe(980); + const links = r.get(key("e2e/home.spec.ts", "[chromium]", "home", "links @smoke"))!; + expect(links.own).toBe("failed"); + expect(links.durationMs).toBe(60_000); + expect(nodeOutput(links).join("\n")).toContain("Timed out 5000ms"); + expect(r.counts()).toMatchObject({ passed: 1, failed: 2 }); + }); +}); + +describe("Playwright configurations", () => { + it("are recognised by the recorded runner or the command line", () => { + expect(frameworkFor(script)).toBe("playwright"); + expect(frameworkFor(npx)).toBe("playwright"); + expect(frameworkFor({ kind: "shell", command: "pnpm exec playwright test --ui", args: [] })).toBe("playwright"); + expect(frameworkFor({ kind: "npm", command: "npm", args: ["run", "test"] })).toBe("js"); + }); + + it("report through the list reporter unless the configuration chose one", () => { + expect(withTestReporting(script).args).toEqual(["run", "e2e", "--", "--reporter=list"]); + expect(withTestReporting(npx).args).toEqual(["playwright", "test", "--reporter=list"]); + const chosen = { ...npx, args: ["playwright", "test", "--reporter=dot"] }; + expect(withTestReporting(chosen)).toBe(chosen); + }); + + it("rerun failed tests by file and title, per project", async () => { + const one = await rerunFailedConfigs(script, failedTestPaths(results(WINDOWS))); + expect(one.map((c) => c.args)).toEqual([ + ["run", "e2e", "--", "tests/cart.spec.ts", "--grep", "(?:^| )(?:cart fails)(?: @\\S+)*$"], + ]); + expect(new RegExp(one[0]!.args.at(-1)!).test(" cart.spec.ts cart fails @slow")).toBe(true); + expect(new RegExp(one[0]!.args.at(-1)!).test(" cart.spec.ts cart fails later")).toBe(false); + + const paths = [ + ["e2e/a.spec.ts", "[chromium]", "a", "one"], + ["e2e/b.spec.ts", "[firefox]", "b.c", "two"], + ]; + const split = await testsConfigs({ ...npx, args: ["playwright", "test", "--project=webkit"] }, paths, "2 tests"); + expect(split.map((c) => [c.name, c.args])).toEqual([ + [ + "2 tests (chromium)", + ["playwright", "test", "e2e/a.spec.ts", "--grep", "(?:^| )(?:a one)(?: @\\S+)*$", "--project", "chromium"], + ], + [ + "2 tests (firefox)", + ["playwright", "test", "e2e/b.spec.ts", "--grep", "(?:^| )(?:b\\.c two)(?: @\\S+)*$", "--project", "firefox"], + ], + ]); + }); +}); + +describe("Playwright gutter targets", () => { + const spec = [ + 'import { test, expect } from "@playwright/test";', // 0 + "", + "test.describe('cart', () => {", // 2 + " test.describe.serial('totals', () => {", // 3 + " test('sums', async ({ page }) => {});", // 4 + " test.fixme('rounds', async () => {});", // 5 + " });", + " test.fail('known bug', async () => {", // 7 + " await test.step('opens', async () => {});", + " });", + "});", + ].join("\n"); + + it("finds test.describe blocks and modified tests, not steps", () => { + expect(detectRunTargets(spec, "e2e/cart.spec.ts").map((t) => [t.line, t.kind, t.path.join("/")])).toEqual([ + [2, "suite", "cart"], + [3, "suite", "cart/totals"], + [4, "test", "cart/totals/sums"], + [5, "test", "cart/totals/rounds"], + [7, "test", "cart/known bug"], + ]); + }); + + it("run a test or describe block by its declaration line", () => { + const [cart, , sums] = detectRunTargets(spec, "e2e/cart.spec.ts"); + expect(targetConfig(sums!, "e2e/cart.spec.ts", [script], spec)?.args).toEqual([ + "run", + "e2e", + "--", + "e2e/cart.spec.ts:5", + ]); + const web = { ...npx, cwd: "web", module: "web" }; + expect(targetConfig(cart!, "web/e2e/cart.spec.ts", [web], spec)?.args).toEqual([ + "playwright", + "test", + "e2e/cart.spec.ts:3", + ]); + }); + + it("send specs to Playwright and other tests to the project's other runner", () => { + const vitest = cfg({ id: "npm:test", kind: "npm", command: "npm", args: ["run", "test"] }); + const configs = [vitest, npx]; + expect(testBasesFor("e2e/cart.spec.ts", configs, spec).map((c) => c.id)).toEqual(["playwright"]); + const unit = "import { test } from 'vitest';\ntest('adds', () => {});"; + expect(testBasesFor("src/cart.test.ts", configs, unit).map((c) => c.id)).toEqual(["npm:test"]); + expect(testBasesFor("src/cart.test.ts", configs).map((c) => c.id)).toEqual(["npm:test", "playwright"]); + }); +}); diff --git a/src/features/run/testing/playwright.ts b/src/features/run/testing/playwright.ts new file mode 100644 index 000000000..b4703616e --- /dev/null +++ b/src/features/run/testing/playwright.ts @@ -0,0 +1,101 @@ +/** + * Playwright Test's `list` reporter (the run adds `--reporter=list`): one line per finished + * test, ` ✓ 3 [chromium] › tests/cart.spec.ts:12:3 › cart › adds (25ms)` (`ok` / `x` on + * Windows consoles), then the failures' details and the summary. + */ +import { parseDuration, type TestEvent, type TestOutputParser, type TestStatus } from "./types"; + +const SEP = " › "; +const RESULT_RE = /^\s+(✓|ok|✘|x|-)\s+\d+\s+(.+)$/; +const FAILURE_HEADER_RE = /^\s+\d+\) (.+?) ─+$/; +const SUMMARY_RE = /^\s+(\d+) (passed|failed|flaky|skipped|did not run|interrupted)(?: \(([^)]+)\))?$/; +const TITLE_LOCATION_RE = /^(.+):(\d+):(\d+)$/; +const DURATION_RE = /\s\((\d+(?:\.\d+)?(?:ms|s|m|h))\)$/; +const RETRY_RE = /\s\(retry #\d+\)$/; + +/** A printed test title: `[project] › file:line:col › describe › test`. */ +export interface PlaywrightTitle { + /** Results tree path: the file, `[project]` when the run names projects, then the titles. */ + path: string[]; + file: string; + line: number; + col: number; +} + +export function parsePlaywrightTitle(text: string): PlaywrightTitle | null { + const parts = text.split(SEP); + const project = /^\[(.+)\]$/.exec(parts[0] ?? ""); + if (project) parts.shift(); + const loc = TITLE_LOCATION_RE.exec(parts.shift() ?? ""); + if (!loc || !parts.length) return null; + const file = loc[1]!.replace(/\\/g, "/"); + return { + path: [file, ...(project ? [`[${project[1]}]`] : []), ...parts], + file, + line: Number(loc[2]), + col: Number(loc[3]), + }; +} + +/** The `[project]` segment of a results path, if any. */ +export function playwrightProject(path: readonly string[]): string | null { + const m = /^\[(.+)\]$/.exec(path[1] ?? ""); + return m && path.length > 2 ? m[1]! : null; +} + +/** The describe chain and test title of a results path (without the file and project). */ +export function playwrightTitles(path: readonly string[]): string[] { + return path.slice(playwrightProject(path) === null ? 1 : 2); +} + +function markStatus(mark: string): Exclude { + if (mark === "✓" || mark === "ok") return "passed"; + return mark === "-" ? "skipped" : "failed"; +} + +export function playwrightParser(): TestOutputParser { + /** The test whose failure details the following lines are. */ + let failure: string[] | null = null; + return { + feed(raw) { + const line = raw.replace(/\s+$/, ""); + const events: TestEvent[] = []; + let m: RegExpExecArray | null; + if ((m = SUMMARY_RE.exec(line))) { + failure = null; + const n = Number(m[1]); + const durationMs = parseDuration(m[3]); + if (m[2] === "passed") events.push({ type: "summary", passed: n, durationMs }); + else if (m[2] === "failed") events.push({ type: "summary", failed: n }); + else if (m[2] === "skipped") events.push({ type: "summary", skipped: n }); + return events; + } + if ((m = FAILURE_HEADER_RE.exec(line))) { + const title = parsePlaywrightTitle(m[1]!); + failure = title?.path ?? null; + return events; + } + const result = RESULT_RE.exec(line); + const duration = result && DURATION_RE.exec(result[2]!); + const title = result && parsePlaywrightTitle(result[2]!.slice(0, duration?.index).replace(RETRY_RE, "")); + if (result && title) { + // Failures print at the end, or after their test with PLAYWRIGHT_LIST_PRINT_FAILURES_INLINE. + failure = null; + events.push({ + type: "result", + path: title.path, + status: markStatus(result[1]!), + durationMs: parseDuration(duration?.[1]), + }); + events.push({ + type: "location", + path: title.path, + location: { path: title.file, line: title.line, col: title.col, resolve: "path" }, + }); + return events; + } + if (failure) events.push({ type: "output", path: failure, line: raw }); + return events; + }, + }; +} diff --git a/src/features/run/testing/rerun.ts b/src/features/run/testing/rerun.ts index cb9caa814..d3c089440 100644 --- a/src/features/run/testing/rerun.ts +++ b/src/features/run/testing/rerun.ts @@ -12,6 +12,7 @@ import { goTestParts, withoutGoSelection } from "../goArguments"; import { withMavenTests } from "../mavenTests"; import { frameworkFor } from "./index"; import { dotnetFilter } from "./dotnet"; +import { playwrightProject, playwrightTitles } from "./playwright"; import { nodeStatus, type TestNode, type TestResults } from "./results"; /** Paths of failed tests: failed leaves, plus failed suites without any failed children reported. */ @@ -86,6 +87,27 @@ function jsArgs(config: RunConfig, paths: string[][]): string[] | null { return appendScriptArgs(config.command, args, [...files, ...filter]); } +/** + * Playwright: the files, `--grep` on the describe chain and title (its grep text is the project, + * the file relative to the test directory, the titles and the tags, space separated), and the + * project when the run named one (`testsConfigs` splits a selection by project). + */ +function playwrightArgs(config: RunConfig, paths: string[][]): string[] | null { + const files = unique(paths.map((p) => p[0]!).filter(Boolean)); + if (!files.length) return null; + const titles = unique(paths.map((p) => playwrightTitles(p).join(" ")).filter(Boolean)); + const project = playwrightProject(paths[0]!); + const grep = titles.length ? ["--grep", `(?:^| )(?:${titles.map(escapeRegExp).join("|")})(?: @\\S+)*$`] : []; + const { before, after } = splitDashDash(config.args); + const flags = ["-g", "--grep", ...(project === null ? [] : ["--project"])]; + const args = after === null ? dropFlag(before, flags) : [...before, "--", ...dropFlag(after, flags)]; + return appendScriptArgs(config.command, args, [ + ...files, + ...grep, + ...(project === null ? [] : ["--project", project]), + ]); +} + function pytestArgs(base: string[], paths: string[][]): string[] | null { const ids = unique(paths.map((p) => p.join("::"))); if (!ids.length) return null; @@ -168,7 +190,7 @@ export function rerunFailedConfigs(config: RunConfig, paths: string[][]): RunCon return testsConfigs(config, paths, `Failed: ${baseName}`); } -/** Go filters apply to every package in an invocation, so each package keeps its own selection. */ +/** Go filters apply to every package of an invocation, Playwright's to every project: each keeps its own selection. */ export function testsConfigs(config: RunConfig, paths: string[][], name: string): RunConfig[] | Promise { if (!paths.length) return []; if (config.params?.framework === "plugin") { @@ -177,8 +199,10 @@ export function testsConfigs(config: RunConfig, paths: string[][], name: string) return selected instanceof Promise ? selected.then(list) : list(selected); } const groups = new Map(); + const framework = frameworkFor(config); for (const path of paths) { - const key = frameworkFor(config) === "go" ? (path[0] ?? "") : ""; + const key = + framework === "go" ? (path[0] ?? "") : framework === "playwright" ? (playwrightProject(path) ?? "") : ""; const group = groups.get(key) ?? []; group.push(path); groups.set(key, group); @@ -235,6 +259,9 @@ function builtinTestsConfig(config: RunConfig, paths: string[][], name: string): case "js": args = jsArgs(config, paths); break; + case "playwright": + args = playwrightArgs(config, paths); + break; case "pytest": args = pytestArgs(config.args, paths); break;