Merge changes I1f7b0181,I1ee616a3 into tm-qpr-dev

* changes:
  New lint detector for Context.getSystemService()
  Move API lint stubs to common class
This commit is contained in:
TreeHugger Robot
2022-10-05 12:47:38 +00:00
committed by Android (Google) Code Review
11 changed files with 518 additions and 339 deletions

View File

@@ -0,0 +1,75 @@
/*
* Copyright (C) 2022 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.internal.systemui.lint
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.SourceCodeScanner
import com.intellij.psi.PsiMethod
import org.jetbrains.uast.UCallExpression
/** Detects usage of Context.getSystemService() and suggests to use an injected instance instead. */
@Suppress("UnstableApiUsage")
class NonInjectedServiceDetector : Detector(), SourceCodeScanner {
override fun getApplicableMethodNames(): List<String> {
return listOf("getSystemService")
}
override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
val evaluator = context.evaluator
if (
!evaluator.isStatic(method) &&
method.name == "getSystemService" &&
method.containingClass?.qualifiedName == "android.content.Context"
) {
context.report(
ISSUE,
method,
context.getNameLocation(node),
"Use @Inject to get the handle to a system-level services instead of using " +
"Context.getSystemService()"
)
}
}
companion object {
@JvmField
val ISSUE: Issue =
Issue.create(
id = "NonInjectedService",
briefDescription =
"System-level services should be retrieved using " +
"@Inject instead of Context.getSystemService().",
explanation =
"Context.getSystemService() should be avoided because it makes testing " +
"difficult. Instead, use an injected service. For example, " +
"instead of calling Context.getSystemService(UserManager.class), " +
"use @Inject and add UserManager to the constructor",
category = Category.CORRECTNESS,
priority = 8,
severity = Severity.WARNING,
implementation =
Implementation(NonInjectedServiceDetector::class.java, Scope.JAVA_FILE_SCOPE)
)
}
}

View File

