diff --git a/fixtures/README.md b/fixtures/README.md index eddb2089d..ed7bda4f1 100644 --- a/fixtures/README.md +++ b/fixtures/README.md @@ -25,6 +25,7 @@ something to show. | `python-profiling/` | Python 3.10+ (standard library only) | `python cpu_heavy.py` (Run › Profile) | — | — | — | | `tailwind-app/` | Node 22+, pnpm/npm, Tailwind CSS 4, React | `pnpm dev` | — | — | `flex` conflicting with `block` in `src/App.tsx` | | `zig-app/` | Zig 0.17 | `zig build run` | `zig build test` | — | — | +| `swiftpm-app/` | Swift 6+ (Xcode or a swift.org toolchain) | — | `swift test` (XCTest and Swift Testing) | `OPENIDEA_FAIL=1 swift test` | — | | `biome-app/` | Node 22+, `@biomejs/biome` (`npm install`) | `npm start` | — | — | `let` never reassigned, `==` and a duplicate CSS `color` (Biome) | | `dprint-app/` | Node 22+, `dprint` (`npm install`) | `npm start` | — | — | unformatted `src/index.ts` / `src/data.json` (dprint); `README.md` keeps Prettier | | `stylelint-app/` | Node 22+, `stylelint` (`npm install`) | — | — | — | long hex colour, unknown property, empty block, duplicate selector (Stylelint) | diff --git a/fixtures/swiftpm-app/.gitignore b/fixtures/swiftpm-app/.gitignore new file mode 100644 index 000000000..2d9f16e2d --- /dev/null +++ b/fixtures/swiftpm-app/.gitignore @@ -0,0 +1,2 @@ +.build/ +.swiftpm/ diff --git a/fixtures/swiftpm-app/Package.swift b/fixtures/swiftpm-app/Package.swift new file mode 100644 index 000000000..5bcaf9951 --- /dev/null +++ b/fixtures/swiftpm-app/Package.swift @@ -0,0 +1,12 @@ +// swift-tools-version:6.0 +import PackageDescription + +let package = Package( + name: "Tally", + // Swift Testing needs macOS 10.15, above the default deployment target of older toolchains. + platforms: [.macOS(.v10_15)], + targets: [ + .target(name: "Tally"), + .testTarget(name: "TallyTests", dependencies: ["Tally"]), + ] +) diff --git a/fixtures/swiftpm-app/Sources/Tally/Tally.swift b/fixtures/swiftpm-app/Sources/Tally/Tally.swift new file mode 100644 index 000000000..1e64afc01 --- /dev/null +++ b/fixtures/swiftpm-app/Sources/Tally/Tally.swift @@ -0,0 +1,4 @@ +/// Sums prices in cents. +public func total(_ prices: [Int]) -> Int { + prices.reduce(0, +) +} diff --git a/fixtures/swiftpm-app/Tests/TallyTests/TallySwiftTests.swift b/fixtures/swiftpm-app/Tests/TallyTests/TallySwiftTests.swift new file mode 100644 index 000000000..2b76144ea --- /dev/null +++ b/fixtures/swiftpm-app/Tests/TallyTests/TallySwiftTests.swift @@ -0,0 +1,24 @@ +import Foundation +import Testing +@testable import Tally + +@Suite struct TallySuite { + @Test func addsPrices() { + #expect(total([1, 2, 3]) == 6) + } + + @Test("Total of a single price") + func singlePrice() { + #expect(total([7]) == 7) + } + + // Fails on purpose with OPENIDEA_FAIL=1, skipped otherwise. + @Test(.enabled(if: ProcessInfo.processInfo.environment["OPENIDEA_FAIL"] != nil)) + func deliberatelyFails() { + #expect(total([1]) == 2) + } +} + +@Test func freeFunctionTest() { + #expect(total([]) == 0) +} diff --git a/fixtures/swiftpm-app/Tests/TallyTests/TallyXCTests.swift b/fixtures/swiftpm-app/Tests/TallyTests/TallyXCTests.swift new file mode 100644 index 000000000..ff542849d --- /dev/null +++ b/fixtures/swiftpm-app/Tests/TallyTests/TallyXCTests.swift @@ -0,0 +1,18 @@ +import XCTest +@testable import Tally + +final class TallyXCTests: XCTestCase { + func testTotalOfNothingIsZero() { + XCTAssertEqual(total([]), 0) + } + + func testTotalAddsPrices() { + XCTAssertEqual(total([1, 2]), 3) + } + + // Fails on purpose with OPENIDEA_FAIL=1, skipped otherwise. + func testDeliberatelyFails() throws { + try XCTSkipUnless(ProcessInfo.processInfo.environment["OPENIDEA_FAIL"] != nil) + XCTAssertEqual(total([2, 2]), 5) + } +} diff --git a/src/features/run/producers.test.ts b/src/features/run/producers.test.ts index 2e03ba0fd..8a3800c88 100644 --- a/src/features/run/producers.test.ts +++ b/src/features/run/producers.test.ts @@ -1,3 +1,5 @@ +import swiftXCTests from "../../../fixtures/swiftpm-app/Tests/TallyTests/TallyXCTests.swift?raw"; +import swiftTesting from "../../../fixtures/swiftpm-app/Tests/TallyTests/TallySwiftTests.swift?raw"; import { afterEach, describe, expect, it, vi } from "vitest"; import * as projectRoots from "@/platform/projectRoots"; import type { HierarchyItem, RunConfig } from "@/platform/ipc"; @@ -520,6 +522,66 @@ describe("single-file producers (scratches)", () => { }); }); + it("SwiftPM tests: XCTest methods, @Test functions and suites run swift test --filter in the package", () => { + const input = (path: string, content: string, line?: number): ContextInput => ({ + path: `${ROOT}/${path}`, + root: ROOT, + configs: [], + content, + line, + }); + const xc = "fixtures/swiftpm-app/Tests/TallyTests/TallyXCTests.swift"; + const st = "fixtures/swiftpm-app/Tests/TallyTests/TallySwiftTests.swift"; + expect(fileTargets(input(xc, swiftXCTests), swiftXCTests).map((t) => [t.kind, t.name, t.line])).toEqual([ + ["suite", "TallyXCTests", 3], + ["test", "TallyXCTests.testTotalOfNothingIsZero", 4], + ["test", "TallyXCTests.testTotalAddsPrices", 8], + ["test", "TallyXCTests.testDeliberatelyFails", 13], + ]); + expect(fileTargets(input(st, swiftTesting), swiftTesting).map((t) => [t.kind, t.name, t.line])).toEqual([ + ["suite", "TallySuite", 4], + ["test", "TallySuite.addsPrices", 5], + ["test", "TallySuite.singlePrice", 10], + ["test", "TallySuite.deliberatelyFails", 16], + ["test", "freeFunctionTest", 21], + ]); + const e = env({ swift: "6.4" }); + const one = produceContext(input(xc, swiftXCTests, 9), e)!; + expect(one).toMatchObject({ name: "TallyXCTests.testTotalAddsPrices", scope: "element" }); + expect(one.config).toMatchObject({ + kind: "swift", + args: ["test", "--filter", String.raw`\.TallyXCTests/testTotalAddsPrices\b`], + cwd: "fixtures/swiftpm-app", + isTest: true, + }); + expect(produceContext(input(st, swiftTesting, 4), e)!.config!.args[2]).toBe(String.raw`\.TallySuite\b`); + expect(produceContext(input(st, swiftTesting, 21), e)!.config!.args[2]).toBe(String.raw`\.freeFunctionTest\b`); + // Nested types, attributes on their own line, a package at the project root. + const nested = [ + "import Testing", + "struct Outer {", + " @Suite(.serialized)", + " struct Inner {", + ' @Test("Each", arguments: [1, 2])', + " func each(n: Int) { #expect(n > 0) }", + " func helper() {}", + " }", + "}", + ].join("\n"); + expect(fileTargets(input("Tests/AppTests/N.swift", nested), nested).map((t) => t.path)).toEqual([ + ["Outer"], + ["Outer", "Inner"], + ["Outer", "Inner", "each"], + ]); + expect(produceContext(input("Tests/AppTests/N.swift", nested, 5), e)!.config).toMatchObject({ + args: ["test", "--filter", String.raw`\.Outer/Inner/each\b`], + cwd: null, + }); + // Outside a test target (`Sources/`), or without a test framework import: no targets. + expect(fileTargets(input("Sources/App/N.swift", nested), nested)).toEqual([]); + expect(fileTargets(input("Tests/AppTests/N.swift", "func testX() {}"), "func testX() {}")).toEqual([]); + }); + it("Rust in a Cargo project: cargo run --bin / --example, not rustc", () => { const cargo = [ cfg({ id: "cargo:run:server", kind: "cargo", command: "cargo", args: ["run", "--bin", "server"] }), diff --git a/src/features/run/producers.ts b/src/features/run/producers.ts index 893b2886e..f7babc877 100644 --- a/src/features/run/producers.ts +++ b/src/features/run/producers.ts @@ -37,6 +37,7 @@ import { firstTopLevelType, scanJvmTargets, simpleClassName } from "./jvmTargets import { isWindows } from "./jvmTypes"; import { inheritedRunTargets } from "./inheritedMain"; import { withMavenTests } from "./mavenTests"; +import { escapeRegExp } from "./testing/rerun"; import { detectRunTargets, goFuzzConfig, @@ -45,6 +46,8 @@ import { hasDoctests, specsInSpecDirectory, testsInTestDirectory, + swiftPackageDir, + swiftTargets, zigTargets, type RunTarget, } from "./targets"; @@ -691,6 +694,26 @@ function zigFile(input: ContextInput, env: ToolEnv, s: FileSite, test?: { name: return { name, scope, config, debug: { build: buildConfig, config: binary } }; } +/** + * A SwiftPM test or suite: `swift test --filter` in the package directory. The filter is a regular + * expression over `Module.Type/test()` (XCTest: `Module.Class/testX`), anchored at the module's dot. + */ +function swiftTest(env: ToolEnv, s: FileSite, target: RunTarget): Produced | null { + const dir = swiftPackageDir(s.idPath); + if (dir === null) return null; + const swift = pick(env, toolsFor("swift")); + if (!swift) return { name: target.name, scope: "element", missing: missing("swift", s.file, toolsFor("swift")) }; + const filter = `\\.${target.path.map(escapeRegExp).join("/")}\\b`; + const config: RunConfig = { + ...fileConfig(s, "swift", swift.command, ["test", "--filter", filter]), + id: `context:file:${s.idPath}#${target.path.join("/")}`, + name: target.name, + cwd: dir || null, + isTest: true, + }; + return { name: target.name, scope: "element", config }; +} + /** The executable of the file's `build.zig` whose root source file it is. */ function zigExecutable(rel: string, configs: readonly RunConfig[]): RunConfig | undefined { return buildOwners(rel, configs, ["zig-application"]).find((c) => c.params?.source === relativeToCwd(rel, c)); @@ -1162,6 +1185,7 @@ export function fileTargets( const rust = /\.rs$/.test(input.path); if (/\.(c|cpp|cc|cxx)$/.test(input.path)) return standaloneTargets(content, input.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 = s.inProject && (cargoOwner(s.rel, input.configs).length > 0 || /(^|\/)(src|tests|examples|benches)\//.test(s.rel)); if (rust && !cargo) return standaloneTargets(content, input.path); @@ -1201,6 +1225,7 @@ function elementProduction(input: ContextInput, env: ToolEnv, target: RunTarget) const file = produceFile(input, env); return file ? { ...file, scope: "element" } : null; } + if (/\.swift$/.test(input.path)) return swiftTest(env, s, target); if (/\.zig$/.test(input.path)) { // `--test-filter` matches a substring of the test's full name. return zigFile(input, env, s, { name: target.name, filter: target.name }); diff --git a/src/features/run/runGutter.ts b/src/features/run/runGutter.ts index dce4b6fc8..5f872987c 100644 --- a/src/features/run/runGutter.ts +++ b/src/features/run/runGutter.ts @@ -32,7 +32,7 @@ import { targetLanguage, type RunTarget } from "./targets"; import { onTestStatesChanged, testState, testStatesVersion, type StateQuery, type TestState } from "./testing/states"; /** Languages with gutter run targets (C / C++ `main` included). */ -const hasGutterTargets = (path: string) => !!targetLanguage(path) || /\.(c|cpp|cc|cxx|zig)$/.test(path); +const hasGutterTargets = (path: string) => !!targetLanguage(path) || /\.(c|cpp|cc|cxx|zig|swift)$/.test(path); import styles from "./Run.module.css"; import { tx } from "@/platform/i18n"; diff --git a/src/features/run/store.ts b/src/features/run/store.ts index 11016bb96..9c0f8d2c1 100644 --- a/src/features/run/store.ts +++ b/src/features/run/store.ts @@ -50,6 +50,7 @@ import { import { PluginTestOutput } from "./testing/plugin"; import { GoTestOutput } from "./testing/go"; import { RecordsOutput } from "./testing/records"; +import { SwiftTestOutput } from "./testing/swift"; import { DotnetReports } from "./testing/dotnet"; import { moveToReportedClasses } from "./testing/jvm"; import { RubyTestOutput } from "./testing/ruby"; @@ -823,7 +824,9 @@ function newRuntime(config: RunConfig): SessionRuntime { framework === "python-unittest" || framework === "python-doctest" ? new RecordsOutput(feed) - : null; + : framework === "swift" // Swift Testing's event stream + ? new SwiftTestOutput(feed) + : null; const runtime: SessionRuntime = { stdout, tests, diff --git a/src/features/run/targets.ts b/src/features/run/targets.ts index 47d064607..66e313947 100644 --- a/src/features/run/targets.ts +++ b/src/features/run/targets.ts @@ -451,6 +451,68 @@ export function zigTargets(content: string): RunTarget[] { return out; } +/** + * The package directory of a SwiftPM test file (`Tests//…`, SwiftPM's layout): `""` for the + * project root, null for files outside a test target. + */ +export function swiftPackageDir(relPath: string): string | null { + const m = /^(?:(.*)\/)?Tests\/[^/]+\/.+\.swift$/.exec(relPath); + return m ? (m[1] ?? "") : null; +} + +/** + * Swift tests: `func test…()` methods of `XCTestCase` subclasses, Swift Testing `@Test` functions + * (free or in a type), and the types holding them or marked `@Suite`. Paths are the enclosing types + * and the function (`[TallySuite, addsPrices]`), as `swift test --filter` and the results name them. + */ +export function swiftTargets(content: string): RunTarget[] { + if (content.length > MAX_SCAN || !/^\s*import\s+(XCTest|Testing)\b/m.test(content)) return []; + const out: RunTarget[] = []; + const types: { name: string; depth: number; line: number; xctest: boolean; suite: boolean; tests: number }[] = []; + let depth = 0; + let testAttr = false; + let suiteAttr = false; + content.split("\n").forEach((raw, i) => { + // Braces outside string literals and line comments decide nesting. + const line = raw.replace(/"(?:[^"\\]|\\.)*"/g, '""').replace(/\/\/.*$/, ""); + if (/@Test\b/.test(line)) testAttr = true; + if (/@Suite\b/.test(line)) suiteAttr = true; + const type = + /\b(class|struct|actor|enum|extension)\s+(?!func\b|var\b|let\b|subscript\b)(\w+)(?:\s*:\s*([^{]*))?/.exec(line); + const func = /\bfunc\s+(\w+)\s*\(/.exec(line); + if (type) { + const xctest = type[1] === "class" && /\bXCTestCase\b/.test(type[3] ?? ""); + types.push({ name: type[2]!, depth, line: i, xctest, suite: suiteAttr, tests: 0 }); + testAttr = suiteAttr = false; + } else if (func) { + const owner = types[types.length - 1]; + const direct = owner ? depth === owner.depth + 1 : depth === 0; + const xctest = !!owner?.xctest && direct && /^test/.test(func[1]!) && /\(\s*\)/.test(line); + if (direct && (testAttr || xctest)) { + const path = [...types.map((t) => t.name), func[1]!]; + out.push({ line: i, kind: "test", name: path.join("."), path }); + types.forEach((t) => t.tests++); + } + testAttr = suiteAttr = false; + } + for (const ch of line) { + if (ch === "{") depth++; + else if (ch === "}") { + depth--; + const t = types[types.length - 1]; + if (t && depth === t.depth) { + types.pop(); + if (t.tests || t.suite) { + const path = [...types.map((o) => o.name), t.name]; + out.push({ line: t.line, kind: "suite", name: path.join("."), path }); + } + } + } + } + }); + return out.sort((a, b) => a.line - b.line); +} + /** Whether the project tests with Mocha or `node --test`, which look in `test/` by default, whatever a file's name. */ export function testsInTestDirectory(configs: readonly RunConfig[]): boolean { return configs.some((c) => c.isTest && ["mocha", "node-test"].includes(frameworkFor(c))); diff --git a/src/features/run/testing/fixtures/swift-test.txt b/src/features/run/testing/fixtures/swift-test.txt new file mode 100644 index 000000000..41df04933 --- /dev/null +++ b/src/features/run/testing/fixtures/swift-test.txt @@ -0,0 +1,55 @@ +Test Suite 'All tests' started at 2026-11-29 13:12:44.379. +Test Suite 'TallyTests.xctest' started at 2026-11-29 13:12:44.380. +Test Suite 'TallyXCTests' started at 2026-11-29 13:12:44.380. +Test Case '-[TallyTests.TallyXCTests testDeliberatelyFails]' started. +/work/tally/Tests/TallyTests/TallyXCTests.swift:16: error: -[TallyTests.TallyXCTests testDeliberatelyFails] : XCTAssertEqual failed: ("4") is not equal to ("5") +Test Case '-[TallyTests.TallyXCTests testDeliberatelyFails]' failed (0.861 seconds). +Test Case '-[TallyTests.TallyXCTests testTotalAddsPrices]' started. +Test Case '-[TallyTests.TallyXCTests testTotalAddsPrices]' passed (0.000 seconds). +Test Case '-[TallyTests.TallyXCTests testTotalOfNothingIsZero]' started. +Test Case '-[TallyTests.TallyXCTests testTotalOfNothingIsZero]' passed (0.000 seconds). +Test Suite 'TallyXCTests' failed at 2026-11-29 13:12:45.241. + Executed 3 tests, with 1 failure (0 unexpected) in 0.861 (0.861) seconds +Test Suite 'TallyTests.xctest' failed at 2026-11-29 13:12:45.241. + Executed 3 tests, with 1 failure (0 unexpected) in 0.861 (0.861) seconds +Test Suite 'All tests' failed at 2026-11-29 13:12:45.241. + Executed 3 tests, with 1 failure (0 unexpected) in 0.861 (0.863) seconds +{"kind":"test","payload":{"id":"TallyTests.TallySuite","kind":"suite","name":"TallySuite","sourceLocation":{"_filePath":"/work/tally/Tests/TallyTests/TallySwiftTests.swift","column":2,"fileID":"TallyTests/TallySwiftTests.swift","line":5}},"version":0} +{"kind":"test","payload":{"id":"TallyTests.TallySuite/addsPrices()/TallySwiftTests.swift:6:6","isParameterized":false,"kind":"function","name":"addsPrices()","sourceLocation":{"_filePath":"/work/tally/Tests/TallyTests/TallySwiftTests.swift","column":6,"fileID":"TallyTests/TallySwiftTests.swift","line":6}},"version":0} +{"kind":"test","payload":{"id":"TallyTests.TallySuite/deliberatelyFails()/TallySwiftTests.swift:16:6","isParameterized":false,"kind":"function","name":"deliberatelyFails()","sourceLocation":{"_filePath":"/work/tally/Tests/TallyTests/TallySwiftTests.swift","column":6,"fileID":"TallyTests/TallySwiftTests.swift","line":16}},"version":0} +{"kind":"test","payload":{"displayName":"Total of a single price","id":"TallyTests.TallySuite/singlePrice()/TallySwiftTests.swift:10:6","isParameterized":false,"kind":"function","name":"singlePrice()","sourceLocation":{"_filePath":"/work/tally/Tests/TallyTests/TallySwiftTests.swift","column":6,"fileID":"TallyTests/TallySwiftTests.swift","line":10}},"version":0} +{"kind":"test","payload":{"id":"TallyTests.freeFunctionTest()/TallySwiftTests.swift:22:2","isParameterized":false,"kind":"function","name":"freeFunctionTest()","sourceLocation":{"_filePath":"/work/tally/Tests/TallyTests/TallySwiftTests.swift","column":2,"fileID":"TallyTests/TallySwiftTests.swift","line":22}},"version":0} +􀟈 Test run started. +􀄵 Testing Library Version: 2084 +􀄵 Target Platform: arm64e-apple-macos14.0 +{"kind":"event","payload":{"instant":{"absolute":1002387.960608416,"since1970":1795925565.331415},"kind":"runStarted","messages":[{"symbol":"default","text":"Test run started."},{"symbol":"details","text":"Testing Library Version: 2084"},{"symbol":"details","text":"Target Platform: arm64e-apple-macos14.0"}]},"version":0} +􀟈 Suite TallySuite started. +{"kind":"event","payload":{"instant":{"absolute":1002387.9607822909,"since1970":1795925565.331587},"kind":"testStarted","messages":[{"symbol":"default","text":"Suite TallySuite started."}],"testID":"TallyTests.TallySuite"},"version":0} +􀟈 Test freeFunctionTest() started. +􀟈 Test "Total of a single price" started. +􀟈 Test addsPrices() started. +{"kind":"event","payload":{"instant":{"absolute":1002387.96094275,"since1970":1795925565.331747},"kind":"testStarted","messages":[],"testID":"TallyTests.freeFunctionTest()/TallySwiftTests.swift:22:2"},"version":0} +{"kind":"event","payload":{"instant":{"absolute":1002387.960960291,"since1970":1795925565.3317652},"kind":"testStarted","messages":[],"testID":"TallyTests.TallySuite/singlePrice()/TallySwiftTests.swift:10:6"},"version":0} +{"kind":"event","payload":{"instant":{"absolute":1002387.961029125,"since1970":1795925565.331833},"kind":"testStarted","messages":[],"testID":"TallyTests.TallySuite/deliberatelyFails()/TallySwiftTests.swift:16:6"},"version":0} +{"kind":"event","payload":{"instant":{"absolute":1002387.9610167079,"since1970":1795925565.331821},"kind":"testStarted","messages":[],"testID":"TallyTests.TallySuite/addsPrices()/TallySwiftTests.swift:6:6"},"version":0} +{"kind":"event","payload":{"instant":{"absolute":1002387.9610810829,"since1970":1795925565.331886},"kind":"testEnded","messages":[],"testID":"TallyTests.TallySuite/singlePrice()/TallySwiftTests.swift:10:6"},"version":0} +{"kind":"event","payload":{"instant":{"absolute":1002387.961088875,"since1970":1795925565.331893},"kind":"testEnded","messages":[],"testID":"TallyTests.TallySuite/addsPrices()/TallySwiftTests.swift:6:6"},"version":0} +􀟈 Test deliberatelyFails() started. +{"kind":"event","payload":{"instant":{"absolute":1002387.961088208,"since1970":1795925565.331893},"kind":"testEnded","messages":[],"testID":"TallyTests.freeFunctionTest()/TallySwiftTests.swift:22:2"},"version":0} +􁁛 Test addsPrices() passed after 0.001 seconds. +􁁛 Test "Total of a single price" passed after 0.001 seconds. +􁁛 Test freeFunctionTest() passed after 0.001 seconds. +􀢄 Test deliberatelyFails() recorded an issue at TallySwiftTests.swift:18:9: Expectation failed: total([1]) == 2 +􀄵 total([1]) == 2 → false +􀄵 total([1]) → 1 +{"kind":"event","payload":{"_comments":[],"_sourceLocation":{"_filePath":"/work/tally/Tests/TallyTests/TallySwiftTests.swift","column":9,"fileID":"TallyTests/TallySwiftTests.swift","line":18},"instant":{"absolute":1002387.961264291,"since1970":1795925565.332068},"issue":{"_backtrace":[{"address":4420228072}],"_expression":{"children":[{"runtimeTypeName":"Swift.Int","runtimeValue":"1","sourceCode":"total([1])"},{"runtimeTypeName":"Swift.Int","runtimeValue":"2","sourceCode":"2"}],"runtimeTypeName":"Swift.Bool","runtimeValue":"false","sourceCode":"total([1]) == 2"},"isKnown":false,"sourceLocation":{"_filePath":"/work/tally/Tests/TallyTests/TallySwiftTests.swift","column":9,"fileID":"TallyTests/TallySwiftTests.swift","line":18}},"kind":"issueRecorded","messages":[{"symbol":"fail","text":"Expectation failed: total([1]) == 2"},{"symbol":"details","text":"total([1]) == 2 → false"},{"_indentation":1,"symbol":"details","text":"total([1]) → 1"}],"testID":"TallyTests.TallySuite/deliberatelyFails()/TallySwiftTests.swift:16:6"},"version":0} +{"kind":"event","payload":{"instant":{"absolute":1002387.961713666,"since1970":1795925565.332518},"kind":"testEnded","messages":[],"testID":"TallyTests.TallySuite/deliberatelyFails()/TallySwiftTests.swift:16:6"},"version":0} +􀢄 Test deliberatelyFails() failed after 0.001 seconds with 1 issue. +􀄵 // Fails on purpose with OPENIDEA_FAIL=1, skipped otherwise. +􀢄 Suite TallySuite failed after 0.001 seconds with 1 issue. +{"kind":"event","payload":{"instant":{"absolute":1002387.961779875,"since1970":1795925565.332584},"kind":"testEnded","messages":[{"symbol":"fail","text":"Suite TallySuite failed after 0.001 seconds with 1 issue."}],"testID":"TallyTests.TallySuite"},"version":0} +􀢄 Test run with 4 tests in 1 suite failed after 0.001 seconds with 1 issue. +{"kind":"event","payload":{"instant":{"absolute":1002387.961824083,"since1970":1795925565.332628},"kind":"runEnded","messages":[{"symbol":"fail","text":"Test run with 4 tests in 1 suite failed after 0.001 seconds with 1 issue."}]},"version":0} +Note: Some test targets reported failures: + - TallyTests (XCTest) + - TallyTests (Swift Testing) diff --git a/src/features/run/testing/index.ts b/src/features/run/testing/index.ts index 975243e60..c5472b269 100644 --- a/src/features/run/testing/index.ts +++ b/src/features/run/testing/index.ts @@ -17,7 +17,9 @@ import { withDoctestReporter } from "./pythonDoctest"; import { withUnittestReporter } from "./pythonUnittest"; import { rubyParser } from "./ruby"; import { unittestParser } from "./unittest"; +import { swiftParser, withSwiftEventStream } from "./swift"; import { zigParser } from "./zig"; +import { isWindows } from "../jvmTypes"; import type { TestEvent, TestOutputParser } from "./types"; import { appendScriptArgs } from "../scriptArgs"; @@ -34,6 +36,7 @@ export { pytestParser, recordsParser, rubyParser, + swiftParser, unittestParser, zigParser, }; @@ -67,6 +70,8 @@ export type Framework = | "ruby" | "dotnet" | "zig" + /** `swift test`: XCTest and Swift Testing. */ + | "swift" | "auto"; type FrameworkConfig = Pick & @@ -125,6 +130,7 @@ export function frameworkFor(config: FrameworkConfig): Framework { if (/\bmanage\.py test\b/.test(cmd)) return "unittest"; if (/(^|[/\\\s])(phpunit|pest)(\.phar|\.bat)?(\s|$)/.test(cmd)) return "phpunit"; if (/\bgo\s+test\b/.test(cmd)) return "go"; + if (/(^|[/\\\s])swift(\.exe)?\s+test(\s|$)/.test(cmd)) return "swift"; if (/\b(gradlew?|mvnw?)\b/.test(cmd)) return "jvm"; return "auto"; } @@ -182,6 +188,7 @@ export function withTestReporting(config: T): T { // `zig build test` prints nothing for a passing (or cached) run; the summary reports the counts. return config.args.includes("--summary") ? config : { ...config, args: [...config.args, "--summary", "all"] }; } + if (frameworkFor(config) === "swift") return { ...config, args: withSwiftEventStream(config.args, isWindows()) }; if (frameworkFor(config) === "unittest") { const chosen = config.args.some((a) => /^(-v|--verbosity)(=?\d)?$/.test(a)); return chosen ? config : { ...config, args: [...config.args, "-v", "2"] }; @@ -227,6 +234,8 @@ export function createTestParser(config: FrameworkConfig): TestOutputParser { return rubyParser(); case "zig": return zigParser(); + case "swift": + return swiftParser(); default: return combinedParser([ cargoParser(), diff --git a/src/features/run/testing/rerun.test.ts b/src/features/run/testing/rerun.test.ts index c15b1f844..2b9890b94 100644 --- a/src/features/run/testing/rerun.test.ts +++ b/src/features/run/testing/rerun.test.ts @@ -175,6 +175,21 @@ describe("rerunFailedConfig", () => { expect(new Set(configs.map((config) => config.id)).size).toBe(2); }); + it("swift: a --filter per failed test, replacing the run's own", async () => { + expect( + (await rerunFailedConfig(cfg("swift", "swift", ["test", "--filter", "Old"]), [ + ["TallyTests", "TallyXCTests", "testDeliberatelyFails"], + ["TallyTests", "TallySuite", "deliberatelyFails()"], + ]))!.args, + ).toEqual([ + "test", + "--filter", + String.raw`\bTallyTests[./]TallyXCTests[./]testDeliberatelyFails\b`, + "--filter", + String.raw`\bTallyTests[./]TallySuite[./]deliberatelyFails\b`, + ]); + }); + it("zig: --test-filter per failed test, straight for `zig test` and via the module root for `zig build`", async () => { expect( (await rerunFailedConfig(cfg("zig", "zig", ["test", "src/calc.zig"]), [ diff --git a/src/features/run/testing/rerun.ts b/src/features/run/testing/rerun.ts index a39609d55..d5d1ffc18 100644 --- a/src/features/run/testing/rerun.ts +++ b/src/features/run/testing/rerun.ts @@ -347,6 +347,15 @@ function builtinTestsConfig(config: RunConfig, paths: string[][], name: string): args = ["test", file, ...rest, ...names.flatMap((n) => ["--test-filter", n])]; break; } + case "swift": { + // `--filter` per test: a regular expression over `Module.Type/test()` (XCTest on Linux names + // no module), so the path's parts may be joined by either separator. + const filters = unique( + paths.map((p) => String.raw`\b${p.map((n) => escapeRegExp(n.replace(/\(.*\)$/, ""))).join("[./]")}\b`), + ); + args = [...dropFlag(config.args, ["--filter"]), ...filters.flatMap((f) => ["--filter", f])]; + break; + } case "jvm": args = jvmArgs(config, paths); break; diff --git a/src/features/run/testing/swift.test.ts b/src/features/run/testing/swift.test.ts new file mode 100644 index 000000000..01a6bf54f --- /dev/null +++ b/src/features/run/testing/swift.test.ts @@ -0,0 +1,106 @@ +import { describe, expect, it } from "vitest"; +import { createTestParser, frameworkFor, parseAll, withTestReporting } from "./index"; +import { TestResults } from "./index"; +import { matchesTarget } from "./states"; +import { SwiftTestOutput, swiftParser, swiftTestPath, withSwiftEventStream } from "./swift"; +// `swift test` of fixtures/swiftpm-app (Swift 6.4), stdout and stderr, with the event stream on stdout. +import run from "./fixtures/swift-test.txt?raw"; + +function results(text: string) { + const r = new TestResults(); + r.apply(parseAll(swiftParser(), text)); + return r; +} + +const leaf = (r: TestResults, ...path: string[]) => r.get(path.join("\u0000")); + +describe("swift test", () => { + it("roots XCTest and Swift Testing results at the test module", () => { + const r = results(run); + expect(r.roots.map((n) => n.name)).toEqual(["TallyTests"]); + expect(leaf(r, "TallyTests", "TallyXCTests", "testTotalAddsPrices")?.own).toBe("passed"); + expect(leaf(r, "TallyTests", "TallyXCTests", "testDeliberatelyFails")?.own).toBe("failed"); + expect(leaf(r, "TallyTests", "TallySuite", "addsPrices()")?.own).toBe("passed"); + expect(leaf(r, "TallyTests", "TallySuite", "singlePrice()")?.own).toBe("passed"); + expect(leaf(r, "TallyTests", "TallySuite", "deliberatelyFails()")?.own).toBe("failed"); + expect(leaf(r, "TallyTests", "freeFunctionTest()")?.own).toBe("passed"); + }); + + it("keeps failure messages and source locations", () => { + const r = results(run); + const xc = leaf(r, "TallyTests", "TallyXCTests", "testDeliberatelyFails")!; + expect(xc.output).toContain('XCTAssertEqual failed: ("4") is not equal to ("5")'); + expect(xc.location).toMatchObject({ path: "/work/tally/Tests/TallyTests/TallyXCTests.swift", line: 16 }); + const st = leaf(r, "TallyTests", "TallySuite", "deliberatelyFails()")!; + expect(st.output).toContain("Expectation failed: total([1]) == 2"); + expect(st.location).toMatchObject({ path: "/work/tally/Tests/TallyTests/TallySwiftTests.swift", line: 16, col: 6 }); + }); + + it("reads skipped tests and ignores known issues", () => { + const events = parseAll( + swiftParser(), + [ + '{"kind":"test","payload":{"id":"M.S","kind":"suite","name":"S"},"version":0}', + '{"kind":"event","payload":{"kind":"testSkipped","testID":"M.S/off()/F.swift:3:4","messages":[]},"version":0}', + '{"kind":"event","payload":{"kind":"testStarted","testID":"M.S/known()/F.swift:5:4","instant":{"absolute":1}},"version":0}', + '{"kind":"event","payload":{"kind":"issueRecorded","testID":"M.S/known()/F.swift:5:4","issue":{"isKnown":true}},"version":0}', + '{"kind":"event","payload":{"kind":"testEnded","testID":"M.S/known()/F.swift:5:4","instant":{"absolute":1.5}},"version":0}', + '{"kind":"event","payload":{"kind":"testEnded","testID":"M.S","messages":[]},"version":0}', + "Test Case 'Calc.testSkip' skipped (0.001 seconds)", + ].join("\n"), + ); + expect(events).toContainEqual({ type: "result", path: ["M", "S", "off()"], status: "skipped" }); + expect(events).toContainEqual({ type: "result", path: ["M", "S", "known()"], status: "passed", durationMs: 500 }); + expect(events).toContainEqual({ type: "result", path: ["Calc", "testSkip"], status: "skipped", durationMs: 1 }); + expect(events.some((e) => "path" in e && e.path.join("/") === "M/S")).toBe(false); + }); + + it("matches gutter targets, which name no module or argument list", () => { + expect(matchesTarget(["TallyTests", "TallySuite", "addsPrices()"], { path: ["TallySuite", "addsPrices"] })).toBe( + true, + ); + expect(matchesTarget(["TallyTests", "freeFunctionTest()"], { path: ["freeFunctionTest"] })).toBe(true); + expect(matchesTarget(["TallyTests", "TallyXCTests", "testX"], { path: ["TallyXCTests", "testX"] })).toBe(true); + }); + + it("splits test IDs into module, types and function", () => { + expect(swiftTestPath("TallyTests.Outer/Inner/each(n:)/TallySwiftTests.swift:26:10")).toEqual([ + "TallyTests", + "Outer", + "Inner", + "each(n:)", + ]); + expect(swiftTestPath("TallyTests.freeFunctionTest()/TallySwiftTests.swift:20:2")).toEqual([ + "TallyTests", + "freeFunctionTest()", + ]); + }); + + it("hides the event stream from the console", () => { + const shown = new SwiftTestOutput(() => {}).feed(run); + const text = shown.map((c) => c.text).join(""); + expect(text).not.toContain('{"kind":'); + expect(text).toContain("Test addsPrices() passed"); + }); + + it("is picked for swift test and adds the event stream once", () => { + const config = { kind: "swift", command: "swift", args: ["test", "--filter", "X"] }; + expect(frameworkFor(config)).toBe("swift"); + expect(frameworkFor({ kind: "swift", command: "swift", args: ["main.swift"] })).toBe("auto"); + expect(frameworkFor({ kind: "shell", command: "/usr/bin/swift", args: ["test"] })).toBe("swift"); + expect(createTestParser(config)).toBeDefined(); + const args = withSwiftEventStream(config.args, false); + expect(args).toEqual([ + "test", + "--filter", + "X", + "--experimental-event-stream-output", + "/dev/stdout", + "--experimental-event-stream-version", + "0", + ]); + expect(withSwiftEventStream(args, false)).toEqual(args); + expect(withSwiftEventStream(config.args, true)).toEqual(config.args); + expect(withTestReporting(config).args.length).toBeGreaterThanOrEqual(3); + }); +}); diff --git a/src/features/run/testing/swift.ts b/src/features/run/testing/swift.ts new file mode 100644 index 000000000..db0027451 --- /dev/null +++ b/src/features/run/testing/swift.ts @@ -0,0 +1,137 @@ +/** + * `swift test`: XCTest's per-test lines (`Test Case '-[Module.Class method]' passed (0.001 seconds).`) + * and Swift Testing's JSON event stream, which `withSwiftEventStream` sends to stdout next to the + * human-readable output. Results are rooted at the test module: `TallyTests > TallySuite > addsPrices()`. + */ +import { TestStdout, type TestEvent, type TestLocation, type TestOutputParser } from "./types"; + +// macOS: `-[TallyTests.TallyXCTests testAdds]`; swift-corelibs-xctest (Linux, Windows): `TallyXCTests.testAdds`. +const XC_NAME = String.raw`(?:-\[(\w+)\.(\w+) (\w+)\]|(\w+)\.(\w+))`; +const XC_CASE_RE = new RegExp( + String.raw`^Test Case '${XC_NAME}' (started|passed|failed|skipped)\b(?: \((\d+(?:\.\d+)?) seconds\))?`, +); +const XC_ERROR_RE = new RegExp(String.raw`^(.+\.swift):(\d+): error: ${XC_NAME} : (.*)$`); + +/** A Swift Testing event stream record (ABI version 0), as far as the tree reads it. */ +interface StreamRecord { + kind: "test" | "event"; + version: number; + payload: { + kind: string; + id?: string; + testID?: string; + sourceLocation?: { _filePath?: string; filePath?: string; line: number; column: number }; + instant?: { absolute: number }; + issue?: { isKnown?: boolean }; + messages?: { text: string }[]; + }; +} + +function streamRecord(line: string): StreamRecord | null { + if (!line.startsWith('{"kind":')) return null; + try { + const r = JSON.parse(line) as StreamRecord; + return (r.kind === "test" || r.kind === "event") && typeof r.payload === "object" ? r : null; + } catch { + return null; + } +} + +/** + * `TallyTests.TallySuite/addsPrices()/TallySwiftTests.swift:5:6` → `[TallyTests, TallySuite, addsPrices()]`: + * the module, the enclosing types and the function, without the trailing source location. + */ +export function swiftTestPath(id: string): string[] { + const parts = id.split("/"); + if (parts.length > 1 && /:\d+:\d+$/.test(parts[parts.length - 1]!)) parts.pop(); + const dot = parts[0]!.indexOf("."); + return dot < 0 ? parts : [parts[0]!.slice(0, dot), parts[0]!.slice(dot + 1), ...parts.slice(1)]; +} + +export function swiftParser(): TestOutputParser { + const suites = new Set(); + const locations = new Map(); + const started = new Map(); + const failed = new Set(); + + const xctest = (line: string): TestEvent[] => { + let m = XC_CASE_RE.exec(line); + if (m) { + const path = m[1] ? [m[1], m[2]!, m[3]!] : [m[4]!, m[5]!]; + const status = m[6]!; + if (status === "started") return [{ type: "start", path }]; + const durationMs = m[7] === undefined ? undefined : Number(m[7]) * 1000; + return [{ type: "result", path, status: status as "passed" | "failed" | "skipped", durationMs }]; + } + m = XC_ERROR_RE.exec(line); + if (m) { + const path = m[3] ? [m[3], m[4]!, m[5]!] : [m[6]!, m[7]!]; + return [ + { type: "location", path, location: { path: m[1]!, line: Number(m[2]), resolve: "path" } }, + { type: "output", path, line: m[8]! }, + ]; + } + return []; + }; + + const stream = (r: StreamRecord): TestEvent[] => { + const p = r.payload; + if (r.kind === "test") { + if (!p.id) return []; + if (p.kind === "suite") suites.add(p.id); + const loc = p.sourceLocation; + const file = loc?._filePath ?? loc?.filePath; + if (loc && file) locations.set(p.id, { path: file, line: loc.line, col: loc.column, resolve: "path" }); + return []; + } + const id = p.testID; + // Suites finish through their tests; their own events only repeat them. + if (!id || suites.has(id)) return []; + const path = swiftTestPath(id); + const location = locations.get(id); + const located: TestEvent[] = location ? [{ type: "location", path, location }] : []; + switch (p.kind) { + case "testStarted": + if (p.instant) started.set(id, p.instant.absolute); + return [{ type: "start", path }, ...located]; + case "testSkipped": + return [...located, { type: "result", path, status: "skipped" }]; + case "issueRecorded": + if (p.issue?.isKnown) return []; + failed.add(id); + return (p.messages ?? []).map((m) => ({ type: "output", path, line: m.text })); + case "testEnded": { + const from = started.get(id); + const durationMs = from !== undefined && p.instant ? (p.instant.absolute - from) * 1000 : undefined; + return [{ type: "result", path, status: failed.has(id) ? "failed" : "passed", durationMs }]; + } + default: + return []; + } + }; + + return { + feed(line) { + const r = streamRecord(line); + return r ? stream(r) : xctest(line); + }, + }; +} + +/** The console shows the runners' own output; the event stream's records are the tree's. */ +export class SwiftTestOutput extends TestStdout { + constructor(feedLine: (line: string) => void) { + super(feedLine, (line) => (streamRecord(line) ? "" : line + "\n")); + } +} + +/** + * `swift test` with Swift Testing's event stream on stdout (`/dev/stdout`: not on Windows, where only + * XCTest results reach the tree). Swift 6.0's SwiftPM knows only the `--experimental-` spelling, which + * later toolchains still accept next to `--event-stream-output-path`. + */ +export function withSwiftEventStream(args: string[], windows: boolean): string[] { + const chosen = args.some((a) => a === "--event-stream-output-path" || a === "--experimental-event-stream-output"); + if (windows || chosen) return args; + return [...args, "--experimental-event-stream-output", "/dev/stdout", "--experimental-event-stream-version", "0"]; +}