-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathconnector_test.cpp
More file actions
597 lines (455 loc) · 16.4 KB
/
Copy pathconnector_test.cpp
File metadata and controls
597 lines (455 loc) · 16.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//
// Copyright 2009-2026, AMT – The Association For Manufacturing Technology (“AMT”)
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/// @file
/// Test the SHDR connector behavior. The connector handles the lower level communications for the
/// adapter.
// Ensure that gtest is the first header otherwise Windows raises an error
#include <gtest/gtest.h>
// Keep this comment to keep gtest.h above. (clang-format off/on is not working here!)
#include <boost/asio/read_until.hpp>
#include <boost/asio/write.hpp>
#include <chrono>
#include <date/date.h> // This file is to allow std::chrono types to be output to a stream
#include <memory>
#include <sstream>
#include <thread>
#include "mtconnect/source/adapter/shdr/connector.hpp"
namespace date {};
using namespace date;
using namespace std;
using namespace std::chrono;
using namespace mtconnect;
using namespace mtconnect::source::adapter;
using namespace mtconnect::source::adapter::shdr;
namespace asio = boost::asio;
using tcp = boost::asio::ip::tcp;
namespace ip = boost::asio::ip;
namespace sys = boost::system;
using namespace chrono_literals;
// main
int main(int argc, char* argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
/// @brief Mock adapter for this connector.
class TestConnector : public Connector
{
public:
TestConnector(boost::asio::io_context::strand& strand, const std::string& server,
unsigned int port, std::chrono::seconds legacyTimeout = std::chrono::seconds {5},
std::chrono::seconds reconnectInterval = std::chrono::seconds {10},
std::optional<std::chrono::milliseconds> heartbeat = std::nullopt)
: Connector(strand, server, port, legacyTimeout, reconnectInterval, heartbeat),
m_disconnected(false),
m_strand(strand)
{}
bool start(unsigned short port)
{
m_port = port;
return Connector::start();
}
void processData(const std::string& data) override
{
if (data[0] == '*')
protocolCommand(data);
else
{
m_data = data;
m_list.emplace_back(m_data);
}
}
void protocolCommand(const std::string& data) override { m_command = data; }
void connecting() override {}
void disconnected() override { m_disconnected = true; }
void connected() override { m_disconnected = false; }
bool heartbeats() { return m_heartbeats; }
void startHeartbeats(std::string& aString) { Connector::startHeartbeats(aString); }
void resetHeartbeats() { m_heartbeats = false; }
public:
std::vector<std::string> m_list;
std::string m_data;
std::string m_command;
bool m_disconnected;
boost::asio::io_context::strand& m_strand;
};
/// @brief Connector test runner
class ConnectorTest : public testing::Test
{
protected:
ConnectorTest() : m_strand(m_context) {}
void SetUp() override
{
m_connector = std::make_unique<TestConnector>(m_strand, "127.0.0.1", m_port);
m_connector->m_disconnected = true;
m_connected = false;
}
void TearDown() override
{
m_context.stop();
m_connector.reset();
if (m_server)
m_server->close();
m_server.reset();
m_acceptor.reset();
}
void startServer(const std::string addr = "127.0.0.1")
{
tcp::endpoint sp(ip::make_address(addr), 0);
m_connected = false;
m_acceptor = make_unique<tcp::acceptor>(m_context, sp);
ASSERT_TRUE(m_acceptor->is_open());
tcp::endpoint ep = m_acceptor->local_endpoint();
m_port = ep.port();
m_acceptor->async_accept([this](sys::error_code ec, tcp::socket socket) {
if (ec)
cout << ec.category().message(ec.value()) << ": " << ec.message() << endl;
ASSERT_FALSE(ec);
ASSERT_TRUE(socket.is_open());
m_connected = true;
m_server = make_unique<tcp::socket>(std::move(socket));
});
}
template <typename Rep, typename Period>
void runUntil(chrono::duration<Rep, Period> to, function<bool()> pred)
{
int runs;
for (runs = 0; runs < 50 && !pred(); runs++)
{
if (m_context.run_one_for(to) == 0)
break;
}
EXPECT_TRUE(pred());
}
void send(const std::string& s)
{
ASSERT_TRUE(m_server);
asio::streambuf outoging;
std::ostream os(&outoging);
os << s;
sys::error_code ec;
asio::write(*m_server, outoging, ec);
ASSERT_FALSE(ec);
}
template <typename Rep, typename Period>
string read(chrono::duration<Rep, Period> dur)
{
m_line.clear();
asio::streambuf data;
asio::async_read_until(*m_server, data, '\n', [this, &data](sys::error_code ec, size_t len) {
EXPECT_FALSE(ec);
if (ec)
{
cout << ec.category().message(ec.value()) << ": " << ec.message() << endl;
}
else
{
istream is(&data);
string line;
getline(is, m_line);
}
});
runUntil(dur, [this]() { return !m_line.empty(); });
return m_line;
}
std::unique_ptr<TestConnector> m_connector;
unsigned short m_port {0};
boost::asio::io_context m_context;
boost::asio::io_context::strand m_strand;
std::unique_ptr<asio::ip::tcp::socket> m_server;
std::unique_ptr<tcp::acceptor> m_acceptor;
bool m_connected;
string m_line;
};
/// @test check if the connector is able to connect to a socket. Make sure it sends a ping.
TEST_F(ConnectorTest, should_be_able_to_connect)
{
ASSERT_TRUE(m_connector->m_disconnected);
startServer();
/// - Start the connector
m_connector->start(m_port);
/// - Wait for 5 seconds for a connection
runUntil(5s, [this]() -> bool { return m_connected && m_connector->isConnected(); });
/// - Check for a ping
EXPECT_FALSE(m_connector->m_disconnected);
auto line = read(1s);
ASSERT_EQ("* PING", line);
}
/// @test check if the connector can receive data from the connector
TEST_F(ConnectorTest, should_be_able_to_read_data_from_a_socket)
{
// Start the accept thread
ASSERT_TRUE(m_connector->m_disconnected);
startServer();
m_connector->start(m_port);
runUntil(2s, [this]() -> bool { return m_connected && m_connector->isConnected(); });
send("Hello Connector\n");
runUntil(1s, [this]() -> bool { return !m_connector->m_data.empty(); });
ASSERT_EQ("Hello Connector", m_connector->m_data);
}
/// @test check if the connector disconnects
TEST_F(ConnectorTest, should_disconnect_when_server_closes_the_connection)
{
// Start the accept thread
startServer();
m_connector->start(m_port);
runUntil(2s, [this]() -> bool { return m_connected && m_connector->isConnected(); });
ASSERT_FALSE(m_connector->m_disconnected);
m_server->close();
runUntil(2s, [this]() -> bool { return m_connector->m_disconnected; });
ASSERT_TRUE(m_connector->m_disconnected);
}
/// @test check if the connector correctly handles a protocol command starting with a `*`
TEST_F(ConnectorTest, should_process_a_protocol_command)
{
// Start the accept thread
startServer();
m_connector->start(m_port);
runUntil(2s, [this]() -> bool { return m_connected && m_connector->isConnected(); });
send("* Hello Connector\n");
runUntil(1s, [this]() -> bool { return !m_connector->m_command.empty(); });
ASSERT_EQ("* Hello Connector", m_connector->m_command);
}
TEST_F(ConnectorTest, heartbeat_is_enabled_after_valid_pong_received)
{
// Start the accept thread
startServer();
m_connector->start(m_port);
runUntil(2s, [this]() -> bool { return m_connected && m_connector->isConnected(); });
auto line = read(1s);
ASSERT_EQ("* PING", line);
send("* PONG 1000\n");
runUntil(2s, [this]() -> bool { return m_connector->heartbeats(); });
// Respond to the heartbeat of 1 second
ASSERT_TRUE(m_connector->heartbeats());
ASSERT_EQ(std::chrono::milliseconds {1000}, m_connector->heartbeatFrequency());
}
TEST_F(ConnectorTest, heartbeat_pong_response_keeps_connection_alive)
{
// TODO Copy&Paste from Heartbeat
// Start the accept thread
startServer();
m_connector->start(m_port);
runUntil(2s, [this]() -> bool { return m_connected && m_connector->isConnected(); });
auto line = read(1s);
ASSERT_EQ("* PING", line);
send("* PONG 1000\n");
runUntil(2s, [this]() -> bool { return m_connector->heartbeats(); });
// Respond to the heartbeat of 1 second
ASSERT_TRUE(m_connector->heartbeats());
ASSERT_EQ(std::chrono::milliseconds {1000}, m_connector->heartbeatFrequency());
auto last_heartbeat = system_clock::now();
// Test to make sure we can send and receive 5 heartbeats
for (int i = 0; i < 5; i++)
{
auto line = read(2s);
auto now = system_clock::now();
ASSERT_TRUE(now - last_heartbeat < 2000ms);
last_heartbeat = now;
// Respond to the heartbeat of 1 second
send("* PONG 1000\n");
ASSERT_FALSE(m_connector->m_disconnected);
}
}
TEST_F(ConnectorTest, data_response_keeps_connection_alive_during_heartbeat)
{
startServer();
m_connector->start(m_port);
runUntil(2s, [this]() -> bool { return m_connected && m_connector->isConnected(); });
auto line = read(1s);
ASSERT_EQ("* PING", line);
send("* PONG 1000\n");
runUntil(2s, [this]() -> bool { return m_connector->heartbeats(); });
// Respond to the heartbeat of 1 second
ASSERT_TRUE(m_connector->heartbeats());
ASSERT_EQ(std::chrono::milliseconds {1000}, m_connector->heartbeatFrequency());
auto last_heartbeat = system_clock::now();
// Test to make sure we can send and receive 5 heartbeats
for (int i = 0; i < 5; i++)
{
auto line = read(2s);
auto now = system_clock::now();
ASSERT_TRUE(now - last_heartbeat < 2000ms);
last_heartbeat = now;
// Respond to the heartbeat of 1 second
send("Some Data\n");
ASSERT_FALSE(m_connector->m_disconnected);
}
}
TEST_F(ConnectorTest, connection_is_disconnected_when_heartbeat_times_out)
{
startServer();
m_connector->start(m_port);
runUntil(2s, [this]() -> bool { return m_connected && m_connector->isConnected(); });
auto line = read(1s);
ASSERT_EQ("* PING", line);
send("* PONG 1000\n");
runUntil(2s, [this]() -> bool { return m_connector->heartbeats(); });
// Respond to the heartbeat of 1 second
ASSERT_TRUE(m_connector->heartbeats());
ASSERT_EQ(std::chrono::milliseconds {1000}, m_connector->heartbeatFrequency());
// Respond to the heartbeat of 1 second
m_context.run_for(2200ms);
ASSERT_TRUE(m_connector->m_disconnected);
}
TEST_F(ConnectorTest, connection_is_disconnected_when_legacy_timeout_expires)
{
startServer();
m_connector->start(m_port);
runUntil(2s, [this]() -> bool { return m_connected && m_connector->isConnected(); });
auto line = read(1s);
ASSERT_EQ("* PING", line);
// Write some data...
send("Hello connector\n");
// No pings, but timeout after 5 seconds of silence
// Respond to the heartbeat of 1 second
m_context.run_for(5200ms);
ASSERT_TRUE(m_connector->m_disconnected);
}
TEST_F(ConnectorTest, fragmented_data_is_assembled_into_complete_lines)
{
startServer();
m_connector->start(m_port);
runUntil(2s, [this]() -> bool { return m_connected && m_connector->isConnected(); });
// Test data fragmentation
send("Hello");
ASSERT_EQ((string) "", m_connector->m_data);
m_context.run_for(2ms);
send(" There\n");
runUntil(1s, [this]() { return !m_connector->m_data.empty(); });
ASSERT_EQ((string) "Hello There", m_connector->m_data);
m_connector->m_data.clear();
send("Hello");
m_context.run_for(2ms);
ASSERT_EQ((string) "", m_connector->m_data);
send(" There\nAnd ");
runUntil(1s, [this]() { return !m_connector->m_data.empty(); });
ASSERT_EQ((string) "Hello There", m_connector->m_data);
m_connector->m_data.clear();
send("Again\nXXX");
runUntil(1s, [this]() { return !m_connector->m_data.empty(); });
ASSERT_EQ((string) "And Again", m_connector->m_data);
}
TEST_F(ConnectorTest, multiple_lines_are_correctly_framed_from_stream)
{
startServer();
m_connector->start(m_port);
runUntil(2s, [this]() -> bool { return m_connected && m_connector->isConnected(); });
m_connector->m_list.clear();
send("first\nseco");
m_context.run_for(2ms);
send("nd\nthird\nfourth\nfifth");
m_context.run_for(2ms);
ASSERT_EQ((size_t)4, m_connector->m_list.size());
ASSERT_EQ((string) "first", m_connector->m_list[0]);
ASSERT_EQ((string) "second", m_connector->m_list[1]);
ASSERT_EQ((string) "third", m_connector->m_list[2]);
ASSERT_EQ((string) "fourth", m_connector->m_list[3]);
}
TEST_F(ConnectorTest, command_is_sent_with_star_prefix_to_server)
{
startServer();
m_connector->start(m_port);
runUntil(2s, [this]() -> bool { return m_connected && m_connector->isConnected(); });
auto line = read(1s);
ASSERT_EQ("* PING", line);
ASSERT_TRUE(m_connector->isConnected());
m_connector->sendCommand("Hello There;");
line = read(1s);
ASSERT_EQ("* Hello There;", line);
}
TEST_F(ConnectorTest, connector_connects_via_ipv6_address)
{
// TODO: Need to port to Windows > VISTA
#if !defined(WIN32) && !defined(AGENT_WITHOUT_IPV6)
m_connector.reset();
startServer("::1");
boost::asio::io_context::strand strand(m_context);
m_connector = std::make_unique<TestConnector>(strand, "::1", m_port);
m_connector->start(m_port);
runUntil(2s, [this]() -> bool { return m_connected && m_connector->isConnected(); });
ASSERT_FALSE(m_connector->m_disconnected);
#endif
}
TEST_F(ConnectorTest, should_start_heartbeats_when_a_valid_pong_is_received)
{
ASSERT_TRUE(!m_connector->heartbeats());
string line = "* PONG ";
m_connector->startHeartbeats(line);
ASSERT_TRUE(!m_connector->heartbeats());
line = "* PONK ";
m_connector->startHeartbeats(line);
ASSERT_TRUE(!m_connector->heartbeats());
line = "* PONG ";
m_connector->startHeartbeats(line);
ASSERT_TRUE(!m_connector->heartbeats());
line = "* PONG FLAB";
m_connector->startHeartbeats(line);
ASSERT_TRUE(!m_connector->heartbeats());
line = "* PONG 123";
m_connector->startHeartbeats(line);
ASSERT_TRUE(m_connector->heartbeats());
ASSERT_EQ(std::chrono::milliseconds {123}, m_connector->heartbeatFrequency());
m_connector->resetHeartbeats();
line = "* PONG 456 ";
m_connector->startHeartbeats(line);
ASSERT_TRUE(m_connector->heartbeats());
ASSERT_EQ(std::chrono::milliseconds {456}, m_connector->heartbeatFrequency());
line = "* PONG 323";
m_connector->startHeartbeats(line);
ASSERT_TRUE(m_connector->heartbeats());
ASSERT_EQ(std::chrono::milliseconds {323}, m_connector->heartbeatFrequency());
}
TEST_F(ConnectorTest, trailing_whitespace_is_trimmed_from_received_lines)
{
startServer();
m_connector->start(m_port);
runUntil(2s, [this]() -> bool { return m_connected && m_connector->isConnected(); });
m_connector->m_list.clear();
send("first \r\nseco");
m_context.run_for(2ms);
send("nd \t\r\n \t \r\n\n third \v\r\t\nfourth \f\t\r\nr \nfifth");
m_context.run_for(2ms);
ASSERT_EQ((size_t)5, m_connector->m_list.size());
ASSERT_EQ((string) "first", m_connector->m_list[0]);
ASSERT_EQ((string) "second", m_connector->m_list[1]);
ASSERT_EQ((string) " third", m_connector->m_list[2]);
ASSERT_EQ((string) "fourth", m_connector->m_list[3]);
ASSERT_EQ((string) "r", m_connector->m_list[4]);
}
/// @test validate the heartbeat override works for the connector.
TEST_F(ConnectorTest, should_override_adapter_heartbeat_in_pong)
{
boost::asio::io_context::strand strand(m_context);
m_connector = std::make_unique<TestConnector>(strand, "127.0.0.1", m_port, 600s, 10s, 123ms);
m_connector->m_disconnected = true;
m_connected = false;
ASSERT_TRUE(!m_connector->heartbeats());
string line = "* PONG 888";
m_connector->startHeartbeats(line);
ASSERT_TRUE(m_connector->heartbeats());
ASSERT_EQ(std::chrono::milliseconds {123}, m_connector->heartbeatFrequency());
m_connector->resetHeartbeats();
line = "* PONG 456 ";
m_connector->startHeartbeats(line);
ASSERT_TRUE(m_connector->heartbeats());
ASSERT_EQ(std::chrono::milliseconds {123}, m_connector->heartbeatFrequency());
line = "* PONG 323";
m_connector->startHeartbeats(line);
ASSERT_TRUE(m_connector->heartbeats());
ASSERT_EQ(std::chrono::milliseconds {123}, m_connector->heartbeatFrequency());
}