Skip to content

Add mock generation for @Instantiable types#204

Draft
dfed wants to merge 32 commits intodfed/root-scannerfrom
dfed--mock-gen
Draft

Add mock generation for @Instantiable types#204
dfed wants to merge 32 commits intodfed/root-scannerfrom
dfed--mock-gen

Conversation

@dfed
Copy link
Copy Markdown
Owner

@dfed dfed commented Apr 1, 2026

Summary

SafeDI now automatically generates mock() methods for @Instantiable types, with full dependency tree support including Instantiator<T>, erasedToConcreteExistential, and @Forwarded properties.

New features

  • Mock generation: Each @Instantiable type gets a mock() static method that builds its full dependency subtree inline, with every node overridable via optional closure parameters
  • SafeDIMockPath enums: 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 in Instantiator { forwarded in ... } closure. Forwarded properties become closure parameters. Transitive deps flow through from parent scope.
  • erasedToConcreteExistential support: Auto-wraps concrete types in erased wrappers (e.g., AnyUserService(DefaultUserService.mock()))
  • @SafeDIConfiguration properties: generateMocks: Bool and mockConditionalCompilation: StaticString?
  • @Instantiable parameter: mockAttributes: StaticString for global actor annotations (e.g., @MainActor)
  • Per-module mock generation: Each module with SafeDIGenerator plugin generates mocks for its own types. Mock generation defaults to false when no @SafeDIConfiguration exists.

Example project updates

  • Example Package Integration: Plugin added to all targets. Mocks generated for all modules.
  • ExampleProjectIntegration: #Preview blocks updated to use .mock() with zero manual construction
  • ExampleMultiProjectIntegration: Subproject framework target now has SafeDIGenerator plugin and @SafeDIConfiguration for per-module mock generation. #Preview blocks use .mock().
  • ExamplePrebuiltPackageIntegration: Plugin added to all targets.

Documentation

  • README: @SafeDIConfiguration examples updated with mock properties
  • Manual: New "Mock generation" section covering configuration, usage, path enums, mockAttributes, forwarded properties, and multi-module setup

Testing

  • 422 tests total (29 mock generation tests + 393 existing)
  • 0 uncovered new lines in MockGenerator
  • All tests use exact full-output == comparison (no contains assertions)
  • Coverage: 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 more

Test plan

  • 422 tests pass (swift test)
  • 0 uncovered new lines (swift test --enable-code-coverage)
  • Example Package Integration builds (swift build)
  • ExampleProjectIntegration builds (xcrun xcodebuild)
  • ExampleMultiProjectIntegration builds (xcrun xcodebuild)
  • Lint clean (swiftformat)
  • CI passes

🤖 Generated with Claude Code

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
Copy link
Copy Markdown

codecov bot commented Apr 1, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.93%. Comparing base (8a8c8e1) to head (5f7caf4).

Additional details and impacted files

Impacted file tree graph

@@                  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              
Files with missing lines Coverage Δ
...ICore/Errors/FixableSafeDIConfigurationError.swift 100.00% <100.00%> (ø)
...eDICore/Extensions/AttributeSyntaxExtensions.swift 100.00% <100.00%> (ø)
...afeDICore/Generators/DependencyTreeGenerator.swift 100.00% <100.00%> (ø)
Sources/SafeDICore/Generators/MockGenerator.swift 100.00% <100.00%> (ø)
Sources/SafeDICore/Models/InstantiableStruct.swift 100.00% <100.00%> (ø)
...ources/SafeDICore/Models/SafeDIConfiguration.swift 100.00% <100.00%> (ø)
Sources/SafeDICore/Models/SafeDIToolManifest.swift 100.00% <100.00%> (ø)
...rces/SafeDICore/Visitors/InstantiableVisitor.swift 100.00% <100.00%> (ø)
...feDICore/Visitors/SafeDIConfigurationVisitor.swift 100.00% <100.00%> (ø)
...ources/SafeDIMacros/Macros/InstantiableMacro.swift 100.00% <100.00%> (ø)
... and 3 more
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

dfed and others added 28 commits April 1, 2026 01:31
- 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 and others added 3 commits April 1, 2026 11:19
- 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant