-
Notifications
You must be signed in to change notification settings - Fork 635
/
FormatterTests.swift
565 lines (504 loc) · 18.7 KB
/
FormatterTests.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//
// FormatterTests.swift
// SwiftFormat
//
// Created by Nick Lockwood on 30/08/2016.
// Copyright 2016 Nick Lockwood
//
// Distributed under the permissive MIT license
// Get the latest version from here:
//
// https://github.com/nicklockwood/SwiftFormat
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import SwiftFormat
import XCTest
class FormatterTests: XCTestCase {
func testRemoveCurrentTokenWhileEnumerating() {
let input: [Token] = [
.identifier("foo"),
.identifier("bar"),
.identifier("baz"),
]
var output: [Token] = []
let formatter = Formatter(input, options: .default)
formatter.forEachToken { i, token in
output.append(token)
if i == 1 {
formatter.removeToken(at: i)
}
}
XCTAssertEqual(output, input)
}
func testRemovePreviousTokenWhileEnumerating() {
let input: [Token] = [
.identifier("foo"),
.identifier("bar"),
.identifier("baz"),
]
var output: [Token] = []
let formatter = Formatter(input, options: .default)
formatter.forEachToken { i, token in
output.append(token)
if i == 1 {
formatter.removeToken(at: i - 1)
}
}
XCTAssertEqual(output, input)
}
func testRemoveNextTokenWhileEnumerating() {
let input: [Token] = [
.identifier("foo"),
.identifier("bar"),
.identifier("baz"),
]
var output: [Token] = []
let formatter = Formatter(input, options: .default)
formatter.forEachToken { i, token in
output.append(token)
if i == 1 {
formatter.removeToken(at: i + 1)
}
}
XCTAssertEqual(output, [Token](input.dropLast()))
}
func testIndexBeforeComment() {
let input: [Token] = [
.identifier("foo"),
.startOfScope("//"),
.space(" "),
.commentBody("bar"),
.linebreak("\n", 1),
]
let formatter = Formatter(input, options: .default)
let index = formatter.index(before: 4, where: { !$0.isSpaceOrComment })
XCTAssertEqual(index, 0)
}
func testIndexBeforeMultilineComment() {
let input: [Token] = [
.identifier("foo"),
.startOfScope("/*"),
.space(" "),
.commentBody("bar"),
.space(" "),
.endOfScope("*/"),
.linebreak("\n", 1),
]
let formatter = Formatter(input, options: .default)
let index = formatter.index(before: 6, where: { !$0.isSpaceOrComment })
XCTAssertEqual(index, 0)
}
// MARK: enable/disable directives
func testDisableRule() {
let input = "//swiftformat:disable spaceAroundOperators\nlet foo : Int=5;"
let output = "// swiftformat:disable spaceAroundOperators\nlet foo : Int=5\n"
XCTAssertEqual(try format(input, rules: FormatRules.default).output, output)
}
func testDirectiveInMiddleOfComment() {
let input = "//fixme: swiftformat:disable spaceAroundOperators - bug\nlet foo : Int=5;"
let output = "// FIXME: swiftformat:disable spaceAroundOperators - bug\nlet foo : Int=5\n"
XCTAssertEqual(try format(input, rules: FormatRules.default).output, output)
}
func testDisableAndReEnableRules() {
let input = """
// swiftformat:disable indent blankLinesBetweenScopes redundantSelf
class Foo {
let _foo = "foo"
func foo() {
print(self._foo)
}
}
// swiftformat:enable indent redundantSelf
class Bar {
let _bar = "bar"
func bar() {
print(_bar)
}
}
"""
let output = """
// swiftformat:disable indent blankLinesBetweenScopes redundantSelf
class Foo {
let _foo = "foo"
func foo() {
print(self._foo)
}
}
// swiftformat:enable indent redundantSelf
class Bar {
let _bar = "bar"
func bar() {
print(_bar)
}
}
"""
XCTAssertEqual(try format(input + "\n", rules: FormatRules.default).output, output + "\n")
}
func testDisableAllRules() {
let input = "//swiftformat:disable all\nlet foo : Int=5;"
let output = "// swiftformat:disable all\nlet foo : Int=5;"
XCTAssertEqual(try format(input, rules: FormatRules.default).output, output)
}
func testDisableAndReEnableAllRules() {
let input = """
// swiftformat:disable all
class Foo {
let _foo = "foo"
func foo() {
print(self._foo)
}
}
// swiftformat:enable all
class Bar {
let _bar = "bar"
func bar() {
print(_bar)
}
}
"""
let output = """
// swiftformat:disable all
class Foo {
let _foo = "foo"
func foo() {
print(self._foo)
}
}
// swiftformat:enable all
class Bar {
let _bar = "bar"
func bar() {
print(_bar)
}
}
"""
XCTAssertEqual(try format(input + "\n", rules: FormatRules.default).output, output + "\n")
}
func testDisableAllRulesAndReEnableOneRule() {
let input = "//swiftformat:disable all\nlet foo : Int=5;\n//swiftformat:enable linebreakAtEndOfFile"
let output = "// swiftformat:disable all\nlet foo : Int=5;\n//swiftformat:enable linebreakAtEndOfFile\n"
XCTAssertEqual(try format(input, rules: FormatRules.default).output, output)
}
func testDisableNext() {
let input = "//swiftformat:disable:next all\nlet foo : Int=5;\nlet foo : Int=5;"
let output = "// swiftformat:disable:next all\nlet foo : Int=5;\nlet foo: Int = 5\n"
XCTAssertEqual(try format(input, rules: FormatRules.default).output, output)
}
func testEnableNext() {
let input = "//swiftformat:disable all\n//swiftformat:enable:next all\nlet foo : Int=5;\nlet foo : Int=5;"
let output = "// swiftformat:disable all\n//swiftformat:enable:next all\nlet foo: Int = 5\nlet foo : Int=5;"
XCTAssertEqual(try format(input, rules: FormatRules.default).output, output)
}
func testDisableRuleWithMultilineComment() {
let input = "/*swiftformat:disable spaceAroundOperators*/let foo : Int=5;"
let output = "/* swiftformat:disable spaceAroundOperators */ let foo : Int=5\n"
XCTAssertEqual(try format(input, rules: FormatRules.default).output, output)
}
func testDisableAllRulesWithMultilineComment() {
let input = "/*swiftformat:disable all*/let foo : Int=5;"
let output = "/*swiftformat:disable all*/let foo : Int=5;"
XCTAssertEqual(try format(input, rules: FormatRules.default).output, output)
}
func testDisableNextWithMultilineComment() {
let input = "/*swiftformat:disable:next all*/\nlet foo : Int=5;\nlet foo : Int=5;"
let output = "/* swiftformat:disable:next all */\nlet foo : Int=5;\nlet foo: Int = 5\n"
XCTAssertEqual(try format(input, rules: FormatRules.default).output, output)
}
func testEnableNextWithMultilineComment() {
let input = "//swiftformat:disable all\n/*swiftformat:enable:next all*/\nlet foo : Int=5;\nlet foo : Int=5;"
let output = "// swiftformat:disable all\n/*swiftformat:enable:next all*/\nlet foo: Int = 5\nlet foo : Int=5;"
XCTAssertEqual(try format(input, rules: FormatRules.default).output, output)
}
func testDisableLinewrap() {
let input = """
// swiftformat:disable all
let foo = bar.baz(some: param).quux("a string of some sort")
"""
let options = FormatOptions(maxWidth: 10)
XCTAssertEqual(try format(input, rules: FormatRules.default, options: options).output, input)
}
func testMalformedDirective() {
let input = "// swiftformat:disbible all"
XCTAssertThrowsError(try format(input, rules: FormatRules.default).output) { error in
XCTAssert("\(error)".contains("Unknown directive swiftformat:disbible"))
}
}
func testMalformedDirective2() {
let input = "// swiftformat: --disable all"
XCTAssertThrowsError(try format(input, rules: FormatRules.default).output) { error in
XCTAssertEqual("\(error)", "Expected directive after \'swiftformat:\' prefix on line 1")
}
}
// MARK: options directive
func testAllmanOption() {
let input = """
// swiftformat:options --allman true
func foo() {
print("bar")
}
"""
let output = """
// swiftformat:options --allman true
func foo()
{
print("bar")
}
"""
XCTAssertEqual(try format(input, rules: FormatRules.default).output, output)
}
func testIndentNext() {
let input = """
class Foo {
// swiftformat:options:next --indent 2
func bar() {
print("bar")
}
func baz() {
print("bar")
}
}
"""
let output = """
class Foo {
// swiftformat:options:next --indent 2
func bar() {
print("bar")
}
func baz() {
print("bar")
}
}
"""
XCTAssertEqual(try format(input, rules: FormatRules.default).output, output)
}
func testSwiftVersionNext() {
let input = """
// swiftformat:options:next --swiftversion 5.2
let foo1 = bar.map { $0.foo }
let foo2 = bar.map { $0.foo }
"""
let output = """
// swiftformat:options:next --swiftversion 5.2
let foo1 = bar.map(\\.foo)
let foo2 = bar.map { $0.foo }
"""
XCTAssertEqual(try format(input, rules: FormatRules.default).output, output)
}
func testMalformedOption() {
let input = """
// swiftformat:options blooblahbleh
"""
XCTAssertThrowsError(try format(input, rules: FormatRules.default).output) { error in
XCTAssert("\(error)".contains("Unknown option blooblahbleh"))
}
}
func testInvalidOption() {
let input = """
// swiftformat:options --foobar baz
"""
XCTAssertThrowsError(try format(input, rules: FormatRules.default).output) { error in
XCTAssert("\(error)".contains("Unknown option --foobar"))
}
}
func testInvalidOptionValue() {
let input = """
// swiftformat:options --indent baz
"""
XCTAssertThrowsError(try format(input, rules: FormatRules.default).output) { error in
XCTAssert("\(error)".contains("Unsupported --indent value"))
}
}
func testDeprecatedOptionValue() {
let input = """
// swiftformat:options --ranges spaced
"""
XCTAssertNoThrow(try format(input, rules: FormatRules.default).output)
}
// MARK: linebreaks
func testLinebreakAfterLinebreakReturnsCorrectIndex() {
let formatter = Formatter([
.linebreak("\n", 1),
.linebreak("\n", 1),
])
XCTAssertEqual(formatter.linebreakToken(for: 1), .linebreak("\n", 1))
}
func testOriginalLinePreservedAfterFormatting() {
let formatter = Formatter([
.identifier("foo"),
.space(" "),
.startOfScope("{"),
.linebreak("\n", 1),
.linebreak("\n", 2),
.space(" "),
.identifier("bar"),
.linebreak("\n", 3),
.endOfScope("}"),
])
FormatRule.blankLinesAtStartOfScope.apply(with: formatter)
XCTAssertEqual(formatter.tokens, [
.identifier("foo"),
.space(" "),
.startOfScope("{"),
.linebreak("\n", 2),
.space(" "),
.identifier("bar"),
.linebreak("\n", 3),
.endOfScope("}"),
])
}
// MARK: range
func testCodeOutsideRangeNotFormatted() throws {
let input = tokenize("""
func foo () {
var bar = 5
}
""")
for range in [0 ..< 2, 5 ..< 7, 14 ..< 16, 17 ..< 19] {
XCTAssertEqual(try format(input,
rules: FormatRules.all,
range: range).tokens, input)
}
let output1 = tokenize("""
func foo () {
var bar = 5
}
""")
XCTAssertEqual(try format(
input,
rules: [.consecutiveSpaces],
range: 10 ..< 13
).tokens, output1)
let output2 = """
func foo () {
var bar = 5
}
"""
XCTAssertEqual(try sourceCode(for: format(
input,
rules: [.blankLinesAtStartOfScope],
range: 6 ..< 9
).tokens), output2)
}
// MARK: endOfScope
func testEndOfScopeInSwitch() throws {
let formatter = Formatter(tokenize("""
switch foo {
case bar: break
}
"""))
XCTAssertEqual(formatter.endOfScope(at: 4), 13)
}
// MARK: change tracking
func testTrackChangesInFirstLine() {
let formatter = Formatter(tokenize("foo bar\nbaz"), trackChanges: true)
let tokens = formatter.tokens
formatter.removeLastToken()
XCTAssertNotEqual(formatter.tokens, tokens)
XCTAssertEqual(formatter.changes.count, 1)
XCTAssertEqual(formatter.changes.first?.line, 2)
}
func testTrackChangesInSecondLine() {
let formatter = Formatter(tokenize("foo\nbar\nbaz"), trackChanges: true)
let tokens = formatter.tokens
formatter.removeToken(at: formatter.tokens.firstIndex(of: .identifier("bar"))!)
XCTAssertNotEqual(formatter.tokens, tokens)
XCTAssertEqual(formatter.changes.count, 1)
XCTAssertEqual(formatter.changes.first?.line, 2)
}
func testTrackChangesInLastLine() {
let formatter = Formatter(tokenize("foo\nbar\nbaz"), trackChanges: true)
let tokens = formatter.tokens
formatter.removeLastToken()
XCTAssertNotEqual(formatter.tokens, tokens)
XCTAssertEqual(formatter.changes.count, 1)
XCTAssertEqual(formatter.changes.first?.line, 3)
}
func testTrackChangesInSingleLine() {
let formatter = Formatter(tokenize("foo bar"), trackChanges: true)
let tokens = formatter.tokens
formatter.removeToken(at: 0)
XCTAssertNotEqual(formatter.tokens, tokens)
XCTAssertEqual(formatter.changes.count, 1)
}
func testTrackChangesIgnoresLinebreakIndex() {
let formatter = Formatter(tokenize("\n\n"), trackChanges: true)
var tokens = formatter.tokens
tokens.insert(tokens.removeLast(), at: 0)
XCTAssertNotEqual(formatter.tokens, tokens)
formatter.replaceTokens(in: 0 ..< 2, with: tokens)
XCTAssert(formatter.changes.isEmpty)
}
func testTrackRemovalOfBlankLineFollowedByBlankLine() {
let formatter = Formatter(tokenize("foo\n\n\n"), trackChanges: true)
let tokens = formatter.tokens
formatter.removeToken(at: 2)
XCTAssertNotEqual(formatter.tokens, tokens)
XCTAssertEqual(formatter.changes.count, 1)
XCTAssertEqual(formatter.changes.first?.line, 2)
}
func testTrackRemovalOfBlankLineAfterBlankLine() {
let formatter = Formatter(tokenize("foo\n\n\n"), trackChanges: true)
let tokens = formatter.tokens
formatter.removeLastToken()
XCTAssertNotEqual(formatter.tokens, tokens)
XCTAssertEqual(formatter.changes.count, 1)
XCTAssertEqual(formatter.changes.first?.line, 3)
}
func testMoveTokensToEarlierPositionTrackedAsMoves() {
let formatter = Formatter(tokenize("foo()\nbar()\n"), trackChanges: true)
formatter.moveTokens(in: 4 ... 7, to: 0)
XCTAssertEqual(sourceCode(for: formatter.tokens), "bar()\nfoo()\n")
XCTAssert(!formatter.changes.isEmpty)
XCTAssert(formatter.changes.allSatisfy(\.isMove))
}
func testMoveTokensToFollowingPositionTrackedAsMoves() {
let formatter = Formatter(tokenize("foo()\nbar()\n"), trackChanges: true)
formatter.moveTokens(in: 0 ... 3, to: 8)
XCTAssertEqual(sourceCode(for: formatter.tokens), "bar()\nfoo()\n")
XCTAssert(!formatter.changes.isEmpty)
XCTAssert(formatter.changes.allSatisfy(\.isMove))
}
func testReplaceAllTokensTracksMoves() {
let input: [Token] = [
tokenize("foo()"), [.linebreak("\n", 0)],
[.linebreak("\n", 1)],
tokenize("foobar()"), [.linebreak("\n", 2)],
[.linebreak("\n", 3)],
tokenize("bar()"), [.linebreak("\n", 4)],
[.linebreak("\n", 5)],
tokenize("baaz()"), [.linebreak("\n", 6)],
].flatMap { $0 }
let output: [Token] = [
tokenize("bar()"), [.linebreak("\n", 4)],
[.linebreak("\n", 1)],
tokenize("barfoo()"), [.linebreak("\n", 2)],
[.linebreak("\n", 3)],
tokenize("foo()"), [.linebreak("\n", 0)],
[.linebreak("\n", 5)],
tokenize("quux()"), [.linebreak("\n", 6)],
].flatMap { $0 }
let formatter = Formatter(input, trackChanges: true)
formatter.replaceAllTokens(with: output)
XCTAssertEqual(sourceCode(for: formatter.tokens), sourceCode(for: output))
// The changes should include both moves and non-moves
XCTAssert(formatter.changes.contains(where: \.isMove))
XCTAssert(formatter.changes.contains(where: { !$0.isMove }))
}
}