-
Notifications
You must be signed in to change notification settings - Fork 0
/
XCTestCase+Snapshot.swift
57 lines (44 loc) · 2.42 KB
/
XCTestCase+Snapshot.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
import XCTest
extension XCTestCase {
func assert(snapshot: UIImage, named name: String, file: StaticString = #file, line: UInt = #line) {
let snapshotURL = makeSnapshotURL(named: name, file: file)
let snapshotData = makeSnapshotData(for: snapshot, file: file, line: line)
guard let storedSnapshotData = try? Data(contentsOf: snapshotURL) else {
XCTFail("Failed to load stored snapshot at URL: \(snapshotURL). Use the `record` method to store a snapshot before asserting.", file: file, line: line)
return
}
if snapshotData != storedSnapshotData {
let temporarySnapshotURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
.appendingPathComponent(snapshotURL.lastPathComponent)
try? snapshotData?.write(to: temporarySnapshotURL)
XCTFail("New snapshot does not match stored snapshot. New snapshot URL: \(temporarySnapshotURL), Stored snapshot URL: \(snapshotURL)", file: file, line: line)
}
}
func record(snapshot: UIImage, named name: String, file: StaticString = #file, line: UInt = #line) {
let snapshotURL = makeSnapshotURL(named: name, file: file)
let snapshotData = makeSnapshotData(for: snapshot, file: file, line: line)
do {
try FileManager.default.createDirectory(
at: snapshotURL.deletingLastPathComponent(),
withIntermediateDirectories: true
)
try snapshotData?.write(to: snapshotURL)
XCTFail("Record succeeded - use 'assert' to compair the Snapshots from now on.", file: file, line: line)
} catch {
XCTFail("Failed to record snapshot with error: \(error)", file: file, line: line)
}
}
private func makeSnapshotURL(named name: String, file: StaticString) -> URL {
return URL(fileURLWithPath: String(describing: file))
.deletingLastPathComponent()
.appendingPathComponent("snapshots")
.appendingPathComponent("\(name).png")
}
private func makeSnapshotData(for snapshot: UIImage, file: StaticString, line: UInt) -> Data? {
guard let data = snapshot.pngData() else {
XCTFail("Failed to generate PNG data representation from snapshot", file: file, line: line)
return nil
}
return data
}
}