I’m making an attempt to create a macro to help in testing on a manufacturing app and have been making an attempt a good few various things. Extra element:
Desired Consequence:
Within the challenge we’ve got lots of protocols, so given the under:
protocol Foo {
var bar: Bool { get }
func fooBar() -> Bool
}
We need to create a @Testable
that will we’d use like so:
@Testable
ultimate class FooSpy: Foo { }
This class can be outlined within the Testing bundle and we might anticipate the macro to broaden into:
ultimate class FooSpy: Foo {
var bar: Bool
var fooBarExpectation = XCTestExpectation()
var fooBarToReturn: Bool = false
func fooBar() -> Bool {
fooBarExpectation.fullFill()
return fooBarToReturn
}
}
Strategy
I’ve managed to create a PeerMacro
that does the above by setting the protocol
as @Testable
. The difficulty is that the macro expands in place the place the protocol is and as such numerous testing associated code would not compile because of lack of imports and so forth.
I then went on to try to make an ExtensionMacro in order that I may mark the Take a look at class as @Testable
which is contained in the take a look at goal and thus has the required imports. The difficulty is, that with this strategy I do not appear to get entry to the Protocols
conformance necessities. Code under
public struct Testable: ExtensionMacro {
personal static let extractor = Extractor()
public static func enlargement(of node: SwiftSyntax.AttributeSyntax,
attachedTo declaration: some SwiftSyntax.DeclGroupSyntax,
providingExtensionsOf sort: some SwiftSyntax.TypeSyntaxProtocol,
conformingTo protocols: [SwiftSyntax.TypeSyntax],
in context: some SwiftSyntaxMacros.MacroExpansionContext) throws -> [SwiftSyntax.ExtensionDeclSyntax] {
// Right here I am making an attempt to get the protocol particulars (extractor under):
let protocolDeclaration = strive extractor.extractProtocolDeclaration(from: declaration)
Extractor:
struct Extractor {
func extractClassDeclaration(
from declaration: DeclGroupSyntax
) throws -> ProtocolDeclSyntax {
guard let protocolDeclaration = declaration.as(ProtocolDeclSyntax) else {
throw TestableMacroError.invalidProtocol
}
return protocolDeclaration
}
}
The plain problem is that with the ExtensionMacro
, the declaration
is now not the identical as when it is a PeerMacro
so this code would not work.
How can I (if i even can) get the protocol particulars from a DeclGroupSyntax
?