Skip to content

Commit 87ebba0

Browse files
committed
feat: add the image serialization plugin api
1 parent 7b0bbba commit 87ebba0

28 files changed

+1000
-176
lines changed

Package.swift

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,14 @@ let package = Package(
1515
name: "SnapshotTesting",
1616
targets: ["SnapshotTesting"]
1717
),
18+
.library(
19+
name: "SnapshotTestingPlugin",
20+
targets: ["SnapshotTestingPlugin"]
21+
),
22+
.library(
23+
name: "ImageSerializationPlugin",
24+
targets: ["ImageSerializationPlugin"]
25+
),
1826
.library(
1927
name: "InlineSnapshotTesting",
2028
targets: ["InlineSnapshotTesting"]
@@ -25,7 +33,16 @@ let package = Package(
2533
],
2634
targets: [
2735
.target(
28-
name: "SnapshotTesting"
36+
name: "SnapshotTesting",
37+
dependencies: [
38+
"ImageSerializationPlugin",
39+
"SnapshotTestingPlugin"
40+
]
41+
),
42+
.target(name: "SnapshotTestingPlugin"),
43+
.target(
44+
name: "ImageSerializationPlugin",
45+
dependencies: ["SnapshotTestingPlugin"]
2946
),
3047
.target(
3148
name: "InlineSnapshotTesting",

README.md

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ targets: [
230230
[available-strategies]: https://swiftpackageindex.com/pointfreeco/swift-snapshot-testing/main/documentation/snapshottesting/snapshotting
231231
[defining-strategies]: https://swiftpackageindex.com/pointfreeco/swift-snapshot-testing/main/documentation/snapshottesting/customstrategies
232232

233-
## Plug-ins
233+
## Strategies / Plug-ins
234234

235235
- [AccessibilitySnapshot](https://github.com/cashapp/AccessibilitySnapshot) adds easy regression
236236
testing for iOS accessibility.
@@ -273,6 +273,18 @@ targets: [
273273
- [SnapshotVision](https://github.com/gregersson/swift-snapshot-testing-vision) adds snapshot
274274
strategy for text recognition on views and images. Uses Apples Vision framework.
275275

276+
- [Image Serialization Plugin - HEIC](https://github.com/mackoj/swift-snapshot-testing-plugin-heic) allow all the
277+
strategy that create image as output to store them in `.heic` storage format which reduces file sizes
278+
in comparison to PNG.
279+
280+
- [Image Serialization Plugin - WEBP](https://github.com/mackoj/swift-snapshot-testing-plugin-heic) allow all the
281+
strategy that create image as output to store them in `.webp` storage format which reduces file sizes
282+
in comparison to PNG.
283+
284+
- [Image Serialization Plugin - JXL](https://github.com/mackoj/swift-snapshot-testing-plugin-heic) allow all the
285+
strategy that create image as output to store them in `.jxl` storage format which reduces file sizes
286+
in comparison to PNG.
287+
276288
Have you written your own SnapshotTesting plug-in?
277289
[Add it here](https://github.com/pointfreeco/swift-snapshot-testing/edit/master/README.md) and
278290
submit a pull request!
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
#if canImport(SwiftUI)
2+
import Foundation
3+
import SnapshotTestingPlugin
4+
5+
#if canImport(UIKit)
6+
import UIKit.UIImage
7+
/// A type alias for `UIImage` when UIKit is available.
8+
public typealias SnapImage = UIImage
9+
#elseif canImport(AppKit)
10+
import AppKit.NSImage
11+
/// A type alias for `NSImage` when AppKit is available.
12+
public typealias SnapImage = NSImage
13+
#endif
14+
15+
/// A type alias that combines `ImageSerialization` and `SnapshotTestingPlugin` protocols.
16+
///
17+
/// `ImageSerializationPlugin` is a convenient alias used to conform to both `ImageSerialization` and `SnapshotTestingPlugin` protocols.
18+
/// This allows for image serialization plugins that also support snapshot testing, leveraging the Objective-C runtime while maintaining image serialization capabilities.
19+
public typealias ImageSerializationPlugin = ImageSerialization & SnapshotTestingPlugin
20+
21+
// TODO: async throws will be added later to encodeImage and decodeImage
22+
/// A protocol that defines methods for encoding and decoding images in various formats.
23+
///
24+
/// The `ImageSerialization` protocol is intended for classes that provide functionality to serialize (encode) and deserialize (decode) images.
25+
/// Implementing this protocol allows a class to specify the image format it supports and to handle image data conversions.
26+
/// This protocol is designed to be used in environments where SwiftUI is available and supports platform-specific image types via `SnapImage`.
27+
public protocol ImageSerialization {
28+
29+
/// The image format that the serialization plugin supports.
30+
///
31+
/// Each conforming class must specify the format it handles, using the `ImageSerializationFormat` enum. This property helps the `ImageSerializer`
32+
/// determine which plugin to use for a given format during image encoding and decoding.
33+
static var imageFormat: ImageSerializationFormat { get }
34+
35+
/// Encodes a `SnapImage` into a data representation.
36+
///
37+
/// This method converts the provided image into the appropriate data format. It may eventually support asynchronous operations and error handling using `async throws`.
38+
///
39+
/// - Parameter image: The image to be encoded.
40+
/// - Returns: The encoded image data, or `nil` if encoding fails.
41+
func encodeImage(_ image: SnapImage) -> Data?
42+
43+
/// Decodes image data into a `SnapImage`.
44+
///
45+
/// This method converts the provided data back into an image. It may eventually support asynchronous operations and error handling using `async throws`.
46+
///
47+
/// - Parameter data: The image data to be decoded.
48+
/// - Returns: The decoded image, or `nil` if decoding fails.
49+
func decodeImage(_ data: Data) -> SnapImage?
50+
}
51+
#endif
52+
53+
/// An enumeration that defines the image formats supported by the `ImageSerialization` protocol.
54+
///
55+
/// The `ImageSerializationFormat` enum is used to represent various image formats. It includes a predefined case for PNG images and a flexible case for plugins,
56+
/// allowing for the extension of formats via plugins identified by unique string values.
57+
public enum ImageSerializationFormat: RawRepresentable, Sendable, Equatable {
58+
59+
public static let defaultValue: ImageSerializationFormat = .png
60+
61+
/// Represents the default image format aka PNG.
62+
case png
63+
64+
/// Represents a custom image format provided by a plugin.
65+
///
66+
/// This case allows for the extension of image formats beyond the predefined ones by using a unique string identifier.
67+
case plugins(String)
68+
69+
/// Initializes an `ImageSerializationFormat` instance from a raw string value.
70+
///
71+
/// This initializer converts a string value into an appropriate `ImageSerializationFormat` case.
72+
///
73+
/// - Parameter rawValue: The string representation of the image format.
74+
public init?(rawValue: String) {
75+
switch rawValue {
76+
case "png": self = .png
77+
default: self = .plugins(rawValue)
78+
}
79+
}
80+
81+
/// The raw string value of the `ImageSerializationFormat`.
82+
///
83+
/// This computed property returns the string representation of the current image format.
84+
public var rawValue: String {
85+
switch self {
86+
case .png: return "png"
87+
case let .plugins(value): return value
88+
}
89+
}
90+
}

Sources/SnapshotTesting/AssertSnapshot.swift

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,49 @@
11
import XCTest
2+
import ImageSerializationPlugin
23

34
#if canImport(Testing)
45
// NB: We are importing only the implementation of Testing because that framework is not available
56
// in Xcode UI test targets.
67
@_implementationOnly import Testing
78
#endif
89

10+
/// Whether or not to change the default output image format to something else.
11+
@available(
12+
*,
13+
deprecated,
14+
message:
15+
"Use 'withSnapshotTesting' to customize the image output format. See the documentation for more information."
16+
)
17+
public var imageFormat: ImageSerializationFormat {
18+
get {
19+
_imageFormat
20+
}
21+
set { _imageFormat = newValue }
22+
}
23+
24+
@_spi(Internals)
25+
public var _imageFormat: ImageSerializationFormat {
26+
get {
27+
#if canImport(Testing)
28+
if let test = Test.current {
29+
for trait in test.traits.reversed() {
30+
if let diffTool = (trait as? _SnapshotsTestTrait)?.configuration.imageFormat {
31+
return diffTool
32+
}
33+
}
34+
}
35+
#endif
36+
return __imageFormat
37+
}
38+
set {
39+
__imageFormat = newValue
40+
}
41+
}
42+
43+
@_spi(Internals)
44+
public var __imageFormat: ImageSerializationFormat = .defaultValue
45+
46+
947
/// Enhances failure messages with a command line diff tool expression that can be copied and pasted
1048
/// into a terminal.
1149
@available(
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
# Image Serialization Plugin
2+
3+
Image Serialization Plugin is a plugin based on the PluginAPI, it provides support for encoding and decoding images. It leverages the plugin architecture to extend its support for different image formats without needing to modify the core system.
4+
5+
Plugins that conform to the `ImageSerializationPlugin` protocol can be registered into the `PluginRegistry` and used to encode or decode images in different formats, such as PNG, JPEG, WebP, HEIC, and more.
6+
7+
When a plugin supporting a specific image format is available, the `ImageSerializer` can dynamically choose the correct plugin based on the image format required, ensuring modularity and scalability in image handling.
8+
9+
10+
# Image Serialization Plugin
11+
12+
The **Image Serialization Plugin** extends the functionality of the SnapshotTesting library by enabling support for multiple image formats through a plugin architecture. This PluginAPI allows image encoding and decoding to be easily extended without modifying the core logic of the system.
13+
14+
## Overview
15+
16+
The **Image Serialization Plugin** provides an interface for encoding and decoding images in various formats. By conforming to both the `ImageSerialization` and `SnapshotTestingPlugin` protocols, it integrates with the broader plugin system, allowing for the seamless addition of new image formats. The default implementation supports PNG, but this architecture allows users to define custom plugins for other formats.
17+
18+
### Image Serialization Plugin Architecture
19+
20+
The **Image Serialization Plugin** relies on the PluginAPI that is a combination of protocols and a centralized registry to manage and discover plugins. The architecture allows for dynamic registration of image serialization plugins, which can be automatically discovered at runtime using the Objective-C runtime. This makes the system highly extensible, with plugins being automatically registered without the need for manual intervention.
21+
22+
#### Key Components:
23+
24+
1. **`ImageSerialization` Protocol**:
25+
- Defines the core methods for encoding and decoding images.
26+
- Requires plugins to specify the image format they support using the `ImageSerializationFormat` enum.
27+
- Provides methods for encoding (`encodeImage`) and decoding (`decodeImage`) images.
28+
29+
2. **`ImageSerializationFormat` Enum**:
30+
- Represents supported image formats.
31+
- Includes predefined formats such as `.png` and extensible formats through the `.plugins(String)` case, allowing for custom formats to be introduced via plugins.
32+
33+
3. **`ImageSerializer` Class**:
34+
- Responsible for encoding and decoding images using the registered plugins.
35+
- Retrieves available plugins from the `PluginRegistry` and uses the first matching plugin for the requested image format.
36+
- Provides default implementations for PNG encoding and decoding if no plugin is available for a given format.
37+
38+
#### Example Plugin Flow:
39+
40+
1. **Plugin Discovery**:
41+
- Plugins are automatically discovered at runtime through the Objective-C runtime, which identifies classes that conform to both the `ImageSerialization` and `SnapshotTestingPlugin` protocols.
42+
43+
2. **Plugin Registration**:
44+
- Each plugin registers itself with the `PluginRegistry`, allowing it to be retrieved when needed for image serialization.
45+
46+
3. **Image Encoding/Decoding**:
47+
- When an image needs to be serialized, the `ImageSerializer` checks the available plugins for one that supports the requested format.
48+
- If no plugin is found, it defaults to the built-in PNG encoding/decoding methods.
49+
50+
#### Extensibility
51+
52+
The plugin architecture allows developers to introduce new image formats without modifying the core SnapshotTesting library. By creating a new plugin that conforms to `ImageSerializationPlugin`, you can easily add support for additional image formats.
53+
54+
Here are a few example plugins demonstrating how to extend the library with new image formats:
55+
56+
- **[Image Serialization Plugin - HEIC](https://github.com/mackoj/swift-snapshot-testing-plugin-heic)**: Enables storing images in the `.heic` format, which reduces file sizes compared to PNG.
57+
- **[Image Serialization Plugin - WEBP](https://github.com/mackoj/swift-snapshot-testing-plugin-webp)**: Allows storing images in the `.webp` format, which offers better compression than PNG.
58+
- **[Image Serialization Plugin - JXL](https://github.com/mackoj/swift-snapshot-testing-plugin-jxl)**: Facilitates storing images in the `.jxl` format, which provides superior compression and quality compared to PNG.
59+
60+
## Usage
61+
62+
For example, if you want to use JPEG XL as a new image format for your snapshots, you can follow these steps. This approach applies to any image format as long as you have a plugin that conforms to `ImageSerializationPlugin`.
63+
64+
1. **Add the Dependency**: Include the appropriate image serialization plugin as a dependency in your `Package.swift` file. For JPEG XL, it would look like this:
65+
66+
```swift
67+
.package(url: "https://github.com/mackoj/swift-snapshot-testing-plugin-jxl.git", revision: "0.0.1"),
68+
```
69+
70+
2. **Link to Your Test Target**: Add the image serialization plugin to your test target's dependencies:
71+
72+
```swift
73+
.product(name: "JXLImageSerializer", package: "swift-snapshot-testing-plugin-jxl"),
74+
```
75+
76+
3. **Import and Set Up**: In your test file, import the serializer and configure the image format in the `setUp()` method:
77+
78+
```swift
79+
import JXLImageSerializer
80+
81+
override class func setUp() {
82+
SnapshotTesting.imageFormat = JXLImageSerializer.imageFormat
83+
}
84+
```
85+
86+
Alternatively, you can specify the image format for individual assertions:
87+
88+
```swift
89+
assertSnapshot(of: label, as: .image(precision: 0.9, format: JXLImageSerializer.imageFormat))
90+
```
91+
92+
This setup demonstrates how to integrate a specific image format plugin. Replace `JXLImageSerializer` with the appropriate plugin and format for other image formats.
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Plugins
2+
3+
SnapshotTesting offers a wide range of built-in snapshot strategies, and over the years, third-party developers have introduced new ones. However, when there’s a need for functionality that spans multiple strategies, plugins become essential.
4+
5+
## Overview
6+
7+
Plugins provide greater flexibility and extensibility by enabling shared behavior across different strategies without the need to duplicate code or modify each strategy individually. They can be dynamically discovered, registered, and executed at runtime, making them ideal for adding new functionality without altering the core system. This architecture promotes modularity and decoupling, allowing features to be easily added or swapped out without impacting existing functionality.
8+
9+
### Plugin architecture
10+
11+
The plugin architecture is designed around the concept of **dynamic discovery and registration**. Plugins conform to specific protocols, such as `SnapshotTestingPlugin`, and are registered automatically by the `PluginRegistry`. This registry manages plugin instances, allowing them to be retrieved by identifier or filtered by the protocols they conform to.
12+
13+
The primary components of the plugin system include:
14+
15+
- **Plugin Protocols**: Define the behavior that plugins must implement.
16+
- **PluginRegistry**: Manages plugin discovery, registration, and retrieval.
17+
- **Objective-C Runtime Integration**: Allows automatic discovery of plugins that conform to specific protocols.
18+
19+
The `PluginRegistry` is a singleton that registers plugins during its initialization. Plugins can be retrieved by their identifier or cast to specific types, allowing flexible interaction.

Sources/SnapshotTesting/Documentation.docc/SnapshotTesting.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,11 @@ Powerfully flexible snapshot testing.
2323
- ``withSnapshotTesting(record:diffTool:operation:)-2kuyr``
2424
- ``SnapshotTestingConfiguration``
2525

26+
### Plugins
27+
28+
- <doc:Plugins>
29+
- <doc:ImageSerializationPlugin>
30+
2631
### Deprecations
2732

2833
- <doc:SnapshotTestingDeprecations>

0 commit comments

Comments
 (0)