Debian Codegraph @

tests/TrustTests/src/android/trust/test/lib/LockStateTrackingRule.kt

raw
1 /*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package android.trust.test.lib
18
19 import android.app.trust.TrustManager
20 import android.app.trust.TrustManager.TrustListener
21 import android.content.Context
22 import android.util.Log
23 import android.view.WindowManagerGlobal
24 import androidx.test.core.app.ApplicationProvider.getApplicationContext
25 import org.junit.rules.TestRule
26 import org.junit.runner.Description
27 import org.junit.runners.model.Statement
28
29 /**
30 * Rule for tracking the lock state of the device based on events emitted to [TrustListener].
31 */
32 class LockStateTrackingRule : TestRule {
33 private val context: Context = getApplicationContext()
34 private val windowManager = WindowManagerGlobal.getWindowManagerService()
35
36 @Volatile lateinit var lockState: LockState
37 private set
38
39 override fun apply(base: Statement, description: Description) = object : Statement() {
40 override fun evaluate() {
41 lockState = LockState(locked = windowManager.isKeyguardLocked)
42 val trustManager = context.getSystemService(TrustManager::class.java) as TrustManager
43 val listener = Listener()
44
45 trustManager.registerTrustListener(listener)
46 try {
47 base.evaluate()
48 } finally {
49 trustManager.unregisterTrustListener(listener)
50 }
51 }
52 }
53
54 fun assertLocked() {
55 wait("un-locked per TrustListener") { lockState.locked == true }
56 wait("keyguard lock") { windowManager.isKeyguardLocked }
57 }
58
59 fun assertUnlocked() {
60 wait("locked per TrustListener") { lockState.locked == false }
61 }
62
63 inner class Listener : TrustListener {
64 override fun onTrustChanged(
65 enabled: Boolean,
66 newlyUnlocked: Boolean,
67 userId: Int,
68 flags: Int,
69 trustGrantedMessages: MutableList<String>
70 ) {
71 Log.d(TAG, "Device became trusted=$enabled")
72 lockState = lockState.copy(locked = !enabled)
73 }
74
75 override fun onTrustManagedChanged(enabled: Boolean, userId: Int) {
76 }
77
78 override fun onTrustError(message: CharSequence) {
79 }
80 }
81
82 data class LockState(
83 val locked: Boolean? = null
84 )
85
86 companion object {
87 private const val TAG = "LockStateTrackingRule"
88 }
89 }