summaryrefslogtreecommitdiff
path: root/lint/libs/lint-tests/src/test/java/com/android/tools/lint/LintFixPerformerTest.kt
blob: b17d9dfb29fb306a390138e960f40123a2640888 (plain)
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
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.tools.lint

import com.android.SdkConstants
import com.android.tools.lint.checks.LintDetectorDetector
import com.android.tools.lint.checks.infrastructure.TestLintClient
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Incident
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.LintFix
import com.android.tools.lint.detector.api.Location
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.utils.toSystemLineSeparator
import junit.framework.TestCase
import org.intellij.lang.annotations.Language
import java.io.File
import java.io.PrintWriter
import java.io.StringWriter

class LintFixPerformerTest : TestCase() {
    @Suppress("LintImplTextFormat")
    fun check(
        file: File,
        source: String,
        vararg fixes: LintFix,
        expected: String,
        expectedOutput: String? = null,
        expectedFailure: String? = null,
        includeMarkers: Boolean = false
    ) {
        val client = TestLintClient()
        for (fix in fixes) {
            assertTrue(LintFixPerformer.canAutoFix(fix))
        }
        var after: String = source
        var output = ""
        val printStatistics = expectedOutput != null
        val performer = object : LintFixPerformer(client, printStatistics, includeMarkers = includeMarkers) {
            override fun writeFile(pendingFile: PendingEditFile, contents: String) {
                after = contents
            }

            override fun printStatistics(
                writer: PrintWriter,
                editMap: MutableMap<String, Int>,
                appliedEditCount: Int,
                editedFileCount: Int
            ) {
                val stringWriter = StringWriter()
                val collector = PrintWriter(stringWriter)
                super.printStatistics(collector, editMap, appliedEditCount, editedFileCount)
                output = stringWriter.toString()
            }
        }
        val testIncident = Incident().apply {
            issue =
                Issue.create(
                    "_FixPerformerTestIssue",
                    "Sample",
                    "Sample",
                    Category.CORRECTNESS, 5, Severity.WARNING,
                    Implementation(LintDetectorDetector::class.java, Scope.RESOURCE_FILE_SCOPE)
                )
        }
        try {
            performer.fix(file, testIncident, fixes.toList(), source)
        } catch (e: Throwable) {
            if (expectedFailure != null) {
                assertEquals(expectedFailure.trimIndent().trim(), e.message)
            } else {
                throw e
            }
        }
        assertEquals(expected.trimIndent().trim(), after.trim())
        if (expectedOutput != null) {
            assertEquals(
                expectedOutput.trimIndent().trim().toSystemLineSeparator(),
                output.trim()
            )
        }
    }

    fun testSingleReplace() {
        val file = File("bogus.txt")
        val source =
            """
            First line.
            Second line.
            Third line.
            """.trimIndent()

        val range = Location.create(file, source, 0, source.length)
        val fix =
            fix().replace().text("Second").range(range).with("2nd").autoFix().build()
        check(
            file, source, fix,
            expected =
            """
            First line.
            2nd line.
            Third line.""",
            expectedOutput = "Applied 1 edits across 1 files for this fix: Replace with 2nd"
        )
    }

    fun testInvalidTextReplaceFix() {
        val file = File("source.txt")
        val source =
            """
            First line.
            """.trimIndent()

        val range = Location.create(file, source, 0, source.length)
        val fix =
            fix().replace().text("Not Present").range(range).with("2nd").autoFix().build()
        check(
            file, source, fix,
            expected = "First line.",
            expectedFailure = """
                Did not find "Not Present" in "First line." in source.txt as suggested in the quickfix.

                Consider calling ReplaceStringBuilder#range() to set a larger range to
                search than the default highlight range.

                (This fix is associated with the issue id `_FixPerformerTestIssue`,
                reported via com.android.tools.lint.checks.LintDetectorDetector.)
                """
        )
    }

