Skip to content

Commit 29ec14d

Browse files
atamez31allevato
authored andcommitted
Implement XCTAssertDiff function in DiagnosingTestCase class (swiftlang#89)
1 parent ccf3637 commit 29ec14d

File tree

1 file changed

+35
-3
lines changed

1 file changed

+35
-3
lines changed

tools/swift-format/Tests/SwiftFormatTests/DiagnosingTestCase.swift

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,14 +87,46 @@ public class DiagnosingTestCase: XCTestCase {
8787
let syntax = try SourceFileSyntax.parse(input)
8888
let formatter = formatType.init(context: context!)
8989
let result = formatter.visit(syntax)
90-
91-
XCTAssertEqual(result.description, expected,
92-
file: file, line: line)
90+
XCTAssertDiff(result: result.description, expected: expected, file: file, line: line)
9391
} catch {
9492
XCTFail("\(error)", file: file, line: line)
9593
}
9694
}
9795

96+
/// Asserts that the two expressions have the same value, and provides a detailed
97+
/// message in the case there is a difference between both expression.
98+
///
99+
/// - Parameters:
100+
/// - result: The result of formatting the input code.
101+
/// - expected: The expected result of formatting the input code.
102+
/// - file: The file the test resides in (defaults to the current caller's file)
103+
/// - line: The line the test resides in (defaults to the current caller's line)
104+
func XCTAssertDiff(result: String, expected: String, file: StaticString, line: UInt) {
105+
let resultLines = result.components(separatedBy: .newlines)
106+
let expectedLines = expected.components(separatedBy: .newlines)
107+
let minCount = min(resultLines.count, expectedLines.count)
108+
let maxCount = max(resultLines.count, expectedLines.count)
109+
110+
var index = 0
111+
// Iterates through both expressions while there are no differences.
112+
while index < minCount && resultLines[index] == expectedLines[index] { index += 1 }
113+
114+
// If the index is not the same as the number of lines, it's because a
115+
// difference was found.
116+
if maxCount != index {
117+
let message = """
118+
Actual and expected have a difference on line of code \(index + 1)
119+
Actual line of code: "\(resultLines[index])"
120+
Expected line of code: "\(expectedLines[index])"
121+
ACTUAL:
122+
("\(result)")
123+
EXPECTED:
124+
("\(expected)")
125+
"""
126+
XCTFail(message, file: file, line: line)
127+
}
128+
}
129+
98130
/// Asserts that a specific diagnostic message was not emitted.
99131
///
100132
/// - Parameters:

0 commit comments

Comments
 (0)