1 /*
2  * Copyright (C) 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 <audio_utils/CommandThread.h>
18 
19 #include <gtest/gtest.h>
20 
TEST(commandthread,basic)21 TEST(commandthread, basic) {
22     android::audio_utils::CommandThread ct;
23 
24     ct.add("one", [](){});
25     ct.add("two", [](){});
26     ct.quit();
27     EXPECT_EQ(0, ct.size());
28     EXPECT_EQ("", ct.dump());
29 }
30 
TEST(commandthread,full)31 TEST(commandthread, full) {
32     std::mutex m;
33     std::condition_variable cv;
34     int stage = 0;
35     android::audio_utils::CommandThread ct;
36 
37     // load the CommandThread queue.
38     ct.add("one", [&]{
39         std::unique_lock ul(m);
40         stage = 1;
41         cv.notify_one();
42         cv.wait(ul, [&] { return stage == 2; });
43     });
44     ct.add("two", [&]{
45         std::unique_lock ul(m);
46         stage = 3;
47         cv.notify_one();
48         cv.wait(ul, [&] { return stage == 4; });
49     });
50     ct.add("three", [&]{
51         std::unique_lock ul(m);
52         stage = 5;
53         cv.notify_one();
54         cv.wait(ul, [&] { return stage == 6; });
55     });
56 
57     std::unique_lock ul(m);
58 
59     // step through each command in the queue.
60 
61     cv.wait(ul, [&] { return stage == 1; });
62     EXPECT_EQ(2, ct.size());
63     EXPECT_EQ("two\nthree\n", ct.dump());
64     stage = 2;
65     cv.notify_one();
66 
67     cv.wait(ul, [&] { return stage == 3; });
68     EXPECT_EQ(1, ct.size());
69     EXPECT_EQ("three\n", ct.dump());
70     stage = 4;
71     cv.notify_one();
72 
73     cv.wait(ul, [&] { return stage == 5; });
74     EXPECT_EQ(0, ct.size());
75     EXPECT_EQ("", ct.dump());
76     stage = 6;
77     cv.notify_one();
78 }
79