1 #include "test_base.hpp"
2
BaseTest(const char * clientDevicePath,const char * serverDevicePath,const char * serviceName)3 BaseTest::BaseTest(const char* clientDevicePath, const char* serverDevicePath,
4 const char* serviceName)
5 {
6 std::string socatCmd = std::format(
7 "socat -x -v -d -d pty,link={},rawer,echo=0,parenb,{} pty,link={},rawer,echo=0,parenb,{} & echo $!",
8 serverDevicePath, strBaudeRate, clientDevicePath, strBaudeRate);
9
10 // Start socat in the background and capture its PID
11 FILE* fp = popen(socatCmd.c_str(), "r");
12 EXPECT_NE(fp, nullptr) << "Failed to start socat: " << strerror(errno);
13 EXPECT_GT(fscanf(fp, "%d", &socatPid), 0);
14 pclose(fp);
15
16 // Wait for socat to start up
17 sleep(1);
18
19 fdClient = open(clientDevicePath, O_RDWR | O_NOCTTY | O_NONBLOCK);
20 EXPECT_NE(fdClient, -1) << "Failed to open serial port " << clientDevicePath
21 << " with error: " << strerror(errno);
22
23 fdServer = open(serverDevicePath, O_RDWR | O_NOCTTY | O_NONBLOCK);
24 EXPECT_NE(fdServer, -1) << "Failed to open serial port " << serverDevicePath
25 << " with error: " << strerror(errno);
26
27 ctx.request_name(serviceName);
28
29 serverTester = std::make_unique<TestIntf::ServerTester>(ctx, fdServer);
30 }
31
~BaseTest()32 BaseTest::~BaseTest() noexcept
33 {
34 if (fdClient != -1)
35 {
36 close(fdClient);
37 fdClient = -1;
38 }
39 if (fdServer != -1)
40 {
41 close(fdServer);
42 fdServer = -1;
43 }
44 kill(socatPid, SIGTERM);
45 }
46
SetUp()47 void BaseTest::SetUp()
48 {
49 serverThread = std::thread(&BaseTest::ServerRequestHandler, this);
50 }
51
TearDown()52 void BaseTest::TearDown()
53 {
54 exitThread.store(true);
55 if (serverThread.joinable())
56 {
57 serverThread.join();
58 }
59 }
60
ServerRequestHandler()61 void BaseTest::ServerRequestHandler()
62 {
63 while (!exitThread.load())
64 {
65 serverTester->processRequests();
66 }
67 }
68