blob: 158172504a0418da4e158ea3a4847beefe347350 [file] [log] [blame]
Artem Senicheve8837d52020-06-07 11:59:04 +03001// SPDX-License-Identifier: Apache-2.0
2// Copyright (C) 2020 YADRO
3
4#include "host_console.hpp"
5
6#include <sys/socket.h>
7#include <sys/un.h>
8
9#include <gtest/gtest.h>
10
11static constexpr char socketPath[] = "\0obmc-console";
12
13/**
14 * @class HostConsoleTest
15 * @brief Persistent file storage tests.
16 */
17class HostConsoleTest : public ::testing::Test
18{
19 protected:
20 void startServer(const char* socketId)
21 {
22 // Start server
23 serverSocket = socket(AF_UNIX, SOCK_STREAM, 0);
24 ASSERT_NE(serverSocket, -1);
25 std::string path(socketPath, socketPath + sizeof(socketPath) - 1);
26 if (*socketId)
27 {
28 path += '.';
29 path += socketId;
30 }
31 sockaddr_un sa;
32 sa.sun_family = AF_UNIX;
33 memcpy(&sa.sun_path, path.c_str(), path.length());
34 const socklen_t len = sizeof(sa) - sizeof(sa.sun_path) + path.length();
35 ASSERT_NE(
36 bind(serverSocket, reinterpret_cast<const sockaddr*>(&sa), len),
37 -1);
38 ASSERT_NE(listen(serverSocket, 1), -1);
39 }
40
41 void TearDown() override
42 {
43 // Stop server
44 if (serverSocket != -1)
45 {
46 close(serverSocket);
47 }
48 }
49
50 int serverSocket = -1;
51};
52
53TEST_F(HostConsoleTest, SingleHost)
54{
55 const char* socketId = "";
56 startServer(socketId);
57
58 HostConsole con(socketId);
59 con.connect();
60
61 const int clientSocket = accept(serverSocket, nullptr, nullptr);
62 EXPECT_NE(clientSocket, -1);
63 close(clientSocket);
64}
65
66TEST_F(HostConsoleTest, MultiHost)
67{
68 const char* socketId = "host123";
69 startServer(socketId);
70
71 HostConsole con(socketId);
72 con.connect();
73
74 const int clientSocket = accept(serverSocket, nullptr, nullptr);
75 EXPECT_NE(clientSocket, -1);
76
77 const char* data = "test data";
78 const size_t len = strlen(data);
79 EXPECT_EQ(send(clientSocket, data, len, 0), len);
80
81 char buf[64];
82 memset(buf, 0, sizeof(buf));
83 EXPECT_EQ(con.read(buf, sizeof(buf)), len);
84 EXPECT_STREQ(buf, data);
85 EXPECT_EQ(con.read(buf, sizeof(buf)), 0);
86
87 close(clientSocket);
88}