-
Notifications
You must be signed in to change notification settings - Fork 99
/
HaveValidSnapshot.swift
354 lines (300 loc) · 14.8 KB
/
HaveValidSnapshot.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
#if SWIFT_PACKAGE
import iOSSnapshotTestCase
#else
import FBSnapshotTestCase
#endif
import Foundation
import Nimble
import QuartzCore
import UIKit
@objc public protocol Snapshotable {
var snapshotObject: UIView? { get }
}
extension UIViewController: Snapshotable {
public var snapshotObject: UIView? {
self.beginAppearanceTransition(true, animated: false)
self.endAppearanceTransition()
return view
}
}
extension UIView: Snapshotable {
public var snapshotObject: UIView? {
return self
}
}
@objc
public class FBSnapshotTest: NSObject {
var referenceImagesDirectory: String?
var tolerance: CGFloat = 0
var pixelTolerance: CGFloat = 0
static let sharedInstance = FBSnapshotTest()
public class func setReferenceImagesDirectory(_ directory: String?) {
sharedInstance.referenceImagesDirectory = directory
}
// swiftlint:disable:next function_parameter_count
class func compareSnapshot(_ instance: Snapshotable,
isDeviceAgnostic: Bool = false,
usesDrawRect: Bool = false,
snapshot: String,
record: Bool,
referenceDirectory: String,
tolerance: CGFloat,
perPixelTolerance: CGFloat,
filename: String,
identifier: String? = nil,
shouldIgnoreScale: Bool = false) -> Bool {
let testName = parseFilename(filename: filename)
let snapshotController: FBSnapshotTestController = FBSnapshotTestController(test: self)
snapshotController.folderName = testName
if isDeviceAgnostic {
snapshotController.fileNameOptions = [.device, .OS, .screenSize, .screenScale]
} else if shouldIgnoreScale {
snapshotController.fileNameOptions = .none
} else {
snapshotController.fileNameOptions = .screenScale
}
snapshotController.recordMode = record
snapshotController.referenceImagesDirectory = referenceDirectory
snapshotController.imageDiffDirectory = defaultImageDiffDirectory
snapshotController.usesDrawViewHierarchyInRect = usesDrawRect
let reason = "Missing value for referenceImagesDirectory - " +
"Call FBSnapshotTest.setReferenceImagesDirectory(FB_REFERENCE_IMAGE_DIR)"
assert(snapshotController.referenceImagesDirectory != nil, reason)
guard let snapshotObject = instance.snapshotObject else {
fatalError("Failed unwrapping Snapshot Object")
}
do {
try snapshotController.compareSnapshot(ofViewOrLayer: snapshotObject,
selector: Selector(snapshot),
identifier: identifier,
perPixelTolerance: perPixelTolerance,
overallTolerance: tolerance)
let image = try snapshotController.referenceImage(for: Selector(snapshot), identifier: identifier)
attach(image: image, named: "Reference_\(snapshot)")
} catch let error {
let info = (error as NSError).userInfo
if let ref = info[FBReferenceImageKey] as? UIImage {
attach(image: ref, named: "Reference_\(snapshot)")
}
if let captured = info[FBCapturedImageKey] as? UIImage {
attach(image: captured, named: "Captured_\(snapshot)")
}
if let diff = info[FBDiffedImageKey] as? UIImage {
attach(image: diff, named: "Diffed_\(snapshot)")
}
return false
}
return true
}
private static func attach(image: UIImage, named name: String) {
XCTContext.runActivity(named: name) { activity in
let attachment = XCTAttachment(image: image)
attachment.name = name
activity.add(attachment)
}
}
}
// Note that these must be lower case.
private var testFolderSuffixes = ["tests", "specs"]
public func setNimbleTestFolder(_ testFolder: String) {
testFolderSuffixes = [testFolder.lowercased()]
}
public func setNimbleTolerance(_ tolerance: CGFloat) {
FBSnapshotTest.sharedInstance.tolerance = tolerance
}
public func setNimblePixelTolerance(_ pixelTolerance: CGFloat) {
FBSnapshotTest.sharedInstance.pixelTolerance = pixelTolerance
}
public func recordAllSnapshots() {
switchChecksWithRecords = true
}
func getDefaultReferenceDirectory(_ sourceFileName: FileString) -> String {
if let globalReference = FBSnapshotTest.sharedInstance.referenceImagesDirectory {
return globalReference
}
if let environmentReference = ProcessInfo.processInfo.environment["FB_REFERENCE_IMAGE_DIR"] {
return environmentReference
}
// Search the test file's path to find the first folder with a test suffix,
// then append "/ReferenceImages" and use that.
// Grab the file's path
let fileName = NSString(string: "\(sourceFileName)")
let pathComponents = fileName.pathComponents as NSArray
// Find the directory in the path that ends with a test suffix.
let testPath = pathComponents.first { component -> Bool in
return !testFolderSuffixes.filter {
(component as AnyObject).lowercased.hasSuffix($0)
}.isEmpty
}
guard let testDirectory = testPath else {
fatalError("Could not infer reference image folder – You should provide a reference dir using " +
"FBSnapshotTest.setReferenceImagesDirectory(FB_REFERENCE_IMAGE_DIR) " +
"or by setting the FB_REFERENCE_IMAGE_DIR environment variable")
}
// Recombine the path components and append our own image directory.
let currentIndex = pathComponents.index(of: testDirectory) + 1
let folderPathComponents = pathComponents.subarray(with: NSRange(location: 0, length: currentIndex)) as NSArray
let folderPath = folderPathComponents.componentsJoined(by: "/")
return folderPath + "/ReferenceImages"
}
private var defaultImageDiffDirectory: String {
if let environmentReference = ProcessInfo.processInfo.environment["IMAGE_DIFF_DIR"] {
return environmentReference
}
return NSTemporaryDirectory()
}
private func parseFilename(filename: String) -> String {
let nsName = filename as NSString
let type = ".\(nsName.pathExtension)"
let sanitizedName = nsName.lastPathComponent.replacingOccurrences(of: type, with: "")
return sanitizedName
}
func sanitizedTestName(_ name: String?) -> String {
guard let testName = currentTestName() else {
fatalError("Test matchers must be called from inside a test block")
}
var filename = name ?? testName
filename = filename.replacingOccurrences(of: "root example group, ", with: "")
let characterSet = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_")
let components = filename.components(separatedBy: characterSet.inverted)
return components.joined(separator: "_")
}
func getPixelTolerance() -> CGFloat {
return FBSnapshotTest.sharedInstance.pixelTolerance
}
func getTolerance() -> CGFloat {
return FBSnapshotTest.sharedInstance.tolerance
}
private func performSnapshotTest<T: Snapshotable>(_ name: String?,
identifier: String? = nil,
isDeviceAgnostic: Bool = false,
usesDrawRect: Bool = false,
actualExpression: Expression<T>,
pixelTolerance: CGFloat? = nil,
tolerance: CGFloat?,
shouldIgnoreScale: Bool) -> PredicateResult {
// swiftlint:disable:next force_try force_unwrapping
let instance = try! actualExpression.evaluate()!
let testFileLocation = actualExpression.location.file
let referenceImageDirectory = getDefaultReferenceDirectory(testFileLocation)
let snapshotName = sanitizedTestName(name)
let tolerance = tolerance ?? getTolerance()
let pixelTolerance = pixelTolerance ?? getPixelTolerance()
let filename = "\(actualExpression.location.file)"
let result = FBSnapshotTest.compareSnapshot(instance, isDeviceAgnostic: isDeviceAgnostic,
usesDrawRect: usesDrawRect, snapshot: snapshotName, record: false,
referenceDirectory: referenceImageDirectory, tolerance: tolerance,
perPixelTolerance: pixelTolerance,
filename: filename, identifier: identifier,
shouldIgnoreScale: shouldIgnoreScale)
return PredicateResult(status: PredicateStatus(bool: result),
message: .fail("expected a matching snapshot in \(snapshotName)"))
}
private func recordSnapshot<T: Snapshotable>(_ name: String?,
identifier: String? = nil,
isDeviceAgnostic: Bool = false,
usesDrawRect: Bool = false,
actualExpression: Expression<T>,
shouldIgnoreScale: Bool) -> PredicateResult {
// swiftlint:disable:next force_try force_unwrapping
let instance = try! actualExpression.evaluate()!
let testFileLocation = actualExpression.location.file
let referenceImageDirectory = getDefaultReferenceDirectory(testFileLocation)
let snapshotName = sanitizedTestName(name)
let tolerance = getTolerance()
let pixelTolerance = getPixelTolerance()
let filename = "\(actualExpression.location.file)"
var message: String = ""
if FBSnapshotTest.compareSnapshot(instance,
isDeviceAgnostic: isDeviceAgnostic,
usesDrawRect: usesDrawRect,
snapshot: snapshotName,
record: true,
referenceDirectory: referenceImageDirectory,
tolerance: tolerance,
perPixelTolerance: pixelTolerance,
filename: filename,
identifier: identifier,
shouldIgnoreScale: shouldIgnoreScale) {
let name = name ?? snapshotName
message = "snapshot \(name) successfully recorded, replace recordSnapshot with a check"
} else if let name = name {
message = "expected to record a snapshot in \(name)"
} else {
message = "expected to record a snapshot"
}
return PredicateResult(status: PredicateStatus(bool: false),
message: .fail(message))
}
private func currentTestName() -> String? {
return CurrentTestCaseTracker.shared.currentTestCase?.sanitizedName
}
internal var switchChecksWithRecords = false
public func haveValidSnapshot<T: Snapshotable>(named name: String? = nil,
identifier: String? = nil,
usesDrawRect: Bool = false,
pixelTolerance: CGFloat? = nil,
tolerance: CGFloat? = nil,
shouldIgnoreScale: Bool = false) -> Nimble.Predicate<T> {
return Predicate { actualExpression in
if switchChecksWithRecords {
return recordSnapshot(name,
identifier: identifier,
usesDrawRect: usesDrawRect,
actualExpression: actualExpression,
shouldIgnoreScale: shouldIgnoreScale)
}
return performSnapshotTest(name,
identifier: identifier,
usesDrawRect: usesDrawRect,
actualExpression: actualExpression,
pixelTolerance: pixelTolerance,
tolerance: tolerance,
shouldIgnoreScale: shouldIgnoreScale)
}
}
public func haveValidDeviceAgnosticSnapshot<T: Snapshotable>(named name: String? = nil,
identifier: String? = nil,
usesDrawRect: Bool = false,
pixelTolerance: CGFloat? = nil,
tolerance: CGFloat? = nil,
shouldIgnoreScale: Bool = false) -> Nimble.Predicate<T> {
return Predicate { actualExpression in
if switchChecksWithRecords {
return recordSnapshot(name,
identifier: identifier,
isDeviceAgnostic: true,
usesDrawRect: usesDrawRect,
actualExpression: actualExpression,
shouldIgnoreScale: shouldIgnoreScale)
}
return performSnapshotTest(name,
identifier: identifier,
isDeviceAgnostic: true,
usesDrawRect: usesDrawRect,
actualExpression: actualExpression,
pixelTolerance: pixelTolerance,
tolerance: tolerance,
shouldIgnoreScale: shouldIgnoreScale)
}
}
public func recordSnapshot<T: Snapshotable>(named name: String? = nil,
identifier: String? = nil,
usesDrawRect: Bool = false,
shouldIgnoreScale: Bool = false) -> Nimble.Predicate<T> {
return Predicate { actualExpression in
return recordSnapshot(name, identifier: identifier, usesDrawRect: usesDrawRect,
actualExpression: actualExpression,
shouldIgnoreScale: shouldIgnoreScale)
}
}
public func recordDeviceAgnosticSnapshot<T: Snapshotable>(named name: String? = nil,
identifier: String? = nil,
usesDrawRect: Bool = false,
shouldIgnoreScale: Bool = false) -> Nimble.Predicate<T> {
return Predicate { actualExpression in
return recordSnapshot(name, identifier: identifier, isDeviceAgnostic: true, usesDrawRect: usesDrawRect,
actualExpression: actualExpression,
shouldIgnoreScale: shouldIgnoreScale)
}
}