@@ -27,6 +27,7 @@ import com.android.tools.lint.detector.api.SourceCodeScanner
import com.intellij.psi.PsiMethod import com.intellij.psi.PsiMethod
import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.UCallExpression
@Suppress("UnstableApiUsage")
class RegisterReceiverViaContextDetector : Detector(), SourceCodeScanner { class RegisterReceiverViaContextDetector : Detector(), SourceCodeScanner {
override fun getApplicableMethodNames(): List<String> { override fun getApplicableMethodNames(): List<String> {

View File

@@ -35,6 +35,7 @@ class SystemUIIssueRegistry : IssueRegistry() {
GetMainLooperViaContextDetector.ISSUE, GetMainLooperViaContextDetector.ISSUE,
RegisterReceiverViaContextDetector.ISSUE, RegisterReceiverViaContextDetector.ISSUE,
SoftwareBitmapDetector.ISSUE, SoftwareBitmapDetector.ISSUE,
NonInjectedServiceDetector.ISSUE,
) )
override val api: Int override val api: Int

View File

@@ -0,0 +1,156 @@
/*
* Copyright (C) 2022 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.internal.systemui.lint
import com.android.tools.lint.checks.infrastructure.LintDetectorTest.java
/*
* This file contains stubs of framework APIs and System UI classes for testing purposes only. The
* stubs are not used in the lint detectors themselves.
*/
@Suppress("UnstableApiUsage")
internal val androidStubs =
arrayOf(
java(
"""
package android.app;
public class ActivityManager {
public static int getCurrentUser() {}
}
"""
),
java(
"""
package android.os;
import android.content.pm.UserInfo;
import android.annotation.UserIdInt;
public class UserManager {
public UserInfo getUserInfo(@UserIdInt int userId) {}
}
"""
),
java("""
package android.annotation;
public @interface UserIdInt {}
"""),
java("""
package android.content.pm;
public class UserInfo {}
"""),
java("""
package android.os;
public class Looper {}
"""),
java("""
package android.os;
public class Handler {}
"""),
java("""
package android.content;
public class ServiceConnection {}
"""),
java("""
package android.os;
public enum UserHandle {
ALL
}
"""),
java(
"""
package android.content;
import android.os.UserHandle;
import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.Executor;
public class Context {
public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter, int flags) {}
public void registerReceiverAsUser(
BroadcastReceiver receiver, UserHandle user, IntentFilter filter,
String broadcastPermission, Handler scheduler) {}
public void registerReceiverForAllUsers(
BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission,
Handler scheduler) {}
public void sendBroadcast(Intent intent) {}
public void sendBroadcast(Intent intent, String receiverPermission) {}
public void sendBroadcastAsUser(Intent intent, UserHandle userHandle, String permission) {}
public void bindService(Intent intent) {}
public void bindServiceAsUser(
Intent intent, ServiceConnection connection, int flags, UserHandle userHandle) {}
public void unbindService(ServiceConnection connection) {}
public Looper getMainLooper() { return null; }
public Executor getMainExecutor() { return null; }
public Handler getMainThreadHandler() { return null; }
public final @Nullable <T> T getSystemService(@NonNull Class<T> serviceClass) { return null; }
public abstract @Nullable Object getSystemService(@ServiceName @NonNull String name);
}
"""
),
java(
"""
package android.app;
import android.content.Context;
public class Activity extends Context {}
"""
),
java(
"""
package android.graphics;
public class Bitmap {
public enum Config {
ARGB_8888,
RGB_565,
HARDWARE
}
public static Bitmap createBitmap(int width, int height, Config config) {
return null;
}
}
"""
),
java("""
package android.content;
public class BroadcastReceiver {}
"""),
java("""
package android.content;
public class IntentFilter {}
"""),
java(
"""
package com.android.systemui.settings;
import android.content.pm.UserInfo;
public interface UserTracker {
int getUserId();
UserInfo getUserInfo();
}
"""
),
)

View File

@@ -17,26 +17,26 @@
package com.android.internal.systemui.lint package com.android.internal.systemui.lint
import com.android.tools.lint.checks.infrastructure.LintDetectorTest import com.android.tools.lint.checks.infrastructure.LintDetectorTest
import com.android.tools.lint.checks.infrastructure.TestFile
import com.android.tools.lint.checks.infrastructure.TestFiles import com.android.tools.lint.checks.infrastructure.TestFiles
import com.android.tools.lint.checks.infrastructure.TestLintTask import com.android.tools.lint.checks.infrastructure.TestLintTask
import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.Issue
import org.junit.Test import org.junit.Test
@Suppress("UnstableApiUsage")
class BindServiceViaContextDetectorTest : LintDetectorTest() { class BindServiceViaContextDetectorTest : LintDetectorTest() {
override fun getDetector(): Detector = BindServiceViaContextDetector() override fun getDetector(): Detector = BindServiceViaContextDetector()
override fun lint(): TestLintTask = super.lint().allowMissingSdk(true) override fun lint(): TestLintTask = super.lint().allowMissingSdk(true)
override fun getIssues(): List<Issue> = listOf( override fun getIssues(): List<Issue> = listOf(BindServiceViaContextDetector.ISSUE)
BindServiceViaContextDetector.ISSUE)
private val explanation = "Binding or unbinding services are synchronous calls" private val explanation = "Binding or unbinding services are synchronous calls"
@Test @Test
fun testBindService() { fun testBindService() {
lint().files( lint()
.files(
TestFiles.java( TestFiles.java(
""" """
package test.pkg; package test.pkg;
@@ -49,8 +49,10 @@ class BindServiceViaContextDetectorTest : LintDetectorTest() {
} }
} }
""" """
).indented(), )
*stubs) .indented(),
*stubs
)
.issues(BindServiceViaContextDetector.ISSUE) .issues(BindServiceViaContextDetector.ISSUE)
.run() .run()
.expectWarningCount(1) .expectWarningCount(1)
@@ -59,7 +61,8 @@ class BindServiceViaContextDetectorTest : LintDetectorTest() {
@Test @Test
fun testBindServiceAsUser() { fun testBindServiceAsUser() {
lint().files( lint()
.files(
TestFiles.java( TestFiles.java(
""" """
package test.pkg; package test.pkg;
@@ -73,8 +76,10 @@ class BindServiceViaContextDetectorTest : LintDetectorTest() {
} }
} }
""" """
).indented(), )
*stubs) .indented(),
*stubs
)
.issues(BindServiceViaContextDetector.ISSUE) .issues(BindServiceViaContextDetector.ISSUE)
.run() .run()
.expectWarningCount(1) .expectWarningCount(1)
@@ -83,7 +88,8 @@ class BindServiceViaContextDetectorTest : LintDetectorTest() {
@Test @Test
fun testUnbindService() { fun testUnbindService() {
lint().files( lint()
.files(
TestFiles.java( TestFiles.java(
""" """
package test.pkg; package test.pkg;
@@ -96,45 +102,15 @@ class BindServiceViaContextDetectorTest : LintDetectorTest() {
} }
} }
""" """
).indented(), )
*stubs) .indented(),
*stubs
)
.issues(BindServiceViaContextDetector.ISSUE) .issues(BindServiceViaContextDetector.ISSUE)
.run() .run()
.expectWarningCount(1) .expectWarningCount(1)
.expectContains(explanation) .expectContains(explanation)
} }
private val contextStub: TestFile = java( private val stubs = androidStubs
"""
package android.content;
import android.os.UserHandle;
public class Context {
public void bindService(Intent intent) {};
public void bindServiceAsUser(Intent intent, ServiceConnection connection, int flags,
UserHandle userHandle) {};
public void unbindService(ServiceConnection connection) {};
}
"""
)
private val serviceConnectionStub: TestFile = java(
"""
package android.content;
public class ServiceConnection {}
"""
)
private val userHandleStub: TestFile = java(
"""
package android.os;
public enum UserHandle {
ALL
}
"""
)
private val stubs = arrayOf(contextStub, serviceConnectionStub, userHandleStub)
} }

