agentleFS
readiumreadium/swift-toolkit/.claude/skills/write-tests/SKILL.md

write-tests

Skill574 starsChanged 14 days agoBSD-3-ClauseView on GitHub

Write Swift unit tests using Swift Testing (the modern Apple testing framework, not XCTest). Use this skill whenever the user asks to write tests, add test cases, create a test suite, or test a Swift type or function. Also triggers when the user asks to convert XCTest tests to Swift Testing, or when adding new tests to an existing XCTest-based file (always convert first). Invoke proactively when the user has just written a new Swift type or function and hasn't tested it yet.

We split this skill into the rules it gives an agent

17 rules. 0 are common, 6 are distinctive, and 11 are very specific to this project.

  • 0

    Common

    Most of the 65 edited versions we read keep these.

  • 6

    Distinctive

    This author's own choices. Worth a look.

  • 11

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Write idiomatic Swift unit tests using Swift Testing.

    line 8
  2. Distinctive:

    If the user asks to add tests to an existing XCTest file, convert the whole file to Swift Testing first, then add the new tests.

    line 16
  3. Very specific:

    Never use // MARK: inside a test suite type: Use a nested struct instead.

    line 37
  4. Very specific:

    Add @Suite to attach a trait (.serialized, .disabled("reason")), or to give a nested suite a display name which reads as a sentence with …

    line 66
  5. Distinctive:

    When each case of a parameterized test holds more than one value, declare a dedicated struct nested in the suite instead of using a tuple.

    line 92
  6. Distinctive:

    Use the same style for the whole file: either function names only, or sentences for every nested suite and test.

    line 148
  7. Very specific:

    Use init / deinit instead of setUp/tearDown.

    line 172
  8. Very specific:

    Wait for an event, never for a duration.

    line 188
  9. Distinctive:

    Don't write a test which passes by letting a wait expire, to prove that something did not happen.

    line 190
  10. Very specific:

    Don't block a thread of the cooperative pool (Thread.sleep, DispatchSemaphore.wait).

    line 191
  11. Very specific:

    Don't expect a value which depends on scheduling, such as the exact number of tasks running at once.

    line 192
  12. Very specific:

    Remove : XCTestCase, change class → struct

    line 212
  13. Very specific:

    Remove test prefix from all method names

    line 213
  14. Very specific:

    Remove continueAfterFailure = false — use try #require(...) where needed

    line 216
  15. Very specific:

    Do not keep any @Suite("...") on the top-level struct — struct URLTests needs no annotation.

    line 241
  16. Very specific:

    Never use static helpers inside a test suite.

    line 247
  17. Distinctive:

    No sleep, short timeout or expectation which depends on scheduling?

    line 268

“Common” is measured: kept by at least 6 in 10 of the 65 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Write Tests

Write idiomatic Swift unit tests using Swift Testing.

Non-negotiable: always Swift Testing

Do not write XCTest.

Even when the user doesn't mention a framework, use Swift Testing. XCTest is legacy. The only exception is UI tests, which still require XCTest.

If the user asks to add tests to an existing XCTest file, convert the whole file to Swift Testing first, then add the new tests.

A correct file always looks like this:

import Testing

struct FooTests {
    struct Something {
        @Test func returnsHelloWorld() {
            let foo = Foo()
            #expect(foo.something() == "Hello world")
        }
    }
}

Suite structure

Organize tests in nested struct types. Each top-level suite covers one tested type.

Never use // MARK: inside a test suite type. Use a nested struct instead. A // MARK: at file scope (to label a helpers section at the bottom) is the only acceptable use.

// ✅ Correct — nested struct for organization
struct URLTests {

    struct Absolute {
        @Test func isUnchanged() { ... }
        @Test func withFragment() { ... }
    }

    struct Relative {
        @Test func resolution() { ... }
        @Test func withDotDot() { ... }
    }
}

// ❌ Wrong — MARK inside a suite type
struct URLTests {
    // MARK: - Absolute    ← must become `struct Absolute { ... }`
    @Test func isUnchanged() { ... }

