mirror of
https://github.com/affaan-m/ECC.git
synced 2026-09-17 23:28:04 +02:00
* fix(skills): move version into metadata and normalize to semver 29 skills declared `version` at the top level of their frontmatter. The schema reads it from `metadata`, so tooling that follows the schema either misses it or has to special-case the top level. Three motion skills also declared `version: 1.0`, which is not a valid semantic version; normalized to `1.0.0`. No behavioral change — frontmatter metadata only. * fix(skills): state activation triggers in skill descriptions 148 skills described what they cover but never named the situation that should trigger them. Since the description is what Claude matches against to decide whether to load a skill, a description without a trigger makes activation guesswork — the skill is either missed or loaded at the wrong time. Added a "Use when ..." clause to each, derived from the skill's own body (most already stated the trigger under "## When to Use" or in the opening line; that intent is now reflected in the frontmatter where it is actually read from). Descriptions were only appended to; no existing wording was removed. * fix(skills): sync activation triggers into the Codex skill mirror 10 of the skills whose descriptions changed are also mirrored under `.agents/skills/`, where the description was previously a verbatim copy. Left alone, the two surfaces would disagree about when the skill applies. Only the description line is synced; the Codex copies keep their reduced frontmatter, since that validator accepts only name, description, metadata, license, and allowed-tools. * fix(skills): correct three activation clauses from review - autonomous-loops: the clause pulled new loop work into a skill that its own body marks as a compatibility shim retained for one release. It now points at the canonical continuous-agent-loop instead. - continuous-learning: the description carried the v1 routing directive twice; collapsed to one. - homelab-pihole-dns: the clause fired on any broken home DNS. Narrowed to tasks that actually involve Pi-hole. * chore: retain current main lockfile --------- Co-authored-by: Çağrı Solakoğlu <cagri.solakoglu@vtcenerji.com> Co-authored-by: haelyra <49814733+haelyra@users.noreply.github.com>
192 lines
6.0 KiB
Markdown
192 lines
6.0 KiB
Markdown
---
|
|
name: swift-protocol-di-testing
|
|
description: Protocol-based dependency injection for testable Swift code — mock file system, network, and external APIs using focused protocols and Swift Testing. Use when Swift code needs testing and file system, network, or external APIs must be mocked.
|
|
metadata:
|
|
origin: ECC
|
|
---
|
|
|
|
# Swift Protocol-Based Dependency Injection for Testing
|
|
|
|
Patterns for making Swift code testable by abstracting external dependencies (file system, network, iCloud) behind small, focused protocols. Enables deterministic tests without I/O.
|
|
|
|
## When to Activate
|
|
|
|
- Writing Swift code that accesses file system, network, or external APIs
|
|
- Need to test error handling paths without triggering real failures
|
|
- Building modules that work across environments (app, test, SwiftUI preview)
|
|
- Designing testable architecture with Swift concurrency (actors, Sendable)
|
|
|
|
## Core Pattern
|
|
|
|
### 1. Define Small, Focused Protocols
|
|
|
|
Each protocol handles exactly one external concern.
|
|
|
|
```swift
|
|
// File system access
|
|
public protocol FileSystemProviding: Sendable {
|
|
func containerURL(for purpose: Purpose) -> URL?
|
|
}
|
|
|
|
// File read/write operations
|
|
public protocol FileAccessorProviding: Sendable {
|
|
func read(from url: URL) throws -> Data
|
|
func write(_ data: Data, to url: URL) throws
|
|
func fileExists(at url: URL) -> Bool
|
|
}
|
|
|
|
// Bookmark storage (e.g., for sandboxed apps)
|
|
public protocol BookmarkStorageProviding: Sendable {
|
|
func saveBookmark(_ data: Data, for key: String) throws
|
|
func loadBookmark(for key: String) throws -> Data?
|
|
}
|
|
```
|
|
|
|
### 2. Create Default (Production) Implementations
|
|
|
|
```swift
|
|
public struct DefaultFileSystemProvider: FileSystemProviding {
|
|
public init() {}
|
|
|
|
public func containerURL(for purpose: Purpose) -> URL? {
|
|
FileManager.default.url(forUbiquityContainerIdentifier: nil)
|
|
}
|
|
}
|
|
|
|
public struct DefaultFileAccessor: FileAccessorProviding {
|
|
public init() {}
|
|
|
|
public func read(from url: URL) throws -> Data {
|
|
try Data(contentsOf: url)
|
|
}
|
|
|
|
public func write(_ data: Data, to url: URL) throws {
|
|
try data.write(to: url, options: .atomic)
|
|
}
|
|
|
|
public func fileExists(at url: URL) -> Bool {
|
|
FileManager.default.fileExists(atPath: url.path)
|
|
}
|
|
}
|
|
```
|
|
|
|
### 3. Create Mock Implementations for Testing
|
|
|
|
```swift
|
|
public final class MockFileAccessor: FileAccessorProviding, @unchecked Sendable {
|
|
public var files: [URL: Data] = [:]
|
|
public var readError: Error?
|
|
public var writeError: Error?
|
|
|
|
public init() {}
|
|
|
|
public func read(from url: URL) throws -> Data {
|
|
if let error = readError { throw error }
|
|
guard let data = files[url] else {
|
|
throw CocoaError(.fileReadNoSuchFile)
|
|
}
|
|
return data
|
|
}
|
|
|
|
public func write(_ data: Data, to url: URL) throws {
|
|
if let error = writeError { throw error }
|
|
files[url] = data
|
|
}
|
|
|
|
public func fileExists(at url: URL) -> Bool {
|
|
files[url] != nil
|
|
}
|
|
}
|
|
```
|
|
|
|
### 4. Inject Dependencies with Default Parameters
|
|
|
|
Production code uses defaults; tests inject mocks.
|
|
|
|
```swift
|
|
public actor SyncManager {
|
|
private let fileSystem: FileSystemProviding
|
|
private let fileAccessor: FileAccessorProviding
|
|
|
|
public init(
|
|
fileSystem: FileSystemProviding = DefaultFileSystemProvider(),
|
|
fileAccessor: FileAccessorProviding = DefaultFileAccessor()
|
|
) {
|
|
self.fileSystem = fileSystem
|
|
self.fileAccessor = fileAccessor
|
|
}
|
|
|
|
public func sync() async throws {
|
|
guard let containerURL = fileSystem.containerURL(for: .sync) else {
|
|
throw SyncError.containerNotAvailable
|
|
}
|
|
let data = try fileAccessor.read(
|
|
from: containerURL.appendingPathComponent("data.json")
|
|
)
|
|
// Process data...
|
|
}
|
|
}
|
|
```
|
|
|
|
### 5. Write Tests with Swift Testing
|
|
|
|
```swift
|
|
import Testing
|
|
|
|
@Test("Sync manager handles missing container")
|
|
func testMissingContainer() async {
|
|
let mockFileSystem = MockFileSystemProvider(containerURL: nil)
|
|
let manager = SyncManager(fileSystem: mockFileSystem)
|
|
|
|
await #expect(throws: SyncError.containerNotAvailable) {
|
|
try await manager.sync()
|
|
}
|
|
}
|
|
|
|
@Test("Sync manager reads data correctly")
|
|
func testReadData() async throws {
|
|
let mockFileAccessor = MockFileAccessor()
|
|
mockFileAccessor.files[testURL] = testData
|
|
|
|
let manager = SyncManager(fileAccessor: mockFileAccessor)
|
|
let result = try await manager.loadData()
|
|
|
|
#expect(result == expectedData)
|
|
}
|
|
|
|
@Test("Sync manager handles read errors gracefully")
|
|
func testReadError() async {
|
|
let mockFileAccessor = MockFileAccessor()
|
|
mockFileAccessor.readError = CocoaError(.fileReadCorruptFile)
|
|
|
|
let manager = SyncManager(fileAccessor: mockFileAccessor)
|
|
|
|
await #expect(throws: SyncError.self) {
|
|
try await manager.sync()
|
|
}
|
|
}
|
|
```
|
|
|
|
## Best Practices
|
|
|
|
- **Single Responsibility**: Each protocol should handle one concern — don't create "god protocols" with many methods
|
|
- **Sendable conformance**: Required when protocols are used across actor boundaries
|
|
- **Default parameters**: Let production code use real implementations by default; only tests need to specify mocks
|
|
- **Error simulation**: Design mocks with configurable error properties for testing failure paths
|
|
- **Only mock boundaries**: Mock external dependencies (file system, network, APIs), not internal types
|
|
|
|
## Anti-Patterns to Avoid
|
|
|
|
- Creating a single large protocol that covers all external access
|
|
- Mocking internal types that have no external dependencies
|
|
- Using `#if DEBUG` conditionals instead of proper dependency injection
|
|
- Forgetting `Sendable` conformance when used with actors
|
|
- Over-engineering: if a type has no external dependencies, it doesn't need a protocol
|
|
|
|
## When to Use
|
|
|
|
- Any Swift code that touches file system, network, or external APIs
|
|
- Testing error handling paths that are hard to trigger in real environments
|
|
- Building modules that need to work in app, test, and SwiftUI preview contexts
|
|
- Apps using Swift concurrency (actors, structured concurrency) that need testable architecture
|