22import UIKit
33import XCTest
44
5+ extension Diffing where Value == UIImage {
6+ /// A pixel-diffing strategy for UIImage's which requires a 100% match.
7+ public static let image = Diffing . image ( precision: 1 )
8+
9+ /// A pixel-diffing strategy for UIImage that allows customizing how precise the matching must be.
10+ ///
11+ /// - Parameter precision: A value between 0 and 1, where 1 means the images must match 100% of their pixels.
12+ /// - Returns: A new diffing strategy.
13+ public static func image( precision: Float ) -> Diffing {
14+ return Diffing (
15+ toData: { $0. pngData ( ) ! } ,
16+ fromData: { UIImage ( data: $0, scale: UIScreen . main. scale) ! }
17+ ) { old, new in
18+ guard !compare( old, new, precision: precision) else { return nil }
19+ let difference = SnapshotTesting . diff ( old, new)
20+ let message = new. size == old. size
21+ ? " Expected snapshot to match reference "
22+ : " Expected snapshot@ \( new. size) to match reference@ \( old. size) "
23+ let oldAttachment = XCTAttachment ( image: old)
24+ oldAttachment. name = " reference "
25+ let newAttachment = XCTAttachment ( image: new)
26+ newAttachment. name = " failure "
27+ let differenceAttachment = XCTAttachment ( image: difference)
28+ differenceAttachment. name = " difference "
29+ return (
30+ message,
31+ [ oldAttachment, newAttachment, differenceAttachment]
32+ )
33+ }
34+ }
35+ }
36+
537extension Snapshotting where Value == UIImage , Format == UIImage {
638 /// A snapshot strategy for comparing images based on pixel equality.
739 public static var image : Snapshotting {
@@ -14,26 +46,7 @@ extension Snapshotting where Value == UIImage, Format == UIImage {
1446 public static func image( precision: Float ) -> Snapshotting {
1547 return . init(
1648 pathExtension: " png " ,
17- diffing: . init(
18- toData: { $0. pngData ( ) ! } ,
19- fromData: { UIImage ( data: $0, scale: UIScreen . main. scale) ! }
20- ) { old, new in
21- guard !compare( old, new, precision: precision) else { return nil }
22- let difference = diff ( old, new)
23- let message = new. size == old. size
24- ? " Expected snapshot to match reference "
25- : " Expected snapshot@ \( new. size) to match reference@ \( old. size) "
26- let oldAttachment = XCTAttachment ( image: old)
27- oldAttachment. name = " reference "
28- let newAttachment = XCTAttachment ( image: new)
29- newAttachment. name = " failure "
30- let differenceAttachment = XCTAttachment ( image: difference)
31- differenceAttachment. name = " difference "
32- return (
33- message,
34- [ oldAttachment, newAttachment, differenceAttachment]
35- )
36- }
49+ diffing: . image( precision: precision)
3750 )
3851 }
3952}
0 commit comments