1 // Copyright (C) 2018 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 #include "host-common/HostGoldfishPipe.h"
15 
16 #include "host-common/AndroidMessagePipe.h"
17 
18 #include <gtest/gtest.h>
19 
20 namespace android {
21 
22 class HostGoldfishPipeTest : public ::testing::Test {
23 protected:
SetUp()24     void SetUp() override {
25         AndroidPipe::Service::resetAll();
26         mDevice = HostGoldfishPipeDevice::get();
27     }
28 
TearDown()29     void TearDown() override {
30         AndroidPipe::Service::resetAll();
31         // mDevice is singleton, no need to tear down
32     }
33     HostGoldfishPipeDevice* mDevice = nullptr;
34 };
35 
TEST_F(HostGoldfishPipeTest,Basic)36 TEST_F(HostGoldfishPipeTest, Basic) { }
37 
TEST_F(HostGoldfishPipeTest,MessagePipe)38 TEST_F(HostGoldfishPipeTest, MessagePipe) {
39    const char kPayload[] = "Hello World";
40    const char kResponse[] = "response";
41 
42    bool ran = false;
43 
44    auto myDecodeAndExecute =
45        [kPayload, kResponse, &ran](
46           const std::vector<uint8_t>& input,
47           std::vector<uint8_t>* output) {
48        EXPECT_STREQ(kPayload, (char*)input.data());
49        size_t bytes = strlen(kResponse) + 1;
50        output->resize(bytes);
51        memset(output->data(), 0x0, bytes);
52        memcpy(output->data(), kResponse, strlen(kResponse));
53        ran = true;
54    };
55 
56    registerAndroidMessagePipeService(
57        "testMessagePipe", myDecodeAndExecute);
58 
59    auto pipe = mDevice->connect("testMessagePipe");
60 
61    int32_t payloadSz = strlen(kPayload) + 1;
62    EXPECT_EQ(sizeof(int32_t),
63              mDevice->write(pipe, &payloadSz, sizeof(int32_t)));
64 
65    std::vector<uint8_t> toSend(payloadSz, 0);
66    memcpy(toSend.data(), kPayload, strlen(kPayload));
67    EXPECT_TRUE(mDevice->write(pipe, toSend).ok());
68 
69    int32_t responseSize = 0;
70    EXPECT_EQ(sizeof(int32_t),
71              mDevice->read(pipe, (void*)&responseSize, sizeof(int32_t)));
72 
73    EXPECT_TRUE(ran);
74 
75    auto response = mDevice->read(pipe, responseSize);
76    EXPECT_TRUE(response.ok());
77    EXPECT_STREQ(kResponse, (char*)(response.ok()->data()));
78 
79    mDevice->close(pipe);
80 }
81 
82 } // namespace android
83