TYPE3
[iec.git] / src / type3_AndroidCloud / anbox-master / tests / anbox / common / message_channel_tests.cpp
1 // Copyright 2014 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "anbox/common/message_channel.h"
16
17 #include <gtest/gtest.h>
18
19 #include <string>
20 #include <thread>
21
22 namespace anbox {
23 namespace common {
24 TEST(MessageChannel, SingleThreadWithInt) {
25     MessageChannel<int, 3U> channel;
26     channel.send(1);
27     channel.send(2);
28     channel.send(3);
29
30     int ret;
31     channel.receive(&ret);
32     EXPECT_EQ(1, ret);
33     channel.receive(&ret);
34     EXPECT_EQ(2, ret);
35     channel.receive(&ret);
36     EXPECT_EQ(3, ret);
37 }
38
39 TEST(MessageChannel, SingleThreadWithStdString) {
40     MessageChannel<std::string, 5U> channel;
41     channel.send(std::string("foo"));
42     channel.send(std::string("bar"));
43     channel.send(std::string("zoo"));
44
45     std::string str;
46     channel.receive(&str);
47     EXPECT_STREQ("foo", str.c_str());
48     channel.receive(&str);
49     EXPECT_STREQ("bar", str.c_str());
50     channel.receive(&str);
51     EXPECT_STREQ("zoo", str.c_str());
52 }
53
54 TEST(MessageChannel, TwoThreadsPingPong) {
55     struct PingPongState {
56         MessageChannel<std::string, 3U> in;
57         MessageChannel<std::string, 3U> out;
58     };
59
60     PingPongState state;
61
62     std::thread thread([&](){
63         for (;;) {
64             std::string str;
65             state.in.receive(&str);
66             state.out.send(str);
67             if (str == "quit")
68                 break;
69         }
70         return 0;
71     });
72
73     std::string str;
74     const size_t kCount = 100;
75     for (size_t n = 0; n < kCount; ++n) {
76         state.in.send(std::string("foo"));
77         state.in.send(std::string("bar"));
78         state.in.send(std::string("zoo"));
79         state.out.receive(&str);
80         EXPECT_STREQ("foo", str.c_str());
81         state.out.receive(&str);
82         EXPECT_STREQ("bar", str.c_str());
83         state.out.receive(&str);
84         EXPECT_STREQ("zoo", str.c_str());
85     }
86     state.in.send(std::string("quit"));
87     state.out.receive(&str);
88     EXPECT_STREQ("quit", str.c_str());
89
90     thread.join();
91 }
92
93 } // namespace common
94 } // namespace anbox