How to make a function only callable from tests?

i have a function that is defined like this:

extension Outliner
{
    @_spi(testable)
    public consuming
    func outlines() -> [Outline]
    {
        self.cache.clear()
    }
}

it is gated by the @_spi(testable) already, but i want to go even further and prevent this function from being called from within the module in which it resides, as its only purpose is to provide a testing hook for checking assertions. what is the best way to do this?

1 Like

I think you can gate compilation on if XCTest can be imported, but I haven’t tried it in a while:

#if canImport(XCTest)
…
#endif

alas, these test targets are not true SPM test targets, rather they are just ordinary executableTargets.

Just wondering if it would make sense to create an extension in your test target and add that function outlines?

Could you just have a custom define on that target that accomplishes the same thing then? .executableTarget's swiftSettings argument has a .define factory method.

Curious as well how this can be solved.

this was one of the first things i tried, but the define flags only affect the target they are applied to; they are not recursively propagated to its dependencies.

1 Like