1 /*
2  * Copyright 2024 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 <future>
18 
19 #include <compositionengine/impl/HwcAsyncWorker.h>
20 #include <gtest/gtest.h>
21 
22 namespace android::compositionengine {
23 namespace {
24 
25 using namespace std::chrono_literals;
26 
27 // For the edge case tests below, how much real time should be spent trying to reproduce edge cases
28 // problems in a loop.
29 //
30 // Larger values mean problems are more likely to be detected, at the cost of making the unit test
31 // run slower.
32 //
33 // As we expect the tests to be run continuously, even a short loop will eventually catch
34 // problems, though not necessarily from changes in the same build that introduce them.
35 constexpr auto kWallTimeForEdgeCaseTests = 5ms;
36 
TEST(HwcAsyncWorker,continuousTasksEdgeCase)37 TEST(HwcAsyncWorker, continuousTasksEdgeCase) {
38     // Ensures that a single worker that is given multiple tasks in short succession will run them.
39 
40     impl::HwcAsyncWorker worker;
41     const auto endTime = std::chrono::steady_clock::now() + kWallTimeForEdgeCaseTests;
42     while (std::chrono::steady_clock::now() < endTime) {
43         auto f1 = worker.send([] { return false; });
44         EXPECT_FALSE(f1.get());
45         auto f2 = worker.send([] { return true; });
46         EXPECT_TRUE(f2.get());
47     }
48 }
49 
TEST(HwcAsyncWorker,constructAndDestroyEdgeCase)50 TEST(HwcAsyncWorker, constructAndDestroyEdgeCase) {
51     // Ensures that newly created HwcAsyncWorkers can be immediately destroyed.
52 
53     const auto endTime = std::chrono::steady_clock::now() + kWallTimeForEdgeCaseTests;
54     while (std::chrono::steady_clock::now() < endTime) {
55         impl::HwcAsyncWorker worker;
56     }
57 }
58 
TEST(HwcAsyncWorker,newlyCreatedRunsTasksEdgeCase)59 TEST(HwcAsyncWorker, newlyCreatedRunsTasksEdgeCase) {
60     // Ensures that newly created HwcAsyncWorkers will run a task if given one immediately.
61 
62     const auto endTime = std::chrono::steady_clock::now() + kWallTimeForEdgeCaseTests;
63     while (std::chrono::steady_clock::now() < endTime) {
64         impl::HwcAsyncWorker worker;
65         auto f = worker.send([] { return true; });
66         f.get();
67     }
68 }
69 
70 } // namespace
71 } // namespace android::compositionengine
72