I am trying to create some tests inside a swift package that require the a coreML model. I am trying to copy the compiled model into the working bundle, but when I run the tests, the resource is not found using the Bundle.main.url() method. The project also compiles and runs successfully when running command+b.
My file structure:
My Package.swift:
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "AudioPreprocessingSPM",
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "AudioPreprocessingSPM",
targets: ["AudioPreprocessingSPM"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "AudioPreprocessingSPM",
dependencies: [],
resources: [.copy("A-6.swift"), .copy("A-6.mlmodelc")]),
.testTarget(
name: "AudioPreprocessingSPMTests",
dependencies: ["AudioPreprocessingSPM"],
resources: [.copy("A-6.swift"), .copy("A-6.mlmodelc")]),
]
)
My Package Test:
@testable import AudioPreprocessingSPM
final class AudioEngineTests: XCTestCase {
func testCreateAudioEngineInstance() {
var model = try! A_6(configuration: .init())
}
}
My modified A-6.swift file:
class A_6 {
let model: MLModel
/// URL of model assuming it was installed in the same bundle as this class
class var urlOfModelInThisBundle : URL {
var bundles = Bundle.allBundles.map{ return $0.bundlePath }
return Bundle.main.url(forResource: "A-6", withExtension: "mlmodelc")!
}
// Removed unmodified portions of auto generated file below
}
I am not very familiar with how bundling works for a swift package, but I believe that is where the issue lies.
Error Received when running test: Fatal error: Unexpectedly found nil while unwrapping an Optional value: file AudioPreprocessingSPMTests/A-6.swift, line 100 2021-07-04 11:37:21.785589-0400 xctest[79167:2602315] Fatal error: Unexpectedly found nil while unwrapping an Optional value: file AudioPreprocessingSPMTests/A-6.swift, line 100
The default generation of file A-6.swift also fails:
class var urlOfModelInThisBundle : URL {
let bundle = Bundle(for: A_6.self)
return bundle.url(forResource: "A-6", withExtension: "mlmodelc")!
}
Thanks for your help
No idea why this is happening, but the issue was that I had the mlmodelc file in the resources folder. Despite adding the resources in the package.swift, the Bundle.module property was not available because the generated resource_bundle_accessor.swift file was not generating. All I needed to do was more the mlmodelc file outside the resources folder and it worked.