mas/Tests/masTests/Extensions/Bundle+JSON.swift
Ross Goldberg d413d8cfa1
Move MasKit module to mas.
Move MasKitTests module to masTests.

Rename MasKit enum as Mas.

Upgrade swift-tools-version from 5.3 to 5.6.1.

swift-tools-version 5.5+ is necessary to allow test code to import executable target code,
to allow MasKit library code to be moved into the mas executable.

Upgrade to swift-tools-version to 5.6.1 instead of to 5.5 because they support all the same macOS versions.

Standardize comments.

Signed-off-by: Ross Goldberg <484615+rgoldberg@users.noreply.github.com>
2024-10-14 03:44:03 -04:00

52 lines
1.6 KiB
Swift

//
// Bundle+JSON.swift
// masTests
//
// Created by Ben Chatelain on 1/5/19.
// Copyright © 2019 mas-cli. All rights reserved.
//
import Foundation
extension Data {
/// Unsafe initializer for loading data from string paths.
/// - Parameter file: Relative path within the JSON folder
init(from fileName: String) {
let fileURL = Bundle.url(for: fileName)!
try! self.init(contentsOf: fileURL, options: .mappedIfSafe)
}
}
extension Bundle {
/// Locates a JSON response file from the test bundle.
///
/// - Parameter fileName: Name of file to locate.
/// - Returns: URL to file.
static func url(for fileName: String) -> URL? {
// The Swift Package Manager places resources in a separate bundle from the executable.
// 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_masTests.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.
private func url(for fileName: String) -> URL? {
url(
forResource: fileName.fileNameWithoutExtension,
withExtension: fileName.fileExtension,
subdirectory: "JSON"
)
}
}