blob: 6a16148fa801a47a3e4dd2fb30ddc92e6a5f88d1 [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
Chau Ly47734e22023-07-19 08:03:18 +000011static constexpr char socketPath[] = "\0obmc-console";
12static constexpr std::string defaultSocketId = "default";
Artem Senicheve8837d52020-06-07 11:59:04 +030013
14/**
15 * @class HostConsoleTest
16 * @brief Persistent file storage tests.
17 */
18class HostConsoleTest : public ::testing::Test
19{
20 protected:
21 void startServer(const char* socketId)
22 {
23 // Start server
24 serverSocket = socket(AF_UNIX, SOCK_STREAM, 0);
25 ASSERT_NE(serverSocket, -1);
26 std::string path(socketPath, socketPath + sizeof(socketPath) - 1);
Chau Ly47734e22023-07-19 08:03:18 +000027 path += '.';
Artem Senicheve8837d52020-06-07 11:59:04 +030028 if (*socketId)
29 {
Artem Senicheve8837d52020-06-07 11:59:04 +030030 path += socketId;
31 }
Chau Ly47734e22023-07-19 08:03:18 +000032 else
33 {
34 path += defaultSocketId;
35 }
Artem Senicheve8837d52020-06-07 11:59:04 +030036 sockaddr_un sa;
37 sa.sun_family = AF_UNIX;
38 memcpy(&sa.sun_path, path.c_str(), path.length());
39 const socklen_t len = sizeof(sa) - sizeof(sa.sun_path) + path.length();
40 ASSERT_NE(
41 bind(serverSocket, reinterpret_cast<const sockaddr*>(&sa), len),
42 -1);
43 ASSERT_NE(listen(serverSocket, 1), -1);
44 }
45
46 void TearDown() override
47 {
48 // Stop server
49 if (serverSocket != -1)
50 {
51 close(serverSocket);
52 }
53 }
54
55 int serverSocket = -1;
56};
57
58TEST_F(HostConsoleTest, SingleHost)
59{
60 const char* socketId = "";
61 startServer(socketId);
62
63 HostConsole con(socketId);
64 con.connect();
65
66 const int clientSocket = accept(serverSocket, nullptr, nullptr);
67 EXPECT_NE(clientSocket, -1);
68 close(clientSocket);
69}
70
71TEST_F(HostConsoleTest, MultiHost)
72{
73 const char* socketId = "host123";
74 startServer(socketId);
75
76 HostConsole con(socketId);
77 con.connect();
78
79 const int clientSocket = accept(serverSocket, nullptr, nullptr);
80 EXPECT_NE(clientSocket, -1);
81
82 const char* data = "test data";
83 const size_t len = strlen(data);
84 EXPECT_EQ(send(clientSocket, data, len, 0), len);
85
86 char buf[64];
87 memset(buf, 0, sizeof(buf));
88 EXPECT_EQ(con.read(buf, sizeof(buf)), len);
89 EXPECT_STREQ(buf, data);
90 EXPECT_EQ(con.read(buf, sizeof(buf)), 0);
91
92 close(clientSocket);
93}