forked from pinterest/ktlint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KtLintTest.kt
564 lines (538 loc) · 24.1 KB
/
KtLintTest.kt
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
package com.pinterest.ktlint.core
import com.pinterest.ktlint.core.AutoCorrectErrorRule.Companion.STRING_VALUE_AFTER_AUTOCORRECT
import com.pinterest.ktlint.core.DummyRuleWithCustomEditorConfigProperty.Companion.SOME_CUSTOM_RULE_PROPERTY
import com.pinterest.ktlint.core.api.UsesEditorConfigProperties
import com.pinterest.ktlint.core.ast.ElementType.REGULAR_STRING_PART
import com.pinterest.ktlint.core.ast.isRoot
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.ec4j.core.model.PropertyType
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafElement
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
class KtLintTest {
/**
* API Consumers directly use the ktlint-core module. Tests in this module should guarantee that the API is kept
* stable.
*/
@Nested
inner class ApiConsumer {
@Nested
inner class LintViaExperimentalParams {
@Test
fun `Given that an empty ruleSet is provided than throw an error`() {
assertThatThrownBy {
KtLint.lint(
KtLint.ExperimentalParams(
fileName = "some-filename",
text = "fun main() {}",
ruleSets = emptyList(),
userData = emptyMap(),
cb = { _, _ -> },
script = false,
editorConfigPath = null,
debug = false
)
)
}.isInstanceOf(IllegalStateException::class.java)
.hasMessage("No runnable rules found. Please ensure that at least one is enabled.")
}
@Test
fun `Given a non empty ruleset and empty userData then do not throw an error`() {
var numberOfRootNodesVisited = 0
KtLint.lint(
KtLint.ExperimentalParams(
fileName = "some-filename",
text = "fun main() {}",
ruleSets = listOf(
RuleSet(
"standard",
DummyRule { node ->
if (node.isRoot()) {
numberOfRootNodesVisited++
}
}
)
),
userData = emptyMap(),
cb = { _, _ -> },
script = false,
editorConfigPath = null,
debug = false
)
)
assertThat(numberOfRootNodesVisited).isEqualTo(1)
}
@Test
fun `Given a non empty ruleset and userData that contains one default editor config property then throw an error`() {
assertThatThrownBy {
KtLint.lint(
KtLint.ExperimentalParams(
fileName = "some-filename",
text = "fun main() {}",
ruleSets = listOf(
RuleSet("standard", DummyRule())
),
userData = mapOf("max_line_length" to "80"),
cb = { _, _ -> },
script = false,
editorConfigPath = null,
debug = false
)
)
}.isInstanceOf(IllegalStateException::class.java)
.hasMessage(
"UserData should not contain '.editorconfig' properties [max_line_length]. Such properties " +
"should be passed via the 'ExperimentalParams.editorConfigOverride' field. Note that " +
"this is only required for properties that (potentially) contain a value that differs " +
"from the actual value in the '.editorconfig' file."
)
}
@Test
fun `Given a non empty ruleset and userData that contains multiple default editor config properties then throw an error`() {
assertThatThrownBy {
KtLint.lint(
KtLint.ExperimentalParams(
fileName = "some-filename",
text = "fun main() {}",
ruleSets = listOf(
RuleSet("standard", DummyRule())
),
userData = mapOf(
"indent_style" to "space",
"indent_size" to "4"
),
cb = { _, _ -> },
script = false,
editorConfigPath = null,
debug = false
)
)
}.isInstanceOf(IllegalStateException::class.java)
.hasMessage(
"UserData should not contain '.editorconfig' properties [indent_size, indent_style]. Such" +
" properties should be passed via the 'ExperimentalParams.editorConfigOverride' field. " +
"Note that this is only required for properties that (potentially) contain a value that " +
"differs from the actual value in the '.editorconfig' file."
)
}
@Test
fun `Given a non empty ruleset and userData that refers to a custom Rule property then do throw an error`() {
assertThatThrownBy {
KtLint.lint(
KtLint.ExperimentalParams(
fileName = "some-filename",
text = "fun main() {}",
ruleSets = listOf(
RuleSet("standard", DummyRuleWithCustomEditorConfigProperty())
),
userData = mapOf(SOME_CUSTOM_RULE_PROPERTY to "false"),
cb = { _, _ -> },
script = false,
editorConfigPath = null,
debug = false
)
)
}.isInstanceOf(IllegalStateException::class.java)
.hasMessage(
"UserData should not contain '.editorconfig' properties [$SOME_CUSTOM_RULE_PROPERTY]. Such" +
" properties should be passed via the 'ExperimentalParams.editorConfigOverride' field. " +
"Note that this is only required for properties that (potentially) contain a value that " +
"differs from the actual value in the '.editorconfig' file."
)
}
@Test
fun `Given a rule returning an errors which can and can not be autocorrected than that state of the error can be retrieved in the callback`() {
val code =
"""
val foo = "${AutoCorrectErrorRule.STRING_VALUE_NOT_TO_BE_CORRECTED}"
val bar = "${AutoCorrectErrorRule.STRING_VALUE_TO_BE_AUTOCORRECTED}"
""".trimIndent()
val callbacks = mutableListOf<CallbackResult>()
KtLint.lint(
KtLint.ExperimentalParams(
text = code,
ruleSets = listOf(
RuleSet("standard", AutoCorrectErrorRule())
),
userData = emptyMap(),
cb = { e, corrected ->
callbacks.add(
CallbackResult(
line = e.line,
col = e.col,
ruleId = e.ruleId,
detail = e.detail,
canBeAutoCorrected = e.canBeAutoCorrected,
corrected = corrected
)
)
},
script = false,
editorConfigPath = null,
debug = false
)
)
assertThat(callbacks).containsExactly(
CallbackResult(
line = 1,
col = 12,
ruleId = "auto-correct",
detail = AutoCorrectErrorRule.ERROR_MESSAGE_CAN_NOT_BE_AUTOCORRECTED,
canBeAutoCorrected = false,
corrected = false
),
CallbackResult(
line = 2,
col = 12,
ruleId = "auto-correct",
detail = AutoCorrectErrorRule.ERROR_MESSAGE_CAN_BE_AUTOCORRECTED,
canBeAutoCorrected = true,
corrected = false
)
)
}
}
@Nested
inner class FormatViaExperimentalParams {
@Test
fun `Given that an empty ruleSet is provided than throw an error`() {
assertThatThrownBy {
KtLint.format(
KtLint.ExperimentalParams(
fileName = "some-filename",
text = "fun main() {}",
ruleSets = emptyList(),
userData = emptyMap(),
cb = { _, _ -> },
script = false,
editorConfigPath = null,
debug = false
)
)
}.isInstanceOf(IllegalStateException::class.java)
.hasMessage("No runnable rules found. Please ensure that at least one is enabled.")
}
@Test
fun `Given a non empty ruleset and empty userData then do not throw an error`() {
var numberOfRootNodesVisited = 0
KtLint.format(
KtLint.ExperimentalParams(
fileName = "some-filename",
text = "fun main() {}",
ruleSets = listOf(
RuleSet(
"standard",
DummyRule { node ->
if (node.isRoot()) {
numberOfRootNodesVisited++
}
}
)
),
userData = emptyMap(),
cb = { _, _ -> },
script = false,
editorConfigPath = null,
debug = false
)
)
assertThat(numberOfRootNodesVisited).isEqualTo(1)
}
@Test
fun `Given a non empty ruleset and userData that contains one default editor config property then throw an error`() {
assertThatThrownBy {
KtLint.format(
KtLint.ExperimentalParams(
fileName = "some-filename",
text = "fun main() {}",
ruleSets = listOf(
RuleSet("standard", DummyRule())
),
userData = mapOf("max_line_length" to "80"),
cb = { _, _ -> },
script = false,
editorConfigPath = null,
debug = false
)
)
}.isInstanceOf(IllegalStateException::class.java)
.hasMessage(
"UserData should not contain '.editorconfig' properties [max_line_length]. Such properties " +
"should be passed via the 'ExperimentalParams.editorConfigOverride' field. Note that " +
"this is only required for properties that (potentially) contain a value that differs " +
"from the actual value in the '.editorconfig' file."
)
}
@Test
fun `Given a non empty ruleset and userData that contains multiple default editor config properties then throw an error`() {
assertThatThrownBy {
KtLint.format(
KtLint.ExperimentalParams(
fileName = "some-filename",
text = "fun main() {}",
ruleSets = listOf(
RuleSet("standard", DummyRule())
),
userData = mapOf(
"indent_style" to "space",
"indent_size" to "4"
),
cb = { _, _ -> },
script = false,
editorConfigPath = null,
debug = false
)
)
}.isInstanceOf(IllegalStateException::class.java)
.hasMessage(
"UserData should not contain '.editorconfig' properties [indent_size, indent_style]. Such" +
" properties should be passed via the 'ExperimentalParams.editorConfigOverride' field. " +
"Note that this is only required for properties that (potentially) contain a value that " +
"differs from the actual value in the '.editorconfig' file."
)
}
@Test
fun `Given a non empty ruleset and userData that refers to a custom Rule property then do throw an error`() {
assertThatThrownBy {
KtLint.format(
KtLint.ExperimentalParams(
fileName = "some-filename",
text = "fun main() {}",
ruleSets = listOf(
RuleSet("standard", DummyRuleWithCustomEditorConfigProperty())
),
userData = mapOf(SOME_CUSTOM_RULE_PROPERTY to "false"),
cb = { _, _ -> },
script = false,
editorConfigPath = null,
debug = false
)
)
}.isInstanceOf(IllegalStateException::class.java)
.hasMessage(
"UserData should not contain '.editorconfig' properties [$SOME_CUSTOM_RULE_PROPERTY]. Such" +
" properties should be passed via the 'ExperimentalParams.editorConfigOverride' field. " +
"Note that this is only required for properties that (potentially) contain a value that " +
"differs from the actual value in the '.editorconfig' file."
)
}
}
@Test
fun `Given a rule returning an errors which can and can not be autocorrected than that state of the error can be retrieved in the callback`() {
val code =
"""
val foo = "${AutoCorrectErrorRule.STRING_VALUE_NOT_TO_BE_CORRECTED}"
val bar = "${AutoCorrectErrorRule.STRING_VALUE_TO_BE_AUTOCORRECTED}"
""".trimIndent()
val formattedCode =
"""
val foo = "${AutoCorrectErrorRule.STRING_VALUE_NOT_TO_BE_CORRECTED}"
val bar = "$STRING_VALUE_AFTER_AUTOCORRECT"
""".trimIndent()
val callbacks = mutableListOf<CallbackResult>()
val actualFormattedCode = KtLint.format(
KtLint.ExperimentalParams(
text = code,
ruleSets = listOf(
RuleSet("standard", AutoCorrectErrorRule())
),
userData = emptyMap(),
cb = { e, corrected ->
callbacks.add(
CallbackResult(
line = e.line,
col = e.col,
ruleId = e.ruleId,
detail = e.detail,
canBeAutoCorrected = e.canBeAutoCorrected,
corrected = corrected
)
)
},
script = false,
editorConfigPath = null,
debug = false
)
)
assertThat(actualFormattedCode).isEqualTo(formattedCode)
assertThat(callbacks).containsExactly(
CallbackResult(
line = 1,
col = 12,
ruleId = "auto-correct",
detail = AutoCorrectErrorRule.ERROR_MESSAGE_CAN_NOT_BE_AUTOCORRECTED,
canBeAutoCorrected = false,
corrected = false
),
CallbackResult(
line = 2,
col = 12,
ruleId = "auto-correct",
detail = AutoCorrectErrorRule.ERROR_MESSAGE_CAN_BE_AUTOCORRECTED,
canBeAutoCorrected = true,
corrected = true
)
)
}
}
@Test
fun testRuleExecutionOrder() {
open class R(
private val bus: MutableList<String>,
id: String,
visitorModifiers: Set<VisitorModifier> = emptySet()
) : Rule(id, visitorModifiers) {
private var done = false
override fun visit(
node: ASTNode,
autoCorrect: Boolean,
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit
) {
if (node.isRoot()) {
bus.add("file:$id")
} else if (!done) {
bus.add(id)
done = true
}
}
}
val bus = mutableListOf<String>()
KtLint.lint(
KtLint.ExperimentalParams(
text = "fun main() {}",
ruleSets = listOf(
RuleSet(
"standard",
object : R(
bus = bus,
id = "e",
visitorModifiers = setOf(VisitorModifier.RunAsLateAsPossible)
) {},
object : R(
bus = bus,
id = "d",
visitorModifiers = setOf(
VisitorModifier.RunOnRootNodeOnly,
VisitorModifier.RunAsLateAsPossible
)
) {},
R(
bus = bus,
id = "b"
),
object : R(
bus = bus,
id = "a",
visitorModifiers = setOf(
VisitorModifier.RunOnRootNodeOnly
)
) {},
R(
bus = bus,
id = "c"
)
)
),
cb = { _, _ -> }
)
)
assertThat(bus).isEqualTo(listOf("file:a", "file:b", "file:c", "file:d", "file:e", "b", "c", "e"))
}
@Test
fun testFormatUnicodeBom() {
val code = getResourceAsText("spec/format-unicode-bom.kt.spec")
val actual = KtLint.format(
KtLint.ExperimentalParams(
text = code,
ruleSets = listOf(
RuleSet("standard", DummyRule())
),
cb = { _, _ -> }
)
)
assertThat(actual).isEqualTo(code)
}
}
private class DummyRuleWithCustomEditorConfigProperty :
Rule("dummy-rule-with-custom-editor-config-property"),
UsesEditorConfigProperties {
override val editorConfigProperties: List<UsesEditorConfigProperties.EditorConfigProperty<*>> =
listOf(someCustomRuleProperty)
override fun visit(
node: ASTNode,
autoCorrect: Boolean,
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit
) {
}
companion object {
const val SOME_CUSTOM_RULE_PROPERTY = "some-custom-rule-property"
val someCustomRuleProperty: UsesEditorConfigProperties.EditorConfigProperty<Boolean> =
UsesEditorConfigProperties.EditorConfigProperty(
type = PropertyType.LowerCasingPropertyType(
SOME_CUSTOM_RULE_PROPERTY,
"some-custom-rule-property-description",
PropertyType.PropertyValueParser.BOOLEAN_VALUE_PARSER,
setOf(true.toString(), false.toString())
),
defaultValue = false
)
}
}
/**
* A dummy rule for testing. Optionally the rule can be created with a lambda to be executed for each node visited.
*/
private open class DummyRule(
val block: (node: ASTNode) -> Unit = {}
) : Rule("dummy-rule") {
override fun visit(
node: ASTNode,
autoCorrect: Boolean,
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit
) {
block(node)
}
}
/**
* A dummy rule for testing
*/
private class AutoCorrectErrorRule : Rule("auto-correct") {
override fun visit(
node: ASTNode,
autoCorrect: Boolean,
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit
) {
if (node.elementType == REGULAR_STRING_PART) {
when (node.text) {
STRING_VALUE_TO_BE_AUTOCORRECTED -> {
emit(node.startOffset, ERROR_MESSAGE_CAN_BE_AUTOCORRECTED, true)
if (autoCorrect) {
(node as LeafElement).replaceWithText(STRING_VALUE_AFTER_AUTOCORRECT)
}
}
STRING_VALUE_NOT_TO_BE_CORRECTED ->
emit(node.startOffset, ERROR_MESSAGE_CAN_NOT_BE_AUTOCORRECTED, false)
}
}
}
companion object {
const val STRING_VALUE_TO_BE_AUTOCORRECTED = "string-value-to-be-autocorrected"
const val STRING_VALUE_NOT_TO_BE_CORRECTED = "string-value-not-to-be-corrected"
const val STRING_VALUE_AFTER_AUTOCORRECT = "string-value-after-autocorrect"
const val ERROR_MESSAGE_CAN_BE_AUTOCORRECTED = "This string value is not allowed and can be autocorrected"
const val ERROR_MESSAGE_CAN_NOT_BE_AUTOCORRECTED = "This string value is not allowed but can not be autocorrected"
}
}
private fun getResourceAsText(path: String) =
(ClassLoader.getSystemClassLoader().getResourceAsStream(path) ?: throw RuntimeException("$path not found"))
.bufferedReader()
.readText()
private data class CallbackResult(
val line: Int,
val col: Int,
val ruleId: String,
val detail: String,
val canBeAutoCorrected: Boolean,
val corrected: Boolean
)