1 /*
2  * Copyright (C) 2023 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 package com.android.systemui.flags
17 
18 import android.test.suitebuilder.annotation.SmallTest
19 import com.android.systemui.SysuiTestCase
20 import com.android.systemui.keyguard.WakefulnessLifecycle
21 import com.android.systemui.keyguard.WakefulnessLifecycle.WAKEFULNESS_ASLEEP
22 import com.android.systemui.keyguard.WakefulnessLifecycle.WAKEFULNESS_AWAKE
23 import com.google.common.truth.Truth.assertThat
24 import org.junit.Before
25 import org.junit.Test
26 import org.mockito.ArgumentCaptor
27 import org.mockito.Mock
28 import org.mockito.Mockito.verify
29 import org.mockito.Mockito.`when` as whenever
30 import org.mockito.MockitoAnnotations
31 
32 /**
33  * Be careful with the {FeatureFlagsReleaseRestarter} in this test. It has a call to System.exit()!
34  */
35 @SmallTest
36 class ScreenIdleConditionTest : SysuiTestCase() {
37     private lateinit var condition: ScreenIdleCondition
38 
39     @Mock private lateinit var wakefulnessLifecycle: WakefulnessLifecycle
40 
41     @Before
42     fun setup() {
43         MockitoAnnotations.initMocks(this)
44         condition = ScreenIdleCondition(wakefulnessLifecycle)
45     }
46 
47     @Test
48     fun testCondition_awake() {
49         whenever(wakefulnessLifecycle.wakefulness).thenReturn(WAKEFULNESS_AWAKE)
50 
51         assertThat(condition.canRestartNow {}).isFalse()
52     }
53 
54     @Test
55     fun testCondition_asleep() {
56         whenever(wakefulnessLifecycle.wakefulness).thenReturn(WAKEFULNESS_ASLEEP)
57 
58         assertThat(condition.canRestartNow {}).isTrue()
59     }
60 
61     @Test
62     fun testCondition_invokesRetry() {
63         whenever(wakefulnessLifecycle.wakefulness).thenReturn(WAKEFULNESS_AWAKE)
64         var retried = false
65         val retryFn = { retried = true }
66 
67         // No restart yet, but we do register a listener now.
68         assertThat(condition.canRestartNow(retryFn)).isFalse()
69         val captor = ArgumentCaptor.forClass(WakefulnessLifecycle.Observer::class.java)
70         verify(wakefulnessLifecycle).addObserver(captor.capture())
71 
72         whenever(wakefulnessLifecycle.wakefulness).thenReturn(WAKEFULNESS_ASLEEP)
73 
74         captor.value.onFinishedGoingToSleep()
75         assertThat(retried).isTrue()
76     }
77 }
78