diff --git a/.github/workflows/VerifyChanges.yaml b/.github/workflows/VerifyChanges.yaml index 9ead405..d582bb3 100644 --- a/.github/workflows/VerifyChanges.yaml +++ b/.github/workflows/VerifyChanges.yaml @@ -7,36 +7,36 @@ on: branches: ["main"] env: - XCODE_VERSION: 26.3 + XCODE_VERSION: 27.2 jobs: lint: name: Lint - runs-on: macos-26 + runs-on: xcode-27 steps: - name: Checkout uses: actions/checkout@v6 - name: Select Xcode ${{ env.XCODE_VERSION }} run: sudo xcode-select -s /Applications/Xcode_"$XCODE_VERSION".app - name: Lint - run: Scripts/lint + run: Tools/lint build-and-test: name: Build and Test (${{ matrix.platform }}) needs: lint - runs-on: macos-26 + runs-on: xcode-27 strategy: fail-fast: false matrix: include: - platform: iOS - xcode_destination: "platform=iOS Simulator,name=iPhone 17 Pro" + xcode_destination: "platform=iOS Simulator,OS=27.2,name=iPhone 18 Pro" - platform: macOS xcode_destination: "platform=macOS,arch=arm64" - platform: tvOS - xcode_destination: "platform=tvOS Simulator,name=Apple TV 4K (3rd generation)" + xcode_destination: "platform=tvOS Simulator,OS=27.2,name=Apple TV 4K (4th generation)" - platform: watchOS - xcode_destination: "platform=watchOS Simulator,name=Apple Watch Series 11 (46mm)" + xcode_destination: "platform=watchOS Simulator,OS=27.2,name=Apple Watch Series 12 (46mm)" env: DEV_BUILDS: DevBuilds/Sources @@ -96,8 +96,12 @@ jobs: path: ${{ env.XCODE_TEST_PRODUCTS_PATH }} key: ${{ steps.cache-xctestproducts-restore.outputs.cache-primary-key }} + # Optional until Xcode records coverage for Swift packages again. With Xcode 27.2, result + # bundles have no coverage for package targets, so xccov can’t report it. - name: Log Code Coverage + id: coverage if: github.event_name != 'push' + continue-on-error: true env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | @@ -123,7 +127,7 @@ jobs: include-hidden-files: true - name: Upload xccovPretty output - if: github.event_name != 'push' + if: github.event_name != 'push' && steps.coverage.outcome == 'success' uses: actions/upload-artifact@v7 with: name: xccovPrettyOutput-${{ matrix.platform }} @@ -140,11 +144,14 @@ jobs: steps: - name: Download xccovPretty output + id: download-coverage + continue-on-error: true uses: actions/download-artifact@v8 with: name: xccovPrettyOutput-macOS - name: Post Code Coverage Comment + if: steps.download-coverage.outcome == 'success' uses: thollander/actions-comment-pull-request@v3 with: file-path: xccovPretty-macOS.output diff --git a/.gitignore b/.gitignore index 0023a53..f61d4f3 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,5 @@ DerivedData/ .swiftpm/configuration/registries.json .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata .netrc + +.rumdl_cache/ diff --git a/.rumdl.toml b/.rumdl.toml new file mode 100644 index 0000000..45c9f28 --- /dev/null +++ b/.rumdl.toml @@ -0,0 +1,30 @@ +# MD005 is off with it, since it flattens indented lists. MD029 is off because list numbers are +# content: rumdl splits lists whose markers are right-aligned (" 9.", "10.") and its fix renumbers +# the second half from 1. MD076 is off because the style guide puts nested lists and code blocks +# inside list items without blank lines between items. +[global] +disable = ["MD005", "MD029", "MD032", "MD033", "MD036", "MD025", "MD041", "MD046", "MD057", "MD060", "MD076"] +respect_gitignore = true + +[MD004] +style = "dash" + +[MD007] +indent = 4 +start-indented = true +start-indent = 2 +style = "fixed" + +[MD012] +maximum = 2 + +[MD013] +line-length = 100 +code-blocks = false +tables = false +headings = false +reflow = true + +[MD022] +lines-above = [0, 2, 1, 1, 1, 1] +lines-below = 1 diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..7b54560 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,72 @@ +# Agent Guidelines + +DevFoundation is a Swift package of foundational utilities for Apple platforms: +networking, an event bus, date providers, concurrency helpers, paging, remote +localization, and assorted utility types. It also includes `dfob`, a command-line tool +that obfuscates and deobfuscates data. + + +## Building and testing + + - `swift build` and `swift test` build and test the package. + - `swift test --filter dfobTests` runs only the `dfob` tests. + - Xcode test plans in `Build Support/Test Plans/` run the tests with coverage, as CI does. + + +## Writing style + + - Follow the [Markdown Style Guide](Documentation/MarkdownStyleGuide.md) for all Markdown. + - **Use typographic quotes and apostrophes, not straight ones,** in all Markdown, all code + documentation (doc comments and standalone comments), and all user-facing strings: + - Apostrophes: ’ (U+2019), as in “it’s” + - Single quotes: ‘ (U+2018) and ’ (U+2019) + - Double quotes: “ (U+201C) and ” (U+201D) + + Straight quotes (`'` and `"`) are still correct in code itself: string literal delimiters, + code spans, code blocks, identifiers, and configuration files. + + +## Attribution + +Never credit an agent or other code generation tool. Don’t add `Co-Authored-By` trailers or +“Generated with” lines to commits or pull requests, and don’t name an agent in file headers, +comments, or documentation. File headers name the git user. The programmer who uses a tool is +accountable for the changes it helped make. + + +## Commits and pull requests + +A commit message is a short summary of what the commit does, then a blank line and a bulleted list +of the changes, close to what a changelog would say. Messages are plain text with lines of 72 +characters or fewer. A pull request uses its commit message: the title is the summary, and the +body is the bullets. + +Add an entry to `CHANGELOG.md` for changes that affect the library’s users. + + +## Code + +Follow these guides before writing or reviewing Swift: + + - [Dependency Injection](Documentation/DependencyInjection.md) + - [Swift Style Guide](Documentation/SwiftStyleGuide.md) + - [Testing Guidelines](Documentation/Testing/TestingGuidelines.md) + - [Test Mocks](Documentation/Testing/TestMocks.md) + - [Async Test Patterns](Documentation/Testing/AsyncTestPatterns.md) + +Also: + + - Document and test every public API, and keep test coverage above 99%. + - Setting `DateProviders.current` to an auto-updating date provider causes an infinite + loop. + + +## Formatting and linting + + - `Tools/format` formats Swift with swift-format and Markdown with rumdl, in place. + - `Tools/lint` checks both, plus comment line length, which swift-format doesn’t check. + - Configuration is in `.swift-format` (120-character lines) and `.rumdl.toml` (100-character + lines for Markdown). + - `Tools/install-git-hooks` installs a pre-push hook that runs `Tools/lint`. + +Run `Tools/lint` before considering a change done. diff --git a/CHANGELOG.md b/CHANGELOG.md index 96d1d99..416e8d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # DevFoundation Changelog + +## 1.12.0: November 24, 2026 + +This release requires Swift 6.4 (Xcode 27) to build. It also enables Swift’s +`NonisolatedNonsendingByDefault` upcoming feature, which changes where some of DevFoundation’s +asynchronous code runs: + + - Nonisolated asynchronous functions, like `HTTPClient.load(_:)` and the pagers’ `loadPage` + functions, now run on their caller’s actor instead of on the global concurrent executor. + - `CurrentValueMulticaster`’s `values()` sequence now waits for values on its caller’s actor. + - The `next` closure passed to `HTTPClientInterceptor.intercept(request:context:next:)` is + explicitly `@concurrent`, so it still runs off its caller’s actor, and existing interceptors + don’t need to change. + + ## 1.11.0: August 4, 2026 This release adds `RemoteLocalizedFormatStringPolicy` for controlling whether content from a remote diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 1447f05..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1,260 +0,0 @@ -# CLAUDE.md - -This file provides guidance to Claude Code (claude.ai/code) when working with code in this -repository. - - -## Development Commands - -### Building and Testing - - - **Build**: `swift build` - - **Test all**: `swift test` - - **Test specific target**: `swift test --filter DevFoundationTests` or - `swift test --filter dfobTests` - - **Test with coverage**: Use Xcode test plans in `Build Support/Test Plans/` - (AllTests.xctestplan for all tests) - -### Code Quality - - - **Lint**: `Scripts/lint` (uses `swift format lint --recursive --strict`) - - **Format**: `swift format --recursive Sources/ Tests/` - -### GitHub Actions - -The repository uses GitHub Actions for CI/CD with the workflow in -`.github/workflows/VerifyChanges.yaml`. The workflow: - - - Lints code on PRs using `swift format` - - Builds and tests on iOS, macOS, tvOS, and watchOS - - Generates code coverage reports using xccovPretty - - Uses Xcode 26.3 and macOS 26 runners - - -## Architecture Overview - -DevFoundation is a Swift package providing foundational utilities for iOS, macOS, tvOS, visionOS, -and watchOS development. It consists of two main products: - -### 1. DevFoundation Library - -A comprehensive utility library with the following major components: - -#### Networking Layer - - - **WebServiceClient**: Generic web service client with declarative request/response handling - - **HTTPClient**: Lower-level HTTP client with request/response interceptors - - **WebServiceRequest**: Protocol for defining web service requests - - **BaseURLConfiguring**: Protocol for managing different base URLs (staging, production, etc.) - - **HTTPClientInterceptor**: Protocol for request/response modification - - **URLRequestLoader**: Protocol for loading URL requests - - **SimulatedURLRequestLoader**: Network request simulation framework for testing and development - -#### Event System - - - **EventBus**: Type-safe event bus for decoupled component communication - - **BusEventObserver**: Protocol for observing bus events - - **ContextualBusEventObserver**: Observer with contextual event handling - -#### Date Management - - - **DateProvider**: Protocol for abstracting date/time sources - - **DateProviders**: Namespace providing system, scaled, and offset date providers - - **SystemDateProvider**: Default system date provider - - **OffsetDateProvider**: Date provider with fixed offset - - **ScaledDateProvider**: Date provider with time scaling - -#### Concurrency Utilities - - - **ExecutionGroup**: Utility for managing concurrent operations - - **WithTimeout**: Structured concurrency timeout utility with cancellation support - - **DispatchQueue extensions**: Non-overcommitting and standard queue utilities - -#### Paging System - - - **OffsetPage**: Protocol for pages with offset-based pagination - - **SequentialPageLoader**: Protocol for loading pages sequentially - - **SequentialPager**: Concrete pager for sequential page access - - **RandomAccessPageLoader**: Protocol for loading pages at specific offsets - - **RandomAccessPager**: Concrete pager for random access to pages - -#### Remote Localization - - - **Bundle+RemoteContent**: `Bundle.makeRemoteContentBundle(at:localizedStrings:)` and - `Bundle.defaultRemoteContentBundle` for supplying and configuring remote content - - **remoteLocalizedString/remoteLocalizedFormatString**: Resolve a key against the remote - content bundle, falling back to the local bundle - - **#remoteLocalizedString**: Macros wrapping the above for plain and format-string lookups - - **RemoteLocalizedFormatStringPolicy**: Decides whether a remote format string may be used; - disallowed by default, since an unvetted remote format string can crash the app or leak memory - -#### Utility Types - - - **AnySendableHashable**: Type-erased sendable hashable wrapper - - **DottedHierarchicalID**: Hierarchical identifier with dot notation - - **ExpiringValue**: Value wrapper with expiration logic - - **GibberishGenerator**: Lorem ipsum and placeholder text generation with customizable lexicons - - **HashableByID**: Protocol for hashable-by-identity types - - **IdentifiableBySelf**: Protocol for types identifiable by themselves - - **JSONValue**: Unified JSON value representation - - **ObservableReference**: Reference wrapper for observable objects - - **OptionalRepresentable**: Protocol for types with optional representations - - **RetryPolicy**: Configurable retry behavior for operations - - **SoftwareComponentID**: Identifier for software components - - **TopLevelCoding**: Protocol for top-level encoding/decoding - - **TypedExtensibleEnum**: Type-safe extensible enumerations - -### 2. dfob Command Line Tool - -A command-line utility for data obfuscation/deobfuscation: - - - Uses Swift ArgumentParser for command-line interface - - Supports obfuscation (`-O`) and deobfuscation (`-D`) operations - - Handles file input/output or stdin/stdout - - Implements custom obfuscation algorithm with configurable key and message sizes - - -## Key Design Patterns - -### Generic Web Service Architecture - -The networking layer uses heavy generics to provide type-safe, declarative web service access: - - - `WebServiceClient` for type-safe clients - - Protocol-based request/response mapping - - Interceptor pattern for request/response modification - -### Protocol-Oriented Date Handling - -Date providers use protocols to enable dependency injection and testing: - - - `DateProvider` protocol abstracts time sources - - `DateProviders.current` provides global date provider configuration - - Warning: Setting `DateProviders.current` to auto-updating providers causes infinite loops - -### Thread-Safe Event Bus - -The event bus uses Swift's new Synchronization framework: - - - `Mutex<[any BusEventObserver]>` for thread-safe observer management - - Type-safe event posting with generic constraints - - Support for both regular and identifiable events - - -#### Extensions - - - **Data+Obfuscation**: Data obfuscation and deobfuscation utilities - - **FixedWidthInteger+BigEndianData**: Big-endian byte conversion utilities - - **RangeReplaceableCollection+RemoveFirst**: Collection manipulation utilities - - **Result+CatchingAsync**: Async result handling utilities - -#### Network Request Simulation - -The `SimulatedURLRequestLoader` provides a comprehensive framework for network request simulation: - - - **RequestComponents**: Parse and analyze URL request components - - **RequestCondition**: Flexible request matching conditions (URL, method, headers, body) - - **Responder**: Configurable response generation with conditions and limits - - **ResponseGenerator**: Generate HTTP responses with customizable status, headers, and body - - **SuccessResponseTemplate**: Template-based successful response generation - - **UnfulfillableRequestError**: Error handling for unmatched requests - - -## Dependencies - -External dependencies managed via Swift Package Manager: - - - **swift-argument-parser**: Command-line argument parsing (dfob tool) - - **swift-numerics**: Numeric utilities (testing) - - **DevTesting**: Custom testing framework - - **URLMock**: URL mocking for tests - - -## Testing - -The codebase maintains >99% test coverage with comprehensive test suites: - - - All major components have corresponding test files - - Mock implementations in `Tests/DevFoundationTests/Testing Helpers/` - - Test utilities for date approximation, random value generation - - Separate test plans for different components - - -## 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/[ModuleName]/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" - - -## 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 - - -## Documentation Style - -When writing Markdown documentation, reference `@Documentation/MarkdownStyleGuide.md` to -ensure consistent formatting, structure, and style across all project documentation. Key -standards: - - - **Line Length**: 100 characters maximum - - **Code Blocks**: Use 4-space indentation instead of fenced blocks - - **Lists**: Use `-` for bullets with proper indentation alignment - - **Spacing**: 2 blank lines between major sections, 1 blank line after headers - - **Terminology**: Use "function" over "method", "type" over "class" - - -## Development Notes - - - Follows Swift API Design Guidelines - - Uses Swift 6.2 with `ExistentialAny` and `MemberImportVisibility` features enabled - - Minimum deployment targets: iOS, macOS, tvOS, visionOS, and watchOS 26 - - Reverse DNS prefix: `com.gauriar.devfoundation` - - All public APIs are documented and tested - - Test coverage target: >99% diff --git a/Documentation/DependencyInjection.md b/Documentation/DependencyInjection.md index 478bf7c..1acfee7 100644 --- a/Documentation/DependencyInjection.md +++ b/Documentation/DependencyInjection.md @@ -1,10 +1,13 @@ -# Dependency Injection +--- +description: Dependency injection: Dependencies struct, Dependency Provider, direct injection +read-when: Designing a new type’s initializer and deciding what to inject vs. pass as a parameter +--- -This document outlines the dependency injection patterns and conventions that I like to use in my -Swift code. +# Dependency Injection -After reading this doc, take a look at the [Test Mocks guide](TestMocks.md) for specific guidance -about how to write mocks. +This document outlines the dependency injection patterns and conventions used throughout this +codebase. After reading it, see [Test Mocks](Testing/TestMocks.md) for how to +write mocks. ## When to Use Dependency Injection @@ -175,9 +178,12 @@ Consume the provider in your type: #### Testing Support -Create a mock provider for testing, using the patterns from [TestMocks.md](TestMocks.md): +Create a mock provider for testing, using `Stub` from DevTesting: final class MockUserServiceDependencyProvider: UserService.DependencyProviding { + // These return existentials and a view model — types with no default stub value — so they + // stay force-unwrapped and must be configured in test setup. Where a return type has a + // default stub value, prefer `= Stub<…>()`. nonisolated(unsafe) var networkClientStub: Stub! nonisolated(unsafe) var telemetryEventLoggerStub: Stub! nonisolated(unsafe) var makeProfileViewModelStub: Stub! diff --git a/Documentation/MarkdownStyleGuide.md b/Documentation/MarkdownStyleGuide.md index 1f6288b..d92d52f 100644 --- a/Documentation/MarkdownStyleGuide.md +++ b/Documentation/MarkdownStyleGuide.md @@ -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..443e866 --- /dev/null +++ b/Documentation/README.md @@ -0,0 +1,10 @@ +# DevFoundation Documentation + +Guides for writing code and docs in DevFoundation: + + - [Dependency Injection](DependencyInjection.md) + - [Swift Style Guide](SwiftStyleGuide.md) + - [Testing Guidelines](Testing/TestingGuidelines.md) + - [Test Mocks](Testing/TestMocks.md) + - [Async Test Patterns](Testing/AsyncTestPatterns.md) + - [Markdown Style Guide](MarkdownStyleGuide.md) diff --git a/Documentation/SwiftStyleGuide.md b/Documentation/SwiftStyleGuide.md new file mode 100644 index 0000000..c4ed6da --- /dev/null +++ b/Documentation/SwiftStyleGuide.md @@ -0,0 +1,113 @@ +--- +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. + - Complex types take their dependencies as the first initializer parameter. See + [Dependency Injection](DependencyInjection.md). + + +## 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 81e8fe5..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/AsyncTestPatterns.md b/Documentation/Testing/AsyncTestPatterns.md new file mode 100644 index 0000000..36a1d7e --- /dev/null +++ b/Documentation/Testing/AsyncTestPatterns.md @@ -0,0 +1,165 @@ +--- +description: Synchronization patterns for testing async and @Observable code without sleeps +read-when: Writing a test that waits on async work, a callback, or @Observable state changes +--- + +# Async Test Patterns + +How to wait on or coordinate async and `@Observable` code in tests. Never use `Task.sleep()` to +wait for work to finish: it makes tests slow and flaky. Use one of the patterns below instead. + + +## Awaiting Async Functions Directly + +The simplest case needs no pattern. Calls to actors and other `async` functions are awaited in the +test like anywhere else: + + // exercise the test by adding the item + try await store.add(item) + + // expect that the store contains it + #expect(try await store.item(withID: item.id) == item) + +The patterns below are for work that a synchronous call starts in the background. + + +## Returning Tasks + +When a function starts a `Task` and doesn’t need to return anything else, return the task, marked +`@discardableResult` so production callers can ignore it: + + @discardableResult + func refresh() -> Task { + Task { + await loader.reload() + } + } + +Tests then await it: + + // exercise the test and wait for it to finish + await viewModel.refresh().value + +Prefer this whenever the signature can change. Use the other patterns when it can’t, such as for a +protocol requirement, or when there’s no task to return. + + +## Observing `@Observable` State + +When an `@Observable` type updates its state from an internal task, wait for the state itself with +`Observations`: + + @MainActor @Test + mutating func loadingShowsItems() async throws { + // set up the test by giving the store two items + let items = [randomItem(), randomItem()] + mockStore.itemsStub = ThrowingStub(defaultReturnValue: items) + + // exercise the test by creating the view model, which loads in a task + let viewModel = ItemListViewModel(dependencies: .init(store: mockStore)) + + // wait for the load to finish + _ = await Observations({ viewModel.isLoading }).first { @Sendable in !$0 } + + // expect that the items are shown + #expect(viewModel.items == items) + } + +`Observations` waits for the real condition, not just for some task to be unblocked. Mark the +closure `@Sendable`, `import Observation`, and make the test `@MainActor`. Write the +`Observations` call inline in each test rather than in a shared helper. + +Use `withObservationTracking` only when a test is verifying observation itself, or needs precise +control over when observation starts and stops. + + +## Confirming Callbacks + +`confirmation` checks that a callback, handler, or closure runs: + + await confirmation { handlerCalled in + let session = Session(onFinish: { _ in + handlerCalled() + }) + + await session.finish() + } + +The test fails if the confirmation is never called. Call it from a `defer` in handlers with early +returns, so it still happens. + + +## Synchronous Calls with Asynchronous Effects + +When a synchronous call causes asynchronous work that the test can only see through a callback, +pair `confirmation` with an `AsyncStream` signal: + + let (signalStream, signaler) = AsyncStream.makeStream() + await confirmation("change reported") { confirm in + observer.onChange = { change in + #expect(change.itemID == item.id) + confirm() + signaler.yield() + } + + // exercise the test by renaming the item + model.rename(item, to: newName) + + // wait for the change to be reported + await signalStream.first { _ in true } + } + + +## Controlling Mocks with Prologues and Epilogues + +A prologue holds a mock open so the test can check intermediate state; an epilogue tells the test +that a mock was reached. [Test Mocks](TestMocks.md#execution-control) covers how mocks implement +them. + +Blocking on a prologue: + + // set up the test with a loader that waits for a signal + let (signalStream, signaler) = AsyncStream.makeStream() + mockLoader.loadPrologue = { + await signalStream.first { _ in true } + } + mockLoader.loadStub = ThrowingStub(defaultReturnValue: data) + + // exercise the test by starting a refresh + let task = viewModel.refresh() + + // expect that the view model shows progress while the load is in flight + #expect(viewModel.isLoading) + + // let the load finish + signaler.yield() + await task.value + +Awaiting an epilogue: + + // set up the test with an epilogue that signals the call + let (signalStream, signaler) = AsyncStream.makeStream() + mockObserver.itemDidChangeEpilogue = { + signaler.yield() + } + + // exercise the test by renaming the item + model.rename(item, to: newName) + + // wait for the observer to be called + await signalStream.first { _ in true } + + // expect that the observer saw the change + #expect(mockObserver.itemDidChangeStub.calls.count == 1) + + +## Anti-Pattern: `Task.yield()` Loops + +Don’t wait for async work with `await Task.yield()` or a `while condition { await Task.yield() }` +loop. A yield gives the scheduler one chance to run something, with no guarantee the awaited work +has progressed. The test races the scheduler, and the race gets worse as more tests run in +parallel. + +One exception: when **setup** must wait for a component to register with a mock and there’s no +stub call or epilogue to hook, a bounded poll on a condition the mock can see directly is +acceptable. Polling for a precondition is fine; yielding to wait for the effect under test is not. diff --git a/Documentation/Testing/TestMocks.md b/Documentation/Testing/TestMocks.md new file mode 100644 index 0000000..b284fdd --- /dev/null +++ b/Documentation/Testing/TestMocks.md @@ -0,0 +1,199 @@ +--- +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 DevFoundation. +Read [Dependency Injection](../DependencyInjection.md) first; it covers what gets injected and +therefore what gets mocked. + + +## 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 DevFoundation’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. + +See [Async Test Patterns](AsyncTestPatterns.md) for how tests use these. + + +## 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..a2ac928 --- /dev/null +++ b/Documentation/Testing/TestingGuidelines.md @@ -0,0 +1,246 @@ +--- +description: Swift Testing conventions, test structure, coverage rules, and DevFoundation 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 DevFoundation. +For how mocks are built, see [Test Mocks](TestMocks.md). +For waiting on async work, see [Async Test Patterns](AsyncTestPatterns.md). + + +## Running Tests + +Run `swift test`, or the AllTests test plan in Xcode, which also reports coverage. +`swift test --filter dfobTests` runs only the `dfob` tests. + + +## 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 `StandardHTTPClientTests`. + +### 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/DevFoundation/Networking/` go in + `Tests/DevFoundationTests/Networking/`. + - **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. + + +## DevFoundation Specifics + +### Networking + +Networking tests never use the network. Use `SimulatedURLRequestLoader` or a mock +`URLRequestLoader` to supply responses. 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 b9d1ad3..8f33e51 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,13 +1,13 @@ { - "originHash" : "b5e1ad211e1b6f6be3d143c9860e34ccae4e248dbaa423c63ac2bb413dd47d34", + "originHash" : "5fb1e17116098512f131b76684080e9588662417089add41074fa5208b78eabf", "pins" : [ { "identity" : "devtesting", "kind" : "remoteSourceControl", "location" : "https://github.com/DevKitOrganization/DevTesting", "state" : { - "revision" : "9dea13f09c19c0521e9ff7b9f14fedb977423b99", - "version" : "1.5.0" + "revision" : "7df52d20dade53d58d818bb255236d45da26bbde", + "version" : "1.7.0" } }, { diff --git a/Package.swift b/Package.swift index ca766fd..6037f97 100644 --- a/Package.swift +++ b/Package.swift @@ -1,11 +1,13 @@ -// swift-tools-version: 6.2 +// swift-tools-version: 6.4 import CompilerPluginSupport import PackageDescription let swiftSettings: [SwiftSetting] = [ .enableUpcomingFeature("ExistentialAny"), + .enableUpcomingFeature("ImmutableWeakCaptures"), .enableUpcomingFeature("MemberImportVisibility"), + .enableUpcomingFeature("NonisolatedNonsendingByDefault"), ] let package = Package( @@ -20,21 +22,21 @@ let package = Package( products: [ .library( name: "DevFoundation", - targets: ["DevFoundation"] + targets: ["DevFoundation"], ), .executable( name: "dfob", targets: [ "DevFoundation", "dfob", - ] + ], ), ], dependencies: [ .package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.6.1"), .package(url: "https://github.com/apple/swift-async-algorithms.git", from: "1.0.4"), .package(url: "https://github.com/apple/swift-numerics.git", from: "1.1.0"), - .package(url: "https://github.com/DevKitOrganization/DevTesting", from: "1.5.0"), + .package(url: "https://github.com/DevKitOrganization/DevTesting", from: "1.7.0"), .package(url: "https://github.com/swiftlang/swift-syntax.git", from: "602.0.0"), .package(url: "https://github.com/prachigauriar/URLMock.git", from: "1.3.6"), ], @@ -45,7 +47,7 @@ let package = Package( .product(name: "AsyncAlgorithms", package: "swift-async-algorithms"), "RemoteLocalizationMacros", ], - swiftSettings: swiftSettings + swiftSettings: swiftSettings, ), .testTarget( name: "DevFoundationTests", @@ -55,18 +57,18 @@ let package = Package( .product(name: "RealModule", package: "swift-numerics"), "URLMock", ], - swiftSettings: swiftSettings + swiftSettings: swiftSettings, ), .macro( - name: "RemoteLocalizationMacros", - dependencies: [ - .product(name: "SwiftCompilerPlugin", package: "swift-syntax"), - .product(name: "SwiftSyntax", package: "swift-syntax"), - .product(name: "SwiftSyntaxBuilder", package: "swift-syntax"), - .product(name: "SwiftSyntaxMacros", package: "swift-syntax"), - ], - swiftSettings: swiftSettings - ), + name: "RemoteLocalizationMacros", + dependencies: [ + .product(name: "SwiftCompilerPlugin", package: "swift-syntax"), + .product(name: "SwiftSyntax", package: "swift-syntax"), + .product(name: "SwiftSyntaxBuilder", package: "swift-syntax"), + .product(name: "SwiftSyntaxMacros", package: "swift-syntax"), + ], + swiftSettings: swiftSettings, + ), .executableTarget( name: "dfob", @@ -74,7 +76,7 @@ let package = Package( .product(name: "ArgumentParser", package: "swift-argument-parser"), "DevFoundation", ], - swiftSettings: swiftSettings + swiftSettings: swiftSettings, ), .testTarget( name: "dfobTests", @@ -84,7 +86,7 @@ let package = Package( "DevTesting", "dfob", ], - swiftSettings: swiftSettings + swiftSettings: swiftSettings, ), - ] + ], ) diff --git a/README.md b/README.md index 3adc9ff..845e148 100644 --- a/README.md +++ b/README.md @@ -4,15 +4,15 @@ DevFoundation is a Swift 6 package that provides useful types and protocols for and apps on Apple platforms. It makes it easy to consume web services, mock web service responses, page through data, post and handle type-safe events across multiple modules, and more. -DevFoundation is fully documented and tested and supports iOS 26+, macOS 26+, tvOS 26+, visionOS 26+, -and watchOS 26+. +DevFoundation is fully documented and tested and supports iOS 26+, macOS 26+, tvOS 26+, visionOS +26+, and watchOS 26+. View our [changelog](CHANGELOG.md) to see what’s new. ## Development Requirements -DevFoundation requires a Swift 6.2+ toolchain to build. We only test on Apple platforms. We follow +DevFoundation 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%. @@ -22,25 +22,19 @@ public interfaces are fully documented and tested. We aim for overall test cover To set up the development environment: - 1. Run `Scripts/install-git-hooks` to install git hooks that automatically check code - formatting on commits and run comprehensive tests before pushing. - 2. Use `Scripts/lint` to manually check code formatting at any time. - 3. Use `Scripts/test-all-platforms` to run tests on all supported platforms locally. + 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 DevFoundation uses GitHub Actions for continuous integration. The CI pipeline: - - **Linting**: Automatically checks code formatting on all pull requests using `swift format` - - **Testing**: Runs tests on macOS (iOS, tvOS, and watchOS testing disabled in CI due to - stability issues) + - **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 -For comprehensive cross-platform testing, developers should run `Scripts/test-all-platforms` -locally or rely on the pre-push git hook which automatically runs all platform tests before -pushing changes. - ## Bugs and Feature Requests diff --git a/Scripts/format b/Scripts/format deleted file mode 100755 index a450349..0000000 --- a/Scripts/format +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash - -# Get the directory where this script is located -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" - -# Go to the repository root (one level up from Scripts) -REPO_ROOT="$(dirname "$SCRIPT_DIR")" - -# Run swift format with --in-place to fix formatting issues -swift format --in-place --recursive \ - "$REPO_ROOT/Sources/" \ - "$REPO_ROOT/Tests/" diff --git a/Scripts/install-git-hooks b/Scripts/install-git-hooks deleted file mode 100755 index 56d6935..0000000 --- a/Scripts/install-git-hooks +++ /dev/null @@ -1,56 +0,0 @@ -#!/bin/bash - -# Get the directory where this script is located -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" - -# Go to the repository root (one level up from Scripts) -REPO_ROOT="$(dirname "$SCRIPT_DIR")" - -# Check if we're in a git repository and get the git directory -# This works for both regular repos and worktrees -cd "$REPO_ROOT" -if ! git rev-parse --git-dir > /dev/null 2>&1; then - echo "Error: Not in a git repository" - exit 1 -fi - -# Get the common git directory (shared across all worktrees) -GIT_COMMON_DIR="$(git rev-parse --git-common-dir)" -if [ ! -d "$GIT_COMMON_DIR" ]; then - echo "Error: Could not find git directory" - exit 1 -fi - -mkdir -p "$GIT_COMMON_DIR/hooks" - -# Function to install the pre-push hook -install_pre_push_hook() { - local pre_push_hook="$GIT_COMMON_DIR/hooks/pre-push" - - echo "Installing pre-push hook..." - - cat > "$pre_push_hook" << 'EOF' -#!/bin/bash - -# Resolve the repository root using git, which correctly handles worktrees -REPO_ROOT="$(git rev-parse --show-toplevel)" - -# Run the lint script -echo "Running lint check..." -if ! "$REPO_ROOT/Scripts/lint"; then - echo "Lint check failed. Please fix formatting issues before pushing." - exit 1 -fi - -echo "Lint check passed." -EOF - - chmod +x "$pre_push_hook" - echo "Pre-push hook installed successfully!" -} - -# Install the pre-push hook -install_pre_push_hook - -echo "All git hooks installed successfully!" -echo "The pre-push hook will run 'Scripts/lint' before each push." diff --git a/Scripts/lint b/Scripts/lint deleted file mode 100755 index 8e11414..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/Sources/" "$REPO_ROOT/Tests/" diff --git a/Sources/DevFoundation/Documentation.docc/ConsumingWebServices.md b/Sources/DevFoundation/Documentation.docc/ConsumingWebServices.md index 47fa9ba..1da3e47 100644 --- a/Sources/DevFoundation/Documentation.docc/ConsumingWebServices.md +++ b/Sources/DevFoundation/Documentation.docc/ConsumingWebServices.md @@ -2,45 +2,46 @@ Access web services and simulate responses. + ## Topics ### HTTP Client -- ``HTTPClient`` -- ``HTTPClientInterceptor`` -- ``URLRequestLoader`` + - ``HTTPClient`` + - ``HTTPClientInterceptor`` + - ``URLRequestLoader`` ### Web Service Client -- ``WebServiceClient`` -- ``BaseURLConfiguring`` -- ``SingleBaseURLConfiguration`` + - ``WebServiceClient`` + - ``BaseURLConfiguring`` + - ``SingleBaseURLConfiguration`` ### Requests and Response Handling -- ``WebServiceRequest`` -- ``JSONBodyWebServiceRequest`` -- ``HTTPBody`` -- ``HTTPHeaderField`` -- ``HTTPMethod`` -- ``HTTPHeaderItem`` -- ``MediaType`` -- ``URLPathComponent`` -- ``HTTPResponse`` -- ``HTTPStatusCode`` + - ``WebServiceRequest`` + - ``JSONBodyWebServiceRequest`` + - ``HTTPBody`` + - ``HTTPHeaderField`` + - ``HTTPMethod`` + - ``HTTPHeaderItem`` + - ``MediaType`` + - ``URLPathComponent`` + - ``HTTPResponse`` + - ``HTTPStatusCode`` ### Network Simulation -- ``SimulatedURLRequestLoader`` + - ``SimulatedURLRequestLoader`` ### Errors -- ``InvalidHTTPStatusCodeError`` -- ``InvalidWebServiceRequestError`` -- ``NonHTTPURLResponseError`` + - ``InvalidHTTPStatusCodeError`` + - ``InvalidWebServiceRequestError`` + - ``NonHTTPURLResponseError`` ### Extensions -- ``Foundation/HTTPURLResponse`` -- ``Foundation/URLRequest`` -- ``Foundation/URLSession`` + - ``Foundation/HTTPURLResponse`` + - ``Foundation/URLRequest`` + - ``Foundation/URLSession`` diff --git a/Sources/DevFoundation/Documentation.docc/Documentation.md b/Sources/DevFoundation/Documentation.docc/Documentation.md index 7cd6566..97583af 100644 --- a/Sources/DevFoundation/Documentation.docc/Documentation.md +++ b/Sources/DevFoundation/Documentation.docc/Documentation.md @@ -5,7 +5,7 @@ Access essential types and services for building your library or app’s foundat ## Overview -DevFoundation is a Swift package that provides foundational utilities for Apple platforms. +DevFoundation is a Swift package that provides foundational utilities for Apple platforms. It offers comprehensive networking capabilities, an event bus, concurrency utilities, a system for paging through data, and essential utility types for building robust applications. @@ -14,90 +14,90 @@ for paging through data, and essential utility types for building robust applica ### Networking -- + - ### Type-Safe Events -- + - ### Paging -- + - ### Live Queries -- ``LiveQuery`` -- ``LiveQueryResultsProducer`` -- ``LiveQuerySchedulingStrategy`` + - ``LiveQuery`` + - ``LiveQueryResultsProducer`` + - ``LiveQuerySchedulingStrategy`` ### Localizing with Remote Content -- ``remoteLocalizedString(_:bundle:)`` -- ``remoteLocalizedString(format:bundle:_:)`` -- ``remoteLocalizedString(_:key:bundle:remoteContentBundle:)`` -- ``remoteLocalizedFormatString(_:key:bundle:remoteContentBundle:policy:)`` -- ``RemoteLocalizedFormatStringPolicy`` -- ``RemoteLocalizedFormatStringPolicies`` -- ``Foundation/Bundle`` + - ``remoteLocalizedString(_:bundle:)`` + - ``remoteLocalizedString(format:bundle:_:)`` + - ``remoteLocalizedString(_:key:bundle:remoteContentBundle:)`` + - ``remoteLocalizedFormatString(_:key:bundle:remoteContentBundle:policy:)`` + - ``RemoteLocalizedFormatStringPolicy`` + - ``RemoteLocalizedFormatStringPolicies`` + - ``Foundation/Bundle`` ### Caching -- ``ExpiringValue`` + - ``ExpiringValue`` ### Observing Changes -- ``ObservableReference`` + - ``ObservableReference`` ### Concurrency Utilities -- ``ExecutionGroup`` -- ``withTimeout(_:priority:operation:)`` -- ``Dispatch/DispatchQueue`` -- ``Swift/Result`` + - ``ExecutionGroup`` + - ``withTimeout(_:priority:operation:)`` + - ``Dispatch/DispatchQueue`` + - ``Swift/Result`` ### Encoding, Decoding, and JSON -- ``JSONValue`` -- ``TopLevelDecoder`` -- ``TopLevelEncoder`` -- ``Foundation/JSONDecoder`` -- ``Foundation/PropertyListDecoder`` + - ``JSONValue`` + - ``TopLevelDecoder`` + - ``TopLevelEncoder`` + - ``Foundation/JSONDecoder`` + - ``Foundation/PropertyListDecoder`` ### Expressing Retry Policies -- ``RetryPolicy`` -- ``PredefinedDelaySequenceRetryPolicy`` -- ``AggregateRetryPolicy`` + - ``RetryPolicy`` + - ``PredefinedDelaySequenceRetryPolicy`` + - ``AggregateRetryPolicy`` ### Generating Gibberish -- ``GibberishGenerator`` + - ``GibberishGenerator`` ### Handling User Inputs -- ``UserSelection`` + - ``UserSelection`` ### Obfuscating and Deobfuscating Data -- ``Foundation/Data`` + - ``Foundation/Data`` ### Working with Dates -- ``Foundation/Date`` -- ``Swift/Duration`` -- ``DateProvider`` -- ``DateProviders`` + - ``Foundation/Date`` + - ``Swift/Duration`` + - ``DateProvider`` + - ``DateProviders`` -### Strongly-Typed IDs and Values +### Strongly-Typed IDs and Values -- ``TypedExtensibleEnum`` -- ``DottedHierarchicalID`` -- ``SoftwareComponentID`` + - ``TypedExtensibleEnum`` + - ``DottedHierarchicalID`` + - ``SoftwareComponentID`` ### Utility Protocols -- ``AnySendableHashable`` -- ``HashableByID`` -- ``IdentifiableBySelf`` -- ``OptionalRepresentable`` -- ``Swift/Optional`` + - ``AnySendableHashable`` + - ``HashableByID`` + - ``IdentifiableBySelf`` + - ``OptionalRepresentable`` + - ``Swift/Optional`` diff --git a/Sources/DevFoundation/Documentation.docc/PagingThroughData.md b/Sources/DevFoundation/Documentation.docc/PagingThroughData.md index 739af50..c9b49b3 100644 --- a/Sources/DevFoundation/Documentation.docc/PagingThroughData.md +++ b/Sources/DevFoundation/Documentation.docc/PagingThroughData.md @@ -1,22 +1,22 @@ # Paging -Easily and efficiently page through data. +Easily and efficiently page through data. + ## Topics ### Sequential Paging -- ``SequentialPager`` -- ``SequentialPageLoader`` -- ``SequentialPaging`` + - ``SequentialPager`` + - ``SequentialPageLoader`` + - ``SequentialPaging`` ### Random Access Paging -- ``RandomAccessPager`` -- ``RandomAccessPageLoader`` -- ``RandomAccessPaging`` + - ``RandomAccessPager`` + - ``RandomAccessPageLoader`` + - ``RandomAccessPaging`` ### Supporting Types -- ``OffsetPage`` - + - ``OffsetPage`` diff --git a/Sources/DevFoundation/Documentation.docc/TypeSafeEvents.md b/Sources/DevFoundation/Documentation.docc/TypeSafeEvents.md index a5a0c25..36003f7 100644 --- a/Sources/DevFoundation/Documentation.docc/TypeSafeEvents.md +++ b/Sources/DevFoundation/Documentation.docc/TypeSafeEvents.md @@ -2,11 +2,12 @@ Post and handle type-safe events across your app’s modules. + ## Topics ### Type-Safe Events -- ``EventBus`` -- ``BusEvent`` -- ``BusEventObserver`` -- ``ContextualBusEventObserver`` + - ``EventBus`` + - ``BusEvent`` + - ``BusEventObserver`` + - ``ContextualBusEventObserver`` diff --git a/Sources/DevFoundation/Networking/HTTP Client/HTTPClientInterceptor.swift b/Sources/DevFoundation/Networking/HTTP Client/HTTPClientInterceptor.swift index 76e784a..3f1844a 100644 --- a/Sources/DevFoundation/Networking/HTTP Client/HTTPClientInterceptor.swift +++ b/Sources/DevFoundation/Networking/HTTP Client/HTTPClientInterceptor.swift @@ -22,13 +22,15 @@ public protocol HTTPClientInterceptor: Sendable { /// - request: The request to intercept. /// - context: Additional context about the request. This type can be used to make decisions about how to perform /// interception. - /// - next: A closure to call to pass the request and context to the next interceptor in the chain. + /// - next: A closure to call to pass the request and context to the next interceptor in the chain. It’s + /// `@concurrent`, so it doesn’t run on the caller’s actor. func intercept( request: URLRequest, context: RequestContext, - next: ( - _ request: URLRequest, - _ context: RequestContext - ) async throws -> HTTPResponse, + next: + @concurrent ( + _ request: URLRequest, + _ context: RequestContext + ) async throws -> HTTPResponse, ) async throws -> HTTPResponse } diff --git a/Sources/DevFoundation/Utility Types/CurrentValueMulticaster.swift b/Sources/DevFoundation/Utility Types/CurrentValueMulticaster.swift index 95f2ddb..87899ba 100644 --- a/Sources/DevFoundation/Utility Types/CurrentValueMulticaster.swift +++ b/Sources/DevFoundation/Utility Types/CurrentValueMulticaster.swift @@ -144,8 +144,11 @@ extension CurrentValueMulticaster { fileprivate var base: AsyncStream.Iterator - public mutating func next() async -> Element? { - await base.next() + /// Returns the next value, or `nil` once the sequence has finished. + /// + /// - Parameter actor: The actor to wait for the value on. Defaults to the caller’s isolation. + public mutating func next(isolation actor: isolated (any Actor)? = #isolation) async -> Element? { + await base.next(isolation: actor) } } diff --git a/Tests/DevFoundationTests/Extensions/Result+CatchingAsyncTests.swift b/Tests/DevFoundationTests/Extensions/Result+CatchingAsyncTests.swift index 0517461..f66e9b0 100644 --- a/Tests/DevFoundationTests/Extensions/Result+CatchingAsyncTests.swift +++ b/Tests/DevFoundationTests/Extensions/Result+CatchingAsyncTests.swift @@ -18,7 +18,7 @@ struct ResultCatchingAsyncTests: RandomValueGenerating { mutating func testResultCatchingAsyncSuccess() async { let expectedValue = randomAlphanumericString() - let result = await Result { () async throws(MockError) -> String in + let result = await Result { () async throws(ArbitraryError) -> String in return expectedValue } @@ -28,9 +28,9 @@ struct ResultCatchingAsyncTests: RandomValueGenerating { @Test mutating func testResultCatchingAsyncFailure() async { - let expectedError = MockError(id: randomInt(in: .min ... .max)) + let expectedError = randomError() - let result = await Result { () async throws(MockError) -> String in + let result = await Result { () async throws(ArbitraryError) -> String in throw expectedError } diff --git a/Tests/DevFoundationTests/Live Query/LiveQueryTests.swift b/Tests/DevFoundationTests/Live Query/LiveQueryTests.swift index 374739b..6e5ab3a 100644 --- a/Tests/DevFoundationTests/Live Query/LiveQueryTests.swift +++ b/Tests/DevFoundationTests/Live Query/LiveQueryTests.swift @@ -169,7 +169,7 @@ struct LiveQueryTests: RandomValueGenerating { // expect the error is captured and previous results are preserved #expect(liveQuery.results == initialResults) - #expect(liveQuery.lastError as? MockError == expectedError) + #expect(liveQuery.lastError as? ArbitraryError == expectedError) } @@ -207,7 +207,7 @@ struct LiveQueryTests: RandomValueGenerating { await signalStream.first { _ in true } #expect(liveQuery.results == nil) - #expect(liveQuery.lastError as? MockError == expectedError) + #expect(liveQuery.lastError as? ArbitraryError == expectedError) // exercise the test by producing successful results liveQuery.queryFragment = fragment2 diff --git a/Tests/DevFoundationTests/Networking/Errors/InvalidWebServiceRequestError.swift b/Tests/DevFoundationTests/Networking/Errors/InvalidWebServiceRequestError.swift index c3636f4..b03f297 100644 --- a/Tests/DevFoundationTests/Networking/Errors/InvalidWebServiceRequestError.swift +++ b/Tests/DevFoundationTests/Networking/Errors/InvalidWebServiceRequestError.swift @@ -24,7 +24,7 @@ struct InvalidWebServiceRequestErrorTests: RandomValueGenerating { underlyingError: underlyingError, ) #expect(error.debugDescription == debugDescription) - #expect(error.underlyingError as? MockError == underlyingError) + #expect(error.underlyingError as? ArbitraryError == underlyingError) } } } diff --git a/Tests/DevFoundationTests/Networking/Requests and Responses/HTTPResponseTests.swift b/Tests/DevFoundationTests/Networking/Requests and Responses/HTTPResponseTests.swift index aeab308..d4e9eb3 100644 --- a/Tests/DevFoundationTests/Networking/Requests and Responses/HTTPResponseTests.swift +++ b/Tests/DevFoundationTests/Networking/Requests and Responses/HTTPResponseTests.swift @@ -51,7 +51,7 @@ struct HTTPResponseTests: RandomValueGenerating { let expectedError = randomError() #expect(throws: expectedError) { - try response.mapBody { (input) throws(MockError) -> String in + try response.mapBody { (input) throws(ArbitraryError) -> String in #expect(input == body) throw expectedError } diff --git a/Tests/DevFoundationTests/Networking/Web Service Client/WebServiceClientTests.swift b/Tests/DevFoundationTests/Networking/Web Service Client/WebServiceClientTests.swift index b467963..ed1fbbc 100644 --- a/Tests/DevFoundationTests/Networking/Web Service Client/WebServiceClientTests.swift +++ b/Tests/DevFoundationTests/Networking/Web Service Client/WebServiceClientTests.swift @@ -58,7 +58,7 @@ struct WebServiceClientTests: RandomValueGenerating { Issue.record("does not throw error") } catch let error as InvalidWebServiceRequestError { #expect(!error.debugDescription.isEmpty) - #expect(error.underlyingError as? MockError == expectedError) + #expect(error.underlyingError as? ArbitraryError == expectedError) } catch { Issue.record("throws unexpected error: \(error)") } diff --git a/Tests/DevFoundationTests/Networking/Web Service Client/WebServiceRequestTests.swift b/Tests/DevFoundationTests/Networking/Web Service Client/WebServiceRequestTests.swift index 8c7b6c3..a22035c 100644 --- a/Tests/DevFoundationTests/Networking/Web Service Client/WebServiceRequestTests.swift +++ b/Tests/DevFoundationTests/Networking/Web Service Client/WebServiceRequestTests.swift @@ -180,7 +180,7 @@ struct WebServiceRequestTests: RandomValueGenerating { Issue.record("does not throw error") } catch let error as InvalidWebServiceRequestError { #expect(!error.debugDescription.isEmpty) - #expect(error.underlyingError as? MockError == expectedError) + #expect(error.underlyingError as? ArbitraryError == expectedError) } catch { Issue.record("throws unexpected error: \(error)") } diff --git a/Tests/DevFoundationTests/Testing Helpers/MockBaseURLConfiguration.swift b/Tests/DevFoundationTests/Testing Helpers/MockBaseURLConfiguration.swift index 59010d4..5c0670e 100644 --- a/Tests/DevFoundationTests/Testing Helpers/MockBaseURLConfiguration.swift +++ b/Tests/DevFoundationTests/Testing Helpers/MockBaseURLConfiguration.swift @@ -10,7 +10,7 @@ import DevTesting import Foundation final class MockBaseURLConfiguration: BaseURLConfiguring { - nonisolated(unsafe) var urlStub: Stub! + nonisolated(unsafe) var urlStub = Stub() func url(for baseURL: Int) -> URL { diff --git a/Tests/DevFoundationTests/Testing Helpers/MockBusEventObserver.swift b/Tests/DevFoundationTests/Testing Helpers/MockBusEventObserver.swift index a104ddd..bc9b385 100644 --- a/Tests/DevFoundationTests/Testing Helpers/MockBusEventObserver.swift +++ b/Tests/DevFoundationTests/Testing Helpers/MockBusEventObserver.swift @@ -10,8 +10,8 @@ import DevTesting import Foundation final class MockBusEventObserver: BusEventObserver { - nonisolated(unsafe) var observeStub: Stub! - nonisolated(unsafe) var observeIdentifiableStub: Stub! + nonisolated(unsafe) var observeStub = Stub() + nonisolated(unsafe) var observeIdentifiableStub = Stub() func observe(_ event: some BusEvent) { diff --git a/Tests/DevFoundationTests/Testing Helpers/MockDateProvider.swift b/Tests/DevFoundationTests/Testing Helpers/MockDateProvider.swift index 8aa30ca..37622ff 100644 --- a/Tests/DevFoundationTests/Testing Helpers/MockDateProvider.swift +++ b/Tests/DevFoundationTests/Testing Helpers/MockDateProvider.swift @@ -10,7 +10,7 @@ import DevTesting import Foundation final class MockDateProvider: DateProvider { - nonisolated(unsafe) var nowStub: Stub! + nonisolated(unsafe) var nowStub = Stub() convenience init(now: Date) { diff --git a/Tests/DevFoundationTests/Testing Helpers/MockError.swift b/Tests/DevFoundationTests/Testing Helpers/MockError.swift deleted file mode 100644 index d3e297e..0000000 --- a/Tests/DevFoundationTests/Testing Helpers/MockError.swift +++ /dev/null @@ -1,12 +0,0 @@ -// -// MockError.swift -// DevFoundation -// -// Created by Prachi Gauriar on 3/15/25. -// - -import Foundation - -struct MockError: Error, Hashable, Sendable { - let id: Int -} diff --git a/Tests/DevFoundationTests/Testing Helpers/MockHTTPClientInterceptor.swift b/Tests/DevFoundationTests/Testing Helpers/MockHTTPClientInterceptor.swift index 9703f45..5438f94 100644 --- a/Tests/DevFoundationTests/Testing Helpers/MockHTTPClientInterceptor.swift +++ b/Tests/DevFoundationTests/Testing Helpers/MockHTTPClientInterceptor.swift @@ -17,7 +17,7 @@ where RequestContext: Sendable { } - nonisolated(unsafe) var interceptStub: ThrowingStub, any Error>! + nonisolated(unsafe) var interceptStub = ThrowingStub, any Error>() nonisolated(unsafe) var nextArguments: [InterceptArguments] = [] nonisolated(unsafe) var interceptPrologue: (@Sendable () async throws -> Void)? @@ -25,7 +25,7 @@ where RequestContext: Sendable { func intercept( request: URLRequest, context: RequestContext, - next: (URLRequest, RequestContext) async throws -> HTTPResponse, + next: @concurrent (URLRequest, RequestContext) async throws -> HTTPResponse, ) async throws -> HTTPResponse { try await interceptPrologue?() diff --git a/Tests/DevFoundationTests/Testing Helpers/MockLiveQueryResultsProducer.swift b/Tests/DevFoundationTests/Testing Helpers/MockLiveQueryResultsProducer.swift index 1003db3..ffa5eae 100644 --- a/Tests/DevFoundationTests/Testing Helpers/MockLiveQueryResultsProducer.swift +++ b/Tests/DevFoundationTests/Testing Helpers/MockLiveQueryResultsProducer.swift @@ -11,9 +11,9 @@ import Foundation @testable import DevFoundation final class MockLiveQueryResultsProducer: LiveQueryResultsProducer where Results: Sendable { - nonisolated(unsafe) var schedulingStrategyStub: Stub! - nonisolated(unsafe) var canonicalQueryFragmentStub: Stub! - nonisolated(unsafe) var resultsStub: ThrowingStub! + nonisolated(unsafe) var schedulingStrategyStub = Stub() + nonisolated(unsafe) var canonicalQueryFragmentStub = Stub() + nonisolated(unsafe) var resultsStub = ThrowingStub() nonisolated(unsafe) var resultsEpilogue: (() async throws -> Void)? @@ -36,3 +36,10 @@ final class MockLiveQueryResultsProducer: LiveQueryResultsProducer wher return try resultsStub(queryFragment) } } + + +extension LiveQuerySchedulingStrategy: DefaultStubValueProviding { + public static var defaultStubValue: LiveQuerySchedulingStrategy { + return .passthrough + } +} diff --git a/Tests/DevFoundationTests/Testing Helpers/MockOffsetPage.swift b/Tests/DevFoundationTests/Testing Helpers/MockOffsetPage.swift index e54b847..4cda739 100644 --- a/Tests/DevFoundationTests/Testing Helpers/MockOffsetPage.swift +++ b/Tests/DevFoundationTests/Testing Helpers/MockOffsetPage.swift @@ -10,7 +10,7 @@ import DevTesting import Foundation final class MockOffsetPage: OffsetPage, HashableByID { - nonisolated(unsafe) var pageOffsetStub: Stub! + nonisolated(unsafe) var pageOffsetStub = Stub() var pageOffset: Int { diff --git a/Tests/DevFoundationTests/Testing Helpers/MockRandomAccessPageLoader.swift b/Tests/DevFoundationTests/Testing Helpers/MockRandomAccessPageLoader.swift index ea9e205..3b614a3 100644 --- a/Tests/DevFoundationTests/Testing Helpers/MockRandomAccessPageLoader.swift +++ b/Tests/DevFoundationTests/Testing Helpers/MockRandomAccessPageLoader.swift @@ -10,9 +10,9 @@ import DevTesting import Foundation final class MockRandomAccessPageLoader: RandomAccessPageLoader where Page: OffsetPage { - nonisolated(unsafe) var pageExistsStub: Stub! + nonisolated(unsafe) var pageExistsStub = Stub() nonisolated(unsafe) var loadPagePrologue: (() async throws -> Void)? - nonisolated(unsafe) var loadPageStub: ThrowingStub! + nonisolated(unsafe) var loadPageStub = ThrowingStub() func pageExists(at offset: Int) -> Bool { diff --git a/Tests/DevFoundationTests/Testing Helpers/MockRemoteLocalizedFormatStringPolicy.swift b/Tests/DevFoundationTests/Testing Helpers/MockRemoteLocalizedFormatStringPolicy.swift index e8fd3d0..b0b7811 100644 --- a/Tests/DevFoundationTests/Testing Helpers/MockRemoteLocalizedFormatStringPolicy.swift +++ b/Tests/DevFoundationTests/Testing Helpers/MockRemoteLocalizedFormatStringPolicy.swift @@ -17,7 +17,7 @@ final class MockRemoteLocalizedFormatStringPolicy: RemoteLocalizedFormatStringPo } - nonisolated(unsafe) var allowsRemoteFormatStringStub: Stub! + nonisolated(unsafe) var allowsRemoteFormatStringStub = Stub() func allowsRemoteFormatString( diff --git a/Tests/DevFoundationTests/Testing Helpers/MockRequestCondition.swift b/Tests/DevFoundationTests/Testing Helpers/MockRequestCondition.swift index 89daac5..04647d8 100644 --- a/Tests/DevFoundationTests/Testing Helpers/MockRequestCondition.swift +++ b/Tests/DevFoundationTests/Testing Helpers/MockRequestCondition.swift @@ -10,8 +10,8 @@ import DevTesting import Foundation final class MockRequestCondition: SimulatedURLRequestLoader.RequestCondition, HashableByID { - nonisolated(unsafe) var isFulfilledStub: Stub! - nonisolated(unsafe) var descriptionStub: Stub! + nonisolated(unsafe) var isFulfilledStub = Stub() + nonisolated(unsafe) var descriptionStub = Stub() func isFulfilled(by requestComponents: SimulatedURLRequestLoader.RequestComponents) -> Bool { diff --git a/Tests/DevFoundationTests/Testing Helpers/MockRetryPolicy.swift b/Tests/DevFoundationTests/Testing Helpers/MockRetryPolicy.swift index 1fe075c..b6569a2 100644 --- a/Tests/DevFoundationTests/Testing Helpers/MockRetryPolicy.swift +++ b/Tests/DevFoundationTests/Testing Helpers/MockRetryPolicy.swift @@ -18,7 +18,7 @@ final class MockRetryPolicy: HashableByID, RetryPolicy { } - nonisolated(unsafe) var retryDelayStub: Stub! + nonisolated(unsafe) var retryDelayStub = Stub() func retryDelay( diff --git a/Tests/DevFoundationTests/Testing Helpers/MockSequentialPageLoader.swift b/Tests/DevFoundationTests/Testing Helpers/MockSequentialPageLoader.swift index 05a2ad3..30cd65b 100644 --- a/Tests/DevFoundationTests/Testing Helpers/MockSequentialPageLoader.swift +++ b/Tests/DevFoundationTests/Testing Helpers/MockSequentialPageLoader.swift @@ -10,9 +10,9 @@ import DevTesting import Foundation final class MockSequentialPageLoader: SequentialPageLoader where Page: OffsetPage { - nonisolated(unsafe) var pageExistsStub: Stub! + nonisolated(unsafe) var pageExistsStub = Stub() nonisolated(unsafe) var loadPagePrologue: (() async throws -> Void)? - nonisolated(unsafe) var loadPageStub: ThrowingStub! + nonisolated(unsafe) var loadPageStub = ThrowingStub() func pageExists(after page: Page) -> Bool { diff --git a/Tests/DevFoundationTests/Testing Helpers/MockURLRequestLoader.swift b/Tests/DevFoundationTests/Testing Helpers/MockURLRequestLoader.swift index ecbdb25..fd11e4d 100644 --- a/Tests/DevFoundationTests/Testing Helpers/MockURLRequestLoader.swift +++ b/Tests/DevFoundationTests/Testing Helpers/MockURLRequestLoader.swift @@ -11,7 +11,7 @@ import Foundation final class MockURLRequestLoader: URLRequestLoader { nonisolated(unsafe) var dataPrologue: (() async throws -> Void)? - nonisolated(unsafe) var dataStub: ThrowingStub! + nonisolated(unsafe) var dataStub = ThrowingStub() func data(for urlRequest: URLRequest) async throws -> (Data, URLResponse) { diff --git a/Tests/DevFoundationTests/Testing Helpers/MockWebServiceRequest.swift b/Tests/DevFoundationTests/Testing Helpers/MockWebServiceRequest.swift index bb46dd7..e71a6e1 100644 --- a/Tests/DevFoundationTests/Testing Helpers/MockWebServiceRequest.swift +++ b/Tests/DevFoundationTests/Testing Helpers/MockWebServiceRequest.swift @@ -22,7 +22,7 @@ final class MockWebServiceRequest: WebServiceRequest { nonisolated(unsafe) var queryItems: [URLQueryItem] nonisolated(unsafe) var automaticallyPercentEncodesQueryItems: Bool nonisolated(unsafe) var httpBodyResult: Result - nonisolated(unsafe) var mapResponseStub: ThrowingStub, String, any Error>! + nonisolated(unsafe) var mapResponseStub = ThrowingStub, String, any Error>() init( diff --git a/Tests/DevFoundationTests/Testing Helpers/RandomValueGenerating+DevFoundation.swift b/Tests/DevFoundationTests/Testing Helpers/RandomValueGenerating+DevFoundation.swift index 7fe7d99..67ff4be 100644 --- a/Tests/DevFoundationTests/Testing Helpers/RandomValueGenerating+DevFoundation.swift +++ b/Tests/DevFoundationTests/Testing Helpers/RandomValueGenerating+DevFoundation.swift @@ -17,10 +17,6 @@ extension RandomValueGenerating { ) } - mutating func randomError() -> MockError { - return MockError(id: randomInt(in: 0 ... .max)) - } - mutating func randomHTTPBody() -> HTTPBody { return HTTPBody(contentType: randomMediaType(), data: randomData()) diff --git a/Tools/format b/Tools/format new file mode 100755 index 0000000..a188a55 --- /dev/null +++ b/Tools/format @@ -0,0 +1,19 @@ +#!/bin/bash + +# Formats Swift with swift-format and Markdown with rumdl, in place. + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(dirname "$SCRIPT_DIR")" + +# Swift files and directories to format, relative to the repository root +SWIFT_PATHS=(Package.swift Sources Tests) +swift_paths=("${SWIFT_PATHS[@]/#/$REPO_ROOT/}") + +exit_status=0 + +swift format --in-place --recursive "${swift_paths[@]}" || exit_status=1 + +# Rewrite Markdown using the rules in .rumdl.toml +"$SCRIPT_DIR/rumdl" fmt "$REPO_ROOT" || exit_status=1 + +exit "$exit_status" diff --git a/Tools/install-git-hooks b/Tools/install-git-hooks new file mode 100755 index 0000000..862c44e --- /dev/null +++ b/Tools/install-git-hooks @@ -0,0 +1,30 @@ +#!/bin/bash + +# Installs a pre-push hook that runs Tools/lint, so formatting problems are caught before CI sees +# them. The hook goes in the repository’s common Git directory, so it applies to every worktree. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(dirname "$SCRIPT_DIR")" + +cd "$REPO_ROOT" +GIT_COMMON_DIR="$(git rev-parse --path-format=absolute --git-common-dir)" +HOOKS_DIR="$GIT_COMMON_DIR/hooks" +mkdir -p "$HOOKS_DIR" + +cat > "$HOOKS_DIR/pre-push" << 'HOOK' +#!/bin/bash + +# Installed by Tools/install-git-hooks. Runs Tools/lint before pushing. +REPO_ROOT="$(git rev-parse --show-toplevel)" + +echo "Running Tools/lint…" +if ! "$REPO_ROOT/Tools/lint"; then + echo "Lint failed. Run Tools/format, or push with --no-verify to skip this check." + exit 1 +fi +HOOK + +chmod +x "$HOOKS_DIR/pre-push" +echo "Installed a pre-push hook that runs Tools/lint." diff --git a/Tools/lint b/Tools/lint new file mode 100755 index 0000000..46518e3 --- /dev/null +++ b/Tools/lint @@ -0,0 +1,37 @@ +#!/bin/bash + +# Lints Swift with swift-format, the length of Swift comments, and Markdown with rumdl. Exits with a +# nonzero status if any check fails, after running all of them. + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(dirname "$SCRIPT_DIR")" + +# Swift files and directories to check, relative to the repository root +SWIFT_PATHS=(Package.swift Sources Tests) +swift_paths=("${SWIFT_PATHS[@]/#/$REPO_ROOT/}") + +exit_status=0 + +swift format lint --strict --recursive "${swift_paths[@]}" || exit_status=1 + +# swift-format doesn’t check the length of standalone or documentation comments, so report those +# over its line length. Perl counts characters rather than bytes. Read the limit with Python rather +# than plutil, which only exists on macOS. +line_length="$(python3 -c 'import json, sys; print(json.load(open(sys.argv[1]))["lineLength"])' \ + "$REPO_ROOT/.swift-format")" +find "${swift_paths[@]}" -name '*.swift' -print0 2>/dev/null | + xargs -0 perl -CDS -sne ' + chomp; + if (m{^\s*//} && length($_) > $limit) { + printf STDERR "%s:%d:%d: error: [CommentLength] wrap this comment, which is %d characters long, to %d or fewer\n", + $ARGV, $., $limit + 1, length($_), $limit; + $found = 1; + } + close ARGV if eof; + END { exit 1 if $found } + ' -- -limit="$line_length" || exit_status=1 + +# Lint Markdown using the rules in .rumdl.toml +"$SCRIPT_DIR/rumdl" check "$REPO_ROOT" || exit_status=1 + +exit "$exit_status" diff --git a/Tools/rumdl b/Tools/rumdl new file mode 100755 index 0000000..5ecc6a7 --- /dev/null +++ b/Tools/rumdl @@ -0,0 +1,40 @@ +#!/bin/bash + +# Runs the pinned version of rumdl, installing it on first use. Pinning keeps local runs and CI on +# the same version, so a new rumdl release can’t change lint results until this version changes. +# Each version is installed once per user into a virtual environment in the user’s cache. + +set -euo pipefail + +RUMDL_VERSION="0.3.5" + +INSTALL_ROOT="${XDG_CACHE_HOME:-$HOME/.cache}/devkit" +INSTALL_DIR="$INSTALL_ROOT/rumdl-$RUMDL_VERSION" +RUMDL="$INSTALL_DIR/bin/rumdl" + +if [[ ! -x "$RUMDL" ]]; then + echo "Installing rumdl ${RUMDL_VERSION} into ${INSTALL_DIR}…" >&2 + mkdir -p "$INSTALL_ROOT" + + # Install into a temporary directory and move it into place, so a run that starts while + # another is installing never sees a partial installation. + staging_dir="$(mktemp -d "$INSTALL_ROOT/rumdl-staging.XXXXXX")" + trap 'rm -rf "$staging_dir"' EXIT + python3 -m venv "$staging_dir" + "$staging_dir/bin/pip" install --quiet --disable-pip-version-check "rumdl==$RUMDL_VERSION" >&2 + + # If another run finished first, keep its copy. exec below skips the EXIT trap, so clean up + # the staging directory here. + if [[ ! -e "$INSTALL_DIR" ]]; then + mv "$staging_dir" "$INSTALL_DIR" + fi + rm -rf "$staging_dir" + trap - EXIT + + if [[ ! -x "$RUMDL" ]]; then + echo "Error: couldn’t install rumdl ${RUMDL_VERSION}" >&2 + exit 1 + fi +fi + +exec "$RUMDL" "$@"