Skip to content

Add mock generation for @Instantiable types#204

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

Add mock generation for @Instantiable types#204
dfed wants to merge 15 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 every @Instantiable type
  • Each mock builds the full dependency subtree inline, with every node overridable via optional closure parameters
  • New @SafeDIConfiguration properties: generateMocks and mockConditionalCompilation
  • New @Instantiable parameter: mockAttributes for global actor annotations the plugin can't detect
  • SafeDIMockPath nested enums describe where each dependency is created in the tree
  • Build plugin generates mock output files alongside DI tree files
  • Multi-module projects can add the plugin to all targets for per-module mocks
  • Updated README, Manual, and example projects

Known limitations (to address in follow-up)

  • Mock generation does not yet handle Instantiator<T>, ErasedInstantiator<T>, SendableInstantiator<T>, or SendableErasedInstantiator<T> property types
  • Mock generation does not yet handle erasedToConcreteExistential (protocol type erasure like AnyUserService)
  • Mock generation does not yet handle @Forwarded properties in transitive tree construction
  • Xcode project examples have generateMocks: false pending these fixes

Test plan

  • 9 new SafeDIToolMockGenerationTests covering: no deps, received deps, instantiated deps, full tree, mockAttributes, conditional compilation (DEBUG/nil/custom), generateMocks=false, extension types
  • Updated 18 SafeDIConfigurationMacroTests for new properties
  • 3 new InstantiableMacroTests for mockAttributes and SafeDIMockPath collision
  • Updated RootScannerTests for mock manifest entries and containsInstantiable
  • All 398 existing tests pass
  • Example Package Integration builds with plugin on all targets
  • 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 (34a266e).

Additional details and impacted files

Impacted file tree graph

@@                 Coverage Diff                 @@
##           dfed/root-scanner     #204    +/-   ##
===================================================
  Coverage              99.92%   99.93%            
===================================================
  Files                     40       41     +1     
  Lines                   3838     4376   +538     
===================================================
+ Hits                    3835     4373   +538     
  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 14 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>
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