diff --git a/.github/workflows/VerifyChanges.yaml b/.github/workflows/VerifyChanges.yaml index 1f9f8db..7b85b16 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 @@ -97,8 +97,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: | @@ -124,7 +128,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 }} @@ -141,11 +145,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 248443c..f951a0e 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,5 @@ DerivedData/ .netrc Open Sourcing/ .claude/settings.local.json + +.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..04dc302 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,72 @@ +# Agent Guidelines + +DevConfiguration is a type-safe configuration wrapper built on Apple’s +swift-configuration. It adds config variables, access reporting through DevFoundation’s +`EventBus`, extensible metadata, and a SwiftUI editor for overriding values at runtime. + + +## Building and testing + + - `swift build` and `swift test` build and test the package. + - Xcode test plans in `Build Support/Test Plans/` run the tests with coverage, as CI does. + - The example app in `App/` builds with Xcode. + + +## 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) + - [MVVM for SwiftUI](Documentation/MVVMForSwiftUI.md) and its + [background](Documentation/MVVMForSwiftUIBackground.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%. + - SwiftUI views don’t have automated tests; their view models do. + + +## 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 b845549..d50be4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,27 +1,52 @@ # DevConfiguration Changelog -## 1.0.0: TBD +## 1.0.0: November 24, 2026 -Description forthcoming. +This is DevConfiguration’s first stable release. It requires Swift 6.4 (Xcode 27) to build. It also +enables Swift’s `NonisolatedNonsendingByDefault` upcoming feature, so `ConfigVariableReader`’s +`fetchValue` and `watchValue` functions now run on their caller’s actor instead of on the global +concurrent executor. -## 0.12.0: TBD +## 0.13.1: July 27, 2026 -This release contains **breaking changes** to the configuration variable editor’s custom content API. +This is a small release that fixes a bug in which the overrides-only filter toggle in the config +editor’s variable list could get stuck in an on, non-interactive state after clearing all overrides. - - `ConfigVariableEditor` no longer takes a `customSectionTitle` parameter. Instead, the `customContent` view - builder is responsible for providing its own `Section` views (or other list content). - - The `customSection` view builder parameter has been renamed to `customContent`. -If you previously presented the editor with a custom section title and content, move the section title into a -`Section` view inside `customContent`. +## 0.13.0: July 27, 2026 + +This release adds the ability to organize configuration variables into logical groups in the +editor’s variable list, along with a filter for quickly finding overridden variables. + + - Config variables can now be assigned a `ConfigVariableGroup` via the new `group` metadata key. + Variables sharing a group are rendered together under a section header; ungrouped variables + appear in a headerless section at the bottom of the list. + - The variable list can now be filtered to show only variables with overrides. + - Variable list rows are now more compact. + + +## 0.12.0: June 24, 2026 + +This release contains **breaking changes** to the configuration variable editor’s custom content +API. + + - `ConfigVariableEditor` no longer takes a `customSectionTitle` parameter. Instead, the + `customContent` view builder is responsible for providing its own `Section` views (or other list + content). + - The `customSection` view builder parameter has been renamed to `customContent`. + - If `customContent` contains multiple `Section` views, each is displayed in a grouped section of + its own. + +If you previously presented the editor with a custom section title and content, move the section +title into a `Section` view inside `customContent`. ## 0.11.0: April 13, 2026 -This release adds a confirm keyboard button on the variable detail screen so that users who edit numeric types can -actually commit the edit. +This release adds a confirm keyboard button on the variable detail screen so that users who edit +numeric types can actually commit the edit. ## 0.10.1: April 5, 2026 @@ -39,18 +64,19 @@ DevConfiguration and Configuration. This release makes the following changes: - - `ConfigVariableEditor` now takes an optional `dismiss` closure instead of an `onSave` closure. This closure takes - an array of modified variables just like `onSave`. However, if the `dismiss` closure is provided, it is the - caller’s responsibility to dismiss the editor. If no closure is provided, the editor will use the environment’s - dismiss action. - - The `requiresRelaunch` config variable metadata key has been removed. In general, consumers should try to - respond to variable changes at runtime. If this is not possible, you can create your own similar metadata key. + - `ConfigVariableEditor` now takes an optional `dismiss` closure instead of an `onSave` closure. + This closure takes an array of modified variables just like `onSave`. However, if the `dismiss` + closure is provided, it is the caller’s responsibility to dismiss the editor. If no closure is + provided, the editor will use the environment’s dismiss action. + - The `requiresRelaunch` config variable metadata key has been removed. In general, consumers + should try to respond to variable changes at runtime. If this is not possible, you can create + your own similar metadata key. ## 0.8.1: March 19, 2026 -This is a small release that updates to DevFoundation 1.8.1 and makes `RegisteredConfigVariable`’s metadata -subscript public. +This is a small release that updates to DevFoundation 1.8.1 and makes `RegisteredConfigVariable`’s +metadata subscript public. ## 0.8.0: March 17, 2026 @@ -60,14 +86,14 @@ This is a small release that sorts metadata keys on the variable detail view of ## 0.7.0: March 17, 2026 -This release adds the `isEditable` metadata value to config variables. When `false`, a config variable will not be -editable in the Config Variable Editor. `true` by default. +This release adds the `isEditable` metadata value to config variables. When `false`, a config +variable will not be editable in the Config Variable Editor. `true` by default. ## 0.6.0: March 11, 2026 -This release enhances the editor UI to show pickers for `CaseIterable` integers and strings, allow editing arrays -and JSON payloads in text editors, and handle formatting better for scalar types. +This release enhances the editor UI to show pickers for `CaseIterable` integers and strings, allow +editing arrays and JSON payloads in text editors, and handle formatting better for scalar types. ## 0.5.0: March 10, 2026 @@ -77,31 +103,32 @@ This release adds the ability for consumers to add a custom section to the confi ## 0.4.1: March 10, 2026 -This release fixes a bug in which editor overrides were read from one UserDefaults instance, but saved to another. +This release fixes a bug in which editor overrides were read from one UserDefaults instance, but +saved to another. ## 0.4.0: March 10, 2026 -This release adds a configuration editor written in SwiftUI. The editor allows consumers to view registered variable -values in a list, see the values of a variables across all the different providers, override values for development -and testing, and view variable metadata values. +This release adds a configuration editor written in SwiftUI. The editor allows consumers to view +registered variable values in a list, see the values of a variables across all the different +providers, override values for development and testing, and view variable metadata values. The UI has only meaningfully been tested on iOS. It has not been accessibility tested. ## 0.3.0: March 10, 2026 -This is a small release that updates `ConfigVariableReader` from a struct to a class to make variable registration -easier for consumers. +This is a small release that updates `ConfigVariableReader` from a struct to a class to make +variable registration easier for consumers. ## 0.2.0: March 10, 2026 -Adds the ability to register variables with `ConfigVariableReader`. This functionality is not yet used, but sets up -the public interface for consumers. +Adds the ability to register variables with `ConfigVariableReader`. This functionality is not yet +used, but sets up the public interface for consumers. ## 0.1.0: March 10, 2026 -Initial version of DevConfiguration with the ability to read variables, with scalar, array, `RawRepresentable`, and -`Codable` types. Also emits access telemetry on the event bus. +Initial version of DevConfiguration with the ability to read variables, with scalar, array, +`RawRepresentable`, and `Codable` types. Also emits access telemetry on the event bus. diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 1de11d5..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1,74 +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**: `xcodebuild build -scheme DevConfiguration -destination 'generic/platform=macOS'` - - **Test all**: `xcodebuild test -scheme DevConfiguration -destination 'platform=macOS'` - - **Test with coverage**: Use Xcode test plans in `Build Support/Test Plans/` - (DevConfiguration.xctestplan) - -### Code Quality - - - **Lint**: `Scripts/lint` (uses `swift format lint --recursive --strict`) - - **Format**: `Scripts/format` - - **Setup git hooks**: `Scripts/install-git-hooks` (lints on push) - -### 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 - - Requires Xcode 26.3 and macOS 26 runners - - -## Architecture Overview - -DevConfiguration is a type-safe configuration wrapper built on Apple's swift-configuration library. -It provides structured configuration management with access reporting via EventBus and extensible -metadata. - -### Source Structure - - - **Sources/DevConfiguration/Core/**: `ConfigVariable`, `ConfigVariableReader`, - `ConfigVariableContent`, `CodableValueRepresentation`, `RegisteredConfigVariable`, - and `ConfigVariableSecrecy` - - **Sources/DevConfiguration/Metadata/**: `ConfigVariableMetadata` and metadata key types - (`DisplayNameMetadataKey`) - - **Sources/DevConfiguration/Access Reporting/**: EventBus-based access and decoding events - -### Key Documents - - - **Documentation/TestingGuidelines.md**: Testing standards and patterns - - **Documentation/TestMocks.md**: Mock creation and usage guidelines - - **Documentation/DependencyInjection.md**: Dependency injection patterns - - **Documentation/MarkdownStyleGuide.md**: Documentation formatting standards - - **Documentation/MVVMForSwiftUI.md**: MVVM architecture for SwiftUI - - **Documentation/MVVMForSwiftUIBackground.md**: Background on MVVM design decisions - - -## Dependencies - -External dependencies managed via Swift Package Manager: - - - **swift-configuration** (Apple): Core configuration provider system - - **DevFoundation**: EventBus, utilities, networking - - **DevTesting**: Stub-based testing framework - - -## 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 - - All public APIs must be documented and tested - - Test coverage target: >99% - - SwiftUI views do not currently have automated tests \ No newline at end of file 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/MVVMForSwiftUI.md b/Documentation/MVVMForSwiftUI.md index 83116d0..f8708bb 100644 --- a/Documentation/MVVMForSwiftUI.md +++ b/Documentation/MVVMForSwiftUI.md @@ -1,18 +1,23 @@ +--- +description: The View/ViewModeling/ViewModel MVVM pattern used for SwiftUI screens in this codebase +read-when: Creating or reviewing a new SwiftUI screen’s View, ViewModeling protocol, and ViewModel +--- + # MVVM for SwiftUI This document defines the MVVM (model-view-view model) architecture pattern we use to write -SwiftUI code in the DevConfiguration codebase. For more background on this MVVM pattern, see +SwiftUI code in the codebase. For more background on this MVVM pattern, see [MVVMForSwiftUIBackground.md](MVVMForSwiftUIBackground.md). ## Overview -Our SwiftUI architecture is composed of thrre related types: a \*View, a \*ViewModeling, a -and \*ViewModel. Screens in the app will often have each of these three types, though it -depends on the screen’s complexity and requirements. Additional types for dependency +Our SwiftUI architecture is composed of three related types: a \*View, a \*ViewModeling, and a +\*ViewModel. Screens in the app will often have each of these three types, though it +depends on the screen’s complexity and requirements. Additional types for dependency injection are also common. -The following sections will demonstrate the types we would create for a "ItemList" screen: +The following sections will demonstrate the types we would create for an “ItemList” screen: ### ItemListViewModeling @@ -32,11 +37,11 @@ protocol to allow the view to react to changes in the view model. Next we define the view, which has no business logic and simply reflects the state of its single property, `viewModel`. The view uses a generic parameter named `ViewModel` that conforms to the -`ItemListViewModeling` protocol. The `viewModel` property is marked as `@State` so that the view -can react to changes in the view model. +`ItemListViewModeling` protocol. The view holds `viewModel` with `let` because its parent owns it; +see [Who Owns the View Model](#who-owns-the-view-model). struct ItemListView: View where ViewModel: ItemListViewModeling { - @State var viewModel: ViewModel + let viewModel: ViewModel var body: some View { List { @@ -48,6 +53,23 @@ can react to changes in the view model. } +### Who Owns the View Model + +How a view holds its view model depends on who owns it and what the view does with it: + + - **`@State`** when the view owns its view model. + - **`@Bindable var`** when a parent owns it and the view needs bindings to its properties. The + `*ViewModeling` protocol must then be `AnyObject, Observable`. + - **A plain `let`** when a parent owns it and the view only reads it or passes it along. The + view still updates when a property its `body` reads changes. Observation tracks those reads + without a property wrapper. + +`@State` keeps the first value it’s given and ignores values passed through `init` on later +rebuilds. A view whose parent may replace its view model must not hold it in `@State`. Since +Xcode 27, `@State` evaluates a default value at its declaration only once. A value passed through +`init` is still built on every rebuild and then discarded. + + ### ItemListViewModel Finally, we create a concrete representation of our view model by implementing the @@ -87,26 +109,26 @@ case. ### Putting It All Together -Typically, a parent view is responsible for creating the child view, using the parent view model to -create the child view model. The parent view model creates the child view model by instantiating it -with a dependency provider. - -We see this below with the `HomeView`/`HomeViewModel` pair. +A parent view model provides its child view models. It can create one up front or when it’s +needed, such as when the person navigates somewhere, but it creates each one once and keeps it +while it’s shown. A view’s `body` never creates a view model, because `body` runs every time the +view is rebuilt. In the example below, `HomeViewModel` creates its item list view model up front. @MainActor protocol HomeViewModeling: Observable { associatedtype SomeItemListViewModel: ItemListViewModeling - func makeItemListViewModel() -> SomeItemListViewModel + var itemListViewModel: SomeItemListViewModel { get } } @Observable - struct HomeViewModel: HomeViewModeling { - func makeItemListViewModel() -> ItemListViewModel { - return ItemListViewModel( - dependencies: .init( - itemFetcher: StandardItemFetcher() - ) + final class HomeViewModel: HomeViewModeling { + let itemListViewModel: ItemListViewModel + + + init() { + self.itemListViewModel = ItemListViewModel( + dependencies: .init(itemFetcher: StandardItemFetcher()) ) } } @@ -116,7 +138,7 @@ We see this below with the `HomeView`/`HomeViewModel` pair. @State var viewModel: ViewModel var body: some View { - ItemListView(viewModel: viewModel.makeItemListViewModel()) + ItemListView(viewModel: viewModel.itemListViewModel) } } @@ -144,7 +166,7 @@ by providing parameterless functions that the view can call to trigger state cha The view can then call the `addRow` function to add a new row to the list. struct ItemListView: View where ViewModel: ItemListViewModeling { - @State var viewModel: ViewModel + let viewModel: ViewModel var body: some View { @@ -166,6 +188,50 @@ The view can then call the `addRow` function to add a new row to the list. ## Misc. Instructions for AI +### File Organization + +When creating MVVM files, place them in a dedicated directory structure under the appropriate +parent folder. + ### Import Requirements - Always include `import SwiftUI` in view files. + +### ViewModeling Protocol Conventions + + - Group properties together logically (e.g. by the content they represent, or by the feature + area they support), and list functions after all properties. + - Skip doc comments on `*ViewModeling` properties by default — the property name should carry + the meaning. Only add one when the property’s behavior is genuinely unusual or requires + special handling that a reader wouldn’t otherwise expect (e.g. a flag that exists specifically + to drive a delayed side effect, or a value whose invalidation rule isn’t obvious from its + name). + +### ViewModel Property Organization + +Declare a view model’s stored properties in blank-line-separated groups, ordered from the most +externally visible to the most internal: + + 1. **Dependencies and configuration**: `dependencies` and any navigation data or other + parameters the view model was created with. + 2. **`*ViewModeling` state**: the `private(set)` properties that satisfy the protocol. + 3. **Internal state**: private properties, subdivided by function, one group per concern. + +Within the internal groups, keep a property next to the others that serve the same purpose. For +example, a feed and its renderer sit together, and a task sits with its cancellation identifier and +the objects it operates on. Don’t order by access level or by `let` versus `var`. + + @Observable + final class ExampleViewModel: ExampleViewModeling { + let dependencies: Dependencies + let navigationData: ExampleNavigationData + + private(set) var error: StandardContentErrorViewModel? + private(set) var isRefreshing = false + + private var feed: Feed? + private(set) var moduleListRenderer: ExampleModuleListRenderer? + + let loadingGroup = ExecutionGroup() + private var loadTask: Task? + } diff --git a/Documentation/MVVMForSwiftUIBackground.md b/Documentation/MVVMForSwiftUIBackground.md index f4ba4d0..6fc55e0 100644 --- a/Documentation/MVVMForSwiftUIBackground.md +++ b/Documentation/MVVMForSwiftUIBackground.md @@ -18,10 +18,10 @@ Before we begin, let’s discuss our goals. We’re interested in writing code t - *Testable*: building correct, adaptable, and maintainable code is very difficult without a large suite of automated tests. Thus we need to architect our code so that it is easy to test using standard unit and integration testing techniques. - - *Portable*: while we primarily write apps that target iOS, that may not always be the case. We - may support other Apple platforms—tvOS, watchOS, or macOS—or we may ship different kinds of - apps, e.g., iMessage extensions or command-line tools for testing. Our code should be portable - enough to enable these use cases. + - *Portable*: while we primarily write apps that target iOS, that may not always be the + case. We may support other Apple platforms—tvOS, watchOS, or macOS—or we may ship + different kinds of apps, e.g., iMessage extensions or command-line tools for testing. + Our code should be portable enough to enable these use cases. - *Efficient*: our code should always aim to efficiently use a device’s resources. We should avoid using any more CPU, memory, battery, or network data allocations than is needed. @@ -30,17 +30,18 @@ is one that the iOS community doesn’t often emphasize, but that we believe is reasoning about MVVM, you will make better architectural decisions if you don’t make assumptions about the types of UIs your code will support. Keep that in mind as you read this document. + ## A Quick Overview of MVVM It’s helpful to do a quick refresher of MVVM to make sure we all understand the roles of different components in the architecture. - - *Models* represent your application’s concepts and operations. That is, they “model” the problem - domain of your app, independent of any particular UI representation. The model layer is where - the real work of your app happens. Because it’s independent of the UI, it should be largely - reusable and portable. For example, the business logic involved in performing a restaurant - search, fetching a menu, and adding a menu item to a cart should work the same, regardless of - what your UI looks like. + - *Models* represent your application’s concepts and operations. That is, they “model” the + problem domain of your app, independent of any particular UI representation. The model layer is + where the real work of your app happens. Because it’s independent of the UI, it should be + largely reusable and portable. For example, the business logic involved in performing a + restaurant search, fetching a menu, and adding a menu item to a cart should work the same, + regardless of what your UI looks like. - *Views* represent the user interface of your application. While this obviously includes traditional parts of your UI, like buttons and screens, it also includes non-visual UI, like speech and textual interfaces. It could go so far as to include a scripting interface since that @@ -53,6 +54,7 @@ components in the architecture. View models also have functions that are used by the view to trigger business logic in response to user input. + ## SwiftUI and MVVM The core challenge with SwiftUI is that views are very difficult to test. They are structs that @@ -79,7 +81,8 @@ struct or nested DependencyProviding and DependencyProvider types. See our [Dependency Injection](DependencyInjection.md) guide for more details. - *View*: The view code. The view has no business logic and simply reflects the state of its view - model, which is a generic parameter named `ViewModel` that conforms to the \*ViewModeling protocol. + model, which is a generic parameter named `ViewModel` that conforms to the \*ViewModeling + protocol. - *ViewModeling*: A protocol that contains the minimal interface for the \*View to perform its function. Each contains properties that are used to store the view’s state, as well as enums that govern the view’s modals and alerts. diff --git a/Documentation/MarkdownStyleGuide.md b/Documentation/MarkdownStyleGuide.md index 9eb9615..d92d52f 100644 --- a/Documentation/MarkdownStyleGuide.md +++ b/Documentation/MarkdownStyleGuide.md @@ -1,7 +1,6 @@ # Markdown Style Guide -This document defines the Markdown formatting standards for documentation in the DevConfiguration -codebase. +This document defines the Markdown formatting standards for documentation in this project. ## General Formatting @@ -23,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: @@ -78,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: @@ -86,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() } ``` @@ -155,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..d43d6e4 --- /dev/null +++ b/Documentation/README.md @@ -0,0 +1,12 @@ +# DevConfiguration Documentation + +Guides for writing code and docs in DevConfiguration: + + - [Dependency Injection](DependencyInjection.md) + - [MVVM for SwiftUI](MVVMForSwiftUI.md) and its + [background](MVVMForSwiftUIBackground.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..d5ea9e0 --- /dev/null +++ b/Documentation/SwiftStyleGuide.md @@ -0,0 +1,115 @@ +--- +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. + - View models are `@MainActor` and `@Observable`. SwiftUI views that use a ViewModeling protocol + make it `@MainActor`. See [MVVM for SwiftUI](MVVMForSwiftUI.md). + - 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 afca4c9..0000000 --- a/Documentation/TestMocks.md +++ /dev/null @@ -1,483 +0,0 @@ -# Test Mock Documentation - -This document outlines the patterns and conventions for writing test mocks in Swift. - -Its helpful to read the [Dependency Injection guide](DependencyInjection.md) before reading this -guide, as it introduces core principles for how we think about dependency injection. - - -## Overview - -We use a consistent approach to mocking based on the DevTesting package's `Stub` and `ThrowingStub` -types. All mocks follow standardized patterns that make them predictable, testable, and -maintainable. - - -## When to Mock vs. Use Types Directly - -Create mock protocols when - - - The type has **non-deterministic behavior** (network calls, file I/O, time-dependent operations) - - You need to **control or observe the behavior** in tests - - The type's behavior **varies across environments** - -Use types directly when - - - The type has **deterministic, predictable behavior** - - Testing with the real implementation provides **sufficient coverage** - - Creating abstractions adds **complexity without testing benefits** - -It's worth pointing out that the following foundational types should be used directly. - - - **`NotificationCenter`**: Posting and observing notifications is predictable - - **`UserDefaults`**: Simple key-value storage with consistent behavior - - **`Bundle`**: Resource loading behavior is consistent and testable - - **`EventBus`**: Synchronous event dispatching with deterministic outcomes - - -## Core Mock Patterns - -### 1. Stub-Based Architecture - -All mocks use `DevTesting`'s `Stub` or `ThrowingStub` types -for function and property implementations: - - import DevTesting - - - final class MockService: ServiceProtocol { - nonisolated(unsafe) var performActionStub: Stub! - - - func performAction(_ input: String) -> Bool { - performActionStub(input) - } - } - -**Key characteristics:** - - - Properties are marked `nonisolated(unsafe)` for Swift 6 concurrency - - Stub properties are force-unwrapped (`!`). Tests must configure them. - - Function implementations simply call the corresponding stub - - -### 2. Argument Structures for Complex Parameters - -When functions have multiple parameters, create dedicated argument structures: - - final class MockTelemetryDestination: TelemetryDestination { - struct LogErrorArguments { - let error: any Error - let attributes: [String : any Encodable] - } - - - nonisolated(unsafe) var logErrorStub: Stub! - - - func logError(_ error: some Error, attributes: [String : any Encodable]) { - logErrorStub(.init(error: error, attributes: attributes)) - } - } - -**Benefits:** - - - Simplifies stub configuration in tests - - Provides clear parameter documentation - - Enables easy verification of function calls - - -### 3. Property-Only Services - -For services that only expose properties (like `MockAppServices`), each property delegates to a -stub: - - final class MockAppServices: PlatformAppServices { - nonisolated(unsafe) var stylesheetStub: Stub! - nonisolated(unsafe) var telemetryEventLoggerStub: Stub! - - - var stylesheet: Stylesheet { - stylesheetStub() - } - - - var telemetryEventLogger: any TelemetryEventLogging { - telemetryEventLoggerStub() - } - } - - -### 4. Generic Mock Types - -For protocols with associated types, create generic mocks: - - struct MockTelemetryEvent: TelemetryEvent - where EventData: Encodable & Sendable { - let name: TelemetryEventName - var eventData: EventData - } - - - extension MockTelemetryEvent: Equatable where EventData: Equatable { } - extension MockTelemetryEvent: Hashable where EventData: Hashable { } - - -**Pattern:** - - - Use generic parameters for flexible data types - - Add conditional conformances for `Equatable` and `Hashable` when possible - - Maintain protocol requirements while allowing test customization - - -### 5. Simple Error Mocks - -For testing error scenarios, use simple enum-based errors: - - enum MockError: Error, CaseIterable, Hashable, Sendable { - case error1 - case error2 - case error3 - } - -**Characteristics:** - - - Implement `CaseIterable` for easy test iteration - - Include `Hashable` and `Sendable` for Swift 6 compatibility - - Use descriptive but simple case names - - -## Mock Organization - -### File Structure and Organization - -#### Directory Structure: - Tests/ - ├── [PackageName]Tests/ # Package-specific tests - │ ├── Unit Tests/ - │ │ └── [ModuleName] # Feature-specific tests - │ │ └── [ProtocolName]Tests.swift - │ └── Testing Support/ # Mock objects and test utilities - │ ├── Mock[ProtocolName].swift # Mock implementations - │ ├── MockError.swift # Test-specific error types - │ └── RandomValueGenerating+[ModuleName].swift # Random value extensions - -#### File Placement Guidelines: - -- **Unit Test files**: Place in `Tests/[PackageName]/Unit Tests/`, matching the path of the source file in - the directory structure under `Sources/` -- **Mock objects**: Always place in `Tests/[PackageName]/Testing Support/` directories -- **One mock per file**: Each protocol should have its own dedicated mock file -- **Sharing mocks**: Do not share mocks between Packages. If the same Mock is needed across - multiple packages, duplicate it. - -### Naming Conventions - - - **File names**: `Mock[ProtocolName].swift` - - **Type names**: `Mock[ProtocolName]` - - **Argument structures**: `[FunctionName]Arguments` - - **Stub properties**: `[functionName]Stub` - - -## Special Patterns - -### 1. Static Stubs for Initializers - -When mocking types with custom initializers, use static stubs: - - final class MockSubapp: Subapp { - struct InitArguments { - let appConfiguration: AppConfiguration - let subappServices: any SubappServices - } - - - nonisolated(unsafe) static var initStub: Stub! - - - init(appConfiguration: AppConfiguration, subappServices: any SubappServices) async { - Self.initStub(.init(appConfiguration: appConfiguration, subappServices: subappServices)) - } - } - - -### 2. Default Stub Values - -For functions that might not be called in every test, provide default stub values: - - final class MockSubapp: Subapp { - // Initialize to non-nil to avoid crashes in tests that don't configure this stub - nonisolated(unsafe) var installTelemetryBusEventHandlersStub: Stub< - TelemetryBusEventObserver, - Void - > = .init() - } - -**CRITICAL - Stubs Accessed by Internal Async Tasks:** - -When testing types that spawn internal `Task`s during initialization, ALL stubs accessed by those -tasks must be initialized in test setup, even if not directly tested. Failure to initialize stubs -will cause crashes when the internal task tries to access them. - -This applies to ANY mock (Observable or not) whose stubs are accessed by background tasks. - -#### Why This is Required: - -When a type spawns internal `Task`s during initialization, those tasks may access properties or -functions on injected dependencies. If those dependencies are mocks with force-unwrapped stubs, and -the stubs haven't been initialized, the app will crash when the internal task tries to access them. - -**Example crash scenario:** - - // Any mock type (Observable or not) - @MainActor - final class MockDataSource: DataSource { - nonisolated(unsafe) var currentItemsStub: Stub! - var currentItems: [Item] { - currentItemsStub(id) // Crashes if stub is nil - } - } - - // Type spawns internal task during init - init(dataSource: any DataSource) { - self.dataSource = dataSource - Task { - // This accesses dataSource.currentItems, triggering the stub - let items = dataSource.currentItems - } - } - - // Test doesn't initialize the stub - @Test - func myTest() { - let mockDataSource = MockDataSource() // currentItemsStub is nil - let processor = ItemProcessor(dataSource: mockDataSource) // Crashes in internal task - } - -#### Solution Pattern: Initialize in Test Setup - -Initialize all stubs that internal tasks will access: - - @MainActor - struct ItemProcessorTests: RandomValueGenerating { - var mockDataSource = MockDataSource() - - init() { - // CRITICAL: Initialize ALL stubs that the type's internal tasks will access - // Even if this particular test doesn't verify these stubs, they must be non-nil - mockDataSource.fetchItemsStub = ThrowingStub(defaultError: nil) - mockDataSource.currentItemsStub = Stub(defaultReturnValue: []) - } - - @Test - mutating func myTest() async throws { - // Create type that spawns internal tasks using mockDataSource - let processor = ItemProcessor(dataSource: mockDataSource) - // ... test logic ... - } - } - -#### How to Identify Required Stubs: - - 1. Look for `Task { }` blocks in the type's initializer - 2. Trace what properties/functions those tasks access on dependencies - 3. Initialize stubs for all accessed properties/functions in test `init()` - 4. Run tests — crashes will identify any missed stubs - - -### 3. Prologue and Epilogue Closures for Execution Control - -For mock functions that need precise control over execution timing, use optional prologue and -epilogue closures that execute before and after the stub. - -#### Prologue Pattern - -Prologues execute before the stub is called: - - final class MockNetworkClient: NetworkClient { - nonisolated(unsafe) var sendRequestPrologue: (() async throws -> Void)? - nonisolated(unsafe) var sendRequestStub: ThrowingStub< - URLRequest, - Response, - any Error - >! - - - func sendRequest(_ request: URLRequest) async throws -> Response { - try await sendRequestPrologue?() - return try sendRequestStub(request) - } - } - -#### Epilogue Pattern - -Epilogues execute after the stub is called. Run the epilogue in a `Task` within a `defer` block: - - final class MockEventLogger: EventLogging { - nonisolated(unsafe) var logEventStub: Stub! - nonisolated(unsafe) var logEventEpilogue: (() async throws -> Void)? - - - func logEvent(_ event: some Event) { - defer { - if let epilogue = logEventEpilogue { - Task { try? await epilogue() } - } - } - logEventStub(event) - } - } - -#### Use Cases - -**Prologues** (execute before stub): - - - **Block before processing**: Delay the mock from executing its core behavior - - **Test pre-call state**: Verify conditions before the mock operation begins - - **Insert delays**: Add artificial timing before processing - - **Coordinate setup**: Ensure test conditions are ready before mock executes - -**Epilogues** (execute after stub): - - - **Signal completion**: Notify tests when the mock operation has finished - - **Test post-call state**: Verify conditions after the stub executes but before returning - - **Coordinate with background work**: Wait for fire-and-forget operations to complete - -#### Example: Blocking with AsyncStream - - let (signalStream, signaler) = AsyncStream.makeStream() - mockClient.sendRequestPrologue = { - await signalStream.first(where: { _ in true }) - } - mockClient.sendRequestStub = ThrowingStub(defaultReturnValue: .init()) - - // Start operation that calls the mock - instance.performAction() - - // Verify intermediate state while mock is blocked - await #expect(instance.isProcessing) - - // Signal completion to unblock - signaler.yield() - -#### Example: Signaling Completion with Epilogue - - let eventLogger = MockEventLogger() - eventLogger.logEventStub = Stub() - - let (signalStream, signaler) = AsyncStream.makeStream() - eventLogger.logEventEpilogue = { - signaler.yield() - } - - // Call function that triggers the mock (e.g., via event bus handler) - eventBus.post(SomeEvent()) - - // Wait for mock to complete - await signalStream.first { _ in true } - - // Verify the mock was called - #expect(eventLogger.logEventStub.calls.count == 1) - -#### Example: Adding Delays - - mockClient.sendRequestPrologue = { - try await Task.sleep(for: .milliseconds(100)) - } - -#### Benefits - - - Separates timing control (prologue/epilogue) from return values/errors (stub) - - Enables testing at different execution phases (before/after stub) - - More precise than arbitrary `Task.sleep()` delays in tests - - Eliminates race conditions from timing-based coordination - - Optional — tests can ignore if timing control isn't needed - - -### 4. Protocol Imports with @testable - -Import protocols under test with `@testable` when accessing internal details: - - import AppPlatform - @testable import protocol AppPlatform.PlatformAppServices - @testable import protocol Telemetry.TelemetryDestination - - -## Usage in Tests - -### 1. Typical Test Setup - - @Test - mutating func testEventLogging() throws { - let mockDestination = MockTelemetryDestination() - mockDestination.logEventStub = .init() // Initialize stub - - let logger = TelemetryEventLogger(telemetryDestination: mockDestination) - logger.logEvent(someEvent) - - // Verify the call was made - #expect(mockDestination.logEventStub.calls.count == 1) - - // Extract and verify arguments - let arguments = try #require(mockDestination.logEventStub.callArguments.first) - #expect(arguments.name == expectedEventName) - #expect(arguments.attributes["key"] as? String == "expectedValue") - } - - -### 2. Return Value Configuration - - @Test - func testServiceCall() { - let mockServices = MockAppServices() - mockServices.stylesheetStub = Stub(defaultReturnValue: .standard) - - let result = systemUnderTest.processWithServices(mockServices) - - // Verify the service was called - #expect(mockServices.stylesheetStub.calls.count == 1) - } - - -### 3. Argument Verification Patterns - - @Test - mutating func testComplexMethodCall() throws { - let mockDestination = MockTelemetryDestination() - mockDestination.logErrorStub = .init() - - let error = MockError.error1 - let attributes = ["key": "value"] - - logger.logError(error, attributes: attributes) - - // Verify call count - #expect(mockDestination.logErrorStub.calls.count == 1) - - // Extract and verify arguments - let arguments = try #require(mockDestination.logErrorStub.callArguments.first) - #expect(arguments.error as? MockError == error) - #expect(arguments.attributes["key"] as? String == "value") - } - - -## Best Practices - - 1. **Always configure stubs**: Force-unwrapped stubs will crash if not configured - 2. **Use argument structures**: Simplifies complex parameter verification - 3. **Leverage DevTesting**: Use the package's call tracking and verification capabilities - 4. **Keep mocks simple**: Avoid complex logic in mock implementations - 5. **Group related mocks**: Place mocks in appropriate Testing Support directories - 6. **Follow naming conventions**: Consistent naming improves maintainability - 7. **Use Swift Testing**: Leverage `@Test`, `#expect()`, and `#require()` for assertions - - -## Thread Safety - -All mocks use `nonisolated(unsafe)` markings for Swift 6 compatibility. This assumes: - - - Tests run on a single thread or properly synchronize access - - Stub configuration happens during test setup before concurrent access - - Mock usage patterns don't require additional synchronization - -When mocking concurrent code, consider additional synchronization mechanisms if needed. diff --git a/Documentation/Testing/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..ad5af39 --- /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 DevConfiguration. +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 DevConfiguration’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 Support/` 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..899fcfe --- /dev/null +++ b/Documentation/Testing/TestingGuidelines.md @@ -0,0 +1,245 @@ +--- +description: Swift Testing conventions, test structure, coverage rules, and DevConfiguration 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 DevConfiguration. +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 DevConfiguration test plan in Xcode, which also reports +coverage. The example app in `App/` builds with Xcode and has no 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 `ConfigVariableReaderTests`. + +### 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 Support/` 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/DevConfiguration/Core/` go in + `Tests/DevConfigurationTests/Unit Tests/Core/`. + - **Shared fixtures and helpers** go in the test target’s `Testing Support/` 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. + + +## DevConfiguration Specifics + +### SwiftUI Views + +SwiftUI views don’t have automated tests. Keep their logic in view models, which do. diff --git a/Documentation/TestingGuidelines.md b/Documentation/TestingGuidelines.md deleted file mode 100644 index 53e7773..0000000 --- a/Documentation/TestingGuidelines.md +++ /dev/null @@ -1,718 +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 - - **MVVM Testing**: See `@Documentation/MVVMForSwiftUI.md` for view model testing approaches - -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 f55b2e3..4204df2 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "bbbdb7212fb727d5c834927ac895df8ab4963c48c8553e7f6618b36673f23701", + "originHash" : "6f758be6a25ca1e9b83b6cbf4629ae8f1aacf7aaba9c78177eab6a6542ccf33e", "pins" : [ { "identity" : "devfoundation", @@ -15,8 +15,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/DevKitOrganization/DevTesting", "state" : { - "revision" : "9dea13f09c19c0521e9ff7b9f14fedb977423b99", - "version" : "1.5.0" + "revision" : "7df52d20dade53d58d818bb255236d45da26bbde", + "version" : "1.7.0" } }, { @@ -33,8 +33,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-async-algorithms.git", "state" : { - "revision" : "6c050d5ef8e1aa6342528460db614e9770d7f804", - "version" : "1.1.1" + "revision" : "9d349bcc328ac3c31ce40e746b5882742a0d1272", + "version" : "1.1.3" } }, { diff --git a/Package.swift b/Package.swift index 8dd5443..2c22280 100644 --- a/Package.swift +++ b/Package.swift @@ -1,10 +1,12 @@ -// swift-tools-version: 6.2 +// swift-tools-version: 6.4 import PackageDescription let swiftSettings: [SwiftSetting] = [ .enableUpcomingFeature("ExistentialAny"), + .enableUpcomingFeature("ImmutableWeakCaptures"), .enableUpcomingFeature("MemberImportVisibility"), + .enableUpcomingFeature("NonisolatedNonsendingByDefault"), ] let package = Package( @@ -19,13 +21,13 @@ let package = Package( products: [ .library( name: "DevConfiguration", - targets: ["DevConfiguration"] - ), + targets: ["DevConfiguration"], + ) ], dependencies: [ .package(url: "https://github.com/apple/swift-configuration", from: "1.1.0"), .package(url: "https://github.com/DevKitOrganization/DevFoundation.git", from: "1.8.1"), - .package(url: "https://github.com/DevKitOrganization/DevTesting", from: "1.5.0"), + .package(url: "https://github.com/DevKitOrganization/DevTesting", from: "1.7.0"), ], targets: [ .target( @@ -35,9 +37,9 @@ let package = Package( .product(name: "DevFoundation", package: "DevFoundation"), ], resources: [ - .process("Resources"), + .process("Resources") ], - swiftSettings: swiftSettings + swiftSettings: swiftSettings, ), .testTarget( name: "DevConfigurationTests", @@ -45,7 +47,7 @@ let package = Package( "DevConfiguration", "DevTesting", ], - swiftSettings: swiftSettings + swiftSettings: swiftSettings, ), - ] + ], ) diff --git a/README.md b/README.md index 1d31833..cfac1de 100644 --- a/README.md +++ b/README.md @@ -12,9 +12,9 @@ View our [changelog](CHANGELOG.md) to see what’s new. ## Development Requirements -DevConfiguration requires a Swift 6.2 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%. +DevConfiguration 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%. SwiftUI views do not currently have automated tests. [SwiftAPIDesignGuidelines]: https://swift.org/documentation/api-design-guidelines/ @@ -23,10 +23,9 @@ SwiftUI views do not currently have automated tests. To set up the development environment: - 1. Run `Scripts/install-git-hooks` to install pre-push hooks that automatically check - code formatting. - 2. Use `Scripts/lint` to manually check code formatting at any time. - 3. Use `Scripts/format` to automatically format code. + 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. ## Bugs and Feature Requests diff --git a/Scripts/format b/Scripts/format deleted file mode 100755 index d238184..0000000 --- a/Scripts/format +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash - -# Get the directory where this script is located -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" - -# Go to the repository root (one level up from Scripts) -REPO_ROOT="$(dirname "$SCRIPT_DIR")" - -# Run swift format with --in-place to fix formatting issues -swift format --in-place --recursive \ - "$REPO_ROOT/App/" \ - "$REPO_ROOT/Sources/" \ - "$REPO_ROOT/Tests/" diff --git a/Scripts/install-git-hooks b/Scripts/install-git-hooks deleted file mode 100755 index 56d6935..0000000 --- a/Scripts/install-git-hooks +++ /dev/null @@ -1,56 +0,0 @@ -#!/bin/bash - -# Get the directory where this script is located -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" - -# Go to the repository root (one level up from Scripts) -REPO_ROOT="$(dirname "$SCRIPT_DIR")" - -# Check if we're in a git repository and get the git directory -# This works for both regular repos and worktrees -cd "$REPO_ROOT" -if ! git rev-parse --git-dir > /dev/null 2>&1; then - echo "Error: Not in a git repository" - exit 1 -fi - -# Get the common git directory (shared across all worktrees) -GIT_COMMON_DIR="$(git rev-parse --git-common-dir)" -if [ ! -d "$GIT_COMMON_DIR" ]; then - echo "Error: Could not find git directory" - exit 1 -fi - -mkdir -p "$GIT_COMMON_DIR/hooks" - -# Function to install the pre-push hook -install_pre_push_hook() { - local pre_push_hook="$GIT_COMMON_DIR/hooks/pre-push" - - echo "Installing pre-push hook..." - - cat > "$pre_push_hook" << 'EOF' -#!/bin/bash - -# Resolve the repository root using git, which correctly handles worktrees -REPO_ROOT="$(git rev-parse --show-toplevel)" - -# Run the lint script -echo "Running lint check..." -if ! "$REPO_ROOT/Scripts/lint"; then - echo "Lint check failed. Please fix formatting issues before pushing." - exit 1 -fi - -echo "Lint check passed." -EOF - - chmod +x "$pre_push_hook" - echo "Pre-push hook installed successfully!" -} - -# Install the pre-push hook -install_pre_push_hook - -echo "All git hooks installed successfully!" -echo "The pre-push hook will run 'Scripts/lint' before each push." diff --git a/Scripts/lint b/Scripts/lint deleted file mode 100755 index d1e2d0a..0000000 --- a/Scripts/lint +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash - -# Get the directory where this script is located -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" - -# Go to the repository root (one level up from Scripts) -REPO_ROOT="$(dirname "$SCRIPT_DIR")" - -# Run swift format lint with full paths to preserve user's PWD -swift format lint --recursive --strict \ - "$REPO_ROOT/App/" \ - "$REPO_ROOT/Sources/" \ - "$REPO_ROOT/Tests/" diff --git a/Sources/DevConfiguration/Core/CodableValueRepresentation.swift b/Sources/DevConfiguration/Core/CodableValueRepresentation.swift index e6a103a..f4c6dc9 100644 --- a/Sources/DevConfiguration/Core/CodableValueRepresentation.swift +++ b/Sources/DevConfiguration/Core/CodableValueRepresentation.swift @@ -60,8 +60,8 @@ public struct CodableValueRepresentation: Sendable { /// Reads raw data synchronously from the reader based on this representation. /// - /// For string-backed representations, this reads a string value and converts it to `Data` using the representation’s - /// encoding. For data-backed representations, this reads a byte array and wraps it in `Data`. + /// For string-backed representations, this reads a string value and converts it to `Data` using the + /// representation’s encoding. For data-backed representations, this reads a byte array and wraps it in `Data`. /// /// - Parameters: /// - reader: The configuration reader to read from. @@ -165,8 +165,8 @@ public struct CodableValueRepresentation: Sendable { /// Watches for raw data changes from the reader based on this representation. /// - /// Each time the underlying configuration value changes, `onUpdate` is called with the new raw data (or `nil` if the - /// key is no longer present). + /// Each time the underlying configuration value changes, `onUpdate` is called with the new raw data (or `nil` if + /// the key is no longer present). /// /// - Parameters: /// - reader: The configuration reader to watch. diff --git a/Sources/DevConfiguration/Core/ConfigVariableContent.swift b/Sources/DevConfiguration/Core/ConfigVariableContent.swift index 989b8ab..9fc86e3 100644 --- a/Sources/DevConfiguration/Core/ConfigVariableContent.swift +++ b/Sources/DevConfiguration/Core/ConfigVariableContent.swift @@ -74,7 +74,8 @@ public struct ConfigVariableContent: Sendable where Value: Sendable { /// content type does not support editing. let parse: (@Sendable (_ input: String) -> ConfigContent?)? - /// Validates that a ``ConfigContent`` value can be decoded into a valid instance of the variable's destination type. + /// Validates that a ``ConfigContent`` value can be decoded into a valid instance of the variable’s destination + /// type. /// /// For primitive types where a successful parse guarantees a valid value, this is `nil`. For types like /// `RawRepresentable` enums or `Codable` values, this checks that the content actually maps to a valid instance of diff --git a/Sources/DevConfiguration/Core/RegisteredConfigVariable.swift b/Sources/DevConfiguration/Core/RegisteredConfigVariable.swift index 0fbc5b6..b0eca8f 100644 --- a/Sources/DevConfiguration/Core/RegisteredConfigVariable.swift +++ b/Sources/DevConfiguration/Core/RegisteredConfigVariable.swift @@ -53,7 +53,8 @@ public struct RegisteredConfigVariable: Sendable { /// editing. let parse: (@Sendable (_ input: String) -> ConfigContent?)? - /// Validates that a ``ConfigContent`` value can be decoded into a valid instance of the variable's destination type. + /// Validates that a ``ConfigContent`` value can be decoded into a valid instance of the variable’s destination + /// type. /// /// Returns `true` if the content is valid. When `nil`, a successful parse is considered sufficient validation. let validate: (@Sendable (_ content: ConfigContent) -> Bool)? diff --git a/Sources/DevConfiguration/Documentation.docc/Documentation.md b/Sources/DevConfiguration/Documentation.docc/Documentation.md index 3a9ab6b..2b3585a 100644 --- a/Sources/DevConfiguration/Documentation.docc/Documentation.md +++ b/Sources/DevConfiguration/Documentation.docc/Documentation.md @@ -1,41 +1,43 @@ # ``DevConfiguration`` -A type-safe wrapper around Swift Configuration with conveniences for type safety and app development. +A type-safe wrapper around Swift Configuration with conveniences for type safety and app +development. ## Overview -DevConfiguration is a type-safe configuration wrapper built on Apple’s Swift Configuration library. It provides -configuration management with extensible metadata, a variable management UI, and access logging via the event bus. +DevConfiguration is a type-safe configuration wrapper built on Apple’s Swift Configuration library. +It provides configuration management with extensible metadata, a variable management UI, and access +logging via the event bus. ## Topics ### Reading Variables -- ``ConfigVariable`` -- ``ConfigVariableReader`` + - ``ConfigVariable`` + - ``ConfigVariableReader`` ### Editor Interface -- ``ConfigVariableEditor`` + - ``ConfigVariableEditor`` ### Variable Metadata -- ``ConfigVariableMetadata`` -- ``ConfigVariableMetadataKey`` + - ``ConfigVariableMetadata`` + - ``ConfigVariableMetadataKey`` ### Access Reporting -- ``EventBusAccessReporter`` -- ``ConfigVariableAccessSucceededEvent`` -- ``ConfigVariableAccessFailedEvent`` -- ``ConfigVariableDecodingFailedEvent`` + - ``EventBusAccessReporter`` + - ``ConfigVariableAccessSucceededEvent`` + - ``ConfigVariableAccessFailedEvent`` + - ``ConfigVariableDecodingFailedEvent`` ### Supporting Types -- ``ConfigVariableContent`` -- ``CodableValueRepresentation`` -- ``EditorControl`` -- ``NamedConfigProvider`` -- ``RegisteredConfigVariable`` + - ``ConfigVariableContent`` + - ``CodableValueRepresentation`` + - ``EditorControl`` + - ``NamedConfigProvider`` + - ``RegisteredConfigVariable`` diff --git a/Tests/DevConfigurationTests/Testing Support/MockError.swift b/Tests/DevConfigurationTests/Testing Support/MockError.swift deleted file mode 100644 index 5888e67..0000000 --- a/Tests/DevConfigurationTests/Testing Support/MockError.swift +++ /dev/null @@ -1,10 +0,0 @@ -// -// MockError.swift -// DevConfiguration -// -// Created by Prachi Gauriar on 2/16/2026. -// - -struct MockError: Error, Hashable { - let id: String -} diff --git a/Tests/DevConfigurationTests/Testing Support/RandomValueGenerating+DevConfiguration.swift b/Tests/DevConfigurationTests/Testing Support/RandomValueGenerating+DevConfiguration.swift index 5deb728..957c4fd 100644 --- a/Tests/DevConfigurationTests/Testing Support/RandomValueGenerating+DevConfiguration.swift +++ b/Tests/DevConfigurationTests/Testing Support/RandomValueGenerating+DevConfiguration.swift @@ -91,11 +91,6 @@ extension RandomValueGenerating { } - mutating func randomError() -> MockError { - return MockError(id: randomAlphanumericString()) - } - - mutating func randomFloat64Array() -> [Float64] { return Array(count: randomInt(in: 0 ... 5)) { randomFloat64(in: -100_000 ... 100_000) } } diff --git a/Tests/DevConfigurationTests/Unit Tests/Access Reporting/ConfigVariableAccessFailedEventTests.swift b/Tests/DevConfigurationTests/Unit Tests/Access Reporting/ConfigVariableAccessFailedEventTests.swift index d8179aa..442f66d 100644 --- a/Tests/DevConfigurationTests/Unit Tests/Access Reporting/ConfigVariableAccessFailedEventTests.swift +++ b/Tests/DevConfigurationTests/Unit Tests/Access Reporting/ConfigVariableAccessFailedEventTests.swift @@ -27,6 +27,6 @@ struct ConfigVariableAccessFailedEventTests: RandomValueGenerating { // expect that the event stores the parameters #expect(event.key == key) - #expect(event.error as? MockError == error) + #expect(event.error as? ArbitraryError == error) } } diff --git a/Tests/DevConfigurationTests/Unit Tests/Access Reporting/ConfigVariableDecodingFailedEventTests.swift b/Tests/DevConfigurationTests/Unit Tests/Access Reporting/ConfigVariableDecodingFailedEventTests.swift index 2bc43b0..c66e2bd 100644 --- a/Tests/DevConfigurationTests/Unit Tests/Access Reporting/ConfigVariableDecodingFailedEventTests.swift +++ b/Tests/DevConfigurationTests/Unit Tests/Access Reporting/ConfigVariableDecodingFailedEventTests.swift @@ -19,7 +19,7 @@ struct ConfigVariableDecodingFailedEventTests: RandomValueGenerating { // set up let key = AbsoluteConfigKey(randomConfigKey()) let targetType: Any.Type = String.self - let error = MockError(id: randomAlphanumericString()) + let error = randomError() // exercise let event = ConfigVariableDecodingFailedEvent(key: key, targetType: targetType, error: error) @@ -27,6 +27,6 @@ struct ConfigVariableDecodingFailedEventTests: RandomValueGenerating { // expect #expect(event.key == key) #expect(event.targetType is String.Type) - #expect(event.error as? MockError == error) + #expect(event.error as? ArbitraryError == error) } } diff --git a/Tests/DevConfigurationTests/Unit Tests/Access Reporting/EventBusAccessReporterTests.swift b/Tests/DevConfigurationTests/Unit Tests/Access Reporting/EventBusAccessReporterTests.swift index c6e7292..9a54946 100644 --- a/Tests/DevConfigurationTests/Unit Tests/Access Reporting/EventBusAccessReporterTests.swift +++ b/Tests/DevConfigurationTests/Unit Tests/Access Reporting/EventBusAccessReporterTests.swift @@ -135,6 +135,6 @@ struct EventBusAccessReporterTests: RandomValueGenerating { // expect that a ConfigVariableAccessFailedEvent was posted with the error let postedEvent = try #require(await eventStream.first { _ in true }) #expect(postedEvent.key == key) - #expect(postedEvent.error as? MockError == error) + #expect(postedEvent.error as? ArbitraryError == error) } } diff --git a/Tests/DevConfigurationTests/Unit Tests/Editor/Config Variable List/ConfigVariableListViewModelTests.swift b/Tests/DevConfigurationTests/Unit Tests/Editor/Config Variable List/ConfigVariableListViewModelTests.swift index 579a7d6..fa60bc0 100644 --- a/Tests/DevConfigurationTests/Unit Tests/Editor/Config Variable List/ConfigVariableListViewModelTests.swift +++ b/Tests/DevConfigurationTests/Unit Tests/Editor/Config Variable List/ConfigVariableListViewModelTests.swift @@ -21,7 +21,7 @@ struct ConfigVariableListViewModelTests: RandomValueGenerating { var workingCopyDisplayName: String! let undoManager = UndoManager() - nonisolated(unsafe) var dismissStub: Stub<[RegisteredConfigVariable], Void>! + nonisolated(unsafe) var dismissStub = Stub<[RegisteredConfigVariable], Void>() init() { @@ -29,7 +29,6 @@ struct ConfigVariableListViewModelTests: RandomValueGenerating { userDefaults.removeObject(forKey: "editorOverrides") editorOverrideProvider = EditorOverrideProvider(userDefaults: userDefaults) workingCopyDisplayName = randomAlphanumericString() - dismissStub = Stub() } diff --git a/Tools/format b/Tools/format new file mode 100755 index 0000000..4d2d83e --- /dev/null +++ b/Tools/format @@ -0,0 +1,19 @@ +#!/bin/bash + +# Formats Swift with swift-format and Markdown with rumdl, in place. + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(dirname "$SCRIPT_DIR")" + +# Swift files and directories to format, relative to the repository root +SWIFT_PATHS=(Package.swift App Sources Tests) +swift_paths=("${SWIFT_PATHS[@]/#/$REPO_ROOT/}") + +exit_status=0 + +swift format --in-place --recursive "${swift_paths[@]}" || exit_status=1 + +# Rewrite Markdown using the rules in .rumdl.toml +"$SCRIPT_DIR/rumdl" fmt "$REPO_ROOT" || exit_status=1 + +exit "$exit_status" diff --git a/Tools/install-git-hooks b/Tools/install-git-hooks new file mode 100755 index 0000000..862c44e --- /dev/null +++ b/Tools/install-git-hooks @@ -0,0 +1,30 @@ +#!/bin/bash + +# Installs a pre-push hook that runs Tools/lint, so formatting problems are caught before CI sees +# them. The hook goes in the repository’s common Git directory, so it applies to every worktree. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(dirname "$SCRIPT_DIR")" + +cd "$REPO_ROOT" +GIT_COMMON_DIR="$(git rev-parse --path-format=absolute --git-common-dir)" +HOOKS_DIR="$GIT_COMMON_DIR/hooks" +mkdir -p "$HOOKS_DIR" + +cat > "$HOOKS_DIR/pre-push" << 'HOOK' +#!/bin/bash + +# Installed by Tools/install-git-hooks. Runs Tools/lint before pushing. +REPO_ROOT="$(git rev-parse --show-toplevel)" + +echo "Running Tools/lint…" +if ! "$REPO_ROOT/Tools/lint"; then + echo "Lint failed. Run Tools/format, or push with --no-verify to skip this check." + exit 1 +fi +HOOK + +chmod +x "$HOOKS_DIR/pre-push" +echo "Installed a pre-push hook that runs Tools/lint." diff --git a/Tools/lint b/Tools/lint new file mode 100755 index 0000000..d7a3304 --- /dev/null +++ b/Tools/lint @@ -0,0 +1,37 @@ +#!/bin/bash + +# Lints Swift with swift-format, the length of Swift comments, and Markdown with rumdl. Exits with a +# nonzero status if any check fails, after running all of them. + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(dirname "$SCRIPT_DIR")" + +# Swift files and directories to check, relative to the repository root +SWIFT_PATHS=(Package.swift App Sources Tests) +swift_paths=("${SWIFT_PATHS[@]/#/$REPO_ROOT/}") + +exit_status=0 + +swift format lint --strict --recursive "${swift_paths[@]}" || exit_status=1 + +# swift-format doesn’t check the length of standalone or documentation comments, so report those +# over its line length. Perl counts characters rather than bytes. Read the limit with Python rather +# than plutil, which only exists on macOS. +line_length="$(python3 -c 'import json, sys; print(json.load(open(sys.argv[1]))["lineLength"])' \ + "$REPO_ROOT/.swift-format")" +find "${swift_paths[@]}" -name '*.swift' -print0 2>/dev/null | + xargs -0 perl -CDS -sne ' + chomp; + if (m{^\s*//} && length($_) > $limit) { + printf STDERR "%s:%d:%d: error: [CommentLength] wrap this comment, which is %d characters long, to %d or fewer\n", + $ARGV, $., $limit + 1, length($_), $limit; + $found = 1; + } + close ARGV if eof; + END { exit 1 if $found } + ' -- -limit="$line_length" || exit_status=1 + +# Lint Markdown using the rules in .rumdl.toml +"$SCRIPT_DIR/rumdl" check "$REPO_ROOT" || exit_status=1 + +exit "$exit_status" diff --git a/Tools/rumdl b/Tools/rumdl new file mode 100755 index 0000000..5ecc6a7 --- /dev/null +++ b/Tools/rumdl @@ -0,0 +1,40 @@ +#!/bin/bash + +# Runs the pinned version of rumdl, installing it on first use. Pinning keeps local runs and CI on +# the same version, so a new rumdl release can’t change lint results until this version changes. +# Each version is installed once per user into a virtual environment in the user’s cache. + +set -euo pipefail + +RUMDL_VERSION="0.3.5" + +INSTALL_ROOT="${XDG_CACHE_HOME:-$HOME/.cache}/devkit" +INSTALL_DIR="$INSTALL_ROOT/rumdl-$RUMDL_VERSION" +RUMDL="$INSTALL_DIR/bin/rumdl" + +if [[ ! -x "$RUMDL" ]]; then + echo "Installing rumdl ${RUMDL_VERSION} into ${INSTALL_DIR}…" >&2 + mkdir -p "$INSTALL_ROOT" + + # Install into a temporary directory and move it into place, so a run that starts while + # another is installing never sees a partial installation. + staging_dir="$(mktemp -d "$INSTALL_ROOT/rumdl-staging.XXXXXX")" + trap 'rm -rf "$staging_dir"' EXIT + python3 -m venv "$staging_dir" + "$staging_dir/bin/pip" install --quiet --disable-pip-version-check "rumdl==$RUMDL_VERSION" >&2 + + # If another run finished first, keep its copy. exec below skips the EXIT trap, so clean up + # the staging directory here. + if [[ ! -e "$INSTALL_DIR" ]]; then + mv "$staging_dir" "$INSTALL_DIR" + fi + rm -rf "$staging_dir" + trap - EXIT + + if [[ ! -x "$RUMDL" ]]; then + echo "Error: couldn’t install rumdl ${RUMDL_VERSION}" >&2 + exit 1 + fi +fi + +exec "$RUMDL" "$@"