-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathTestHelpers.swift
333 lines (294 loc) Β· 14.6 KB
/
TestHelpers.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
import Foundation
import SourceKittenFramework
@testable import SwiftLintFramework
import XCTest
private let violationMarker = "β"
private extension File {
static func temporary(withContents contents: String) -> File {
let url = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent(UUID().uuidString)
.appendingPathExtension("swift")
_ = try? contents.data(using: .utf8)!.write(to: url)
return File(path: url.path)!
}
func makeCompilerArguments() -> [String] {
return ["-sdk", sdkPath(), "-j4", path!]
}
}
extension String {
func stringByAppendingPathComponent(_ pathComponent: String) -> String {
return bridge().appendingPathComponent(pathComponent)
}
}
let allRuleIdentifiers = Array(masterRuleList.list.keys)
func violations(_ string: String, config: Configuration = Configuration()!,
requiresFileOnDisk: Bool = false) -> [StyleViolation] {
File.clearCaches()
let stringStrippingMarkers = string.replacingOccurrences(of: violationMarker, with: "")
guard requiresFileOnDisk else {
let file = File(contents: stringStrippingMarkers)
let linter = Linter(file: file, configuration: config)
return linter.styleViolations
}
let file = File.temporary(withContents: stringStrippingMarkers)
let linter = Linter(file: file, configuration: config, compilerArguments: file.makeCompilerArguments())
return linter.styleViolations.map { violation in
let locationWithoutFile = Location(file: nil, line: violation.location.line,
character: violation.location.character)
return StyleViolation(ruleDescription: violation.ruleDescription, severity: violation.severity,
location: locationWithoutFile, reason: violation.reason)
}
}
private func cleanedContentsAndMarkerOffsets(from contents: String) -> (String, [Int]) {
var contents = contents.bridge()
var markerOffsets = [Int]()
var markerRange = contents.range(of: violationMarker)
while markerRange.location != NSNotFound {
markerOffsets.append(markerRange.location)
contents = contents.replacingCharacters(in: markerRange, with: "").bridge()
markerRange = contents.range(of: violationMarker)
}
return (contents.bridge(), markerOffsets.sorted())
}
private func render(violations: [StyleViolation], in contents: String) -> String {
var contents = contents.bridge().lines().map { $0.content }
for violation in violations.sorted(by: { $0.location > $1.location }) {
guard let line = violation.location.line,
let character = violation.location.character else { continue }
let message = String(repeating: " ", count: character - 1) + "^ " + [
"\(violation.severity.rawValue): ",
"\(violation.ruleDescription.name) Violation: ",
violation.reason,
" (\(violation.ruleDescription.identifier))"].joined()
if line >= contents.count {
contents.append(message)
} else {
contents.insert(message, at: line)
}
}
return (["```"] + contents + ["```"]).joined(separator: "\n")
}
private func render(locations: [Location], in contents: String) -> String {
var contents = contents.bridge().lines().map { $0.content }
for location in locations.sorted(by: > ) {
guard let line = location.line, let character = location.character else { continue }
let content = NSMutableString(string: contents[line - 1])
content.insert("β", at: character - 1)
contents[line - 1] = content.bridge()
}
return (["```"] + contents + ["```"]).joined(separator: "\n")
}
private extension Configuration {
func assertCorrection(_ before: String, expected: String) {
let (cleanedBefore, markerOffsets) = cleanedContentsAndMarkerOffsets(from: before)
let file = File.temporary(withContents: cleanedBefore)
// expectedLocations are needed to create before call `correct()`
let expectedLocations = markerOffsets.map { Location(file: file, characterOffset: $0) }
let includeCompilerArguments = self.rules.contains(where: { $0 is AnalyzerRule })
let compilerArguments = includeCompilerArguments ? file.makeCompilerArguments() : []
let linter = Linter(file: file, configuration: self, compilerArguments: compilerArguments)
let corrections = linter.correct().sorted { $0.location < $1.location }
if expectedLocations.isEmpty {
XCTAssertEqual(corrections.count, before != expected ? 1 : 0)
} else {
XCTAssertEqual(corrections.count, expectedLocations.count)
for (correction, expectedLocation) in zip(corrections, expectedLocations) {
XCTAssertEqual(correction.location, expectedLocation)
}
}
XCTAssertEqual(file.contents, expected)
let path = file.path!
do {
let corrected = try String(contentsOfFile: path, encoding: .utf8)
XCTAssertEqual(corrected, expected)
} catch {
XCTFail("couldn't read file at path '\(path)': \(error)")
}
}
}
private extension String {
func toStringLiteral() -> String {
return "\"" + replacingOccurrences(of: "\n", with: "\\n") + "\""
}
}
internal func makeConfig(_ ruleConfiguration: Any?, _ identifier: String,
skipDisableCommandTests: Bool = false) -> Configuration? {
let superfluousDisableCommandRuleIdentifier = SuperfluousDisableCommandRule.description.identifier
let identifiers = skipDisableCommandTests ? [identifier] : [identifier, superfluousDisableCommandRuleIdentifier]
if let ruleConfiguration = ruleConfiguration, let ruleType = masterRuleList.list[identifier] {
// The caller has provided a custom configuration for the rule under test
return (try? ruleType.init(configuration: ruleConfiguration)).flatMap { configuredRule in
let rules = skipDisableCommandTests ? [configuredRule] : [configuredRule, SuperfluousDisableCommandRule()]
return Configuration(rulesMode: .whitelisted(identifiers), configuredRules: rules)
}
}
return Configuration(rulesMode: .whitelisted(identifiers))
}
private func testCorrection(_ correction: (String, String),
configuration config: Configuration,
testMultiByteOffsets: Bool) {
config.assertCorrection(correction.0, expected: correction.1)
if testMultiByteOffsets {
config.assertCorrection(addEmoji(correction.0), expected: addEmoji(correction.1))
}
}
private func addEmoji(_ string: String) -> String {
return "/* π¨βπ©βπ§βπ¦π¨βπ©βπ§βπ¦π¨βπ©βπ§βπ¦ */\n\(string)"
}
private func addShebang(_ string: String) -> String {
return "#!/usr/bin/env swift\n\(string)"
}
extension XCTestCase {
func verifyRule(_ ruleDescription: RuleDescription,
ruleConfiguration: Any? = nil,
commentDoesntViolate: Bool = true,
stringDoesntViolate: Bool = true,
skipCommentTests: Bool = false,
skipStringTests: Bool = false,
skipDisableCommandTests: Bool = false,
testMultiByteOffsets: Bool = true,
testShebang: Bool = true) {
guard ruleDescription.minSwiftVersion <= .current else {
return
}
guard let config = makeConfig(ruleConfiguration,
ruleDescription.identifier,
skipDisableCommandTests: skipDisableCommandTests) else {
XCTFail("Failed to create configuration")
return
}
let disableCommands: [String]
if skipDisableCommandTests {
disableCommands = []
} else {
disableCommands = ruleDescription.allIdentifiers.map { "// swiftlint:disable \($0)\n" }
}
self.verifyLint(ruleDescription, config: config, commentDoesntViolate: commentDoesntViolate,
stringDoesntViolate: stringDoesntViolate, skipCommentTests: skipCommentTests,
skipStringTests: skipStringTests, disableCommands: disableCommands,
testMultiByteOffsets: testMultiByteOffsets, testShebang: testShebang)
self.verifyCorrections(ruleDescription, config: config, disableCommands: disableCommands,
testMultiByteOffsets: testMultiByteOffsets)
}
func verifyLint(_ ruleDescription: RuleDescription,
config: Configuration,
commentDoesntViolate: Bool = true,
stringDoesntViolate: Bool = true,
skipCommentTests: Bool = false,
skipStringTests: Bool = false,
disableCommands: [String] = [],
testMultiByteOffsets: Bool = true,
testShebang: Bool = true) {
func verify(triggers: [String], nonTriggers: [String]) {
verifyExamples(triggers: triggers, nonTriggers: nonTriggers, configuration: config,
requiresFileOnDisk: ruleDescription.requiresFileOnDisk)
}
let triggers = ruleDescription.triggeringExamples
let nonTriggers = ruleDescription.nonTriggeringExamples
verify(triggers: triggers, nonTriggers: nonTriggers)
if testMultiByteOffsets {
verify(triggers: triggers.map(addEmoji), nonTriggers: nonTriggers.map(addEmoji))
}
if testShebang {
verify(triggers: triggers.map(addShebang), nonTriggers: nonTriggers.map(addShebang))
}
func makeViolations(_ string: String) -> [StyleViolation] {
return violations(string, config: config, requiresFileOnDisk: ruleDescription.requiresFileOnDisk)
}
// Comment doesn't violate
if !skipCommentTests {
XCTAssertEqual(
triggers.flatMap({ makeViolations("/*\n " + $0 + "\n */") }).count,
commentDoesntViolate ? 0 : triggers.count
)
}
// String doesn't violate
if !skipStringTests {
XCTAssertEqual(
triggers.flatMap({ makeViolations($0.toStringLiteral()) }).count,
stringDoesntViolate ? 0 : triggers.count
)
}
// "disable" commands doesn't violate
for command in disableCommands {
XCTAssert(triggers.flatMap({ makeViolations(command + $0) }).isEmpty)
}
}
func verifyCorrections(_ ruleDescription: RuleDescription, config: Configuration,
disableCommands: [String], testMultiByteOffsets: Bool) {
// corrections
ruleDescription.corrections.forEach {
testCorrection($0, configuration: config, testMultiByteOffsets: testMultiByteOffsets)
}
// make sure strings that don't trigger aren't corrected
ruleDescription.nonTriggeringExamples.forEach {
testCorrection(($0, $0), configuration: config, testMultiByteOffsets: testMultiByteOffsets)
}
// "disable" commands do not correct
ruleDescription.corrections.forEach { before, _ in
for command in disableCommands {
let beforeDisabled = command + before
let expectedCleaned = cleanedContentsAndMarkerOffsets(from: beforeDisabled).0
config.assertCorrection(expectedCleaned, expected: expectedCleaned)
}
}
}
private func verifyExamples(triggers: [String], nonTriggers: [String],
configuration config: Configuration, requiresFileOnDisk: Bool) {
// Non-triggering examples don't violate
for nonTrigger in nonTriggers {
let unexpectedViolations = violations(nonTrigger, config: config,
requiresFileOnDisk: requiresFileOnDisk)
if unexpectedViolations.isEmpty { continue }
let nonTriggerWithViolations = render(violations: unexpectedViolations, in: nonTrigger)
XCTFail("nonTriggeringExample violated: \n\(nonTriggerWithViolations)")
}
// Triggering examples violate
for trigger in triggers {
let triggerViolations = violations(trigger, config: config,
requiresFileOnDisk: requiresFileOnDisk)
// Triggering examples with violation markers violate at the marker's location
let (cleanTrigger, markerOffsets) = cleanedContentsAndMarkerOffsets(from: trigger)
if markerOffsets.isEmpty {
if triggerViolations.isEmpty {
XCTFail("triggeringExample did not violate: \n```\n\(trigger)\n```")
}
continue
}
let file = File(contents: cleanTrigger)
let expectedLocations = markerOffsets.map { Location(file: file, characterOffset: $0) }
// Assert violations on unexpected location
let violationsAtUnexpectedLocation = triggerViolations
.filter { !expectedLocations.contains($0.location) }
if !violationsAtUnexpectedLocation.isEmpty {
XCTFail("triggeringExample violate at unexpected location: \n" +
"\(render(violations: violationsAtUnexpectedLocation, in: trigger))")
}
// Assert locations missing violation
let violatedLocations = triggerViolations.map { $0.location }
let locationsWithoutViolation = expectedLocations
.filter { !violatedLocations.contains($0) }
if !locationsWithoutViolation.isEmpty {
XCTFail("triggeringExample did not violate at expected location: \n" +
"\(render(locations: locationsWithoutViolation, in: cleanTrigger))")
}
XCTAssertEqual(triggerViolations.count, expectedLocations.count)
for (triggerViolation, expectedLocation) in zip(triggerViolations, expectedLocations) {
XCTAssertEqual(triggerViolation.location, expectedLocation,
"'\(trigger)' violation didn't match expected location.")
}
}
}
func checkError<T: Error & Equatable>(_ error: T, closure: () throws -> Void) {
do {
try closure()
XCTFail("No error caught")
} catch let rError as T {
if error != rError {
XCTFail("Wrong error caught. Got \(rError) but was expecting \(error)")
}
} catch {
XCTFail("Wrong error caught")
}
}
}