Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inconsistent Output for Protocols with Associated Types #1393

Open
levan9999 opened this issue Jan 3, 2025 · 1 comment
Open

Inconsistent Output for Protocols with Associated Types #1393

levan9999 opened this issue Jan 3, 2025 · 1 comment

Comments

@levan9999
Copy link

levan9999 commented Jan 3, 2025

I use Sourcery in my iOS project to generate mocks for a protocol that conforms to another protocol with associated types. Despite consistent input, the generated output from Sourcery is not consistent. Sometimes the output is correct, but other times it's incorrect, defining Mock as a class with only init.

Here is my AutoMockable.stencil: https://gist.github.com/levan9999/212647d48ef372e025d5794543ab303c

Here’s my setup:

public protocol Foo {
    associatedtype Input
    associatedtype Output
    associatedtype Failure: Error

    @discardableResult
    func bar(parameters: Input) -> AnyPublisher<Output, Failure>
}

// sourcery: AutoMockable
public protocol Bar: Foo
where Input == String,
      Output == Bool,
      Failure == Never { }

Output:

public class Bar: Foo {
    public init() {}
}

However sometimes the output is correct:

public class Bar: Foo {

    public init() {}

    public var barCallsCount = 0
    public var barCalled: Bool { barCallsCount > 0 }
    public var barReturnValue: AnyPublisher<[String], Never>!
    public var barClosure: (() -> AnyPublisher<[String], Never>)?

    public func bar() -> AnyPublisher<[String], Never> {
        barCallsCount += 1
        if let barClosure = barClosure {
            return barClosure()
        } else {
            return barReturnValue
        }
    }
}

How can I ensure Sourcery consistently generates the correct mock for protocols with associated types and type constraints?

Sourcery: 2.2.6
Xcode: 16.1
Language: Swift 6

@levan9999
Copy link
Author

After some investigation, I identified the problem:
I use modular architecture and the issue was that Sourcery couldn't resolve a parent protocol located in another module when generating mocks for a child protocol in the current module. Since Sourcery processes only the specified source files, it lacked the necessary context for the parent protocol.

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

No branches or pull requests

1 participant