1/*
2 * Copyright (C) 2017 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
17package com.android.systemui.util.wakelock;
18
19import static org.junit.Assert.assertFalse;
20import static org.junit.Assert.assertTrue;
21
22import android.content.Context;
23import android.os.PowerManager;
24import android.support.test.InstrumentationRegistry;
25import android.support.test.filters.SmallTest;
26import android.support.test.runner.AndroidJUnit4;
27
28import com.android.systemui.SysuiTestCase;
29
30import org.junit.After;
31import org.junit.Before;
32import org.junit.Test;
33import org.junit.runner.RunWith;
34
35@SmallTest
36@RunWith(AndroidJUnit4.class)
37public class WakeLockTest extends SysuiTestCase {
38
39    WakeLock mWakeLock;
40    PowerManager.WakeLock mInner;
41
42    @Before
43    public void setUp() {
44        mInner = WakeLock.createPartialInner(mContext, WakeLockTest.class.getName());
45        mWakeLock = WakeLock.wrap(mInner);
46    }
47
48    @After
49    public void tearDown() {
50        mInner.setReferenceCounted(false);
51        mInner.release();
52    }
53
54    @Test
55    public void createPartialInner_notHeldYet() {
56        assertFalse(mInner.isHeld());
57    }
58
59    @Test
60    public void wakeLock_acquire() {
61        mWakeLock.acquire();
62        assertTrue(mInner.isHeld());
63    }
64
65    @Test
66    public void wakeLock_release() {
67        mWakeLock.acquire();
68        mWakeLock.release();
69        assertFalse(mInner.isHeld());
70    }
71
72    @Test
73    public void wakeLock_refCounted() {
74        mWakeLock.acquire();
75        mWakeLock.acquire();
76        mWakeLock.release();
77        assertTrue(mInner.isHeld());
78    }
79
80    @Test
81    public void wakeLock_wrap() {
82        boolean[] ran = new boolean[1];
83
84        Runnable wrapped = mWakeLock.wrap(() -> {
85            ran[0] = true;
86        });
87
88        assertTrue(mInner.isHeld());
89        assertFalse(ran[0]);
90
91        wrapped.run();
92
93        assertTrue(ran[0]);
94        assertFalse(mInner.isHeld());
95    }
96}