In Swift 6.2, we introduced attachments to Swift Testing, primarily dealing with untyped or loosely-typed values such as [UInt8]
or String
. I propose adding support for attaching images (namely, instances of Apple's CGImage
, CIImage
, NSImage
, and UIImage
types) and having them be automatically serialized to an appropriate image format such as PNG or JPEG:
import Testing
import UIKit
import SwiftUI
@MainActor @Test func `attaching a SwiftUI view as an image`() throws {
let myView: some View = ...
let image = try #require(ImageRenderer(content: myView).uiImage)
Attachment.record(image, named: "my view", as: .png)
}
Read the full proposal here.
Trying it out
To try this feature out, add a dependency to the main
branch of swift-testing
to your project:
...
dependencies: [
...
.package(
url: "https://github.com/swiftlang/swift-testing.git",
branch: "main"
),
]
Then, add two target dependencies to your test target:
.testTarget(
...
dependencies: [
...
.product(name: "Testing", package: "swift-testing"),
.product(name: "_Testing_ExperimentalImageAttachments", package: "swift-testing"),
]
Add the following imports to any source file that will attach an image to a test:
import X
@_spi(Experimental) import _Testing_X
Where X
is the module name of the image type you're using:
Image Type | Module Name |
---|---|
CGImage |
CoreGraphics |
NSImage |
AppKit |
Support for CIImage
and UIImage
requires changes to the package that haven't been merged yet.
Note: This extra product dependency and extra
import
statement are a side effect of how packages are built. They will not be required in the final implementation of this feature.