    fun testInvalidRegexReplaceFix() {
        val file = File("source.txt")
        val source = "First line."
        val range = Location.create(file, source, 0, source.length)
        val fix =
            fix().replace().pattern("(Not Present)").range(range).with("2nd").autoFix().build()
        check(
            file, source, fix,
            expected = "First line.",
            expectedFailure = """
                Did not match pattern "(Not Present)" in "First line." in source.txt as suggested in the quickfix.

                (This fix is associated with the issue id `_FixPerformerTestIssue`,
                reported via com.android.tools.lint.checks.LintDetectorDetector.)
                """
        )
    }

    fun testLineCleanup() {
        // Regression test for b/185853711
        val file = File("Test.java")
        val source =
            """
            import android.util.Log;
            public class Test {
            }
            """.trimIndent()

        val startOffset = source.indexOf("public")
        val range = Location.create(file, source, startOffset, startOffset + "public".length)
        val fix = fix().replace().range(range).with("").autoFix().build()
        check(
            file, source, fix,
            expected =
            """
            import android.util.Log;
             class Test {
            }
            """,
            expectedOutput = "Applied 1 edits across 1 files for this fix: Delete"
        )
    }

    fun testMultipleReplaces() {
        // Ensures we reorder edits correctly
        val file = File("bogus.txt")
        val source =
            """
            First line.
            Second line.
            Third line.
            """.trimIndent()

        val range = Location.create(file, source, 0, source.length)
        val fix1 =
            fix().replace().text("Third").range(range).with("3rd").autoFix().build()
        val fix2 =
            fix().replace().text("First").range(range).with("1st").autoFix().build()
        val fix3 =
            fix().replace().text("Second").range(range).with("2nd").autoFix().build()
        check(
            file, source, fix1, fix2, fix3,
            expected =
            """
            1st line.
            2nd line.
            3rd line.""",
            expectedOutput =
            """
            Applied 3 edits across 1 files
            1: Replace with 3rd
            1: Replace with 2nd
            1: Replace with 1st
            """
        )
    }

    fun testXmlSetAttribute() {
        val file = File("bogus.txt")
        @Language("XML")
        val source =
            """
            <root>
                <element1 attribute1="value1" />
                <element2 attribute1="value1" attribute2="value2"/>
            </root>
            """.trimIndent()

        val range = Location.create(file, source, source.indexOf("attribute1"), source.length)
        val fix =
            fix().set(SdkConstants.ANDROID_URI, "new_attribute", "new value")
                .range(range).autoFix().build()
        check(
            file, source, fix,
            expected =
            """
            <root xmlns:android="http://schemas.android.com/apk/res/android">
                <element1 attribute1="value1" android:new_attribute="new value"  />
                <element2 attribute1="value1" attribute2="value2"/>
            </root>
            """
        )
    }

    fun testXmlSetAttributeOrder1() {
        val file = File("bogus.txt")
        @Language("XML")
        val source =
            """
            <root xmlns:android="http://schemas.android.com/apk/res/android">
                <element1 android:layout_width="wrap_content" android:width="foo" />
            </root>
            """.trimIndent()

        val range = Location.create(file, source, source.indexOf("element1"), source.length)
        val fix =
            fix().set(SdkConstants.ANDROID_URI, "layout_height", "wrap_content")
                .range(range).autoFix().build()
        check(
            file, source, fix,
            expected =

            """
            <root xmlns:android="http://schemas.android.com/apk/res/android">
                <element1 android:layout_width="wrap_content" android:layout_height="wrap_content" android:width="foo" />
            </root>
            """
        )
    }

    fun testXmlSetAttributeOrder2() {
        val file = File("bogus.txt")
        @Language("XML")
        val source =
            """
            <root xmlns:android="http://schemas.android.com/apk/res/android">
                <element1 android:layout_width="wrap_content" android:width="foo" />
            </root>
            """.trimIndent()

        val range = Location.create(file, source, source.indexOf("element1"), source.length)
        val fix =
            fix().set(SdkConstants.ANDROID_URI, "id", "@+id/my_id")
                .range(range).autoFix().build()
        check(
            file, source, fix,
            expected =
            """
            <root xmlns:android="http://schemas.android.com/apk/res/android">
                <element1 android:id="@+id/my_id" android:layout_width="wrap_content" android:width="foo" />
            </root>
            """
        )
    }

