Robustly find the path to an executable target from within swift-testing

I’m writing some functional tests that work an executable target that I create with SwiftPM, and want to check in on the “most robust way” to get a path to the executable target from within the scope of a test/swift-testing.

In doing a bit of searching, there’s a mechanism to search using the FileManager and Bundles, especially if there’s a class where you can use the Bundle(for:)method and then compute/derive the result from there. (per a semi-related suggestion in Access file in tests with swift-testing)

I also saw some references (from LLM generated answers) to reference and build on getting a location from BUILT_PRODUCTS_DIR, and appending the executable name from there to derive a path. But I wasn’t sure if that was a guarantee, or an option that may or may not be passed in, and which - if either - is a more robust means across platforms (I’m aiming for macOS and Linux, but I’d ideally like to support Windows, Android, etc. if I can do so up front).

Is there a suggested path or provided API from swift-testing to help or support this kind of scenario?

When running tests, the executable target isn't built as a separate product. Rather, its object files are linked into the test target which is run, depending on platform, as either a hosted bundle or as an executable.

The new #bundle macro in Foundation is the approximate replacement for Bundle.init(for:) but, if you have a class handy, Bundle.init(for:) will do what you need.

2 Likes