Add new methods to tizen_base::SharedQueue
[platform/core/base/bundle.git] / tests / tizen-shared-queue_unittests / test_shared_queue.cc
1 /*
2  * Copyright (c) 2023 Samsung Electronics Co., Ltd. All rights reserved.
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 <chrono>
18 #include <iostream>
19 #include <thread>
20
21 #include <gtest/gtest.h>
22 #include <gmock/gmock.h>
23
24 #include "tizen-shared-queue/shared-queue.hpp"
25
26 namespace {
27
28 class Job {
29  public:
30   Job() = default;
31
32   void Do() { done_ = true; }
33   bool Done() const { return done_; }
34
35  private:
36   bool done_ = false;
37 };
38
39 }  // namespace
40
41 TEST(SharedQueueTest, PushAndWaitAndPop) {
42   tizen_base::SharedQueue<Job> queue;
43   std::thread thread([&] {
44         auto job = queue.WaitAndPop();
45         job.Do();
46         queue.Push(std::move(job));
47       });
48   queue.Push(Job());
49   usleep(100);
50   auto job = queue.WaitAndPop();
51   thread.join();
52
53   EXPECT_TRUE(job.Done());
54 }
55
56 TEST(SharedQueueTest, TryAndPop) {
57   tizen_base::SharedQueue<Job> queue;
58   Job job;
59   EXPECT_FALSE(queue.TryAndPop(job));
60   queue.Push(Job());
61   EXPECT_TRUE(queue.TryAndPop(job));
62 }
63
64 TEST(SharedQueueTest, WaitAndPopFor) {
65   tizen_base::SharedQueue<Job> queue;
66   Job job;
67   std::chrono::steady_clock::time_point begin =
68       std::chrono::steady_clock::now();
69   EXPECT_FALSE(queue.WaitAndPopFor(job, 110));
70   std::chrono::steady_clock::time_point end =
71       std::chrono::steady_clock::now();
72   auto elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(
73       end - begin).count();
74   EXPECT_TRUE(elapsed_time > 100);
75
76   queue.Push(Job());
77   begin = std::chrono::steady_clock::now();
78   EXPECT_TRUE(queue.WaitAndPopFor(job, 100));
79   end = std::chrono::steady_clock::now();
80   elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(
81       end - begin).count();
82   EXPECT_TRUE(elapsed_time < 100);
83 }
84
85 TEST(SharedQueueTest, IsEmpty) {
86   tizen_base::SharedQueue<Job> queue;
87   EXPECT_TRUE(queue.IsEmpty());
88   queue.Push(Job());
89   EXPECT_FALSE(queue.IsEmpty());
90 }
91
92 TEST(SharedQueueTest, Size) {
93   tizen_base::SharedQueue<Job> queue;
94   EXPECT_EQ(queue.Size(), 0);
95   queue.Push(Job());
96   EXPECT_EQ(queue.Size(), 1);
97 }