    fun testXmlSetAttributeOrder3() {
        val file = File("bogus.txt")
        @Language("XML")
        val source =
            """
            <root xmlns:android="http://schemas.android.com/apk/res/android">
                <element1 android:layout_width="wrap_content" android:width="foo" />
            </root>
            """.trimIndent()

        val range = Location.create(file, source, source.indexOf("element1"), source.length)
        val fix =
            fix().set(SdkConstants.ANDROID_URI, "z-order", "5")
                .range(range).autoFix().build()
        check(
            file, source, fix,
            expected =
            """
            <root xmlns:android="http://schemas.android.com/apk/res/android">
                <element1 android:layout_width="wrap_content" android:width="foo" android:z-order="5"  />
            </root>
            """
        )
    }

    fun testXmlDeleteAttribute() {
        val file = File("bogus.txt")
        @Language("XML")
        val source =
            """
            <root>
                <element1 attribute1="value1" />
                <element2 attribute1="value1" attribute2="value2"/>
            </root>
            """.trimIndent()

        val range = Location.create(file, source, source.indexOf("attribute2"), source.length)
        val fix =
            fix().unset(null, "attribute2")
                .range(range).autoFix().build()
        check(
            file, source, fix,
            expected =
            """
            <root>
                <element1 attribute1="value1" />
                <element2 attribute1="value1" />
            </root>
            """
        )
    }

    fun testXmlComposite() {
        val file = File("bogus.txt")
        @Language("XML")
        val source =
            """
            <root>
                <element1 attribute1="value1" />
                <element2 attribute1="value1" attribute2="value2"/>
            </root>
            """.trimIndent()

        val range = Location.create(file, source, source.indexOf("attribute1"), source.length)
        val unsetFix = fix().unset(null, "attribute1")
            .range(range).build()
        val setFix =
            fix().set(SdkConstants.ANDROID_URI, "new_attribute", "new value")
                .range(range).build()

        val fix = fix().composite(setFix, unsetFix).autoFix()
        check(
            file, source, fix,
            expected =
            """
            <root xmlns:android="http://schemas.android.com/apk/res/android">
                <element1  android:new_attribute="new value"  />
                <element2 attribute1="value1" attribute2="value2"/>
            </root>
            """
        )
    }

    private fun fix() = LintFix.create()

    fun testAttributeSorting() {
        val attributes = listOf(
            "foo",
            "bar",
            "layout_foo",
            "layout_bar",
            "layout_width",
            "layout_height",
            "id",
            "name"
        )
        val sorted = attributes.sortedWith(
            Comparator { a, b ->
                LintFixPerformer.compareAttributeNames(
                    a,
                    b
                )
            }
        )
        assertEquals(
            "[id, name, layout_width, layout_height, layout_bar, layout_foo, bar, foo]",
            sorted.toString()
        )
    }

    fun testShortenNames() {
        // Regression test for b/https://issuetracker.google.com/241573146
        val file = File("Test.java")
        @Language("java")
        val source =
            """
            package test.pkg;
            import android.graphics.drawable.Drawable;
            import android.graphics.Outline;

            class Test {
                static void getOutline() {
                }
            }
            """.trimIndent()

        val range = Location.create(file, source, 0, source.length)
        val fix =
            fix().replace()
                .text("()")
                .with("(android.graphics.drawable.Drawable drawable, android.graphics.Outline outline)")
                .shortenNames()
                .autoFix()
                .range(range)
                .build()
        check(
            file, source, fix,
            expected =
            """
            package test.pkg;
            import android.graphics.drawable.Drawable;
            import android.graphics.Outline;

            class Test {
                static void getOutline(Drawable drawable, Outline outline) {
                }
            }
            """,
            expectedOutput = "Applied 1 edits across 1 files for this fix: Replace with (android.graphics.drawable.Drawable drawable, android.graphics.Outline outline)",
            includeMarkers = true
        )
    }
}