View File

@@ -1,24 +1,41 @@
/*
* Copyright (C) 2022 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.internal.systemui.lint package com.android.internal.systemui.lint
import com.android.tools.lint.checks.infrastructure.LintDetectorTest import com.android.tools.lint.checks.infrastructure.LintDetectorTest
import com.android.tools.lint.checks.infrastructure.TestFiles import com.android.tools.lint.checks.infrastructure.TestFiles
import com.android.tools.lint.checks.infrastructure.TestFile
import com.android.tools.lint.checks.infrastructure.TestLintTask import com.android.tools.lint.checks.infrastructure.TestLintTask
import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.Issue
import org.junit.Test import org.junit.Test
@Suppress("UnstableApiUsage")
class BroadcastSentViaContextDetectorTest : LintDetectorTest() { class BroadcastSentViaContextDetectorTest : LintDetectorTest() {
override fun getDetector(): Detector = BroadcastSentViaContextDetector() override fun getDetector(): Detector = BroadcastSentViaContextDetector()
override fun lint(): TestLintTask = super.lint().allowMissingSdk(true) override fun lint(): TestLintTask = super.lint().allowMissingSdk(true)
override fun getIssues(): List<Issue> = listOf( override fun getIssues(): List<Issue> = listOf(BroadcastSentViaContextDetector.ISSUE)
BroadcastSentViaContextDetector.ISSUE)
@Test @Test
fun testSendBroadcast() { fun testSendBroadcast() {
lint().files( println(stubs.size)
lint()
.files(
TestFiles.java( TestFiles.java(
""" """
package test.pkg; package test.pkg;
@@ -31,19 +48,23 @@ class BroadcastSentViaContextDetectorTest : LintDetectorTest() {
} }
} }
""" """
).indented(), )
*stubs) .indented(),
*stubs
)
.issues(BroadcastSentViaContextDetector.ISSUE) .issues(BroadcastSentViaContextDetector.ISSUE)
.run() .run()
.expectWarningCount(1) .expectWarningCount(1)
.expectContains( .expectContains(
"Please don't call sendBroadcast/sendBroadcastAsUser directly on " + "Please don't call sendBroadcast/sendBroadcastAsUser directly on " +
"Context, use com.android.systemui.broadcast.BroadcastSender instead.") "Context, use com.android.systemui.broadcast.BroadcastSender instead."
)
} }
@Test @Test
fun testSendBroadcastAsUser() { fun testSendBroadcastAsUser() {
lint().files( lint()
.files(
TestFiles.java( TestFiles.java(
""" """
package test.pkg; package test.pkg;
@@ -56,19 +77,24 @@ class BroadcastSentViaContextDetectorTest : LintDetectorTest() {
context.sendBroadcastAsUser(intent, UserHandle.ALL, "permission"); context.sendBroadcastAsUser(intent, UserHandle.ALL, "permission");
} }
} }
""").indented(), """
*stubs) )
.indented(),
*stubs
)
.issues(BroadcastSentViaContextDetector.ISSUE) .issues(BroadcastSentViaContextDetector.ISSUE)
.run() .run()
.expectWarningCount(1) .expectWarningCount(1)
.expectContains( .expectContains(
"Please don't call sendBroadcast/sendBroadcastAsUser directly on " + "Please don't call sendBroadcast/sendBroadcastAsUser directly on " +
"Context, use com.android.systemui.broadcast.BroadcastSender instead.") "Context, use com.android.systemui.broadcast.BroadcastSender instead."
)
} }
@Test @Test
fun testSendBroadcastInActivity() { fun testSendBroadcastInActivity() {
lint().files( lint()
.files(
TestFiles.java( TestFiles.java(
""" """
package test.pkg; package test.pkg;
@@ -82,19 +108,24 @@ class BroadcastSentViaContextDetectorTest : LintDetectorTest() {
} }
} }
""").indented(), """
*stubs) )
.indented(),
*stubs
)
.issues(BroadcastSentViaContextDetector.ISSUE) .issues(BroadcastSentViaContextDetector.ISSUE)
.run() .run()
.expectWarningCount(1) .expectWarningCount(1)
.expectContains( .expectContains(
"Please don't call sendBroadcast/sendBroadcastAsUser directly on " + "Please don't call sendBroadcast/sendBroadcastAsUser directly on " +
"Context, use com.android.systemui.broadcast.BroadcastSender instead.") "Context, use com.android.systemui.broadcast.BroadcastSender instead."
)
} }
@Test @Test
fun testNoopIfNoCall() { fun testNoopIfNoCall() {
lint().files( lint()
.files(
TestFiles.java( TestFiles.java(
""" """
package test.pkg; package test.pkg;
@@ -106,45 +137,15 @@ class BroadcastSentViaContextDetectorTest : LintDetectorTest() {
context.startActivity(intent); context.startActivity(intent);
} }
} }
""").indented(), """
*stubs) )
.indented(),
*stubs
)
.issues(BroadcastSentViaContextDetector.ISSUE) .issues(BroadcastSentViaContextDetector.ISSUE)
.run() .run()
.expectClean() .expectClean()
} }
private val contextStub: TestFile = java( private val stubs = androidStubs
"""
package android.content;
import android.os.UserHandle;
public class Context {
public void sendBroadcast(Intent intent) {};
public void sendBroadcast(Intent intent, String receiverPermission) {};
public void sendBroadcastAsUser(Intent intent, UserHandle userHandle,
String permission) {};
}
"""
)
private val activityStub: TestFile = java(
"""
package android.app;
import android.content.Context;
public class Activity extends Context {}
"""
)
private val userHandleStub: TestFile = java(
"""
package android.os;
public enum UserHandle {
ALL
}
"""
)
private val stubs = arrayOf(contextStub, activityStub, userHandleStub)
} }

View File

@@ -17,13 +17,13 @@
package com.android.internal.systemui.lint package com.android.internal.systemui.lint
import com.android.tools.lint.checks.infrastructure.LintDetectorTest import com.android.tools.lint.checks.infrastructure.LintDetectorTest
import com.android.tools.lint.checks.infrastructure.TestFile
import com.android.tools.lint.checks.infrastructure.TestFiles import com.android.tools.lint.checks.infrastructure.TestFiles
import com.android.tools.lint.checks.infrastructure.TestLintTask import com.android.tools.lint.checks.infrastructure.TestLintTask
import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.Issue
import org.junit.Test import org.junit.Test
@Suppress("UnstableApiUsage")
class GetMainLooperViaContextDetectorTest : LintDetectorTest() { class GetMainLooperViaContextDetectorTest : LintDetectorTest() {
override fun getDetector(): Detector = GetMainLooperViaContextDetector() override fun getDetector(): Detector = GetMainLooperViaContextDetector()
@@ -35,7 +35,8 @@ class GetMainLooperViaContextDetectorTest : LintDetectorTest() {
@Test @Test
fun testGetMainThreadHandler() { fun testGetMainThreadHandler() {
lint().files( lint()
.files(
TestFiles.java( TestFiles.java(
""" """
package test.pkg; package test.pkg;
@@ -48,8 +49,10 @@ class GetMainLooperViaContextDetectorTest : LintDetectorTest() {
} }
} }
""" """
).indented(), )
*stubs) .indented(),
*stubs
)
.issues(GetMainLooperViaContextDetector.ISSUE) .issues(GetMainLooperViaContextDetector.ISSUE)
.run() .run()
.expectWarningCount(1) .expectWarningCount(1)
@@ -58,7 +61,8 @@ class GetMainLooperViaContextDetectorTest : LintDetectorTest() {
@Test @Test
fun testGetMainLooper() { fun testGetMainLooper() {
lint().files( lint()
.files(
TestFiles.java( TestFiles.java(
""" """
package test.pkg; package test.pkg;
@@ -71,8 +75,10 @@ class GetMainLooperViaContextDetectorTest : LintDetectorTest() {
} }
} }
""" """
).indented(), )
*stubs) .indented(),
*stubs
)
.issues(GetMainLooperViaContextDetector.ISSUE) .issues(GetMainLooperViaContextDetector.ISSUE)
.run() .run()
.expectWarningCount(1) .expectWarningCount(1)
@@ -81,7 +87,8 @@ class GetMainLooperViaContextDetectorTest : LintDetectorTest() {
@Test @Test
fun testGetMainExecutor() { fun testGetMainExecutor() {
lint().files( lint()
.files(
TestFiles.java( TestFiles.java(
""" """
package test.pkg; package test.pkg;
@@ -94,42 +101,15 @@ class GetMainLooperViaContextDetectorTest : LintDetectorTest() {
} }
} }
""" """
).indented(), )
*stubs) .indented(),
*stubs
)
.issues(GetMainLooperViaContextDetector.ISSUE) .issues(GetMainLooperViaContextDetector.ISSUE)
.run() .run()
.expectWarningCount(1) .expectWarningCount(1)
.expectContains(explanation) .expectContains(explanation)
} }
private val contextStub: TestFile = java( private val stubs = androidStubs
"""
package android.content;
import android.os.Handler;import android.os.Looper;import java.util.concurrent.Executor;
public class Context {
public Looper getMainLooper() { return null; };
public Executor getMainExecutor() { return null; };
public Handler getMainThreadHandler() { return null; };
}
"""
)
private val looperStub: TestFile = java(
"""
package android.os;
public class Looper {}
"""
)
private val handlerStub: TestFile = java(
"""
package android.os;
public class Handler {}
"""
)
private val stubs = arrayOf(contextStub, looperStub, handlerStub)
} }

View File

@@ -0,0 +1,85 @@
/*
* Copyright (C) 2022 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.internal.systemui.lint
import com.android.tools.lint.checks.infrastructure.LintDetectorTest
import com.android.tools.lint.checks.infrastructure.TestFiles
import com.android.tools.lint.checks.infrastructure.TestLintTask
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Issue
import org.junit.Test
@Suppress("UnstableApiUsage")
class NonInjectedServiceDetectorTest : LintDetectorTest() {
override fun getDetector(): Detector = NonInjectedServiceDetector()
override fun lint(): TestLintTask = super.lint().allowMissingSdk(true)
override fun getIssues(): List<Issue> = listOf(NonInjectedServiceDetector.ISSUE)
@Test
fun testGetServiceWithString() {
lint()
.files(
TestFiles.java(
"""
package test.pkg;
import android.content.Context;
public class TestClass1 {
public void getSystemServiceWithoutDagger(Context context) {
context.getSystemService("user");
}
}
"""
)
.indented(),
*stubs
)
.issues(NonInjectedServiceDetector.ISSUE)
.run()
.expectWarningCount(1)
.expectContains("Use @Inject to get the handle")
}
@Test
fun testGetServiceWithClass() {
lint()
.files(
TestFiles.java(
"""
package test.pkg;
import android.content.Context;
import android.os.UserManager;
public class TestClass2 {
public void getSystemServiceWithoutDagger(Context context) {
context.getSystemService(UserManager.class);
}
}
"""
)
.indented(),
*stubs
)
.issues(NonInjectedServiceDetector.ISSUE)
.run()
.expectWarningCount(1)
.expectContains("Use @Inject to get the handle")
}
private val stubs = androidStubs
}

View File

@@ -17,26 +17,26 @@
package com.android.internal.systemui.lint package com.android.internal.systemui.lint
import com.android.tools.lint.checks.infrastructure.LintDetectorTest import com.android.tools.lint.checks.infrastructure.LintDetectorTest
import com.android.tools.lint.checks.infrastructure.TestFile
import com.android.tools.lint.checks.infrastructure.TestFiles import com.android.tools.lint.checks.infrastructure.TestFiles
import com.android.tools.lint.checks.infrastructure.TestLintTask import com.android.tools.lint.checks.infrastructure.TestLintTask
import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.Issue
import org.junit.Test import org.junit.Test
@Suppress("UnstableApiUsage")
class RegisterReceiverViaContextDetectorTest : LintDetectorTest() { class RegisterReceiverViaContextDetectorTest : LintDetectorTest() {
override fun getDetector(): Detector = RegisterReceiverViaContextDetector() override fun getDetector(): Detector = RegisterReceiverViaContextDetector()
override fun lint(): TestLintTask = super.lint().allowMissingSdk(true) override fun lint(): TestLintTask = super.lint().allowMissingSdk(true)
override fun getIssues(): List<Issue> = listOf( override fun getIssues(): List<Issue> = listOf(RegisterReceiverViaContextDetector.ISSUE)
RegisterReceiverViaContextDetector.ISSUE)
private val explanation = "BroadcastReceivers should be registered via BroadcastDispatcher." private val explanation = "BroadcastReceivers should be registered via BroadcastDispatcher."
@Test @Test
fun testRegisterReceiver() { fun testRegisterReceiver() {
lint().files( lint()
.files(
TestFiles.java( TestFiles.java(
""" """
package test.pkg; package test.pkg;
@@ -51,8 +51,10 @@ class RegisterReceiverViaContextDetectorTest : LintDetectorTest() {
} }
} }
""" """
).indented(), )
*stubs) .indented(),
*stubs
)
.issues(RegisterReceiverViaContextDetector.ISSUE) .issues(RegisterReceiverViaContextDetector.ISSUE)
.run() .run()
.expectWarningCount(1) .expectWarningCount(1)
@@ -61,7 +63,8 @@ class RegisterReceiverViaContextDetectorTest : LintDetectorTest() {
@Test @Test
fun testRegisterReceiverAsUser() { fun testRegisterReceiverAsUser() {
lint().files( lint()
.files(
TestFiles.java( TestFiles.java(
""" """
package test.pkg; package test.pkg;
@@ -79,8 +82,10 @@ class RegisterReceiverViaContextDetectorTest : LintDetectorTest() {
} }
} }
""" """
).indented(), )
*stubs) .indented(),
*stubs
)
.issues(RegisterReceiverViaContextDetector.ISSUE) .issues(RegisterReceiverViaContextDetector.ISSUE)
.run() .run()
.expectWarningCount(1) .expectWarningCount(1)
@@ -89,7 +94,8 @@ class RegisterReceiverViaContextDetectorTest : LintDetectorTest() {
@Test @Test
fun testRegisterReceiverForAllUsers() { fun testRegisterReceiverForAllUsers() {
lint().files( lint()
.files(
TestFiles.java( TestFiles.java(
""" """
package test.pkg; package test.pkg;
@@ -107,65 +113,15 @@ class RegisterReceiverViaContextDetectorTest : LintDetectorTest() {
} }
} }
""" """
).indented(), )
*stubs) .indented(),
*stubs
)
.issues(RegisterReceiverViaContextDetector.ISSUE) .issues(RegisterReceiverViaContextDetector.ISSUE)
.run() .run()
.expectWarningCount(1) .expectWarningCount(1)
.expectContains(explanation) .expectContains(explanation)
} }
private val contextStub: TestFile = java( private val stubs = androidStubs
"""
package android.content;
import android.os.Handler;
import android.os.UserHandle;
public class Context {
public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
int flags) {};
public void registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user,
IntentFilter filter, String broadcastPermission, Handler scheduler) {};
public void registerReceiverForAllUsers(BroadcastReceiver receiver, IntentFilter filter,
String broadcastPermission, Handler scheduler) {};
}
"""
)
private val broadcastReceiverStub: TestFile = java(
"""
package android.content;
public class BroadcastReceiver {}
"""
)
private val intentFilterStub: TestFile = java(
"""
package android.content;
public class IntentFilter {}
"""
)
private val handlerStub: TestFile = java(
"""
package android.os;
public class Handler {}
"""
)
private val userHandleStub: TestFile = java(
"""
package android.os;
public enum UserHandle {
ALL
}
"""
)
private val stubs = arrayOf(contextStub, broadcastReceiverStub, intentFilterStub, handlerStub,
userHandleStub)
} }

View File

@@ -1,13 +1,29 @@
/*
* Copyright (C) 2022 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.internal.systemui.lint package com.android.internal.systemui.lint
import com.android.tools.lint.checks.infrastructure.LintDetectorTest import com.android.tools.lint.checks.infrastructure.LintDetectorTest
import com.android.tools.lint.checks.infrastructure.TestFile
import com.android.tools.lint.checks.infrastructure.TestFiles import com.android.tools.lint.checks.infrastructure.TestFiles
import com.android.tools.lint.checks.infrastructure.TestLintTask import com.android.tools.lint.checks.infrastructure.TestLintTask
import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.Issue
import org.junit.Test import org.junit.Test
@Suppress("UnstableApiUsage")
class SlowUserQueryDetectorTest : LintDetectorTest() { class SlowUserQueryDetectorTest : LintDetectorTest() {
override fun getDetector(): Detector = SlowUserQueryDetector() override fun getDetector(): Detector = SlowUserQueryDetector()
@@ -134,61 +150,5 @@ class SlowUserQueryDetectorTest : LintDetectorTest() {
.expectClean() .expectClean()
} }
private val activityManagerStub: TestFile = private val stubs = androidStubs
java(
"""
package android.app;
public class ActivityManager {
public static int getCurrentUser() {};
}
"""
)
private val userManagerStub: TestFile =
java(
"""
package android.os;
import android.content.pm.UserInfo;
import android.annotation.UserIdInt;
public class UserManager {
public UserInfo getUserInfo(@UserIdInt int userId) {};
}
"""
)
private val userIdIntStub: TestFile =
java(
"""
package android.annotation;
public @interface UserIdInt {}
"""
)
private val userInfoStub: TestFile =
java(
"""
package android.content.pm;
public class UserInfo {}
"""
)
private val userTrackerStub: TestFile =
java(
"""
package com.android.systemui.settings;
import android.content.pm.UserInfo;
public interface UserTracker {
public int getUserId();
public UserInfo getUserInfo();
}
"""
)
private val stubs =
arrayOf(activityManagerStub, userManagerStub, userIdIntStub, userInfoStub, userTrackerStub)
} }

View File

@@ -17,7 +17,6 @@
package com.android.internal.systemui.lint package com.android.internal.systemui.lint
import com.android.tools.lint.checks.infrastructure.LintDetectorTest import com.android.tools.lint.checks.infrastructure.LintDetectorTest
import com.android.tools.lint.checks.infrastructure.TestFile
import com.android.tools.lint.checks.infrastructure.TestFiles import com.android.tools.lint.checks.infrastructure.TestFiles
import com.android.tools.lint.checks.infrastructure.TestLintTask import com.android.tools.lint.checks.infrastructure.TestLintTask
import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Detector
@@ -36,7 +35,8 @@ class SoftwareBitmapDetectorTest : LintDetectorTest() {
@Test @Test
fun testSoftwareBitmap() { fun testSoftwareBitmap() {
lint().files( lint()
.files(
TestFiles.java( TestFiles.java(
""" """
import android.graphics.Bitmap; import android.graphics.Bitmap;
@@ -48,8 +48,10 @@ class SoftwareBitmapDetectorTest : LintDetectorTest() {
} }
} }
""" """
).indented(), )
*stubs) .indented(),
*stubs
)
.issues(SoftwareBitmapDetector.ISSUE) .issues(SoftwareBitmapDetector.ISSUE)
.run() .run()
.expectWarningCount(2) .expectWarningCount(2)
@@ -58,7 +60,8 @@ class SoftwareBitmapDetectorTest : LintDetectorTest() {
@Test @Test
fun testHardwareBitmap() { fun testHardwareBitmap() {
lint().files( lint()
.files(
TestFiles.java( TestFiles.java(
""" """
import android.graphics.Bitmap; import android.graphics.Bitmap;
@@ -69,29 +72,14 @@ class SoftwareBitmapDetectorTest : LintDetectorTest() {
} }
} }
""" """
).indented(), )
*stubs) .indented(),
*stubs
)
.issues(SoftwareBitmapDetector.ISSUE) .issues(SoftwareBitmapDetector.ISSUE)
.run() .run()
.expectWarningCount(0) .expectWarningCount(0)
} }
private val bitmapStub: TestFile = java( private val stubs = androidStubs
"""
package android.graphics;
public class Bitmap {
public enum Config {
ARGB_8888,
RGB_565,
HARDWARE
}
public static Bitmap createBitmap(int width, int height, Config config) {
return null;
}
}
"""
)
private val stubs = arrayOf(bitmapStub)
} }