🔍 Simplify test resource lookup

This commit is contained in:
Chris Araman 2021-04-28 14:56:24 -07:00
parent 5f1e3afc95
commit c238585df8
No known key found for this signature in database
GPG key ID: BB4499D9E11B61E0

View file

@ -13,7 +13,6 @@ extension Data {
/// - Parameter file: Relative path within the JSON folder
init(from fileName: String) {
let fileURL = Bundle.url(for: fileName)!
print("fileURL: \(fileURL)")
try! self.init(contentsOf: fileURL, options: .mappedIfSafe)
}
}
@ -24,28 +23,30 @@ extension Bundle {
/// - Parameter fileName: Name of file to locate.
/// - Returns: URL to file.
static func url(for fileName: String) -> URL? {
var bundle = Bundle(for: NetworkSessionMock.self)
#if SWIFT_PACKAGE
// The Swift Package Manager places resources in a separate bundle from the executable.
bundle =
Bundle(url: bundle.bundleURL.deletingLastPathComponent().appendingPathComponent("mas_MasKitTests.bundle"))!
#endif
return bundle.url(for: fileName)
// https://forums.swift.org/t/swift-5-3-spm-resources-in-tests-uses-wrong-bundle-path/37051
let bundleURL = Bundle(for: NetworkSessionMock.self)
.bundleURL
.deletingLastPathComponent()
.appendingPathComponent("mas_MasKitTests.bundle")
guard let bundle = Bundle(url: bundleURL),
let url = bundle.url(for: fileName)
else {
fatalError("Unable to load file \(fileName)")
}
return url
}
/// Builds a URL for a file in the JSON directory of the current bundle.
///
/// - Parameter fileName: Name of file to locate.
/// - Returns: URL to file.
func url(for fileName: String) -> URL? {
guard
let url = self.url(
forResource: fileName.fileNameWithoutExtension,
withExtension: fileName.fileExtension,
subdirectory: "JSON"
)
else { fatalError("Unable to load file \(fileName)") }
return url
private func url(for fileName: String) -> URL? {
url(
forResource: fileName.fileNameWithoutExtension,
withExtension: fileName.fileExtension,
subdirectory: "JSON"
)
}
}