diff --git a/.github/workflows/VerifyChanges.yaml b/.github/workflows/VerifyChanges.yaml index 37770ff..5dfa336 100644 --- a/.github/workflows/VerifyChanges.yaml +++ b/.github/workflows/VerifyChanges.yaml @@ -7,36 +7,36 @@ on: branches: ["main"] env: - XCODE_VERSION: 26.3 + XCODE_VERSION: 27.2 jobs: lint: name: Lint - runs-on: macos-26 + runs-on: xcode-27 steps: - name: Checkout uses: actions/checkout@v6 - name: Select Xcode ${{ env.XCODE_VERSION }} run: sudo xcode-select -s /Applications/Xcode_"$XCODE_VERSION".app - name: Lint - run: Scripts/lint + run: Tools/lint build-and-test: name: Build and Test (${{ matrix.platform }}) needs: lint - runs-on: macos-26 + runs-on: xcode-27 strategy: fail-fast: false matrix: include: - platform: iOS - xcode_destination: "platform=iOS Simulator,name=iPhone 17 Pro" + xcode_destination: "platform=iOS Simulator,OS=27.2,name=iPhone 18 Pro" - platform: macOS xcode_destination: "platform=macOS,arch=arm64" - platform: tvOS - xcode_destination: "platform=tvOS Simulator,name=Apple TV 4K (3rd generation)" + xcode_destination: "platform=tvOS Simulator,OS=27.2,name=Apple TV 4K (4th generation)" - platform: watchOS - xcode_destination: "platform=watchOS Simulator,name=Apple Watch Series 11 (46mm)" + xcode_destination: "platform=watchOS Simulator,OS=27.2,name=Apple Watch Series 12 (46mm)" env: DEV_BUILDS: DevBuilds/Sources @@ -96,8 +96,12 @@ jobs: path: ${{ env.XCODE_TEST_PRODUCTS_PATH }} key: ${{ steps.cache-xctestproducts-restore.outputs.cache-primary-key }} + # Optional until Xcode records coverage for Swift packages again. With Xcode 27.2, result + # bundles have no coverage for package targets, so xccov can’t report it. - name: Log Code Coverage + id: coverage if: github.event_name != 'push' + continue-on-error: true env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | @@ -123,7 +127,7 @@ jobs: include-hidden-files: true - name: Upload xccovPretty output - if: github.event_name != 'push' + if: github.event_name != 'push' && steps.coverage.outcome == 'success' uses: actions/upload-artifact@v7 with: name: xccovPrettyOutput-${{ matrix.platform }} @@ -140,11 +144,14 @@ jobs: steps: - name: Download xccovPretty output + id: download-coverage + continue-on-error: true uses: actions/download-artifact@v8 with: name: xccovPrettyOutput-macOS - name: Post Code Coverage Comment + if: steps.download-coverage.outcome == 'success' uses: thollander/actions-comment-pull-request@v3 with: file-path: xccovPretty-macOS.output diff --git a/.gitignore b/.gitignore index 0023a53..f61d4f3 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,5 @@ DerivedData/ .swiftpm/configuration/registries.json .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata .netrc + +.rumdl_cache/ diff --git a/.rumdl.toml b/.rumdl.toml new file mode 100644 index 0000000..45c9f28 --- /dev/null +++ b/.rumdl.toml @@ -0,0 +1,30 @@ +# MD005 is off with it, since it flattens indented lists. MD029 is off because list numbers are +# content: rumdl splits lists whose markers are right-aligned (" 9.", "10.") and its fix renumbers +# the second half from 1. MD076 is off because the style guide puts nested lists and code blocks +# inside list items without blank lines between items. +[global] +disable = ["MD005", "MD029", "MD032", "MD033", "MD036", "MD025", "MD041", "MD046", "MD057", "MD060", "MD076"] +respect_gitignore = true + +[MD004] +style = "dash" + +[MD007] +indent = 4 +start-indented = true +start-indent = 2 +style = "fixed" + +[MD012] +maximum = 2 + +[MD013] +line-length = 100 +code-blocks = false +tables = false +headings = false +reflow = true + +[MD022] +lines-above = [0, 2, 1, 1, 1, 1] +lines-below = 1 diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..d91aa09 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,68 @@ +# Agent Guidelines + +DevTesting is a Swift package of testing utilities in two libraries. DevRandom has a +seedable random number generator and random value extensions that work outside tests. +DevTesting adds `RandomValueGenerating` for repeatable random test data, and `Stub` and +`ThrowingStub` for mocks. Other DevKit packages use it for their tests. + + +## Building and testing + + - `swift build` and `swift test` build and test the package. + - Xcode test plans in `Build Support/Test Plans/` run the tests with coverage, as CI does. + + +## Writing style + + - Follow the [Markdown Style Guide](Documentation/MarkdownStyleGuide.md) for all Markdown. + - **Use typographic quotes and apostrophes, not straight ones,** in all Markdown, all code + documentation (doc comments and standalone comments), and all user-facing strings: + - Apostrophes: ’ (U+2019), as in “it’s” + - Single quotes: ‘ (U+2018) and ’ (U+2019) + - Double quotes: “ (U+201C) and ” (U+201D) + + Straight quotes (`'` and `"`) are still correct in code itself: string literal delimiters, + code spans, code blocks, identifiers, and configuration files. + + +## Attribution + +Never credit an agent or other code generation tool. Don’t add `Co-Authored-By` trailers or +“Generated with” lines to commits or pull requests, and don’t name an agent in file headers, +comments, or documentation. File headers name the git user. The programmer who uses a tool is +accountable for the changes it helped make. + + +## Commits and pull requests + +A commit message is a short summary of what the commit does, then a blank line and a bulleted list +of the changes, close to what a changelog would say. Messages are plain text with lines of 72 +characters or fewer. A pull request uses its commit message: the title is the summary, and the +body is the bullets. + +Add an entry to `CHANGELOG.md` for changes that affect the library’s users. + + +## Code + +Follow these guides before writing or reviewing Swift: + + - [Swift Style Guide](Documentation/SwiftStyleGuide.md) + - [Testing Guidelines](Documentation/Testing/TestingGuidelines.md) + +Also: + + - Document and test every public API, and keep test coverage above 99%. + - Other DevKit packages depend on DevTesting, so public API changes affect them. Update + the DocC documentation in `Sources/*/Documentation.docc/` along with the API. + + +## Formatting and linting + + - `Tools/format` formats Swift with swift-format and Markdown with rumdl, in place. + - `Tools/lint` checks both, plus comment line length, which swift-format doesn’t check. + - Configuration is in `.swift-format` (120-character lines) and `.rumdl.toml` (100-character + lines for Markdown). + - `Tools/install-git-hooks` installs a pre-push hook that runs `Tools/lint`. + +Run `Tools/lint` before considering a change done. diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a7c2f3..bf32c71 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # DevTesting Changelog + +## 1.8.0: November 24, 2026 + +This release requires Swift 6.4 (Xcode 27) to build. There are no other changes. + + ## 1.7.0: November 13, 2026 This release makes it possible to create stubs that return a placeholder value until they’re diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 696cdf5..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1,109 +0,0 @@ -# CLAUDE.md - -This file provides guidance to Claude Code (claude.ai/code) when working with code in this -repository. - - -## Development Commands - -### Building and Testing - - - **Build for testing**: `swift build --package-path . --disable-automatic-resolution` - - **Run tests**: `swift test --package-path . --disable-automatic-resolution` - - **Run tests with code coverage**: Tests are run through the GitHub Actions workflow using - `build_and_test.sh` from DevBuilds - - **Test specific platform**: Use `xcodebuild` with appropriate destination (see - `.github/workflows/VerifyChanges.yaml` for examples) - -### Code Formatting and Linting - - - **Lint check**: `Scripts/lint` (runs `swift format lint --recursive --strict` from anywhere) - - **Format code**: `swift format --in-place --recursive Sources/ Tests/` - - **Manual lint**: `swift format lint --recursive --strict Sources/ Tests/` - - **Swift format configuration**: Uses `.swift-format` file with 4-space indentation and 120 - character line length - -### Git Hooks - - - **Install git hooks**: `Scripts/install-git-hooks` (installs pre-push hook; supports git - worktrees) - - **Pre-push hook**: Automatically runs `Scripts/lint` before each push - -### Documentation - - - **Build documentation**: `swift package generate-documentation` - - **Documentation source**: `Sources/DevTesting/Documentation.docc/` - - -## Code Architecture - -### Core Components - -**RandomValueGenerating Protocol**: The central protocol that test suites conform to for generating -repeatable random test data. Uses `SeedableRandomNumberGenerator` and logs seeds for test -reproducibility. - -**Three Main Feature Areas**: - - 1. **Random Value Generation** (`Sources/DevTesting/Random Value Generation/`): Extensions for - generating random values of various types (String, Data, URL, UUID, etc.) with seeded - randomness - 2. **Collection Generation** (`Sources/DevTesting/Collection Generation/`): Array extensions for - generating collections of random data - 3. **Stubbing** (`Sources/DevTesting/Stubbing/`): `Stub` and `ThrowingStub` classes for mocking - and spying in tests - -### Key Design Patterns - - - **Seeded Randomness**: All random generation uses `SeedableRandomNumberGenerator` to ensure - test reproducibility - - **Logging Integration**: Random seeds are logged using `os.Logger` (subsystem: "DevTesting", - category: "randomization") - - **Swift Testing Integration**: Designed specifically for Swift Testing framework, not XCTest - - **Type Safety**: Extensive use of Swift 6 features including typed throws and existential - types - -### Dependencies - - - **Swift Numerics**: Used for `RealModule` in tests - - **Platform Requirements**: Version 26 of Apple's OSes - - **Swift Version**: Requires Swift 6.2 toolchain - -### Testing Strategy - - - **Test Plans**: Uses `DevTesting.xctestplan` for organized test execution - - **Coverage Target**: Aims for 99%+ test coverage - - **Platform Testing**: Tests run on iOS, macOS, tvOS, and watchOS simulators - - **CI/CD**: GitHub Actions workflow runs builds on iOS, macOS, tvOS, and watchOS - -### Code Style Conventions - - - Always use `where` clauses to declare constraints on generic parameters - - Prefer `Float64` over `Double` and `Float32` over `Float` - - Always attribute files to the current user, not Claude (e.g., "Created by - on mm/dd/yyyy") - -#### Code Formatting and Spacing - - - **2 blank lines between major sections** including: - - Between the last property declaration and first function declaration - - Between all function/computed property implementations at the same scope level - - Between top-level type declarations (class, struct, enum, protocol, extension) - - Before MARK comments that separate major sections - - **1 blank line** for minor separations: - - Between property declarations and nested type definitions - - Between all function definitions in protocols - - After headers in documentation - - After MARK comments that separate major sections - - **File endings**: All Swift files must end with exactly one blank line - -### Documentation Standards - - - **Full Documentation**: All public APIs are documented with Swift DocC - - **API Guidelines**: Follows Swift API Design Guidelines - - **Documentation Comments**: Uses triple-slash comments (`///`) - - **Markdown Style**: Follow `Documentation/MarkdownStyleGuide.md` for consistent formatting: - - 100 character line length - - 4-space indented code blocks (no fenced blocks) - - 2-space indented bullet lists with alignment - - Consistent terminology (function vs method, type vs class) diff --git a/Documentation/MarkdownStyleGuide.md b/Documentation/MarkdownStyleGuide.md index 297157f..d92d52f 100644 --- a/Documentation/MarkdownStyleGuide.md +++ b/Documentation/MarkdownStyleGuide.md @@ -1,6 +1,6 @@ # Markdown Style Guide -This document defines the Markdown formatting standards for documentation in this codebase. +This document defines the Markdown formatting standards for documentation in this project. ## General Formatting @@ -22,10 +22,10 @@ to stay within this limit. Use consistent spacing for visual hierarchy: -- **Between major sections**: 2 blank lines -- **After code blocks**: 1 blank line -- **Before subsections**: 1 blank line -- **After section headers**: 1 blank line + - **Between major sections**: 2 blank lines + - **After code blocks**: 1 blank line + - **Before subsections**: 1 blank line + - **After section headers**: 1 blank line Example: @@ -77,7 +77,7 @@ Use **4-space indentation** for all code blocks instead of fenced blocks: import DevTesting final class MockService: ServiceProtocol { - nonisolated(unsafe) var performActionStub: Stub! + nonisolated(unsafe) var performActionStub = Stub() } ❌ Bad: @@ -85,7 +85,7 @@ Use **4-space indentation** for all code blocks instead of fenced blocks: import DevTesting final class MockService: ServiceProtocol { - nonisolated(unsafe) var performActionStub: Stub! + nonisolated(unsafe) var performActionStub = Stub() } ``` @@ -154,9 +154,19 @@ Use backticks for: Use consistent terminology throughout documents: -- Prefer "function" over "method" when referring to Swift functions -- Use "type" instead of "class" when referring generically to classes/structs/enums -- Use "property" for stored and computed properties + - Prefer “function” over “method” when referring to Swift functions + - Use “type” instead of “class” when referring generically to classes/structs/enums + - Use “property” for stored and computed properties + + +## Typography + +Use typographic quotes and apostrophes, not straight ones, in prose: ’ for apostrophes (“it’s”), +‘ and ’ for single quotes, and “ and ” for double quotes. Straight quotes remain correct inside code +spans and code blocks. + +The same rule applies to code documentation (doc comments and standalone comments) and to +user-facing strings. ## File Structure Examples diff --git a/Documentation/README.md b/Documentation/README.md new file mode 100644 index 0000000..e8f40bb --- /dev/null +++ b/Documentation/README.md @@ -0,0 +1,7 @@ +# DevTesting Documentation + +Guides for writing code and docs in DevTesting: + + - [Swift Style Guide](SwiftStyleGuide.md) + - [Testing Guidelines](Testing/TestingGuidelines.md) + - [Markdown Style Guide](MarkdownStyleGuide.md) diff --git a/Documentation/SwiftStyleGuide.md b/Documentation/SwiftStyleGuide.md new file mode 100644 index 0000000..a07d183 --- /dev/null +++ b/Documentation/SwiftStyleGuide.md @@ -0,0 +1,111 @@ +--- +description: Swift conventions beyond swift-format: file headers, spacing, generics, numerics +read-when: Writing or reviewing Swift, especially new files, doc comments, or generic declarations +--- + +# Swift Style Guide + +swift-format enforces indentation, line length, trailing commas, and access-level defaults; run +`Tools/lint` to check and `Tools/format` to fix (see `.swift-format`). swift-format doesn’t check +the length of standalone or documentation comments, so `Tools/lint` also reports those over the +limit, and they need wrapping by hand. This guide covers the conventions the formatter doesn’t. + + +## Files + + - Attribute new files to the git user, not the agent: `Created by on + MM/DD/YYYY`. + - End every Swift file with exactly one blank line. + + +## Declarations + + - Follow the + [Swift API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/). + - Declare generic constraints in `where` clauses, not inline in the parameter list. + - Prefer `Float64` to `Double` and `Float32` to `Float`. + - Declare a type’s stored properties first, including those with observers, then its + initializers, then its computed properties and functions. Computed properties are + implementations like functions, so they go with functions rather than stored properties. + + +## Doc comments + + - Document every public declaration. + - A doc comment begins with a one-sentence summary, which can wrap onto more lines. swift-format + lints this shape. + - `///` is fine on private members when the member could reasonably become exposed from the + module. Otherwise prefer `//`. + - Omit `- Returns:` and `- Throws:` when they only restate the signature. + + +## Bodies and control flow + +Empty function bodies and control flow are important lines that are easy to miss on one line, so +give them their own lines: + + - Put control flow statements on multiple lines, including early returns such as + `guard X else { return }`. + - Don’t write empty function bodies as `{}`. Span multiple lines and explain why the body is empty + in a comment. + +Example: + + guard let context else { + return + } + + + func invalidate() { + // Does nothing, because this cache never holds expired values. + } + + +## Spacing + +Use 2 blank lines between major sections: + + - Between the last property declaration and the first function or initializer + - Between function, initializer, and computed property implementations at the same scope + - Between top-level declarations (type, protocol, extension) + - Before a MARK comment that separates major sections + +Use 1 blank line for minor separations: + + - Between property declarations and nested type definitions + - Between function requirements in a protocol + - After a MARK comment + +Example: + + struct ItemList { + let store: any ItemStoring + let id: String + var items: [Item] + + + init(store: any ItemStoring, id: String) { + self.store = store + self.id = id + self.items = [] + } + + + var isEmpty: Bool { + // Implementation + } + + + func reload() { + // Implementation + } + } + + + // MARK: - Protocol + + protocol ItemStoring { + func items() async throws -> [Item] + + func save(_ item: Item) async throws + } diff --git a/Documentation/Testing/TestingGuidelines.md b/Documentation/Testing/TestingGuidelines.md new file mode 100644 index 0000000..69f0dc7 --- /dev/null +++ b/Documentation/Testing/TestingGuidelines.md @@ -0,0 +1,180 @@ +--- +description: Swift Testing conventions, test structure, coverage rules, and DevTesting specifics +read-when: Writing or reviewing a test, choosing what to run, or deciding what needs a fixture +--- + +# Testing Guidelines + +How to write and maintain tests in DevTesting. + + +## Running Tests + +Run `swift test`, or the DevTesting-Package test plan in Xcode, which also reports +coverage. DevRandom and DevTesting have separate test targets. + + +## Swift Testing Framework + +**IMPORTANT**: This project uses **Swift Testing**, not XCTest. Don’t apply XCTest patterns or +conventions. + + - **Use the `@Test` attribute** instead of function name conventions. + - **Use `#expect()` and `#require()`** instead of `XCTAssert*()` functions. + - **Use `#expect(throws:)`** for error conditions. + - **Organize tests in structs**, not classes. + +### Test Naming + + - **No “test” prefixes.** Use descriptive names like `initialLoadingState()`. + - **Name test types after the concrete type.** For a protocol with a concrete implementation, + name the tests after the implementation, such as `SeedableRandomNumberGeneratorTests`. + +### Test Structure + +Unit tests have three parts: set up, exercise, and expect. + + - **Set up**: Create the inputs or mocks needed to exercise the unit under test. + - **Exercise**: Exercise the unit under test, usually by calling a function with the inputs from + setup. + - **Expect**: Expect one or more results, using Swift Testing expressions. + +Rules for these sections: + + - Each test has exactly one unit under test. Only its invocation gets an `// exercise` comment. + Other calls during setup or verification use `// set up` or `// expect` comments. + - Mark the start of each section with a comment, such as `// set up the test by creating a + collection with two items` or `// expect that the item order is unchanged`. If two sections + overlap, mention only the more relevant one. + - Every test has `// set up` unless there’s genuinely nothing to set up. + - Every test has `// expect`. + - `// exercise` is required when a distinct line triggers the behavior under test. Omit it only + when the action and the assertion are the same expression. + - Sections can repeat when useful, such as two `// set up` blocks for different dependencies. + - Comments are prose without colons: `// set up the test by creating a mock loader`, not + `// set up:` or `// set up: mock loader`. + - Occasional unstructured comments, like `// unblock and wait for completion`, are fine when + they help. + + +## File Organization + + - **Test files** are named `[TypeName]Tests.swift`, one per type. + - **Test folders mirror source folders.** Tests for `Sources/DevTesting/Stubbing/` go in + `Tests/DevTestingTests/Stubbing/`. + - **Shared fixtures and helpers** go in the test target’s `Supporting Types/` folder. + - **Group tests by function,** each group preceded by a `// MARK: - [FunctionName]` comment. + - **Imports**: `@testable import` the module under test; import testing frameworks normally; + import only what’s needed. + + +## Coverage + + - **Don’t test pure protocols** that have no implementation. + - **Every function and getter** has at least one test. + - **Add tests for edge cases and error conditions,** and test both success and failure for + throwing functions. + +### Throwing Tests + +A test that uses `#expect(throws:)` must be marked `throws`, or the compiler reports “Errors +thrown from here are not handled.” + + @Test + func decodingRejectsUnknownKind() throws { + #expect(throws: DecodingError.self) { + try decoder.decode(Kind.self, from: data) + } + } + +### Boolean Expectations + +Don’t compare Booleans to `true` or `false`. Use the value directly or negate it. Optional +Booleans are the exception, because the comparison unwraps them. + + // ✅ Good + #expect(item.isEnabled) + #expect(!item.isEnabled) + #expect(response.isCached == true) // isCached is Bool? + + // ❌ Bad + #expect(item.isEnabled == true) + +### Use `#require`, Not Force-Unwrapping or Optional Chaining + +Never force-unwrap optionals in tests. A `nil` crashes the test process instead of failing +cleanly. Optional chaining is also wrong, because it silently skips the expectation when the value +is `nil`. + + // ✅ Good + let owner = try #require(item.owner) + #expect(owner.name == "Alice") + + // ❌ Bad: crashes if nil + #expect(item.owner!.name == "Alice") + + // ❌ Bad: passes if nil + #expect(item.owner?.name == "Alice") + +This applies to any optional access, including dictionary lookups, `first` and `last`, and `as?` +casts. Prefer `#require` to `guard let` in test bodies. + +### Safe Array Access + +Never subscript an array based on an earlier `#expect` of its count. If the expectation fails, the +test keeps going and the subscript crashes. + + // ✅ Good + try #require(items.count == 2) + #expect(items[0].name == "first") + + // ✅ Better + let first = try #require(items.first) + #expect(first.name == "first") + + // ✅ Best: no positional access + #expect(items.map(\.name) == ["first", "second"]) + +### Unconditional Failures + +When a path should never be reached in a passing test, use `Issue.record(_:)` with a descriptive +message, then `return`, because recording an issue doesn’t stop the test: + + guard case .success(let value) = result else { + Issue.record("Expected .success, got \(result)") + return + } + +### Main Actor + +Mark test structs and functions `@MainActor` when testing main-actor-isolated code, such as view +models. + + +## Reducing Repetition + +### Shared Setup in `init` + +When most tests in a struct need the same inputs or mocks, create them in the struct’s `init`. +Each test then shows only what makes it different. + +### Helper Functions + +When several tests build similar objects, extract a private helper with clear parameter defaults. + +### Keep Test-Specific Setup in the Test + +Shared setup covers the common baseline. Anything specific to one scenario goes in that test’s +`// set up` section, so readers don’t have to look elsewhere for context. + + +## DevTesting Specifics + +### Testing the Test Utilities + +DevTesting’s tests use its utilities only as the code under test. Test types don’t +conform to `RandomValueGenerating`, and tests don’t use `Stub`, `ThrowingStub`, or +`ArbitraryError` to test anything but themselves, so a bug in a utility can’t hide +itself. Tests that need random values pass a random number generator, usually +`SystemRandomNumberGenerator`, directly to the functions they call, and tests that +need errors declare their own types. diff --git a/Package.swift b/Package.swift index 92ed428..7572a24 100644 --- a/Package.swift +++ b/Package.swift @@ -1,10 +1,12 @@ -// swift-tools-version: 6.2 +// swift-tools-version: 6.4 import PackageDescription let swiftSettings: [SwiftSetting] = [ .enableUpcomingFeature("ExistentialAny"), + .enableUpcomingFeature("ImmutableWeakCaptures"), .enableUpcomingFeature("MemberImportVisibility"), + .enableUpcomingFeature("NonisolatedNonsendingByDefault"), ] let package = Package( @@ -19,12 +21,12 @@ let package = Package( products: [ .library( name: "DevTesting", - targets: ["DevRandom", "DevTesting"] + targets: ["DevRandom", "DevTesting"], ), .library( name: "DevRandom", - targets: ["DevRandom"] - ) + targets: ["DevRandom"], + ), ], dependencies: [ .package(url: "https://github.com/apple/swift-numerics", from: "1.0.0") @@ -32,7 +34,7 @@ let package = Package( targets: [ .target( name: "DevRandom", - swiftSettings: swiftSettings + swiftSettings: swiftSettings, ), .testTarget( name: "DevRandomTests", @@ -40,21 +42,21 @@ let package = Package( "DevRandom", .product(name: "RealModule", package: "swift-numerics"), ], - swiftSettings: swiftSettings + swiftSettings: swiftSettings, ), .target( name: "DevTesting", dependencies: [ "DevRandom" ], - swiftSettings: swiftSettings + swiftSettings: swiftSettings, ), .testTarget( name: "DevTestingTests", dependencies: [ - "DevTesting", + "DevTesting" ], - swiftSettings: swiftSettings + swiftSettings: swiftSettings, ), - ] + ], ) diff --git a/README.md b/README.md index e822ff9..c0c1e50 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ View our [changelog](CHANGELOG.md) to see what’s new. ## Development Requirements -DevTesting requires a Swift 6.2+ toolchain to build. We only test on Apple platforms. We follow the +DevTesting requires a Swift 6.4+ toolchain to build. We only test on Apple platforms. We follow the [Swift API Design Guidelines][SwiftAPIDesignGuidelines]. We take pride in the fact that our public interfaces are fully documented and tested. We aim for overall test coverage over 99%. @@ -57,17 +57,16 @@ interfaces are fully documented and tested. We aim for overall test coverage ove To set up the development environment: - 1. Run `Scripts/install-git-hooks` to install the pre-push hook that automatically checks - code formatting before pushing. - 2. Use `Scripts/lint` to manually check code formatting at any time. - 3. Use `Scripts/format` to auto-fix code formatting issues. + 1. Run `Tools/install-git-hooks` to install a pre-push hook that runs `Tools/lint`. + 2. Use `Tools/lint` to check Swift and Markdown formatting at any time. + 3. Use `Tools/format` to fix formatting issues. ## Continuous Integration DevTesting uses GitHub Actions for continuous integration. The CI pipeline: - - **Linting**: Automatically checks code formatting on all pull requests using `swift format` + - **Linting**: Checks Swift and Markdown formatting on all pull requests using `Tools/lint` - **Testing**: Runs tests on iOS, macOS, tvOS, and watchOS - **Coverage**: Generates code coverage reports using xccovPretty diff --git a/Scripts/format b/Scripts/format deleted file mode 100755 index a450349..0000000 --- a/Scripts/format +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash - -# Get the directory where this script is located -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" - -# Go to the repository root (one level up from Scripts) -REPO_ROOT="$(dirname "$SCRIPT_DIR")" - -# Run swift format with --in-place to fix formatting issues -swift format --in-place --recursive \ - "$REPO_ROOT/Sources/" \ - "$REPO_ROOT/Tests/" diff --git a/Scripts/install-git-hooks b/Scripts/install-git-hooks deleted file mode 100755 index 56d6935..0000000 --- a/Scripts/install-git-hooks +++ /dev/null @@ -1,56 +0,0 @@ -#!/bin/bash - -# Get the directory where this script is located -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" - -# Go to the repository root (one level up from Scripts) -REPO_ROOT="$(dirname "$SCRIPT_DIR")" - -# Check if we're in a git repository and get the git directory -# This works for both regular repos and worktrees -cd "$REPO_ROOT" -if ! git rev-parse --git-dir > /dev/null 2>&1; then - echo "Error: Not in a git repository" - exit 1 -fi - -# Get the common git directory (shared across all worktrees) -GIT_COMMON_DIR="$(git rev-parse --git-common-dir)" -if [ ! -d "$GIT_COMMON_DIR" ]; then - echo "Error: Could not find git directory" - exit 1 -fi - -mkdir -p "$GIT_COMMON_DIR/hooks" - -# Function to install the pre-push hook -install_pre_push_hook() { - local pre_push_hook="$GIT_COMMON_DIR/hooks/pre-push" - - echo "Installing pre-push hook..." - - cat > "$pre_push_hook" << 'EOF' -#!/bin/bash - -# Resolve the repository root using git, which correctly handles worktrees -REPO_ROOT="$(git rev-parse --show-toplevel)" - -# Run the lint script -echo "Running lint check..." -if ! "$REPO_ROOT/Scripts/lint"; then - echo "Lint check failed. Please fix formatting issues before pushing." - exit 1 -fi - -echo "Lint check passed." -EOF - - chmod +x "$pre_push_hook" - echo "Pre-push hook installed successfully!" -} - -# Install the pre-push hook -install_pre_push_hook - -echo "All git hooks installed successfully!" -echo "The pre-push hook will run 'Scripts/lint' before each push." diff --git a/Scripts/lint b/Scripts/lint deleted file mode 100755 index 2050e33..0000000 --- a/Scripts/lint +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash - -# Get the directory where this script is located -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" - -# Go to the repository root (one level up from Scripts) -REPO_ROOT="$(dirname "$SCRIPT_DIR")" - -# Run swift format lint with full paths to preserve user's PWD -swift format lint --strict --recursive "$REPO_ROOT/Sources/" "$REPO_ROOT/Tests/" diff --git a/Sources/DevRandom/Documentation.docc/Documentation.md b/Sources/DevRandom/Documentation.docc/Documentation.md index 6bb5905..f56b3ec 100644 --- a/Sources/DevRandom/Documentation.docc/Documentation.md +++ b/Sources/DevRandom/Documentation.docc/Documentation.md @@ -15,17 +15,17 @@ random value generation to types in the Swift Standard Library and Foundation. ### Generating Random Values -- ``SeedableRandomNumberGenerator`` + - ``SeedableRandomNumberGenerator`` ### Random Value Generation Extensions -- ``Swift/BinaryFloatingPoint`` -- ``Swift/CaseIterable`` -- ``Foundation/Data`` -- ``Foundation/Date`` -- ``Swift/Optional`` -- ``Swift/String`` -- ``Foundation/URL`` -- ``Foundation/URLComponents`` -- ``Foundation/URLQueryItem`` -- ``Foundation/UUID`` + - ``Swift/BinaryFloatingPoint`` + - ``Swift/CaseIterable`` + - ``Foundation/Data`` + - ``Foundation/Date`` + - ``Swift/Optional`` + - ``Swift/String`` + - ``Foundation/URL`` + - ``Foundation/URLComponents`` + - ``Foundation/URLQueryItem`` + - ``Foundation/UUID`` diff --git a/Sources/DevTesting/Documentation.docc/Documentation.md b/Sources/DevTesting/Documentation.docc/Documentation.md index 7ca2572..48fa39d 100644 --- a/Sources/DevTesting/Documentation.docc/Documentation.md +++ b/Sources/DevTesting/Documentation.docc/Documentation.md @@ -26,19 +26,19 @@ detailed information about how those dependencies were used. ### Generating Random Values -- -- ``RandomValueGenerating`` + - + - ``RandomValueGenerating`` ### Stubbing -- -- ``Stub`` -- ``ThrowingStub`` -- ``DefaultStubValueProviding`` -- ``ArbitraryError`` + - + - ``Stub`` + - ``ThrowingStub`` + - ``DefaultStubValueProviding`` + - ``ArbitraryError`` ### Collection Generation Extensions -- ``Swift/Array`` -- ``Swift/Dictionary`` -- ``Swift/Set`` + - ``Swift/Array`` + - ``Swift/Dictionary`` + - ``Swift/Set`` diff --git a/Sources/DevTesting/Documentation.docc/RandomValueGenerating.md b/Sources/DevTesting/Documentation.docc/RandomValueGenerating.md index 42c1cfb..3400118 100644 --- a/Sources/DevTesting/Documentation.docc/RandomValueGenerating.md +++ b/Sources/DevTesting/Documentation.docc/RandomValueGenerating.md @@ -1,61 +1,62 @@ # ``RandomValueGenerating`` + ## Topics ### Seedable Random Number Generation -- ``makeRandomNumberGenerator(seed:)`` -- ``randomNumberGenerator`` -- ``randomSeed`` + - ``makeRandomNumberGenerator(seed:)`` + - ``randomNumberGenerator`` + - ``randomSeed`` ### Collection Elements -- ``randomCase(of:)`` -- ``randomElement(in:)`` + - ``randomCase(of:)`` + - ``randomElement(in:)`` ### Dates -- ``defaultClosedDateRange`` -- ``randomDate(in:)-(ClosedRange?)`` -- ``randomDate(in:)-(Range)`` + - ``defaultClosedDateRange`` + - ``randomDate(in:)-(ClosedRange?)`` + - ``randomDate(in:)-(Range)`` ### Errors -- ``randomError(fileID:function:)`` + - ``randomError(fileID:function:)`` ### Numeric Types -- ``randomFloat64(in:)-(Range)`` -- ``randomFloat64(in:)-(ClosedRange)`` -- ``randomInt(in:)-(Range)`` -- ``randomInt(in:)-(ClosedRange)`` -- ``random(_:in:)-(_,Range)`` -- ``random(_:in:)-(_,ClosedRange)`` -- ``random(_:in:)-(_,Range)`` -- ``random(_:in:)-(_,ClosedRange)`` + - ``randomFloat64(in:)-(Range)`` + - ``randomFloat64(in:)-(ClosedRange)`` + - ``randomInt(in:)-(Range)`` + - ``randomInt(in:)-(ClosedRange)`` + - ``random(_:in:)-(_,Range)`` + - ``random(_:in:)-(_,ClosedRange)`` + - ``random(_:in:)-(_,Range)`` + - ``random(_:in:)-(_,ClosedRange)`` ### Strings -- ``randomAlphanumericString(count:)`` -- ``randomBasicLatinString(count:)`` -- ``randomString(withCharactersFrom:count:)`` + - ``randomAlphanumericString(count:)`` + - ``randomBasicLatinString(count:)`` + - ``randomString(withCharactersFrom:count:)`` ### URL Types -- ``randomURL(includeFragment:includeQueryItems:)`` -- ``randomURLComponents(includeFragment:includeQueryItems:)`` -- ``randomURLQueryItem()`` + - ``randomURL(includeFragment:includeQueryItems:)`` + - ``randomURLComponents(includeFragment:includeQueryItems:)`` + - ``randomURLQueryItem()`` ### Other Common Types -- ``randomBool()`` -- ``randomData(count:)`` -- ``randomOptional(_:)`` -- ``randomUUID()`` + - ``randomBool()`` + - ``randomData(count:)`` + - ``randomOptional(_:)`` + - ``randomUUID()`` diff --git a/Sources/DevTesting/Documentation.docc/UsingRandomValueGeneration.md b/Sources/DevTesting/Documentation.docc/UsingRandomValueGeneration.md index 3678105..481efb7 100644 --- a/Sources/DevTesting/Documentation.docc/UsingRandomValueGeneration.md +++ b/Sources/DevTesting/Documentation.docc/UsingRandomValueGeneration.md @@ -17,8 +17,8 @@ automatically logs the random seeds used in each test, allowing you to reproduce exactly. The random value generation system integrates seamlessly with Swift Testing, automatically logging -seeds both to Apple’s Unified Logging system and as test attachments. This means that when a test -fails, you have multiple ways to capture and reuse the seed that caused the failure, making +seeds both to Apple’s Unified Logging system and as test attachments. This means that when a test +fails, you have multiple ways to capture and reuse the seed that caused the failure, making debugging much more straightforward than with traditional random testing approaches. In this guide, we’ll explore how to use DevTesting’s random value generation effectively in your @@ -168,7 +168,7 @@ DevTesting includes generators for common Foundation types: } The ``RandomValueGenerating/randomURL(includeFragment:includeQueryItems:)`` function creates -realistic URLs with random schemes, hosts, paths, and optionally query parameters and +realistic URLs with random schemes, hosts, paths, and optionally query parameters and fragments. @@ -191,7 +191,7 @@ Work with collections and enumerations easily: let emptyResult = randomElement(in: [Int]()) // nil } -Note that both ``RandomValueGenerating/randomElement(in:)`` and +Note that both ``RandomValueGenerating/randomElement(in:)`` and ``RandomValueGenerating/randomCase(of:)`` return optionals because they return `nil` when called on empty collections. @@ -234,7 +234,7 @@ seeds and provides multiple ways to reproduce test failures. ### Automatic seed logging -Every time you create a random number generator with +Every time you create a random number generator with ``RandomValueGenerating/makeRandomNumberGenerator(seed:)``, DevTesting automatically logs the seed being used. This logging happens in two places: @@ -376,8 +376,9 @@ types. For example: } } -These extensions become immediately available in any test that conforms to ``RandomValueGenerating``, -allowing you to generate complex domain objects with a single function call. +These extensions become immediately available in any test that conforms to +``RandomValueGenerating``, allowing you to generate complex domain objects with a single function +call. ### Combining existing functions @@ -446,7 +447,8 @@ The key benefits include: - **Comprehensive coverage**: Test your code with a wide variety of inputs automatically - **Reproducible failures**: Every random test run can be exactly reproduced using logged seeds - **Easy debugging**: Failed tests become as debuggable as deterministic tests - - **Extensible design**: Create domain-specific random generators that match your application’s data + - **Extensible design**: Create domain-specific random generators that match your application’s + data Whether you’re testing simple functions with varied inputs or complex workflows with intricate data structures, DevTesting’s random value generation gives you the tools to write thorough, maintainable diff --git a/Tools/format b/Tools/format new file mode 100755 index 0000000..a188a55 --- /dev/null +++ b/Tools/format @@ -0,0 +1,19 @@ +#!/bin/bash + +# Formats Swift with swift-format and Markdown with rumdl, in place. + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(dirname "$SCRIPT_DIR")" + +# Swift files and directories to format, relative to the repository root +SWIFT_PATHS=(Package.swift Sources Tests) +swift_paths=("${SWIFT_PATHS[@]/#/$REPO_ROOT/}") + +exit_status=0 + +swift format --in-place --recursive "${swift_paths[@]}" || exit_status=1 + +# Rewrite Markdown using the rules in .rumdl.toml +"$SCRIPT_DIR/rumdl" fmt "$REPO_ROOT" || exit_status=1 + +exit "$exit_status" diff --git a/Tools/install-git-hooks b/Tools/install-git-hooks new file mode 100755 index 0000000..862c44e --- /dev/null +++ b/Tools/install-git-hooks @@ -0,0 +1,30 @@ +#!/bin/bash + +# Installs a pre-push hook that runs Tools/lint, so formatting problems are caught before CI sees +# them. The hook goes in the repository’s common Git directory, so it applies to every worktree. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(dirname "$SCRIPT_DIR")" + +cd "$REPO_ROOT" +GIT_COMMON_DIR="$(git rev-parse --path-format=absolute --git-common-dir)" +HOOKS_DIR="$GIT_COMMON_DIR/hooks" +mkdir -p "$HOOKS_DIR" + +cat > "$HOOKS_DIR/pre-push" << 'HOOK' +#!/bin/bash + +# Installed by Tools/install-git-hooks. Runs Tools/lint before pushing. +REPO_ROOT="$(git rev-parse --show-toplevel)" + +echo "Running Tools/lint…" +if ! "$REPO_ROOT/Tools/lint"; then + echo "Lint failed. Run Tools/format, or push with --no-verify to skip this check." + exit 1 +fi +HOOK + +chmod +x "$HOOKS_DIR/pre-push" +echo "Installed a pre-push hook that runs Tools/lint." diff --git a/Tools/lint b/Tools/lint new file mode 100755 index 0000000..46518e3 --- /dev/null +++ b/Tools/lint @@ -0,0 +1,37 @@ +#!/bin/bash + +# Lints Swift with swift-format, the length of Swift comments, and Markdown with rumdl. Exits with a +# nonzero status if any check fails, after running all of them. + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(dirname "$SCRIPT_DIR")" + +# Swift files and directories to check, relative to the repository root +SWIFT_PATHS=(Package.swift Sources Tests) +swift_paths=("${SWIFT_PATHS[@]/#/$REPO_ROOT/}") + +exit_status=0 + +swift format lint --strict --recursive "${swift_paths[@]}" || exit_status=1 + +# swift-format doesn’t check the length of standalone or documentation comments, so report those +# over its line length. Perl counts characters rather than bytes. Read the limit with Python rather +# than plutil, which only exists on macOS. +line_length="$(python3 -c 'import json, sys; print(json.load(open(sys.argv[1]))["lineLength"])' \ + "$REPO_ROOT/.swift-format")" +find "${swift_paths[@]}" -name '*.swift' -print0 2>/dev/null | + xargs -0 perl -CDS -sne ' + chomp; + if (m{^\s*//} && length($_) > $limit) { + printf STDERR "%s:%d:%d: error: [CommentLength] wrap this comment, which is %d characters long, to %d or fewer\n", + $ARGV, $., $limit + 1, length($_), $limit; + $found = 1; + } + close ARGV if eof; + END { exit 1 if $found } + ' -- -limit="$line_length" || exit_status=1 + +# Lint Markdown using the rules in .rumdl.toml +"$SCRIPT_DIR/rumdl" check "$REPO_ROOT" || exit_status=1 + +exit "$exit_status" diff --git a/Tools/rumdl b/Tools/rumdl new file mode 100755 index 0000000..5ecc6a7 --- /dev/null +++ b/Tools/rumdl @@ -0,0 +1,40 @@ +#!/bin/bash + +# Runs the pinned version of rumdl, installing it on first use. Pinning keeps local runs and CI on +# the same version, so a new rumdl release can’t change lint results until this version changes. +# Each version is installed once per user into a virtual environment in the user’s cache. + +set -euo pipefail + +RUMDL_VERSION="0.3.5" + +INSTALL_ROOT="${XDG_CACHE_HOME:-$HOME/.cache}/devkit" +INSTALL_DIR="$INSTALL_ROOT/rumdl-$RUMDL_VERSION" +RUMDL="$INSTALL_DIR/bin/rumdl" + +if [[ ! -x "$RUMDL" ]]; then + echo "Installing rumdl ${RUMDL_VERSION} into ${INSTALL_DIR}…" >&2 + mkdir -p "$INSTALL_ROOT" + + # Install into a temporary directory and move it into place, so a run that starts while + # another is installing never sees a partial installation. + staging_dir="$(mktemp -d "$INSTALL_ROOT/rumdl-staging.XXXXXX")" + trap 'rm -rf "$staging_dir"' EXIT + python3 -m venv "$staging_dir" + "$staging_dir/bin/pip" install --quiet --disable-pip-version-check "rumdl==$RUMDL_VERSION" >&2 + + # If another run finished first, keep its copy. exec below skips the EXIT trap, so clean up + # the staging directory here. + if [[ ! -e "$INSTALL_DIR" ]]; then + mv "$staging_dir" "$INSTALL_DIR" + fi + rm -rf "$staging_dir" + trap - EXIT + + if [[ ! -x "$RUMDL" ]]; then + echo "Error: couldn’t install rumdl ${RUMDL_VERSION}" >&2 + exit 1 + fi +fi + +exec "$RUMDL" "$@"