Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Image Serialization Plugin #906

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ let package = Package(
name: "SnapshotTesting",
targets: ["SnapshotTesting"]
),
.library(
name: "SnapshotTestingPlugin",
targets: ["SnapshotTestingPlugin"]
),
.library(
name: "ImageSerializationPlugin",
targets: ["ImageSerializationPlugin"]
),
.library(
name: "InlineSnapshotTesting",
targets: ["InlineSnapshotTesting"]
Expand All @@ -25,7 +33,16 @@ let package = Package(
],
targets: [
.target(
name: "SnapshotTesting"
name: "SnapshotTesting",
dependencies: [
"ImageSerializationPlugin",
"SnapshotTestingPlugin"
]
),
.target(name: "SnapshotTestingPlugin"),
.target(
name: "ImageSerializationPlugin",
dependencies: ["SnapshotTestingPlugin"]
),
.target(
name: "InlineSnapshotTesting",
Expand Down
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ targets: [
[available-strategies]: https://swiftpackageindex.com/pointfreeco/swift-snapshot-testing/main/documentation/snapshottesting/snapshotting
[defining-strategies]: https://swiftpackageindex.com/pointfreeco/swift-snapshot-testing/main/documentation/snapshottesting/customstrategies

## Plug-ins
## Strategies / Plug-ins

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

- [Image Serialization Plugin - HEIC](https://github.com/mackoj/swift-snapshot-testing-plugin-heic) allow all the
strategy that create image as output to store them in `.heic` storage format which reduces file sizes
in comparison to PNG.

- [Image Serialization Plugin - WEBP](https://github.com/mackoj/swift-snapshot-testing-plugin-heic) allow all the
strategy that create image as output to store them in `.webp` storage format which reduces file sizes
in comparison to PNG.

- [Image Serialization Plugin - JXL](https://github.com/mackoj/swift-snapshot-testing-plugin-heic) allow all the
strategy that create image as output to store them in `.jxl` storage format which reduces file sizes
in comparison to PNG.

Have you written your own SnapshotTesting plug-in?
[Add it here](https://github.com/pointfreeco/swift-snapshot-testing/edit/master/README.md) and
submit a pull request!
Expand Down
87 changes: 87 additions & 0 deletions Sources/ImageSerializationPlugin/ImageSerializationPlugin.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
#if canImport(SwiftUI)
import Foundation
import SnapshotTestingPlugin

#if canImport(UIKit)
import UIKit.UIImage
/// A type alias for `UIImage` when UIKit is available.
public typealias SnapImage = UIImage
#elseif canImport(AppKit)
import AppKit.NSImage
/// A type alias for `NSImage` when AppKit is available.
public typealias SnapImage = NSImage
#endif

/// A type alias that combines `ImageSerialization` and `SnapshotTestingPlugin` protocols.
///
/// `ImageSerializationPlugin` is a convenient alias used to conform to both `ImageSerialization` and `SnapshotTestingPlugin` protocols.
/// This allows for image serialization plugins that also support snapshot testing, leveraging the Objective-C runtime while maintaining image serialization capabilities.
public typealias ImageSerializationPlugin = ImageSerialization & SnapshotTestingPlugin

// TODO: async throws will be added later to encodeImage and decodeImage
/// A protocol that defines methods for encoding and decoding images in various formats.
///
/// The `ImageSerialization` protocol is intended for classes that provide functionality to serialize (encode) and deserialize (decode) images.
/// Implementing this protocol allows a class to specify the image format it supports and to handle image data conversions.
/// This protocol is designed to be used in environments where SwiftUI is available and supports platform-specific image types via `SnapImage`.
public protocol ImageSerialization {

/// The image format that the serialization plugin supports.
///
/// Each conforming class must specify the format it handles, using the `ImageSerializationFormat` enum. This property helps the `ImageSerializer`
/// determine which plugin to use for a given format during image encoding and decoding.
static var imageFormat: ImageSerializationFormat { get }

/// Encodes a `SnapImage` into a data representation.
///
/// This method converts the provided image into the appropriate data format. It may eventually support asynchronous operations and error handling using `async throws`.
///
/// - Parameter image: The image to be encoded.
/// - Returns: The encoded image data, or `nil` if encoding fails.
func encodeImage(_ image: SnapImage) -> Data?

/// Decodes image data into a `SnapImage`.
///
/// This method converts the provided data back into an image. It may eventually support asynchronous operations and error handling using `async throws`.
///
/// - Parameter data: The image data to be decoded.
/// - Returns: The decoded image, or `nil` if decoding fails.
func decodeImage(_ data: Data) -> SnapImage?
}
#endif

/// An enumeration that defines the image formats supported by the `ImageSerialization` protocol.
///
/// The `ImageSerializationFormat` enum is used to represent various image formats. It includes a predefined case for PNG images and a flexible case for plugins,
/// allowing for the extension of formats via plugins identified by unique string values.
public enum ImageSerializationFormat: RawRepresentable, Sendable, Equatable {

public static let defaultValue: ImageSerializationFormat = .png

/// Represents the default image format aka PNG.
case png

/// Represents a custom image format provided by a plugin.
///
/// This case allows for the extension of image formats beyond the predefined ones by using a unique string identifier.
case plugins(String)

/// Initializes an `ImageSerializationFormat` instance from a raw string value.
///
/// This initializer converts a string value into an appropriate `ImageSerializationFormat` case.
///
/// - Parameter rawValue: The string representation of the image format.
public init?(rawValue: String) {
self = rawValue == "png" ? .png : .plugins(rawValue)
}

/// The raw string value of the `ImageSerializationFormat`.
///
/// This computed property returns the string representation of the current image format.
public var rawValue: String {
switch self {
case .png: return "png"
case let .plugins(value): return value
}
}
}
32 changes: 32 additions & 0 deletions Sources/SnapshotTesting/AssertSnapshot.swift
Original file line number Diff line number Diff line change
@@ -1,9 +1,41 @@
import XCTest
import ImageSerializationPlugin

#if canImport(Testing)
import Testing
#endif

/// Whether or not to change the default output image format to something else.
public var imageFormat: ImageSerializationFormat {
get {
_imageFormat
}
set { _imageFormat = newValue }
}

@_spi(Internals)
public var _imageFormat: ImageSerializationFormat {
get {
#if canImport(Testing)
if let test = Test.current {
for trait in test.traits.reversed() {
if let diffTool = (trait as? _SnapshotsTestTrait)?.configuration.imageFormat {
return diffTool
}
}
}
#endif
return __imageFormat
}
set {
__imageFormat = newValue
}
}

@_spi(Internals)
public var __imageFormat: ImageSerializationFormat = .defaultValue


/// Enhances failure messages with a command line diff tool expression that can be copied and pasted
/// into a terminal.
@available(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# Image Serialization Plugin

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.

## Overview

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.

### Image Serialization Plugin Architecture

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.

#### Key Components:

1. **`ImageSerialization` Protocol**:
- Defines the core methods for encoding and decoding images.
- Requires plugins to specify the image format they support using the `ImageSerializationFormat` enum.
- Provides methods for encoding (`encodeImage`) and decoding (`decodeImage`) images.

2. **`ImageSerializationFormat` Enum**:
- Represents supported image formats.
- Includes predefined formats such as `.png` and extensible formats through the `.plugins(String)` case, allowing for custom formats to be introduced via plugins.

3. **`ImageSerializer` Class**:
- Responsible for encoding and decoding images using the registered plugins.
- Retrieves available plugins from the `PluginRegistry` and uses the first matching plugin for the requested image format.
- Provides default implementations for PNG encoding and decoding if no plugin is available for a given format.

#### Example Plugin Flow:

1. **Plugin Discovery**:
- On Apple platforms Plugins are automatically discovered at runtime through the Objective-C runtime, which identifies classes that conform to both the `ImageSerialization` and `SnapshotTestingPlugin` protocols.

2. **Plugin Registration**:
- Each plugin registers itself with the `PluginRegistry`, allowing it to be retrieved when needed for image serialization.

3. **Image Encoding/Decoding**:
- When an image needs to be serialized, the `ImageSerializer` checks the available plugins for one that supports the requested format.
- If no plugin is found, it defaults to the built-in PNG encoding/decoding methods.

#### Extensibility

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.

Here are a few example plugins demonstrating how to extend the library with new image formats:

- **[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.
- **[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.
- **[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.

## Usage

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`.

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:

```swift
.package(url: "https://github.com/mackoj/swift-snapshot-testing-plugin-jxl.git", revision: "0.0.1"),
```

2. **Link to Your Test Target**: Add the image serialization plugin to your test target's dependencies:

```swift
.product(name: "JXLImageSerializer", package: "swift-snapshot-testing-plugin-jxl"),
```

3. **Import and Set Up**: In your test file, import the serializer and configure the image format in the `setUp()` method:

```swift
import JXLImageSerializer

override class func setUp() {
SnapshotTesting.imageFormat = JXLImageSerializer.imageFormat
}
```

> [!IMPORTANT]
> On **non** Apple platform you will need to call `PluginRegistry.registerPlugin(YourPlugin.init())` to register it.

Alternatively, you can specify the image format for individual assertions:

```swift
assertSnapshot(of: label, as: .image(precision: 0.9, format: JXLImageSerializer.imageFormat))
```

This setup demonstrates how to integrate a specific image format plugin. Replace `JXLImageSerializer` with the appropriate plugin and format for other image formats.
22 changes: 22 additions & 0 deletions Sources/SnapshotTesting/Documentation.docc/Articles/Plugins.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Plugins

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.

## Overview

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.

### Plugin architecture

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.

The primary components of the plugin system include:

- **Plugin Protocols**: Define the behavior that plugins must implement.
- **PluginRegistry**: Manages plugin discovery, registration, and retrieval.
- **Objective-C Runtime Integration**: Allows automatic discovery of plugins that conform to specific protocols.

> [!IMPORTANT]
> On **non** Apple platform you will need to call `PluginRegistry.registerPlugin(YourPlugin.init())` to register your plugin.

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.
5 changes: 5 additions & 0 deletions Sources/SnapshotTesting/Documentation.docc/SnapshotTesting.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ Powerfully flexible snapshot testing.
- ``withSnapshotTesting(record:diffTool:operation:)-2kuyr``
- ``SnapshotTestingConfiguration``

### Plugins

- <doc:Plugins>
- <doc:ImageSerializationPlugin>

### Deprecations

- <doc:SnapshotTestingDeprecations>
Loading
Loading