Skip to content

Commit 180c010

Browse files
BridgeJS: show unified diff on snapshot mismatch (#600)
1 parent 60b9444 commit 180c010

File tree

1 file changed

+35
-6
lines changed

1 file changed

+35
-6
lines changed

Plugins/BridgeJS/Tests/BridgeJSToolTests/SnapshotTesting.swift

Lines changed: 35 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,17 +22,26 @@ func assertSnapshot(
2222

2323
if FileManager.default.fileExists(atPath: snapshotPath.path) {
2424
let existingSnapshot = try String(contentsOf: snapshotPath, encoding: .utf8)
25-
let ok = existingSnapshot == String(data: input, encoding: .utf8)!
25+
let actual = String(data: input, encoding: .utf8)!
26+
let ok = existingSnapshot == actual
2627
let actualFilePath = snapshotPath.path + ".actual"
2728
let updateSnapshots = ProcessInfo.processInfo.environment["UPDATE_SNAPSHOTS"] != nil
28-
func buildComment() -> Comment {
29-
"Snapshot mismatch: \(actualFilePath) \(snapshotPath.path)"
30-
}
29+
3130
if !updateSnapshots {
32-
#expect(ok, buildComment(), sourceLocation: sourceLocation)
3331
if !ok {
34-
try input.write(to: URL(fileURLWithPath: actualFilePath))
32+
try actual.write(toFile: actualFilePath, atomically: true, encoding: .utf8)
3533
}
34+
35+
let diff = ok ? nil : unifiedDiff(expectedPath: snapshotPath.path, actualPath: actualFilePath)
36+
func buildComment() -> Comment {
37+
var message = "Snapshot mismatch: \(actualFilePath) \(snapshotPath.path)"
38+
if let diff {
39+
message.append("\n\n" + diff)
40+
}
41+
return Comment(rawValue: message)
42+
}
43+
44+
#expect(ok, buildComment(), sourceLocation: sourceLocation)
3645
} else {
3746
try input.write(to: snapshotPath)
3847
}
@@ -41,3 +50,23 @@ func assertSnapshot(
4150
#expect(Bool(false), "Snapshot created at \(snapshotPath.path)", sourceLocation: sourceLocation)
4251
}
4352
}
53+
54+
private func unifiedDiff(expectedPath: String, actualPath: String) -> String? {
55+
let process = Process()
56+
process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
57+
process.arguments = ["diff", "-u", expectedPath, actualPath]
58+
let output = Pipe()
59+
process.standardOutput = output
60+
process.standardError = Pipe()
61+
62+
do {
63+
try process.run()
64+
} catch {
65+
return nil
66+
}
67+
process.waitUntilExit()
68+
69+
let data = output.fileHandleForReading.readDataToEndOfFile()
70+
guard !data.isEmpty else { return nil }
71+
return String(data: data, encoding: .utf8)
72+
}

0 commit comments

Comments
 (0)