    // MARK: - Relative    ← must become `struct Relative { ... }`
    @Test func resolution() { ... }
}

@Suite annotation rules:

  • Omit @Suite entirely when the struct name already makes the suite's purpose clear. Swift Testing discovers it automatically.
  • Add @Suite to attach a trait (.serialized, .disabled("reason")), or to give a nested suite a display name which reads as a sentence with the ones of its tests (see Display names).
  • A top-level suite never needs a display name: URLTests does not need @Suite. LocatorTests does not need @Suite. Just write struct URLTests {.

Naming:

  • Top-level suite: <TypeName>Tests (e.g. LocatorTests, URLTests)
  • Nested suites: concept/API name only, no Tests suffix (e.g. Absolute, Relative, Combining, ErrorHandling)

Declaring tests

// Basic
@Test func returnsNilForInvalidInput() { ... }

// Custom display name — see "Display names" below
@Test("Parsing a locator with a fragment") func parseWithFragment() { ... }

// Parameterized — use instead of copying the same test body multiple times
@Test("All formats round-trip", arguments: Format.allCases)
func roundTrip(format: Format) throws { ... }

// Async/throws — just mark the function
@Test func fetchMetadata() async throws { ... }

Arguments with several values

When each case of a parameterized test holds more than one value, declare a dedicated struct nested in the suite instead of using a tuple. Named fields don't need a comment to explain their order, and default values keep the cases short.

The struct is Sendable. Give it a name and conform it to CustomTestStringConvertible, so that the test report shows the name of each case.

// ✅ Correct — a struct with named fields
struct LocatorPosition: Sendable, CustomTestStringConvertible {
    let name: String
    var durations: [TimeInterval?] = [600, 300, 900]
    let locations: Locator.Locations
    let expected: TimelinePosition

    var testDescription: String { name }
}

@Test(arguments: [
    LocatorPosition(
        name: "a progression with a known duration",
        locations: .init(progression: 0.5),
        expected: position(1, 150)
    ),
    LocatorPosition(
        name: "a progression with an unknown duration",
        durations: [600, nil, 900],
        locations: .init(progression: 0.5),
        expected: position(1, 0)
    ),
])
func locatorIsTurnedIntoAPosition(_ example: LocatorPosition) { ... }

// ❌ Wrong — a tuple whose values are only told apart by their position
@Test(arguments: [
    ([600, 300, 900], Locator.Locations(progression: 0.5), position(1, 150)),
    ([600, nil, 900], Locator.Locations(progression: 0.5), position(1, 0)),
] as [([TimeInterval?], Locator.Locations, TimelinePosition)])
func locatorIsTurnedIntoAPosition(durations: [TimeInterval?], locations: Locator.Locations, expected: TimelinePosition) { ... }

A case holding a single value stays a plain argument, e.g. @Test(arguments: [0, -1]).

Display names

A function name is enough for a simple test. When the behavior needs a sentence to be described, give display names to the nested suite and its tests, so that they read as one sentence in the test report. The suite names the subject and each test continues it, starting with a lowercase letter.

struct ResourceAssetLoaderTests {
    @Suite("Invalidating the loader") struct Invalidation {
        @Test("returns once the in-flight streams have stopped")
        func stopsStreams() async throws { ... }

        @Test("refuses the requests which follow, without resolving them")
        func refusesRequests() async throws { ... }
    }
}

Use the same style for the whole file: either function names only, or sentences for every nested suite and test.

Assertions

GoalUse
Verify a condition (continue on failure)#expect(condition)
Verify and halt on failuretry #require(condition)
Unwrap an optional or haltlet x = try #require(optional)
Expect a thrown error#expect(throws: MyError.self) { try ... }
Unconditional failureIssue.record("reason")

Use force unwrap (!) for values that must exist — don't use guard ... else { return }. A crash on force unwrap produces a clear failure with a line number. A silent return makes the test pass incorrectly when a value is nil.

// ✅ Good
let url = URL(string: "https://example.com")!

// ❌ Bad — silently passes if url is nil
guard let url = URL(string: input) else { return }

Setup and teardown

Use init / deinit instead of setUp/tearDown. Each test method gets a fresh instance of the suite struct, so init is sufficient.

struct DatabaseTests {
    let db: Database

    init() async throws {
        db = try await Database.makeInMemory()
    }
}

Waiting for asynchronous events

Tests run in parallel on CI runners with few cores, which can freeze for more than a minute. A test which depends on timing fails there, even when it passes locally every time.

  • Wait for an event, never for a duration. Don't Task.sleep and hope the work is done. Use an AsyncStream with first(within:) from TestSupport, or confirmation(...).
  • A timeout only exists to fail a broken test instead of hanging. Use TimeInterval.testTimeout from TestSupport, never a few seconds.
  • Don't write a test which passes by letting a wait expire, to prove that something did not happen. Wait for a later event instead, then check the state.
  • Don't block a thread of the cooperative pool (Thread.sleep, DispatchSemaphore.wait). When a test must hold a thread, run that part on its own dispatch queue.
  • Don't expect a value which depends on scheduling, such as the exact number of tasks running at once. Expect a bound (<= 3), or gate the tasks so the test controls the order.
// ✅ Good — waits for the event, the timeout is only reached on failure
let (events, continuation) = AsyncStream<Event>.makeStream()
sut.onEvent = { continuation.yield($0) }
sut.start()
#expect(await events.first(within: .testTimeout, where: { $0 == .started }) != nil)

// ❌ Bad — fails on a busy runner
sut.start()
try await Task.sleep(nanoseconds: 500_000_000)
#expect(sut.isStarted)

Converting from XCTest — step by step

Given an XCTest file, apply these transformations in order:

  1. Replace import XCTest → import Testing
  2. Remove : XCTestCase, change class → struct
  3. Remove test prefix from all method names
  4. Replace setUpWithError() → init() throws, tearDownWithError() → deinit (on a class/actor)
  5. Replace assertions: XCTAssertEqual(a, b) → #expect(a == b), XCTAssertNil(x) → #expect(x == nil), XCTUnwrap(x) → try #require(x), XCTFail("msg") → Issue.record("msg")
  6. Remove continueAfterFailure = false — use try #require(...) where needed
  7. Convert every // MARK: group inside the type into a nested struct:
// Before (XCTest)
final class URLTests: XCTestCase {
    // MARK: - Absolute
    func testAbsoluteURLIsUnchanged() { XCTAssertEqual(...) }

    // MARK: - Relative
    func testRelativeURLResolution() { XCTAssertEqual(...) }
}

// After (Swift Testing)
struct URLTests {
    struct Absolute {
        @Test func absoluteURLIsUnchanged() { #expect(...) }
    }

    struct Relative {
        @Test func relativeURLResolution() { #expect(...) }
    }
}

Do not keep any @Suite("...") on the top-level struct — struct URLTests needs no annotation.

Helpers

  • Single-suite helpers: fileprivate functions at the bottom of the file. A // MARK: - Helpers at file scope (outside any suite type) is acceptable.
  • Cross-suite helpers: internal free functions in a dedicated TestHelpers.swift file in the test target, or in their own files for mocks/fakes.
  • Never use static helpers inside a test suite.
// At file scope, after all suite types

// MARK: - Helpers

fileprivate func makeLocator(href: String = "/ch.html", progression: Double? = nil) -> Locator {
    Locator(href: href, type: "text/html", locations: .init(progression: progression))
}

Review checklist (fix before presenting)

  1. Does every file start with import Testing? Zero import XCTest.
  2. Happy path, boundary conditions, and error cases covered?
  3. Similar tests collapsed into @Test(arguments:) parameterized tests, with a struct when a case holds several values?
  4. No // MARK: inside any suite type?
  5. No @Suite without a trait or a display name reading as a sentence with its tests?
  6. No guard ... else { return } — replaced with ! or try #require?
  7. Three or more tests sharing setup? Extract a fileprivate helper.
  8. No sleep, short timeout or expectation which depends on scheduling?

Traits and advanced features

  • .serialized: run a suite's tests sequentially (use only when tests share mutable state)
  • .disabled("reason"): skip a test with a documented reason
  • @Test(.tags(.networking)): tag for CI filtering
  • confirmation(...): for callback-based async events
  • #expect(processExitsWith: .failure) { ... }: for testing precondition/fatalError

Download now (ZIP)

  • Other versions69 projects use a version of this.

    Word for word · 0

    None found.

    Edited · 0

    None found.

    Wrote their own version · 69

    1. remix-run/remix★ 33ksame name
    2. elie222/inbox-zero★ 13ksame name
    3. getsentry/sentry-javascript★ 8.8ksame name
    4. dzhng/jevgrep★ 3.1ksame name
    5. meta-pytorch/OpenEnv★ 2.8ksame name
    6. huggingface/OpenEnv★ 2.8ksame name
    7. JamieMason/syncpack★ 2.1ksame name
    8. dzhng/skills★ 1.4ksame name
    9. clice-io/clice★ 1.4ksame name
    10. ryokun6/ryos★ 1.3ksame name

    59 more not listed

    How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.

  • Used alongsideProjects with it also use close-spec, design-with-images and 10 more.

    Other files people use alongside this one.

    Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
    • dzhngSkill

      close-spec

      When a spec under specs/<feature>/ is done shipping (a write-spec build, or any planned task that produced a spec), archive it to specs/done/ and rewrite it from a build-plan into a durable rationale — the why, the principles, the invariants — pointing back to the real code for the how. Use when implementation has landed and the plan no longer matches what shipped, or the user says a feature/spec is finished. Pairs with [write-spec](../write-spec/SKILL.md) (the plan this closes) and [review](../review/SKILL.md) (run before closing).

      Also in 5 projects that use this

    • dzhngSkill

      design-with-images

      Explore UI and visual design with image generation, then iterate the real implementation against the user-selected concept. Use when brainstorming visual directions, offering mockup variants, or implementing an approved generated design; do not stop at the mockups or the first code approximation.

      Also in 5 projects that use this

    • transitive-bullshitSkill

      compare-screenshots

      Compare screenshots against the intended design, distinguishing approved references from historical baselines. Use for iterative implementation matching, before/after visual review, objective image telemetry, or checking a lone capture for flat, empty, or badly framed content.

      Also in 5 projects that use this

    • LucasMatuszewskiSkill

      audit-agents

      Audit and maintain agent configuration files (.claude/agents, AGENTS.md, CLAUDE.md, agent-memory). Checks for duplicates, outdated info, naming conflicts, wrong technical facts, and files over 200 lines. Fixes all issues and commits.

      Also in 5 projects that use this

    • wolverin0Skill

      audit-decisions

      Standardize remediation decisions, baseline-policy entries, and legal-review banners for accepted, deferred, or policy-blocked audit findings.

      Also in 4 projects that use this

    • rhnfzlSkill

      explore-unknowns

      Walk the user through mapping the unknowns of a task before, during, and after they build it, and hand them a four-quadrant map (settled ground, open decisions, taste, and landmines) they keep. Reach for this eagerly whenever a request is ambiguous or underspecified, the codebase or domain is unfamiliar, the user will "know it when they see it", a reference implementation must be understood before porting, a build-queue or architecture-changing task is about to start, a mid-build deviation needs capturing, or a finished change needs buy-in or verified understanding before merge. Trigger even when the skill is not named: "do a blindspot pass", "find my unknown unknowns", "interview me about this change", "brainstorm the approach for a task I am about to build", "help me scope this", "what am I missing here", "plan this before I build", "I know nothing about X in this codebase". When a territory profile is present it reads memory and the graph first and feeds the map into the build pipeline; without one it degrades to a plain general map. Not for trivial or mechanical tasks with clear acceptance criteria, single-fact lookups, pure debugging of a known symptom, or pure code review, those have their own tools. Do not use it to run the build itself; the map is the deliverable and implementation remains a separate task, whether it has not started or is already underway.

      Also in 5 projects that use this

    • +5 more from dzhng
  • In this repository4 other files it gives its agents.

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.