-
-
Notifications
You must be signed in to change notification settings - Fork 757
/
OptionalWhenBracesSpec.kt
121 lines (112 loc) · 3.51 KB
/
OptionalWhenBracesSpec.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
package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.SourceLocation
import io.gitlab.arturbosch.detekt.test.assertThat
import io.gitlab.arturbosch.detekt.test.compileAndLint
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
class OptionalWhenBracesSpec {
val subject = OptionalWhenBraces()
@Test
fun `does not report necessary braces`() {
val code = """
fun x() {
when (1) {
1 -> print(1)
2 -> {
print(2)
print(2)
}
else -> {
// a comment
println()
}
}
}
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
@Test
fun `reports unnecessary braces`() {
val code = """
fun x() {
when (1) {
1 -> { print(1) }
else -> println()
}
}
"""
assertThat(subject.compileAndLint(code)).hasSize(1)
}
@Test
fun `reports unnecessary braces for nested when`() {
val code = """
import kotlin.random.Random
fun main() {
when(Random.nextBoolean()) {
true -> {
when(Random.nextBoolean()) {
true -> {
println("true")
}
false -> {
println("false")
}
}
println("end")
}
false -> println("false")
}
}
"""
assertThat(subject.compileAndLint(code))
.hasSize(2)
.hasStartSourceLocations(SourceLocation(7, 17), SourceLocation(10, 17))
}
@Test
fun `reports unnecessary braces when the single statement has comments inside`() {
val code = """
fun test(i: Int) {
when {
else -> {
when (i) {
// foo
1 -> println(1)
// bar
else -> println(2)
}
}
}
}
"""
assertThat(subject.compileAndLint(code))
.hasSize(1)
.hasStartSourceLocations(SourceLocation(3, 9))
}
@Nested
inner class `the statement is a lambda expression` {
@Test
fun `does not report if the lambda has no arrow`() {
val code = """
fun test(b: Boolean): (Int) -> Int {
return when (b) {
true -> { { it + 100 } }
false -> { { it + 200 } }
}
}
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
@Test
fun `reports if the lambda has an arrow`() {
val code = """
fun test(b: Boolean): (Int) -> Int {
return when (b) {
true -> { { i -> i + 100 } }
false -> { { i -> i + 200 } }
}
}
"""
assertThat(subject.compileAndLint(code)).hasSize(2)
}
}
}