diff --git a/.github/workflows/VerifyChanges.yaml b/.github/workflows/VerifyChanges.yaml index 791ab6c..880cf63 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 @@ -95,8 +95,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: | @@ -122,7 +126,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 }} @@ -139,11 +143,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..cedcda7 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,67 @@ +# Agent Guidelines + +DevKeychain is a Swift package that provides a modern, type-safe interface to Apple’s +keychain services. + + +## Building and testing + + - `swift build` and `swift test` build the package and run its unit tests. + - Xcode test plans in `Build Support/Test Plans/` run the tests with coverage, as CI does. + The DevKeychainApp test plan runs the integration tests in `App/Tests/` against the + real keychain. + + +## 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) + - [Test Mocks](Documentation/Testing/TestMocks.md) + +Also: + + - Document and test every public API, and keep test coverage above 99%. + + +## 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/App/DevKeychain.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/App/DevKeychain.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 71e36e9..ef4a966 100644 --- a/App/DevKeychain.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/App/DevKeychain.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,13 +1,13 @@ { - "originHash" : "b8a530ee7226c84a565126bfba741f190296a4e2640e77274408c16bd1203631", + "originHash" : "114bc84feab3de3199d3cb5f9b1634a5a7f4d682d403af9351215677fe48e026", "pins" : [ { "identity" : "devtesting", "kind" : "remoteSourceControl", "location" : "https://github.com/Devkitorganization/devtesting", "state" : { - "revision" : "7dcd0757a4fa146ffeede688d649953643014be9", - "version" : "1.2.0" + "revision" : "7df52d20dade53d58d818bb255236d45da26bbde", + "version" : "1.7.0" } } ], diff --git a/CHANGELOG.md b/CHANGELOG.md index f12d30e..aa5153a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ # DevKeychain Changelog +## 1.3.0: November 24, 2026 + +This release requires Swift 6.4 (Xcode 27) to build. There are no other changes. + + ## 1.2.0: July 28, 2026 This update adds support for specifying Keychain item accessibility values. diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 4a10b3b..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1,217 +0,0 @@ -# CLAUDE.md - -This file provides guidance to Claude Code (claude.ai/code) when working with code in this -repository. - - -## Project Overview - -DevKeychain is a Swift package providing a modern, type-safe interface to Apple's keychain -services. It supports version 26 of Apple's OSes and requires a Swift 6.2+ toolchain. - - -## Development Commands - -### Building and Testing - - - **Build**: `swift build` - - **Test all**: `swift test` - - **Test specific**: `swift test --filter ` - - **Test with coverage**: `swift test --enable-code-coverage` - -### Code Quality - - - **Lint**: `Scripts/lint` (uses `swift format lint --recursive --strict`) - - **Format**: `Scripts/format` (uses `swift format --in-place --recursive`) - -### Git Hooks - - - **Install**: `Scripts/install-git-hooks` (installs pre-push hook that runs lint) - - -## Architecture Overview - -### Core Design Pattern - -The codebase follows a **protocol-based architecture** with dependency injection: - - - `KeychainServices` protocol abstracts Security framework operations - - `StandardKeychainServices` provides real implementation - - Mock implementations enable comprehensive testing - - All keychain item types implement `KeychainItemAdditionAttributes` and `KeychainItemQuery` - protocols - -### Key Components - -**Core Layer** (`Sources/DevKeychain/Core/`): - - - `Keychain.swift`: Main keychain interface - - `KeychainServices.swift`: Protocol abstraction over Security framework - - `KeychainItemAdditionAttributes.swift` & `KeychainItemQuery.swift`: Generic protocols for - type-safe operations - -**Keychain Item Types** (`Sources/DevKeychain/Keychain Items/`): - - - `GenericPassword.swift`: Service/account-based passwords - - `InternetPassword.swift`: Server/account-based credentials - - Each type has nested `AdditionAttributes` and `Query` types - -**Error Handling** (`Sources/DevKeychain/Errors/`): - - - `KeychainServicesError.swift`: Wraps OSStatus errors from Security framework - - `KeychainItemMappingError.swift`: Data conversion and mapping errors - -### Testing Architecture - -Uses **Swift Testing** framework with comprehensive mocking: - - - All tests inject mock `KeychainServices` implementations - - `DevTesting` dependency provides Stub system for mocking - - Tests are organized by component in `Tests/DevKeychainTests/` - - Integration tests in `App/Tests/` use real keychain operations - -### Code Organization Patterns - - 1. **Nested Types**: Related functionality grouped within parent types - 2. **Generic Protocols**: Type-safe operations without runtime checks - 3. **Extension-based Helpers**: `Dictionary+KeychainItemMapping.swift` for attribute conversion - 4. **Dependency Injection**: Constructor injection for `KeychainServices` - - -## Development Guidelines - -### Adding New Keychain Item Types - - 1. Create new file in `Sources/DevKeychain/Keychain Items/` - 2. Implement `KeychainItemAdditionAttributes` protocol for adding items - 3. Implement `KeychainItemQuery` protocol for querying items - 4. Add comprehensive tests with both success and failure scenarios - 5. Follow the pattern established by `GenericPassword` and `InternetPassword` - -### Testing Patterns - - - Always use mock `KeychainServices` in unit tests - - Use `DevTesting.Stub` for consistent mocking behavior - - Test both success and error scenarios - - Use randomized test data via `RandomValueGenerating+DevKeychain.swift` - - Follow naming convention: `Tests.swift` - -### Code Style - - - Swift API Design Guidelines strictly enforced - - 120 character line limit (configured in `.swift-format`) - - All public APIs must be documented - - Use descriptive variable names and clear function signatures - - -## CI/CD Configuration - -The project uses GitHub Actions for continuous integration: - - - **Linting**: Automatically checks code formatting on all pull requests using `swift format` - - **Testing**: Builds and tests on iOS, macOS, tvOS, and watchOS - - **Coverage**: Generates code coverage reports using xccovPretty - - Uses Xcode 26.3 and macOS 26 runners - - -## Platform Requirements - - - Swift 6.2+ toolchain required - - Xcode 26.3 for CI/CD - - Apple platforms only (iOS/macOS/tvOS/visionOS/watchOS version 26) - - Uses modern Swift concurrency features - - -## Testing and Mocking Standards - -### Test Mock Architecture - -The codebase uses a consistent stub-based mocking pattern built on the DevTesting framework: - -#### Core Mock Patterns - - - **Stub-based mocks**: All mocks use `Stub` or - `ThrowingStub` - - **Force-unwrapped stubs**: Stub properties are declared with `!` — tests must configure them - - **Swift 6 concurrency**: All stub properties marked `nonisolated(unsafe)` - - **Argument structures**: Complex parameters use dedicated structures (e.g., - `LogErrorArguments`) - -#### Mock Organization - - - **File naming**: `Mock[ProtocolName].swift` - - **Type naming**: `Mock[ProtocolName]` - - **Stub properties**: `[functionName]Stub` - - **Location**: `Tests/DevKeychainTests/Testing Helpers/` - -#### Test Patterns - - - Use `@Test` with Swift Testing framework - - Use `#expect()` and `#require()` for assertions - - Always configure stubs before use to avoid crashes - - Leverage DevTesting's call tracking for verification - - -## Documentation Standards - -Follow the project's Markdown Style Guide: - - - **Line length**: 100 characters max - - **Code blocks**: Use 4-space indentation, not fenced blocks - - **Lists**: Use `-` for bullets, align continuation lines with text - - **Spacing**: 2 blank lines between major sections, 1 after headers - - **Terminology**: Use "function" over "method", "type" over "class" - -When writing Markdown documentation, reference `@Documentation/MarkdownStyleGuide.md` to -ensure consistent formatting, structure, and style across all project documentation. - - -## Code Formatting and Spacing - -The project follows strict spacing conventions for readability and consistency: - - - **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 - - -## Scripts Directory - -The `Scripts/` directory contains utility scripts for development workflow automation: - -### Available Scripts - -**`Scripts/install-git-hooks`**: - - Installs a pre-push git hook that runs `Scripts/lint` for formatting validation - - Works correctly with git worktrees - - Run once per repository to set up automated code quality workflow - -**`Scripts/lint`**: - - Runs `swift format lint` validation with strict mode enabled - - Checks `App/`, `Sources/`, and `Tests/` directories recursively - - Returns non-zero exit code if formatting issues are found - - Used by pre-push hook and can be run manually for code quality verification - -**`Scripts/format`**: - - Runs `swift format --in-place` to automatically fix formatting issues - - Formats `App/`, `Sources/`, and `Tests/` directories recursively - - -## Key Files for Understanding - - - `Sources/DevKeychain/Core/Keychain.swift`: Main API entry point - - `Sources/DevKeychain/Core/KeychainServices.swift`: Core protocol abstraction - - `Sources/DevKeychain/Keychain Items/GenericPassword.swift`: Example keychain item - implementation - - `Tests/DevKeychainTests/Testing Helpers/`: Mock implementations and test utilities - - `Package.swift`: Dependencies and platform requirements - - `.swift-format`: Code formatting configuration - - `Scripts/`: Development workflow automation scripts diff --git a/Documentation/MarkdownStyleGuide.md b/Documentation/MarkdownStyleGuide.md index da25aa8..d92d52f 100644 --- a/Documentation/MarkdownStyleGuide.md +++ b/Documentation/MarkdownStyleGuide.md @@ -11,9 +11,9 @@ Keep all lines under **100 characters**. Break long sentences and paragraphs at to stay within this limit. ✅ Good: - Faucibus consectetur lacinia nostra eros conubia nibh inceptos hendrerit, ante blandit + Faucibus consectetur lacinia nostra eros conubia nibh inceptos hendrerit, ante blandit vulputate imperdiet amet porttitor torquent mattis. - + ❌ Bad: Faucibus consectetur lacinia nostra eros conubia nibh inceptos hendrerit, ante blandit vulputate imperdiet amet porttitor torquent mattis. @@ -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..73e3270 --- /dev/null +++ b/Documentation/README.md @@ -0,0 +1,8 @@ +# DevKeychain Documentation + +Guides for writing code and docs in DevKeychain: + + - [Swift Style Guide](SwiftStyleGuide.md) + - [Testing Guidelines](Testing/TestingGuidelines.md) + - [Test Mocks](Testing/TestMocks.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/TestMocks.md b/Documentation/TestMocks.md deleted file mode 100644 index afca4c9..0000000 --- a/Documentation/TestMocks.md +++ /dev/null @@ -1,483 +0,0 @@ -# Test Mock Documentation - -This document outlines the patterns and conventions for writing test mocks in Swift. - -Its helpful to read the [Dependency Injection guide](DependencyInjection.md) before reading this -guide, as it introduces core principles for how we think about dependency injection. - - -## Overview - -We use a consistent approach to mocking based on the DevTesting package's `Stub` and `ThrowingStub` -types. All mocks follow standardized patterns that make them predictable, testable, and -maintainable. - - -## When to Mock vs. Use Types Directly - -Create mock protocols when - - - The type has **non-deterministic behavior** (network calls, file I/O, time-dependent operations) - - You need to **control or observe the behavior** in tests - - The type's behavior **varies across environments** - -Use types directly when - - - The type has **deterministic, predictable behavior** - - Testing with the real implementation provides **sufficient coverage** - - Creating abstractions adds **complexity without testing benefits** - -It's worth pointing out that the following foundational types should be used directly. - - - **`NotificationCenter`**: Posting and observing notifications is predictable - - **`UserDefaults`**: Simple key-value storage with consistent behavior - - **`Bundle`**: Resource loading behavior is consistent and testable - - **`EventBus`**: Synchronous event dispatching with deterministic outcomes - - -## Core Mock Patterns - -### 1. Stub-Based Architecture - -All mocks use `DevTesting`'s `Stub` or `ThrowingStub` types -for function and property implementations: - - import DevTesting - - - final class MockService: ServiceProtocol { - nonisolated(unsafe) var performActionStub: Stub! - - - func performAction(_ input: String) -> Bool { - performActionStub(input) - } - } - -**Key characteristics:** - - - Properties are marked `nonisolated(unsafe)` for Swift 6 concurrency - - Stub properties are force-unwrapped (`!`). Tests must configure them. - - Function implementations simply call the corresponding stub - - -### 2. Argument Structures for Complex Parameters - -When functions have multiple parameters, create dedicated argument structures: - - final class MockTelemetryDestination: TelemetryDestination { - struct LogErrorArguments { - let error: any Error - let attributes: [String : any Encodable] - } - - - nonisolated(unsafe) var logErrorStub: Stub! - - - func logError(_ error: some Error, attributes: [String : any Encodable]) { - logErrorStub(.init(error: error, attributes: attributes)) - } - } - -**Benefits:** - - - Simplifies stub configuration in tests - - Provides clear parameter documentation - - Enables easy verification of function calls - - -### 3. Property-Only Services - -For services that only expose properties (like `MockAppServices`), each property delegates to a -stub: - - final class MockAppServices: PlatformAppServices { - nonisolated(unsafe) var stylesheetStub: Stub! - nonisolated(unsafe) var telemetryEventLoggerStub: Stub! - - - var stylesheet: Stylesheet { - stylesheetStub() - } - - - var telemetryEventLogger: any TelemetryEventLogging { - telemetryEventLoggerStub() - } - } - - -### 4. Generic Mock Types - -For protocols with associated types, create generic mocks: - - struct MockTelemetryEvent: TelemetryEvent - where EventData: Encodable & Sendable { - let name: TelemetryEventName - var eventData: EventData - } - - - extension MockTelemetryEvent: Equatable where EventData: Equatable { } - extension MockTelemetryEvent: Hashable where EventData: Hashable { } - - -**Pattern:** - - - Use generic parameters for flexible data types - - Add conditional conformances for `Equatable` and `Hashable` when possible - - Maintain protocol requirements while allowing test customization - - -### 5. Simple Error Mocks - -For testing error scenarios, use simple enum-based errors: - - enum MockError: Error, CaseIterable, Hashable, Sendable { - case error1 - case error2 - case error3 - } - -**Characteristics:** - - - Implement `CaseIterable` for easy test iteration - - Include `Hashable` and `Sendable` for Swift 6 compatibility - - Use descriptive but simple case names - - -## Mock Organization - -### File Structure and Organization - -#### Directory Structure: - Tests/ - ├── [PackageName]Tests/ # Package-specific tests - │ ├── Unit Tests/ - │ │ └── [ModuleName] # Feature-specific tests - │ │ └── [ProtocolName]Tests.swift - │ └── Testing Support/ # Mock objects and test utilities - │ ├── Mock[ProtocolName].swift # Mock implementations - │ ├── MockError.swift # Test-specific error types - │ └── RandomValueGenerating+[ModuleName].swift # Random value extensions - -#### File Placement Guidelines: - -- **Unit Test files**: Place in `Tests/[PackageName]/Unit Tests/`, matching the path of the source file in - the directory structure under `Sources/` -- **Mock objects**: Always place in `Tests/[PackageName]/Testing Support/` directories -- **One mock per file**: Each protocol should have its own dedicated mock file -- **Sharing mocks**: Do not share mocks between Packages. If the same Mock is needed across - multiple packages, duplicate it. - -### Naming Conventions - - - **File names**: `Mock[ProtocolName].swift` - - **Type names**: `Mock[ProtocolName]` - - **Argument structures**: `[FunctionName]Arguments` - - **Stub properties**: `[functionName]Stub` - - -## Special Patterns - -### 1. Static Stubs for Initializers - -When mocking types with custom initializers, use static stubs: - - final class MockSubapp: Subapp { - struct InitArguments { - let appConfiguration: AppConfiguration - let subappServices: any SubappServices - } - - - nonisolated(unsafe) static var initStub: Stub! - - - init(appConfiguration: AppConfiguration, subappServices: any SubappServices) async { - Self.initStub(.init(appConfiguration: appConfiguration, subappServices: subappServices)) - } - } - - -### 2. Default Stub Values - -For functions that might not be called in every test, provide default stub values: - - final class MockSubapp: Subapp { - // Initialize to non-nil to avoid crashes in tests that don't configure this stub - nonisolated(unsafe) var installTelemetryBusEventHandlersStub: Stub< - TelemetryBusEventObserver, - Void - > = .init() - } - -**CRITICAL - Stubs Accessed by Internal Async Tasks:** - -When testing types that spawn internal `Task`s during initialization, ALL stubs accessed by those -tasks must be initialized in test setup, even if not directly tested. Failure to initialize stubs -will cause crashes when the internal task tries to access them. - -This applies to ANY mock (Observable or not) whose stubs are accessed by background tasks. - -#### Why This is Required: - -When a type spawns internal `Task`s during initialization, those tasks may access properties or -functions on injected dependencies. If those dependencies are mocks with force-unwrapped stubs, and -the stubs haven't been initialized, the app will crash when the internal task tries to access them. - -**Example crash scenario:** - - // Any mock type (Observable or not) - @MainActor - final class MockDataSource: DataSource { - nonisolated(unsafe) var currentItemsStub: Stub! - var currentItems: [Item] { - currentItemsStub(id) // Crashes if stub is nil - } - } - - // Type spawns internal task during init - init(dataSource: any DataSource) { - self.dataSource = dataSource - Task { - // This accesses dataSource.currentItems, triggering the stub - let items = dataSource.currentItems - } - } - - // Test doesn't initialize the stub - @Test - func myTest() { - let mockDataSource = MockDataSource() // currentItemsStub is nil - let processor = ItemProcessor(dataSource: mockDataSource) // Crashes in internal task - } - -#### Solution Pattern: Initialize in Test Setup - -Initialize all stubs that internal tasks will access: - - @MainActor - struct ItemProcessorTests: RandomValueGenerating { - var mockDataSource = MockDataSource() - - init() { - // CRITICAL: Initialize ALL stubs that the type's internal tasks will access - // Even if this particular test doesn't verify these stubs, they must be non-nil - mockDataSource.fetchItemsStub = ThrowingStub(defaultError: nil) - mockDataSource.currentItemsStub = Stub(defaultReturnValue: []) - } - - @Test - mutating func myTest() async throws { - // Create type that spawns internal tasks using mockDataSource - let processor = ItemProcessor(dataSource: mockDataSource) - // ... test logic ... - } - } - -#### How to Identify Required Stubs: - - 1. Look for `Task { }` blocks in the type's initializer - 2. Trace what properties/functions those tasks access on dependencies - 3. Initialize stubs for all accessed properties/functions in test `init()` - 4. Run tests — crashes will identify any missed stubs - - -### 3. Prologue and Epilogue Closures for Execution Control - -For mock functions that need precise control over execution timing, use optional prologue and -epilogue closures that execute before and after the stub. - -#### Prologue Pattern - -Prologues execute before the stub is called: - - final class MockNetworkClient: NetworkClient { - nonisolated(unsafe) var sendRequestPrologue: (() async throws -> Void)? - nonisolated(unsafe) var sendRequestStub: ThrowingStub< - URLRequest, - Response, - any Error - >! - - - func sendRequest(_ request: URLRequest) async throws -> Response { - try await sendRequestPrologue?() - return try sendRequestStub(request) - } - } - -#### Epilogue Pattern - -Epilogues execute after the stub is called. Run the epilogue in a `Task` within a `defer` block: - - final class MockEventLogger: EventLogging { - nonisolated(unsafe) var logEventStub: Stub! - nonisolated(unsafe) var logEventEpilogue: (() async throws -> Void)? - - - func logEvent(_ event: some Event) { - defer { - if let epilogue = logEventEpilogue { - Task { try? await epilogue() } - } - } - logEventStub(event) - } - } - -#### Use Cases - -**Prologues** (execute before stub): - - - **Block before processing**: Delay the mock from executing its core behavior - - **Test pre-call state**: Verify conditions before the mock operation begins - - **Insert delays**: Add artificial timing before processing - - **Coordinate setup**: Ensure test conditions are ready before mock executes - -**Epilogues** (execute after stub): - - - **Signal completion**: Notify tests when the mock operation has finished - - **Test post-call state**: Verify conditions after the stub executes but before returning - - **Coordinate with background work**: Wait for fire-and-forget operations to complete - -#### Example: Blocking with AsyncStream - - let (signalStream, signaler) = AsyncStream.makeStream() - mockClient.sendRequestPrologue = { - await signalStream.first(where: { _ in true }) - } - mockClient.sendRequestStub = ThrowingStub(defaultReturnValue: .init()) - - // Start operation that calls the mock - instance.performAction() - - // Verify intermediate state while mock is blocked - await #expect(instance.isProcessing) - - // Signal completion to unblock - signaler.yield() - -#### Example: Signaling Completion with Epilogue - - let eventLogger = MockEventLogger() - eventLogger.logEventStub = Stub() - - let (signalStream, signaler) = AsyncStream.makeStream() - eventLogger.logEventEpilogue = { - signaler.yield() - } - - // Call function that triggers the mock (e.g., via event bus handler) - eventBus.post(SomeEvent()) - - // Wait for mock to complete - await signalStream.first { _ in true } - - // Verify the mock was called - #expect(eventLogger.logEventStub.calls.count == 1) - -#### Example: Adding Delays - - mockClient.sendRequestPrologue = { - try await Task.sleep(for: .milliseconds(100)) - } - -#### Benefits - - - Separates timing control (prologue/epilogue) from return values/errors (stub) - - Enables testing at different execution phases (before/after stub) - - More precise than arbitrary `Task.sleep()` delays in tests - - Eliminates race conditions from timing-based coordination - - Optional — tests can ignore if timing control isn't needed - - -### 4. Protocol Imports with @testable - -Import protocols under test with `@testable` when accessing internal details: - - import AppPlatform - @testable import protocol AppPlatform.PlatformAppServices - @testable import protocol Telemetry.TelemetryDestination - - -## Usage in Tests - -### 1. Typical Test Setup - - @Test - mutating func testEventLogging() throws { - let mockDestination = MockTelemetryDestination() - mockDestination.logEventStub = .init() // Initialize stub - - let logger = TelemetryEventLogger(telemetryDestination: mockDestination) - logger.logEvent(someEvent) - - // Verify the call was made - #expect(mockDestination.logEventStub.calls.count == 1) - - // Extract and verify arguments - let arguments = try #require(mockDestination.logEventStub.callArguments.first) - #expect(arguments.name == expectedEventName) - #expect(arguments.attributes["key"] as? String == "expectedValue") - } - - -### 2. Return Value Configuration - - @Test - func testServiceCall() { - let mockServices = MockAppServices() - mockServices.stylesheetStub = Stub(defaultReturnValue: .standard) - - let result = systemUnderTest.processWithServices(mockServices) - - // Verify the service was called - #expect(mockServices.stylesheetStub.calls.count == 1) - } - - -### 3. Argument Verification Patterns - - @Test - mutating func testComplexMethodCall() throws { - let mockDestination = MockTelemetryDestination() - mockDestination.logErrorStub = .init() - - let error = MockError.error1 - let attributes = ["key": "value"] - - logger.logError(error, attributes: attributes) - - // Verify call count - #expect(mockDestination.logErrorStub.calls.count == 1) - - // Extract and verify arguments - let arguments = try #require(mockDestination.logErrorStub.callArguments.first) - #expect(arguments.error as? MockError == error) - #expect(arguments.attributes["key"] as? String == "value") - } - - -## Best Practices - - 1. **Always configure stubs**: Force-unwrapped stubs will crash if not configured - 2. **Use argument structures**: Simplifies complex parameter verification - 3. **Leverage DevTesting**: Use the package's call tracking and verification capabilities - 4. **Keep mocks simple**: Avoid complex logic in mock implementations - 5. **Group related mocks**: Place mocks in appropriate Testing Support directories - 6. **Follow naming conventions**: Consistent naming improves maintainability - 7. **Use Swift Testing**: Leverage `@Test`, `#expect()`, and `#require()` for assertions - - -## Thread Safety - -All mocks use `nonisolated(unsafe)` markings for Swift 6 compatibility. This assumes: - - - Tests run on a single thread or properly synchronize access - - Stub configuration happens during test setup before concurrent access - - Mock usage patterns don't require additional synchronization - -When mocking concurrent code, consider additional synchronization mechanisms if needed. diff --git a/Documentation/Testing/TestMocks.md b/Documentation/Testing/TestMocks.md new file mode 100644 index 0000000..e14951d --- /dev/null +++ b/Documentation/Testing/TestMocks.md @@ -0,0 +1,195 @@ +--- +description: Test mock conventions: Stub and ThrowingStub, argument structures, prologues, naming +read-when: Creating a new mock, or controlling when a mock runs in an async test +--- + +# Test Mocks + +How mocks are built in DevKeychain. + + +## Overview + +Mocks use DevTesting’s `Stub` and `ThrowingStub` types, which record calls and return configured +values. Every mock follows the same patterns, so tests read the same way. These patterns need +DevTesting 1.7 or later. + + +## When to Mock + +Create a mock when a type + + - has **non-deterministic behavior,** like the network, file I/O, time, or system services; + - needs to be **controlled or observed** in a test; or + - **behaves differently across environments,** like a platform API that differs between macOS + and iOS. + +Use the real type when its behavior is **deterministic,** when the real implementation gives +**enough coverage,** or when an abstraction would add **complexity without a testing benefit.** +These are used directly: + + - **Value types** and their operations + - **`NotificationCenter`, `UserDefaults`, and `Bundle`** + + +## Core Patterns + +### 1. Stubs + +Mocks conform to the **protocol,** not the concrete type. Each function or property calls a stub: + + import DevTesting + + + final class MockDataLoader: DataLoading { + nonisolated(unsafe) var baseURLStub = Stub() + nonisolated(unsafe) var loadStub = ThrowingStub() + + + var baseURL: URL { + baseURLStub() + } + + + func load(_ request: URLRequest) throws -> Data { + try loadStub(request) + } + } + + - Stub properties are `nonisolated(unsafe)` for Swift 6 concurrency. + - Function implementations only call their stubs. + - Stubs are **default-initialized** wherever possible, as described below. + +### 2. Default-Initialized Stubs + +An unconfigured, force-unwrapped stub crashes the test process. Under Swift Testing’s parallel +execution, that crash is hard to trace to a test, and it ends the whole run. So stubs start with a +placeholder instead, using DevTesting’s `DefaultStubValueProviding`: + + - **`Stub()`** returns the return type’s `defaultStubValue` until configured. DevTesting conforms + common standard library and Foundation types, using recognizable placeholders where possible, + such as `1_234_567_890` and `"default stub"`. Stubs that return `Void` also have an `init()`. + - **`ThrowingStub()`,** for stubs that throw `any Error`, throws an unspecified error until + configured. + +A default only keeps an unconfigured stub from crashing. It isn’t realistic data or a behavior +contract, so tests still configure every stub whose value they depend on. Because a default +throwing stub throws, a test of a success path must configure it. Never make a failing test pass +by changing a mock’s default; configure the stub in the test. + +Conform DevKeychain’s own types to `DefaultStubValueProviding` in the test target, composing their +properties’ defaults: + + extension Version: DefaultStubValueProviding { + static var defaultStubValue: Version { + return Version(name: .defaultStubValue, revision: .defaultStubValue) + } + } + +Force-unwrap a stub only when no default is possible, such as a return type that can’t be +conformed or a stub that throws a specific error type. Tests must configure those stubs before +they’re called. + +### 3. Argument Structures + +When a function has more than one parameter, the stub takes a nested argument structure: + + final class MockItemStore: ItemStoring { + struct SaveArguments { + let item: Item + let collectionID: Collection.ID + } + + + nonisolated(unsafe) var saveStub = ThrowingStub() + + + func save(_ item: Item, in collectionID: Collection.ID) async throws { + try saveStub(.init(item: item, collectionID: collectionID)) + } + } + +### 4. Delegate Mocks + +Delegate protocols get a `Mock*Delegate` with one stub per function, like any other mock. Never +hand-roll a spy with counters; that loses argument verification. + +### 5. Errors + +When a test just needs an error, use DevTesting’s `ArbitraryError`. `randomError()` creates one +whose description begins with the calling file and function: + + let error = randomError() + mockLoader.loadStub = ThrowingStub(defaultError: error) + + #expect(throws: error) { + try client.fetchItem(withID: itemID) + } + +Don’t declare local error types for individual tests. When a test needs a specific error, such as +one the code under test handles differently, use that error. + + +## Execution Control + +Some async tests need to control when a mock runs. Mock functions can have optional prologue and +epilogue closures: + +| Goal | Use | +|---|---| +| Hold the mock open to inspect intermediate state | Prologue | +| Gate the stub until the test signals | Prologue | +| Wait until a fire-and-forget caller reaches the mock | Epilogue | +| Confirm the mock was called before checking side effects | Epilogue | + +### Prologues + +A prologue runs **before** the stub and is awaited inline, so it can suspend the mock: + + final class MockDataLoader: DataLoading { + nonisolated(unsafe) var loadPrologue: (() async throws -> Void)? + nonisolated(unsafe) var loadStub = ThrowingStub() + + + func load(_ request: URLRequest) async throws -> Data { + try await loadPrologue?() + return try loadStub(request) + } + } + +### Epilogues + +An epilogue runs **after** the stub returns, in a `Task` launched from a `defer` block, so it +doesn’t delay the caller: + + func itemDidChange(_ item: Item) { + defer { + if let epilogue = itemDidChangeEpilogue { + Task { + try? await epilogue() + } + } + } + + itemDidChangeStub(item) + } + +**Common mistake:** using an epilogue to block. The mock has already returned when the epilogue +runs, so awaiting inside it doesn’t keep the caller suspended. Use a prologue to hold a mock open. + + +## Organization and Naming + + - **One mock per file,** named `Mock[ProtocolName].swift`, containing `Mock[ProtocolName]`. + - **Argument structures** are named `[FunctionName]Arguments`. + - **Stub properties** are named `[functionName]Stub`, with `[functionName]Prologue` and + `[functionName]Epilogue` where needed. + - **Mocks live in the test target’s `Testing Helpers/` folder.** When a second test target needs + the same mocks, they move to a shared `*Testing` library target. + + +## Thread Safety + +`nonisolated(unsafe)` assumes that tests configure stubs during setup, before any concurrent +access, and that mocks don’t need further synchronization. Add synchronization if a mock is used +concurrently in ways that break those assumptions. diff --git a/Documentation/Testing/TestingGuidelines.md b/Documentation/Testing/TestingGuidelines.md new file mode 100644 index 0000000..20ce0e5 --- /dev/null +++ b/Documentation/Testing/TestingGuidelines.md @@ -0,0 +1,246 @@ +--- +description: Swift Testing conventions, test structure, coverage rules, and DevKeychain 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 DevKeychain. +For how mocks are built, see [Test Mocks](TestMocks.md). + + +## Running Tests + +Run `swift test` for the unit tests, or the DevKeychain test plan in Xcode, which also +reports coverage. Integration tests run in Xcode with the DevKeychainApp test plan. + + +## 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 `StandardKeychainServicesTests`. + +### 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. + +### Mock Testing Strategy + + - **Verify calls, not mock implementations.** Test that mocks are called correctly. + - **Verify arguments,** not just call counts. Extract them with + `try #require(mock.fooStub.callArguments.first)`, then check their fields: + + @Test + mutating func saveStoresItemInCollection() async throws { + // exercise the test by saving the item + try await library.save(item, in: collectionID) + + // expect that the store was asked to save the item in the collection + #expect(mockStore.saveStub.calls.count == 1) + let arguments = try #require(mockStore.saveStub.callArguments.first) + #expect(arguments.item == item) + #expect(arguments.collectionID == collectionID) + } + + - **Use the standard mocks.** Tests share one mock type for each protocol instead of writing + their own. See [Test Mocks](TestMocks.md). + - **Always mock injected dependencies,** even when the test doesn’t check them. + - **Stub minimally.** Only stub functions that matter to the code under test or that the test + needs to run. Don’t leave comments about omitted stubs. + +### Random Values + +Tests use DevTesting’s `RandomValueGenerating` for inputs whose exact values don’t matter. Swift +Testing’s test structs are immutable, but `RandomValueGenerating` needs `mutating` functions. +Conform the test struct to `RandomValueGenerating`, add +`var randomNumberGenerator = makeRandomNumberGenerator()`, and mark any test that generates random +values as `mutating`: + + struct ItemTests: RandomValueGenerating { + var randomNumberGenerator = makeRandomNumberGenerator() + + + @Test + mutating func renamePreservesID() { + // set up the test by creating an item with a random name + var item = randomItem() + let originalID = item.id + + // exercise the test by renaming it + item.rename(to: randomAlphanumericString()) + + // expect that the ID is unchanged + #expect(item.id == originalID) + } + } + +Put generators for a module’s own types in `RandomValueGenerating+[ModuleName].swift` in that test +target’s `Testing Helpers/` folder, rather than building values inline in each test. + + +## File Organization + + - **Test files** are named `[TypeName]Tests.swift`, one per type. + - **Test folders mirror source folders.** Tests for `Sources/DevKeychain/Core/` go in + `Tests/DevKeychainTests/Core/`. + - **Shared fixtures and helpers** go in the test target’s `Testing Helpers/` 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. + + struct ItemLibraryTests: RandomValueGenerating { + var randomNumberGenerator = makeRandomNumberGenerator() + + let mockStore: MockItemStore + let library: ItemLibrary + + + init() { + mockStore = MockItemStore() + mockStore.itemsStub = ThrowingStub(defaultReturnValue: []) + + library = ItemLibrary(store: mockStore) + } + } + +### 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. + + +## DevKeychain Specifics + +### Unit and Integration Tests + +Unit tests in `Tests/` never touch the real keychain. They inject a +`MockKeychainServices`. Integration tests in `App/Tests/` run inside the DevKeychain +app, which has the entitlements the keychain needs, and use the real keychain. diff --git a/Documentation/TestingGuidelines.md b/Documentation/TestingGuidelines.md deleted file mode 100644 index 141ff45..0000000 --- a/Documentation/TestingGuidelines.md +++ /dev/null @@ -1,717 +0,0 @@ -# Testing Guidelines for Claude Code - -This file provides specific guidance for Claude Code when creating, updating, and maintaining -tests in this repository. - - -## Swift Testing Framework - -**IMPORTANT**: This project uses **Swift Testing framework**, NOT XCTest. Do not apply XCTest -patterns or conventions. - -### Key Differences from XCTest - - - **Use `@Test` attribute** instead of function name conventions - - **Use `#expect()` and `#require()`** instead of `XCTAssert*()` functions - - **Use `#expect(throws:)`** for testing error conditions instead of `XCTAssertThrows` - - **No "test" prefixes** required on function names - - **Struct-based test organization** instead of class-based - -### Test Naming Conventions - - - **No "test" prefixes**: Swift Testing doesn't require "test" prefixes for function names - - **Descriptive names**: Use clear, descriptive names like `initialLoadingState()` instead of - `testInitialLoadingState()` - - **Protocol-specific naming**: For protocols with concrete implementations, name tests after - the concrete type (e.g., `StandardAuthenticationRemoteNotificationHandlerTests`) - -### Unit Test Structure Conventions - -Unit tests typically have 3 portions; setup, exercise, and expect. - - - **Setup**: Create the inputs or mocks necessary to exercise the unit under test - - **Exercise**: Exercise the unit under test, usually by invoking a function using the inputs - prepared during "Setup". - - **Expect**: Expect one or more results to be true, using Swift Testing expressions. - - **IMPORTANT**: Each test should have exactly ONE unit-under-test. Only mark the invocation of - the unit-under-test with an "// exercise" comment. Additional function calls during setup or - verification should use "// set up" or "// expect" comments respectively. - - The beginning of each step should be clearly marked with a code comment, like: - - // set up the test by preparing a mock authenticator - - // exercise the test by initializing the data source - - // expect that the loadUser stub is invoked once - - If two sections overlap, only mention the most relevant information. - -### Mock Testing Strategy - - - **Focus on verification**: Test that mocks are called correctly, not custom mock - implementations - - **Verify parameter passing**: Always check that mocks receive expected arguments, not just - call counts - - **Use standard mocks**: All tests with injectable dependencies should use the same mock - types, not custom mock implementations. - - **Always mock dependencies**: Even when not testing the mocked behavior, always use mocks - to supply dependencies to objects under test. - - **Minimal Stubbing**: Only stub functions that are relevant to the code under test, or - required for the test to execute successfully. - - Do *NOT* leave comments when stubs are omitted because they are irrelevant. - -### ThrowingStub Usage - -**CRITICAL**: DevTesting's `ThrowingStub` has very specific initialization patterns that -differ from regular `Stub`. Using incorrect initializers will cause compilation errors. - -#### Correct ThrowingStub Patterns: - - // For success cases: - ThrowingStub(defaultReturnValue: value) - - // For error cases: - ThrowingStub(defaultError: error) - - // For void return types that don't throw: - ThrowingStub(defaultError: nil) - -#### Common Mistakes to Avoid: - - - ❌ `ThrowingStub(throwingError: error)` - This doesn't exist - - ❌ `ThrowingStub()` with separate configuration - Must provide default in initializer - -### Mock Object Patterns - -Follow established patterns from `@Documentation/TestMocks.md`: - - - **Stub-based architecture**: Use `Stub` and - `ThrowingStub` - - **Thread safety**: Mark stub properties with `nonisolated(unsafe)` - - **Protocol conformance**: Mock the protocol, not the concrete implementation - - **Argument structures**: For complex parameters, create dedicated argument structures - -Example mock structure: - - final class MockProtocolName: ProtocolName { - nonisolated(unsafe) var functionStub: Stub! - - func function(input: InputType) -> OutputType { - functionStub(input) - } - - nonisolated(unsafe) var throwingFunctionStub: ThrowingStub! - - func throwingFunction(input: InputType) throws -> OutputType { - try throwingFunctionStub(input) - } - } - - -### Random Value Generation with Swift Testing - -**IMPORTANT**: Swift Testing uses immutable test structs, but `RandomValueGenerating` requires -`mutating` functions. This creates a specific pattern that must be followed. - -#### Correct Pattern for Random Value Generation: - - @MainActor - struct MyTests: RandomValueGenerating { - var randomNumberGenerator = makeRandomNumberGenerator() - - @Test - mutating func myTest() throws { - let randomValue = randomAlphanumericString() - // ... test logic - } - } - -#### Key Requirements: - - - **Test struct must conform to `RandomValueGenerating`** - - **Include `var randomNumberGenerator = makeRandomNumberGenerator()` property** - - **Mark test functions as `mutating`** when using random value generation - - **Test struct can be immutable** for tests that don't use random values - -#### Dedicated Random Value Extensions: - - - **Dedicated files**: Create `RandomValueGenerating+[ModuleName].swift` files for random value - generation - - **Centralized functions**: Move random value creation functions to these dedicated extension - files - - **Consistent patterns**: Follow existing patterns from other modules - - **Proper imports**: Include necessary `@testable import` statements for modules being - extended - -Example structure: - - import DevTesting - import Foundation - - @testable import ModuleName - - extension RandomValueGenerating { - mutating func randomModuleSpecificType() -> ModuleType { - return ModuleType( - property: randomAlphanumericString() - ) - } - } - - -## File Organization - -### Test Files - - - **Naming pattern**: `[TypeName]Tests.swift` in corresponding Tests directories - - **Location**: Place in `Tests/[ModuleName]/[Category]/` directories - - **One test file per type**: Each type should have its own dedicated test file - - **Organize tests by function**: The tests for the function under test should be organized - together, preceded by a `// MARK: - [FunctionName]` comment. - -### Mock Files - - - **Naming pattern**: `Mock[ProtocolName].swift` - - **Location**: Place in `Tests/[ModuleName]/Testing Support/` directories - - **Protocol-based**: Mock the protocol interface, not concrete implementations - -### Random Value Extensions - - - **Naming pattern**: `RandomValueGenerating+[ModuleName].swift` - - **Location**: Place in `Tests/[ModuleName]/Testing Support/` directories - - **Module-specific**: Create extensions for each module's unique types - -### Import Patterns - - - **Testable imports**: Use `@testable import ModuleName` for modules under test - - **Regular imports**: Use regular imports for testing frameworks and utilities - - **Specific imports**: Import only what's needed to keep dependencies clear - - -## Test Coverage Guidelines - -### Protocols - - **Skip protocol-only tests**: Don't test pure protocols with no implementation - -### Function Coverage - - **Each function/getter**: Should have at least one corresponding test function - - **Multiple scenarios**: Create additional test functions to cover edge cases and error - conditions - - **Error paths**: Test both success and failure scenarios for throwing functions - -### Error Handling in Tests - -**CRITICAL**: Test functions that use `#expect(throws:)` must be marked with `throws`, -otherwise you'll get "Errors thrown from here are not handled" compilation errors. - -#### Correct Pattern: - - @Test - func myTestThatExpectsErrors() throws { - #expect(throws: SomeError.self) { - try somethingThatThrows() - } - } - -#### Common Mistake: - - // ❌ This will cause compilation error - @Test - func myTestThatExpectsErrors() { - #expect(throws: SomeError.self) { - try somethingThatThrows() - } - } - -### Boolean Expressions in Expectations - -Do not compare boolean expressions to `== true` or `== false`. Use the boolean directly or -negate it with `!`. The exception is when the expression is an optional `Bool?`, where the -comparison is needed to unwrap and disambiguate the value. - - // ✅ Good - #expect(instance.isLoading) - #expect(!instance.isLoading) - - // ✅ Good - optional Bool? requires comparison - #expect(instance.optionalFlag == true) - #expect(instance.optionalFlag == false) - - // ❌ Bad - unnecessary comparison - #expect(instance.isLoading == true) - #expect(instance.isLoading == false) - -### Use `#require` Instead of Optional Chaining - -When accessing optional values in tests, use `#require` to unwrap them rather than optional -chaining. This ensures the test fails with a clear message at the point of unwrapping rather -than silently skipping assertions. - - // ✅ Good - fails clearly if nil - let value = try #require(instance.optionalProperty) - #expect(value.name == "expected") - - // ❌ Bad - silently passes if nil - #expect(instance.optionalProperty?.name == "expected") - -### Safe Array Access in Tests - -Never subscript arrays directly based on a prior `#expect` count check. If the expectation -fails, the test continues and the subscript will crash. Use `#require` or a guard to safely -verify bounds before indexing. - - // ✅ Good - test fails safely if count is wrong - #expect(items.count == 2) - let first = try #require(items.first) - #expect(first.name == "expected") - - // ✅ Good - compare mapped arrays to avoid indexing entirely - #expect(items.map(\.name) == ["expected", "other"]) - - // ✅ Good - also safe with explicit bounds check - guard items.count == 2 else { - Issue.record("Expected 2 items, got \(items.count)") - return - } - #expect(items[0].name == "expected") - #expect(items[1].name == "other") - - // ❌ Bad - crashes if count expectation fails - #expect(items.count == 2) - #expect(items[0].name == "expected") - #expect(items[1].name == "other") - -### Unconditional Test Failures - -When a code path should never be reached in a passing test (e.g., a pattern match fails), use -`Issue.record(...)` to record an unconditional failure rather than `#expect(Bool(false), ...)`. -`Issue.record` is the Swift Testing idiomatic API for this, and it produces cleaner failure -output. - -#### Correct Pattern: - - guard case .someCase(let value) = result else { - Issue.record("Expected .someCase, got \(result)") - return - } - #expect(value == expectedValue) - -#### Common Mistake to Avoid: - - // ❌ Avoid - not idiomatic Swift Testing - guard case .someCase(let value) = result else { - #expect(Bool(false), "Expected .someCase, got \(result)") - return - } - -#### Key Points: - - - **Import Testing**: `Issue.record` is part of the `Testing` module — ensure it is imported - - **Provide a descriptive message**: Include what was expected and what was received - - **Use `return` after recording**: Since `Issue.record` does not stop execution, always - return explicitly to prevent further test code from running with invalid state - -### Main Actor Considerations - - **Test isolation**: Mark test structs and functions with `@MainActor` when testing - MainActor-isolated code - - **Mock conformance**: Ensure mocks properly handle MainActor isolation requirements - - **Async testing**: Use proper async/await patterns for testing async code - -### Dependency Injection Testing - - **Mock all dependencies**: Create mocks for all injected dependencies to ensure proper - isolation - - **Verify interactions**: Test that dependencies are called with correct parameters - - **State verification**: Check both mock call counts and state changes in the system under - test - - -## Reducing Repetition in Tests - -### Shared Setup in `init` - -When most tests in a struct need the same mocks or dependencies, create them in the struct's -`init` rather than repeating the setup in every test. This keeps individual tests focused on -what makes them unique. - - @MainActor - struct ItemProcessorTests: RandomValueGenerating { - var randomNumberGenerator = makeRandomNumberGenerator() - - let mockService: MockService - let mockDelegate: MockDelegate - let processor: ItemProcessor - - init() { - mockService = MockService() - mockService.fetchItemsStub = ThrowingStub(defaultReturnValue: []) - - mockDelegate = MockDelegate() - mockDelegate.didUpdateStub = Stub() - - processor = ItemProcessor( - dependencies: .init(service: mockService), - delegate: mockDelegate - ) - } - - @Test - func loadItemsCallsService() async throws { - // exercise the processor — no setup needed, init handled it - await processor.loadItems() - - // expect the service was called - #expect(mockService.fetchItemsStub.calls.count == 1) - } - - @Test - func loadItemsWithCustomData() async throws { - // set up only what differs from the default - let items = [Item(name: "Custom")] - mockService.fetchItemsStub = ThrowingStub(defaultReturnValue: items) - - // exercise - await processor.loadItems() - - // expect - #expect(processor.items.map(\.name) == ["Custom"]) - } - } - -### Helper Functions for Common Test Objects - -When multiple tests construct similar objects with minor variations, extract a helper function. -Keep helpers private to the test file and give them clear names. - - extension ItemProcessorTests { - private func makeItem( - name: String = "Default", - price: Float64 = 9.99 - ) -> Item { - Item(name: name, price: price) - } - } - -### Keep Test-Specific Setup in the Test - -Shared setup should cover the common baseline. Anything unique to a specific test scenario -belongs in that test's "set up" section so readers can see the full context without jumping -to `init` or helpers. - - -## Common Testing Patterns - -**IMPORTANT**: Avoid using `Task.sleep()` for test coordination whenever possible. Instead, use -precise synchronization mechanisms like `AsyncStream`, `confirmation`, mock prologues/epilogues, -or returning tasks. Arbitrary delays make tests slower and less reliable. - -### Testing Initialization - - @Test - func initializationSetsCorrectDefaults() { - let instance = SystemUnderTest() - - #expect(instance.property == expectedDefault) - } - -### Testing Dependency Calls - - @Test - mutating func functionCallsDependency() { - let mock = MockDependency() - mock.functionStub = Stub() - - let instance = SystemUnderTest(dependency: mock) - instance.performAction() - - #expect(mock.functionStub.calls.count == 1) - } - -### Testing Error Scenarios - - @Test - mutating func functionThrowsWhenDependencyFails() { - let mock = MockDependency() - let error = MockError(description: "Test error") - mock.functionStub = ThrowingStub(defaultError: error) - - let instance = SystemUnderTest(dependency: mock) - - #expect(throws: MockError.self) { - try instance.performAction() - } - } - -### Testing Async Operations - - @Test - mutating func asyncFunctionCompletesSuccessfully() async throws { - let mock = MockDependency() - mock.asyncFunctionStub = Stub(defaultReturnValue: expectedResult) - - let instance = SystemUnderTest(dependency: mock) - let result = await instance.performAsyncAction() - - #expect(result == expectedResult) - #expect(mock.asyncFunctionStub.calls.count == 1) - } - -### Using Confirmation to Verify Callbacks - -Swift Testing's `confirmation` API ensures that specific code paths execute. Use it to verify -that callbacks, handlers, or closures are invoked: - - @Test - mutating func handlerIsInvoked() async throws { - let text = randomBasicLatinString() - let customID = randomUUID() - - await confirmation { handlerCalled in - let linkedText = RichTextContent.LinkedText(id: customID, text: text) { - defer { handlerCalled() } - return .handled - } - - #expect(linkedText.text == text) - #expect(linkedText.id == customID) - #expect(linkedText.openHandler() == .handled) - } - } - -**Key points:** - - - Call the confirmation callback (e.g., `handlerCalled()`) when the expected code path - executes - - The test will fail if the callback is never invoked - - Use `defer` in handlers to ensure confirmation happens even if early returns occur - -### Testing Synchronous Interfaces with Asynchronous Work - -When testing code with a synchronous interface that performs asynchronous work internally -(e.g., posting to an event bus, dispatching to a queue), use `AsyncStream` to coordinate -test expectations rather than arbitrary sleep durations: - - @Test - mutating func functionPostsEventAsynchronously() async throws { - // set up the test with mocks and event observer - let observer = ContextualBusEventObserver(context: ()) - eventBus.addObserver(observer) - - let instance = SystemUnderTest(eventBus: eventBus) - - // set up signaling mechanism for async completion - let (signalStream, signaler) = AsyncStream.makeStream() - await confirmation("event posted") { confirm in - observer.addHandler(for: SomeEvent.self) { event, _ in - // expect the event has correct data - #expect(event.eventData.value == expectedValue) - confirm() - signaler.yield() - } - - // exercise the test by calling the synchronous function - instance.performSynchronousFunction() - - // wait for the asynchronous work to complete - await signalStream.first { _ in true } - } - } - -#### Key Points for Synchronous Interfaces with Async Work: - - - **Use `AsyncStream.makeStream()`**: Create a signal stream and signaler to coordinate - completion - - **Signal after confirmation**: Call `signaler.yield()` after calling `confirm()` in the - handler - - **Wait for signal**: Use `await signalStream.first { _ in true }` instead of - `Task.sleep(for:)` - - **Avoid arbitrary delays**: This pattern waits precisely for the async work to complete, - making tests faster and more reliable - - **Common use cases**: Event bus posting, background queue dispatch, timer-based operations - -#### Alternative: Returning Tasks for Testability - -When possible, if a function spawns a `Task` and doesn't need to return a value, consider -returning the task itself to simplify testing. Mark the result as `@discardableResult` so -callers can ignore it in production code: - - @discardableResult - func performBackgroundWork() -> Task { - Task { - // Perform async work... - await someAsyncOperation() - } - } - -This allows tests to await the task completion directly without needing stream-based -coordination: - - @Test - mutating func backgroundWorkCompletes() async throws { - let instance = SystemUnderTest() - - // exercise the test and await the returned task - let task = instance.performBackgroundWork() - await task.value - - // expect the work completed successfully - #expect(instance.workCompletedFlag) - } - -**When to use this pattern:** - - - Function spawns a `Task` internally for background work - - Return value is not otherwise needed - - Tests need to verify completion or side effects - -**When to use `AsyncStream` instead:** - - - Cannot modify the function signature (e.g., protocol requirements, public API constraints) - - Function doesn't spawn a task directly (e.g., posts to event bus, uses callbacks) - - Multiple async operations occur that need individual verification - -### Testing Observable Type State Changes - -**PREFERRED PATTERN**: When testing `@Observable` types that update asynchronously through -internal tasks, use the `Observations` helper from DevFoundation. This pattern is simpler and -more reliable than manual observation tracking. - -#### Preferred: Using Observations Helper - -The `Observations` helper directly observes property changes and waits for specific conditions: - - @Test @MainActor - mutating func propertyUpdatesAsynchronously() async throws { - // set up the test with a task that the type will await - let pendingTask = Task { - return response - } - - // exercise: create instance that spawns internal Task - let instance = SystemUnderTest( - dependencies: dependencies, - pendingTask: pendingTask - ) - - // wait for internal task to process initial state - _ = await Observations({ instance.title }).first { @Sendable _ in true } - - // expect that title was updated by internal task - #expect(instance.title == "Initial Title") - } - -#### Key Points for Observations Pattern: - - - **Use for internal async tasks**: When the type spawns internal `Task`s that update state - - **Observe the property directly**: Pass a closure that reads the property - - **Wait for specific conditions**: Use `.first { condition }` to wait for expected state - - **Mark closure as `@Sendable`**: Required for concurrency safety - - **Simpler than `withObservationTracking`**: No need for manual stream coordination - -#### Alternative: Manual Observation Tracking - -When you need manual control over the observation lifecycle, use `withObservationTracking`: - - @Test @MainActor - mutating func observableStateChangesAsynchronously() async throws { - // set up the test by creating the object and mocked dependencies - let instance = SystemUnderTest() - let mockDependency = MockDependency() - instance.dependency = mockDependency - - // set up observation and confirmation for async state change - let (signalStream, signaler) = AsyncStream.makeStream() - try await confirmation { stateChanged in - withObservationTracking { - _ = instance.observableState - } onChange: { - stateChanged() - signaler.yield() - } - - // exercise the test by triggering the state change - try instance.performActionThatChangesState() - - // await a signal to know the state change occurred - await signalStream.first { @MainActor _ in true } - } - - // expect the final state to be correct - #expect(instance.observableState == expectedFinalState) - } - -**When to use `withObservationTracking`:** - - - Need to verify observation behavior itself (not just state changes) - - Need precise control over when observation starts/stops - - Testing custom observation mechanisms - -**Otherwise, prefer `Observations` helper** for simpler, more focused tests. - -### Testing with Mock Prologue and Epilogue Closures - -When testing code that calls mock functions, you can use prologue and epilogue closures to -control execution timing. Prologues execute before the stub, epilogues execute after. See -`@Documentation/TestMocks.md` for the mock implementation patterns. - -#### Pattern: Blocking Mock Execution - - @Test - mutating func testIntermediateStateWhileProcessing() async throws { - // set up the test with a blocking prologue - let (signalStream, signaler) = AsyncStream.makeStream() - mockClient.sendRequestPrologue = { - await signalStream.first(where: { _ in true }) - } - mockClient.sendRequestStub = ThrowingStub(defaultReturnValue: .init()) - - let instance = SystemUnderTest(client: mockClient) - - // exercise the test by triggering the async operation - instance.performAction() - - // expect intermediate state while mock is blocked - await #expect(instance.isProcessing) - - // signal completion to unblock the mock - signaler.yield() - } - -#### Pattern: Signaling Completion with Epilogue - - @Test - mutating func eventHandlerLogsToTelemetry() async throws { - // set up the test with epilogue for coordination - let eventLogger = MockEventLogger() - eventLogger.logEventStub = Stub() - - let (signalStream, signaler) = AsyncStream.makeStream() - eventLogger.logEventEpilogue = { - signaler.yield() - } - - // exercise the test by posting event - eventBus.post(SomeEvent()) - - // wait for async handler to complete logging - await signalStream.first { _ in true } - - // expect the event was logged - #expect(eventLogger.logEventStub.calls.count == 1) - } - -#### Key Points - - - **Prologues execute before stub**: Control timing before mock processes input - - **Epilogues execute after stub**: Signal completion or coordinate post-execution state - - **Eliminates arbitrary delays**: Replace `Task.sleep` with precise synchronization - - **Test intermediate states**: Verify system behavior at different execution phases - - **Optional by default**: Tests can ignore if timing control isn't needed - - **Separate concerns**: Prologue/epilogue handle timing, stub handles return values/errors - - -## Integration with Existing Documentation - -This testing documentation supplements the main project documentation: - - - **Test Mocks**: See `@Documentation/TestMocks.md` for detailed mock object patterns - - **Dependency Injection**: See `@Documentation/DependencyInjection.md` for dependency - patterns - -When in doubt, follow existing patterns from similar tests in the codebase and reference the -established documentation for architectural guidance. diff --git a/Package.resolved b/Package.resolved index f6512bf..64d1118 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,13 +1,13 @@ { - "originHash" : "f06526c11bdf149ff155cd0af3768d874ac1c852c6eaad9c672a968735b793a8", + "originHash" : "b9bfacfcb9ef8e338ac6a3e9634816e2d164f1e54122b474e4e7cd414434bc4a", "pins" : [ { "identity" : "devtesting", "kind" : "remoteSourceControl", "location" : "https://github.com/DevKitOrganization/DevTesting", "state" : { - "revision" : "7dcd0757a4fa146ffeede688d649953643014be9", - "version" : "1.2.0" + "revision" : "7df52d20dade53d58d818bb255236d45da26bbde", + "version" : "1.7.0" } } ], diff --git a/Package.swift b/Package.swift index f197a66..7298025 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,16 +21,16 @@ let package = Package( products: [ .library( name: "DevKeychain", - targets: ["DevKeychain"] + targets: ["DevKeychain"], ) ], dependencies: [ - .package(url: "https://github.com/DevKitOrganization/DevTesting", from: "1.2.0") + .package(url: "https://github.com/DevKitOrganization/DevTesting", from: "1.7.0") ], targets: [ .target( name: "DevKeychain", - swiftSettings: swiftSettings + swiftSettings: swiftSettings, ), .testTarget( name: "DevKeychainTests", @@ -36,7 +38,7 @@ let package = Package( "DevKeychain", "DevTesting", ], - swiftSettings: swiftSettings + swiftSettings: swiftSettings, ), - ] + ], ) diff --git a/README.md b/README.md index f7ccbff..c41ca63 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ View our [changelog](CHANGELOG.md) to see what’s new. ## Development Requirements -DevKeychain requires a Swift 6.2+ toolchain to build. We only test on Apple platforms. We follow the +DevKeychain 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%. @@ -20,16 +20,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 git hooks that automatically check code - formatting before pushing. - 2. Use `Scripts/lint` to manually check code formatting at any time. + 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 DevKeychain 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**: Builds and 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 d238184..0000000 --- a/Scripts/format +++ /dev/null @@ -1,13 +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/App/" \ - "$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 1901415..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 --recursive --strict "$REPO_ROOT/App/" "$REPO_ROOT/Sources/" "$REPO_ROOT/Tests/" diff --git a/Sources/DevKeychain/Documentation.docc/Documentation.md b/Sources/DevKeychain/Documentation.docc/Documentation.md index d2ce744..a36f861 100644 --- a/Sources/DevKeychain/Documentation.docc/Documentation.md +++ b/Sources/DevKeychain/Documentation.docc/Documentation.md @@ -1,23 +1,23 @@ # ``DevKeychain`` -A Swift package that provides access to Apple keychain services. +A Swift package that provides access to Apple keychain services. ## Overview -DevKeychain is a small package that makes it easy to access and store data in the keychain in a way that feels idiomatic -in Swift. +DevKeychain is a small package that makes it easy to access and store data in the keychain in a way +that feels idiomatic in Swift. ## Topics ### Core -- ``Keychain`` -- ``KeychainItemAdditionAttributes`` -- ``KeychainItemQuery`` + - ``Keychain`` + - ``KeychainItemAdditionAttributes`` + - ``KeychainItemQuery`` ### Keychain Items -- ``GenericPassword`` -- ``InternetPassword`` + - ``GenericPassword`` + - ``InternetPassword`` diff --git a/Tests/DevKeychainTests/Testing Helpers/MockError.swift b/Tests/DevKeychainTests/Testing Helpers/MockError.swift deleted file mode 100644 index 1760ee1..0000000 --- a/Tests/DevKeychainTests/Testing Helpers/MockError.swift +++ /dev/null @@ -1,14 +0,0 @@ -// -// MockError.swift -// DevKeychain -// -// Created by Prachi Gauriar on 6/18/25. -// - -import Foundation - -enum MockError: CaseIterable, Error { - case error1 - case error2 - case error3 -} diff --git a/Tests/DevKeychainTests/Testing Helpers/MockKeychainItemAdditionAttributes.swift b/Tests/DevKeychainTests/Testing Helpers/MockKeychainItemAdditionAttributes.swift index fbed623..e4a06d9 100644 --- a/Tests/DevKeychainTests/Testing Helpers/MockKeychainItemAdditionAttributes.swift +++ b/Tests/DevKeychainTests/Testing Helpers/MockKeychainItemAdditionAttributes.swift @@ -10,8 +10,8 @@ import DevTesting import Foundation final class MockKeychainItemAdditionAttributes: KeychainItemAdditionAttributes where Item: Sendable { - nonisolated(unsafe) var attributesDictionaryStub: Stub! - nonisolated(unsafe) var mapStub: ThrowingStub! + nonisolated(unsafe) var attributesDictionaryStub = Stub() + nonisolated(unsafe) var mapStub = ThrowingStub() var attributesDictionary: [CFString: Any] { diff --git a/Tests/DevKeychainTests/Testing Helpers/MockKeychainItemQuery.swift b/Tests/DevKeychainTests/Testing Helpers/MockKeychainItemQuery.swift index 1cff155..dccc501 100644 --- a/Tests/DevKeychainTests/Testing Helpers/MockKeychainItemQuery.swift +++ b/Tests/DevKeychainTests/Testing Helpers/MockKeychainItemQuery.swift @@ -10,9 +10,9 @@ import DevTesting import Foundation final class MockKeychainItemQuery: KeychainItemQuery where Item: Sendable { - nonisolated(unsafe) var attributesDictionaryStub: Stub! - nonisolated(unsafe) var returnDictionaryStub: Stub! - nonisolated(unsafe) var mapStub: ThrowingStub! + nonisolated(unsafe) var attributesDictionaryStub = Stub() + nonisolated(unsafe) var returnDictionaryStub = Stub() + nonisolated(unsafe) var mapStub = ThrowingStub() var attributesDictionary: [CFString: Any] { diff --git a/Tests/DevKeychainTests/Testing Helpers/MockKeychainService.swift b/Tests/DevKeychainTests/Testing Helpers/MockKeychainService.swift index edf9714..aa46450 100644 --- a/Tests/DevKeychainTests/Testing Helpers/MockKeychainService.swift +++ b/Tests/DevKeychainTests/Testing Helpers/MockKeychainService.swift @@ -11,9 +11,9 @@ import Foundation @testable import protocol DevKeychain.KeychainServices final class MockKeychainServices: KeychainServices { - nonisolated(unsafe) var addItemStub: ThrowingStub<[CFString: Any], AnyObject?, any Error>! - nonisolated(unsafe) var itemsStub: ThrowingStub<[CFString: Any], AnyObject?, any Error>! - nonisolated(unsafe) var deleteItemsStub: ThrowingStub<[CFString: Any], Void, any Error>! + nonisolated(unsafe) var addItemStub = ThrowingStub<[CFString: Any], AnyObject?, any Error>() + nonisolated(unsafe) var itemsStub = ThrowingStub<[CFString: Any], AnyObject?, any Error>() + nonisolated(unsafe) var deleteItemsStub = ThrowingStub<[CFString: Any], Void, any Error>() func addItem(withAttributes attributes: [CFString: Any]) throws -> AnyObject? { diff --git a/Tests/DevKeychainTests/Testing Helpers/RandomValueGenerating+DevKeychain.swift b/Tests/DevKeychainTests/Testing Helpers/RandomValueGenerating+DevKeychain.swift index 7a1b72b..1a61d5c 100644 --- a/Tests/DevKeychainTests/Testing Helpers/RandomValueGenerating+DevKeychain.swift +++ b/Tests/DevKeychainTests/Testing Helpers/RandomValueGenerating+DevKeychain.swift @@ -15,11 +15,6 @@ extension RandomValueGenerating { } - mutating func randomError() -> MockError { - return randomCase(of: MockError.self)! - } - - mutating func randomKeychainDictionary() -> [String: String] { return Dictionary(count: randomInt(in: 3 ... 5)) { (randomAlphanumericString(), randomAlphanumericString()) diff --git a/Tools/format b/Tools/format new file mode 100755 index 0000000..4d2d83e --- /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 App 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..d7a3304 --- /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 App 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" "$@"