blob: 601df64fcb7cd0506ef569700720b251ec896564 [file] [log] [blame]
Tri Vo18177502018-10-20 16:11:24 -07001/*
2 * Copyright 2018 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#include <hardware_legacy/power.h>
18
Tri Voca0b45a2018-11-27 17:56:56 -080019#include <csignal>
20#include <cstdlib>
Tri Vo18177502018-10-20 16:11:24 -070021#include <string>
22#include <thread>
23#include <vector>
24
25#include <gtest/gtest.h>
26
Tri Voca0b45a2018-11-27 17:56:56 -080027using namespace std::chrono_literals;
28
Tri Vo18177502018-10-20 16:11:24 -070029namespace android {
30
Tri Voca0b45a2018-11-27 17:56:56 -080031// Test acquiring/releasing WakeLocks concurrently with process exit.
32TEST(LibpowerTest, ProcessExitTest) {
33 std::atexit([] {
34 // We want to give the other thread enough time trigger a failure and
35 // dump the stack traces.
36 std::this_thread::sleep_for(1s);
37 });
38
39 ASSERT_EXIT(
40 {
41 constexpr int numThreads = 20;
42 std::vector<std::thread> tds;
43 for (int i = 0; i < numThreads; i++) {
44 tds.emplace_back([] {
45 while (true) {
46 // We want ids to be unique.
47 std::string id = std::to_string(rand());
48 ASSERT_EQ(acquire_wake_lock(PARTIAL_WAKE_LOCK, id.c_str()), 0);
49 ASSERT_EQ(release_wake_lock(id.c_str()), 0);
50 }
51 });
52 }
53 for (auto& td : tds) {
54 td.detach();
55 }
56
57 // Give some time for the threads to actually start.
58 std::this_thread::sleep_for(100ms);
59 std::exit(0);
60 },
61 ::testing::ExitedWithCode(0), "");
62}
63
Tri Vo18177502018-10-20 16:11:24 -070064// Stress test acquiring/releasing WakeLocks.
65TEST(LibpowerTest, WakeLockStressTest) {
66 // numThreads threads will acquire/release numLocks locks each.
67 constexpr int numThreads = 20;
Tri Voca0b45a2018-11-27 17:56:56 -080068 constexpr int numLocks = 1000;
Tri Vo18177502018-10-20 16:11:24 -070069 std::vector<std::thread> tds;
70
71 for (int i = 0; i < numThreads; i++) {
72 tds.emplace_back([i] {
73 for (int j = 0; j < numLocks; j++) {
74 // We want ids to be unique.
75 std::string id = std::to_string(i) + "/" + std::to_string(j);
76 ASSERT_EQ(acquire_wake_lock(PARTIAL_WAKE_LOCK, id.c_str()), 0);
77 ASSERT_EQ(release_wake_lock(id.c_str()), 0);
78 }
79 });
80 }
81 for (auto& td : tds) {
82 td.join();
83 }
84}
85
86} // namespace android