Add mock generation for @Instantiable types#204
Draft
dfed wants to merge 32 commits intodfed/root-scannerfrom
Draft
Add mock generation for @Instantiable types#204dfed wants to merge 32 commits intodfed/root-scannerfrom
dfed wants to merge 32 commits intodfed/root-scannerfrom
Conversation
SafeDI now automatically generates `mock()` methods for every `@Instantiable` type, building full dependency subtrees with overridable closure parameters. New @SafeDIConfiguration properties: - `generateMocks: Bool` (default true) — controls mock generation - `mockConditionalCompilation: StaticString?` (default "DEBUG") — #if wrapping New @INSTANTIABLE parameter: - `mockAttributes: StaticString` — attributes for generated mock() (e.g. "@mainactor") Each mock gets a `SafeDIMockPath` enum with nested enums per dependency type, enabling callers to differentiate same-type dependencies at different tree paths. The build plugin now generates mock output files alongside DI tree files. Multi-module projects can add the plugin to all targets for per-module mocks. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dfed/root-scanner #204 +/- ##
=====================================================
+ Coverage 99.92% 99.93% +0.01%
=====================================================
Files 40 41 +1
Lines 3838 4440 +602
=====================================================
+ Hits 3835 4437 +602
Misses 3 3
🚀 New features to boost your workflow:
|
- Deduplicate mock generation for types with fulfillingAdditionalTypes - Add generateMocks/mockConditionalCompilation to ExampleMultiProjectIntegration config - Fix swiftformat lint issues in MockGenerator - Scope mock generation to target files to avoid multi-module duplicates Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Mock generation for Instantiator<T> and erasedToConcreteExistential types is not yet supported. Disable mocks in Xcode project examples (which use these features) while the SPM package examples work correctly. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The Xcode project needs the config file in its project.pbxproj to pick up generateMocks: false. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Remove unreachable isExtension branch from generateSimpleMock and unused defaultConstruction method. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…types - Rewrite SafeDIToolMockGenerationTests to use full output comparison (no `contains`), matching SafeDIToolCodeGenerationTests style - Add #Preview blocks using .mock() to views in both Xcode example projects - Re-enable generateMocks for Xcode example projects - MockGenerator: skip types with Instantiator deps (not yet supported) - MockGenerator: make params required (no default) for types not in type map - Track hasKnownMock per type entry for required vs optional params - Add test for extension-based type with nil conditional compilation - Add test for required parameter when type not in type map Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Types not in the type map (like AnyUserService) now get non-optional closure parameters (@escaping, no `?`) instead of optional closures with a broken default. This ensures the generated code compiles. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
For types instantiated with `erasedToConcreteExistential: true`, the mock now generates TWO parameters: one for the concrete type (DefaultMyService) and one for the erased wrapper (AnyMyService). The erased type's default wraps the concrete type: `AnyMyService(defaultMyService)`. Non-@INSTANTIABLE types now use non-optional @escaping closure parameters instead of optional closures, avoiding broken defaults. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
… coverage - MockGenerator now detects erasedToConcreteExistential relationships globally and auto-generates wrapping for received types (e.g., AnyUserService wraps DefaultUserService.mock()) - #Preview blocks simplified to NameEntryView.mock() and NoteView.mock(userName:) - Consolidated duplicate arg-matching branches in buildInlineConstruction - Added hasReceivedDepsInScope check for sourceType form - Added test for received erased type auto-wrapping - Added test for complex mock with nil conditional compilation Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
For received erased types (like @received AnyUserService), the mock now has only the erased type as a parameter — the concrete type (DefaultUserService) is built inline in the default construction: AnyUserService(DefaultUserService.mock()) For @Instantiated(erasedToConcreteExistential: true) at the root level, both the concrete and erased type remain parameters, with the erased type referencing the concrete variable. #Preview blocks simplified to zero manual construction. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Multiple branches receiving the same @received property - Protocol type fulfilled by fulfillingAdditionalTypes - Multiple roots each getting their own mock file - Construction ordering respects @received dependencies - Four-level deep tree with shared leaf threading 19 mock generation tests total. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The ExampleMultiProjectIntegration uses additionalDirectoriesToInclude for Subproject files. The Xcode plugin only scans target.inputFiles for mock entries, so Subproject types (DefaultUserService, UserDefaults) don't get generated mocks. The single-project example keeps .mock() #Previews since all its files are in the target. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Mock generation does not yet support types from additionalDirectoriesToInclude. The Xcode plugin only scans target.inputFiles for mock entries. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Add test for missing mockConditionalCompilation fix-it - Add test for mockConditionalCompilation without initializer - Add test for inline construction skipping default-valued arguments - Add test for RootScanner.outputFiles computed property - Remove unreachable defensive branches (force-unwrap known-good lookups) - Extract wrapInConditionalCompilation helper to fix coverage instrumentation - Simplify topological sort dependency check 413 tests, 0 uncovered new lines. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Remove hasUnsupportedDeps skip — all @INSTANTIABLE types now get mocks - TypeEntry gains enumName, paramLabel, isInstantiator, builtTypeForwardedProperties - Instantiator deps use property label as enum name - Default wraps inline tree in Instantiator { forwarded in ... } closure - Forwarded props become Instantiator closure parameters - Topological sort handles Instantiator deps (wait for captured parent vars) - No boundary — transitive deps inside Instantiator are parent mock params Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Test Instantiator<T> with forwarded properties (closure param) - Test Instantiator<T> without forwarded properties - Both verify enum naming, parameter types, and inline closure construction Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
When no @SafeDIConfiguration is found, generateMocks now defaults to false. Modules must explicitly opt in via @SafeDIConfiguration. Added enableMockGeneration parameter to test helper and test for the no-config default. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Types included via additionalDirectoriesToInclude are not scanned for mock generation. Document this limitation in the Manual and in the ExampleMultiProjectIntegration SafeDIConfiguration. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Test Instantiator with multiple forwarded properties (tuple destructuring) - Remove unused parameterLabel(for:) method - Update documentation: mock generation is per-module, not per-project Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Force unwraps are not the pattern in this codebase. Restore proper guard/else fallbacks in buildInlineConstruction. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Extension-based type with received deps (inline .instantiate()) - Extension-based type as inline construction target - Instantiator with default-valued built type argument Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Add SafeDIGenerator plugin dependency to Subproject Xcode framework target - Add @SafeDIConfiguration to Subproject with generateMocks: true - Re-enable generateMocks on main app target - Update #Preview blocks to use .mock() - Keep additionalDirectoriesToInclude for DI tree generation Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
All positive mock generation test assertions now use exact full-output
comparison. Only negative checks (!contains("extension")) remain for
tests verifying mocks are NOT generated.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Instantiator types always have hasKnownMock = true because the built type must be @INSTANTIABLE (validated upstream). The else branch was unreachable dead code. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Remove unreachable defensive branches (trust validated data, matching ScopeGenerator/DependencyTreeGenerator pattern of 0 uncovered lines) - Simplify arg building to use nil-coalescing on optional initializer - Keep extension type checks for .instantiate() calls - Add lazy self-instantiation cycle test (exercises topo sort cycle breaker) 422 tests, 0 uncovered lines in MockGenerator. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Remove unreachable empty-mock-file branch (manifest always has matching types) - Restore if-let pattern for mockConditionalCompilation to correctly handle nil (String??) vs absent config 0 uncovered lines in MockGenerator, 422 tests pass. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Replace dictionary force unwraps with optional chaining (?.pathCases.append) and force-unwrapped first with guard/continue. No behavioral change. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
dfed
commented
Apr 1, 2026
- Every test now asserts exact mockFiles.count - Every test now checks ALL mock files with == comparison - Remove unreachable else "DEBUG" branch (sourceConfiguration is guaranteed non-nil when generateMocks is true) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
41 test functions covering: onlyIfAvailable, aliased properties, any protocol types, ErasedInstantiator, SendableInstantiator, SendableErasedInstantiator, multiple layers of Instantiators, complex interdependent dependency graphs, aliased+existential combos. Every test asserts exact mockFiles.count and == on all output files. 433 tests total, 3800+ lines of mock generation tests. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
SafeDI now automatically generates
mock()methods for@Instantiabletypes, with full dependency tree support includingInstantiator<T>,erasedToConcreteExistential, and@Forwardedproperties.New features
@Instantiabletype gets amock()static method that builds its full dependency subtree inline, with every node overridable via optional closure parametersSafeDIMockPathenums: CapitalCase nested enums per dependency type describe where each dependency is created in the tree (case parent,case root,case childA, etc.)Instantiator<T>support: Mock wraps inline tree inInstantiator { forwarded in ... }closure. Forwarded properties become closure parameters. Transitive deps flow through from parent scope.erasedToConcreteExistentialsupport: Auto-wraps concrete types in erased wrappers (e.g.,AnyUserService(DefaultUserService.mock()))@SafeDIConfigurationproperties:generateMocks: BoolandmockConditionalCompilation: StaticString?@Instantiableparameter:mockAttributes: StaticStringfor global actor annotations (e.g.,@MainActor)SafeDIGeneratorplugin generates mocks for its own types. Mock generation defaults tofalsewhen no@SafeDIConfigurationexists.Example project updates
#Previewblocks updated to use.mock()with zero manual construction@SafeDIConfigurationfor per-module mock generation.#Previewblocks use.mock().Documentation
@SafeDIConfigurationexamples updated with mock propertiesmockAttributes, forwarded properties, and multi-module setupTesting
==comparison (nocontainsassertions)Instantiator<T>with/without forwarded properties,erasedToConcreteExistential, extension-based types, deep nesting, multiple branches, protocol fulfillment, lazy self-instantiation cycles, default-valued arguments, conditional compilation variations, and moreTest plan
swift test)swift test --enable-code-coverage)swift build)xcrun xcodebuild)xcrun xcodebuild)swiftformat)🤖 Generated with Claude Code