From 5af0887b438a240487f4ad1747d77a3bee93d1b6 Mon Sep 17 00:00:00 2001 From: Will Sobel Date: Fri, 2 Dec 2022 09:50:33 -0800 Subject: [PATCH] Version 2.0.0.13_RC1 and made username and password optional. Ran clangformat --- CMakeLists.txt | 4 +- src/agent.cpp | 39 ++++---- src/agent.hpp | 2 +- src/configuration/agent_config.cpp | 9 +- src/mqtt/mqtt_client_impl.hpp | 42 ++++---- src/mqtt/mqtt_server_impl.hpp | 14 +-- src/parser/xml_parser.cpp | 2 +- src/parser/xml_parser.hpp | 2 +- src/printer/json_printer.cpp | 2 +- src/printer/printer.hpp | 13 +-- src/printer/xml_printer.cpp | 8 +- src/utilities.hpp | 9 +- test/agent_test.cpp | 15 ++- test/config_test.cpp | 59 +++++------- test/mqtt_isolated_test.cpp | 149 +++++++++++++++-------------- test/mqtt_sink_test.cpp | 82 +++++++--------- test/test_utilities.hpp | 4 +- test/xml_printer_test.cpp | 3 +- 18 files changed, 216 insertions(+), 242 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 030ede85a..45e47305f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,8 +2,8 @@ set(AGENT_VERSION_MAJOR 2) set(AGENT_VERSION_MINOR 0) set(AGENT_VERSION_PATCH 0) -set(AGENT_VERSION_BUILD 12) -set(AGENT_VERSION_RC "_RC25") +set(AGENT_VERSION_BUILD 13) +set(AGENT_VERSION_RC "_RC1") # This minimum version is to support Visual Studio 2017 and C++ feature checking and FetchContent cmake_minimum_required(VERSION 3.16 FATAL_ERROR) diff --git a/src/agent.cpp b/src/agent.cpp index 6997a9b5a..8a0700e19 100644 --- a/src/agent.cpp +++ b/src/agent.cpp @@ -77,8 +77,7 @@ namespace mtconnect { m_context(context), m_strand(m_context), m_xmlParser(make_unique()), - m_schemaVersion( - GetOption(options, config::SchemaVersion)), + m_schemaVersion(GetOption(options, config::SchemaVersion)), m_deviceXmlPath(deviceXmlPath), m_circularBuffer(GetOption(options, config::BufferSize).value_or(17), GetOption(options, config::CheckpointFrequency).value_or(1000)), @@ -104,7 +103,7 @@ namespace mtconnect { // Create the Printers m_printers["xml"] = make_unique(m_pretty); m_printers["json"] = make_unique(jsonVersion, m_pretty); - + if (m_schemaVersion) { for (auto &[k, pr] : m_printers) @@ -125,7 +124,7 @@ namespace mtconnect { { m_schemaVersion.emplace(StrDefaultSchemaVersion()); } - + auto version = IntSchemaVersion(*m_schemaVersion); for (auto &[k, pr] : m_printers) pr->setSchemaVersion(*m_schemaVersion); @@ -135,7 +134,7 @@ namespace mtconnect { { createAgentDevice(); } - + // For the DeviceAdded event for each device for (auto device : devices) addDevice(device); @@ -298,9 +297,9 @@ namespace mtconnect { // Load the configuration for the Agent auto devices = m_xmlParser->parseFile( deviceFile, dynamic_cast(m_printers["xml"].get())); - + if (m_xmlParser->getSchemaVersion() && - IntSchemaVersion(*m_xmlParser->getSchemaVersion()) != IntSchemaVersion(*m_schemaVersion)) + IntSchemaVersion(*m_xmlParser->getSchemaVersion()) != IntSchemaVersion(*m_schemaVersion)) { LOG(info) << "Got version: " << *(m_xmlParser->getSchemaVersion()); LOG(warning) << "Schema version does not match agent schema version, restarting the agent"; @@ -315,7 +314,7 @@ namespace mtconnect { } if (changed) loadCachedProbe(); - + return true; } catch (runtime_error &e) @@ -600,7 +599,8 @@ namespace mtconnect { // Create the Agent Device ErrorList errors; - Properties ps {{"uuid", uuid}, {"id", id}, {"name", "Agent"s}, {"mtconnectVersion", *m_schemaVersion}}; + Properties ps { + {"uuid", uuid}, {"id", id}, {"name", "Agent"s}, {"mtconnectVersion", *m_schemaVersion}}; m_agentDevice = dynamic_pointer_cast(AgentDevice::getFactory()->make("Agent", ps, errors)); if (!errors.empty()) @@ -616,7 +616,7 @@ namespace mtconnect { // Device management and Initialization // ---------------------------------------------- - std::list Agent::loadXMLDeviceFile(const std::string &configXmlPath) + std::list Agent::loadXMLDeviceFile(const std::string &configXmlPath) { NAMED_SCOPE("Agent::loadXMLDeviceFile"); @@ -634,7 +634,7 @@ namespace mtconnect { { m_schemaVersion = StrDefaultSchemaVersion(); } - + return devices; } catch (runtime_error &e) @@ -651,14 +651,14 @@ namespace mtconnect { cerr << f.what() << endl; throw f; } - + return {}; } void Agent::verifyDevice(DevicePtr device) { NAMED_SCOPE("Agent::verifyDevice"); - + auto version = IntSchemaVersion(*m_schemaVersion); // Add the devices to the device map and create availability and @@ -1200,21 +1200,21 @@ namespace mtconnect { if (type) { auto count = m_assetStorage->getCountForDeviceAndType(*device->getUuid(), *type); - + DataSet set; if (count > 0) set.emplace(*type, int64_t(count)); else set.emplace(*type, DataSetValue(), true); - + m_loopback->receive(dc, {{"VALUE", set}}); } else { auto counts = m_assetStorage->getCountsByTypeForDevice(*device->getUuid()); - + DataSet set; - + for (auto &[t, count] : counts) { if (count > 0) @@ -1222,9 +1222,8 @@ namespace mtconnect { else set.emplace(t, DataSetValue(), true); } - - m_loopback->receive(dc, {{"resetTriggered", "RESET_COUNTS"s}, - {"VALUE", set}}); + + m_loopback->receive(dc, {{"resetTriggered", "RESET_COUNTS"s}, {"VALUE", set}}); } } } diff --git a/src/agent.hpp b/src/agent.hpp index 75b9dd6b6..9367e34a5 100644 --- a/src/agent.hpp +++ b/src/agent.hpp @@ -130,7 +130,7 @@ namespace mtconnect { const auto &getSinks() const { return m_sinks; } const auto &getSchemaVersion() const { return m_schemaVersion; } - + // Get device from device map DevicePtr getDeviceByName(const std::string &name); DevicePtr getDeviceByName(const std::string &name) const; diff --git a/src/configuration/agent_config.cpp b/src/configuration/agent_config.cpp index 769ad376a..581c9ebe4 100644 --- a/src/configuration/agent_config.cpp +++ b/src/configuration/agent_config.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -30,7 +31,6 @@ #include #include #include -#include #ifdef __APPLE__ #include @@ -278,7 +278,7 @@ namespace mtconnect::configuration { LOG(warning) << "Detected change in configuration files. Will reload when youngest file is at least " << m_monitorDelay.count() << " seconds old"; - + if (devTime != *m_deviceTime) { auto t = bfs::last_write_time(m_devicesFile); @@ -303,8 +303,7 @@ namespace mtconnect::configuration { { if (cfgTime != *m_configTime) { - LOG(warning) - << "Monitor thread has detected change in configuration files."; + LOG(warning) << "Monitor thread has detected change in configuration files."; LOG(warning) << ".... Restarting agent: " << m_configFile; m_agent->stop(); @@ -720,7 +719,7 @@ namespace mtconnect::configuration { // Make the Agent m_agent = make_unique(getAsyncContext(), m_devicesFile, options); - + // Make the PipelineContext m_pipelineContext = std::make_shared(); m_pipelineContext->m_contract = m_agent->makePipelineContract(); diff --git a/src/mqtt/mqtt_client_impl.hpp b/src/mqtt/mqtt_client_impl.hpp index 77479d8c0..ca6d19cd8 100644 --- a/src/mqtt/mqtt_client_impl.hpp +++ b/src/mqtt/mqtt_client_impl.hpp @@ -51,7 +51,8 @@ namespace mtconnect { mqtt::protocol_version>; using mqtt_tls_client = mqtt_tls_client_ptr; - using mqtt_tls_client_ws = mqtt_tls_client_ws_ptr; template @@ -63,13 +64,11 @@ namespace mtconnect { : MqttClient(ioContext, move(handler)), m_options(options), m_host(GetOption(options, configuration::MqttHost).value_or("localhost")), - m_port(GetOption(options, configuration::MqttPort).value_or(1883)), + m_port(GetOption(options, configuration::MqttPort).value_or(1883)), m_reconnectTimer(ioContext) { - if (auto userName = GetOption(options, configuration::MqttUserName)) - m_username = *userName; - if (auto pswd = GetOption(options, configuration::MqttPassword)) - m_password = *pswd; + m_username = GetOption(options, configuration::MqttUserName); + m_password = GetOption(options, configuration::MqttPassword); std::stringstream url; url << "mqtt://" << m_host << ':' << m_port; @@ -78,7 +77,8 @@ namespace mtconnect { // Some brokers require specific ClientID provided. // If not specified in configuration then generate random one. auto client_id = GetOption(options, configuration::MqttClientId); - if (client_id) { + if (client_id) + { m_identity = *client_id; } else @@ -328,9 +328,9 @@ namespace mtconnect { std::uint16_t m_clientId {0}; - std::string m_username = ""; + std::optional m_username; - std::string m_password = ""; + std::optional m_password; boost::asio::steady_timer m_reconnectTimer; }; @@ -346,10 +346,10 @@ namespace mtconnect { if (!m_client) { m_client = mqtt::make_async_client(m_ioContext, m_host, m_port); - if (!m_username.empty()) - m_client->set_user_name(m_username); - if (!m_password.empty()) - m_client->set_password(m_password); + if (m_username) + m_client->set_user_name(*m_username); + if (m_password) + m_client->set_password(*m_password); } return m_client; @@ -370,10 +370,10 @@ namespace mtconnect { if (!m_client) { m_client = mqtt::make_tls_async_client(m_ioContext, m_host, m_port); - if (!m_username.empty()) - m_client->set_user_name(m_username); - if (!m_password.empty()) - m_client->set_password(m_password); + if (m_username) + m_client->set_user_name(*m_username); + if (m_password) + m_client->set_password(*m_password); auto cacert = GetOption(m_options, configuration::MqttCaCert); if (cacert) @@ -410,10 +410,10 @@ namespace mtconnect { if (!m_client) { m_client = mqtt::make_tls_async_client_ws(m_ioContext, m_host, m_port); - if (!m_username.empty()) - m_client->set_user_name(m_username); - if (!m_password.empty()) - m_client->set_password(m_password); + if (m_username) + m_client->set_user_name(*m_username); + if (m_password) + m_client->set_password(*m_password); auto cacert = GetOption(m_options, configuration::MqttCaCert); if (cacert) diff --git a/src/mqtt/mqtt_server_impl.hpp b/src/mqtt/mqtt_server_impl.hpp index 6b2dab9ac..3461cfad8 100644 --- a/src/mqtt/mqtt_server_impl.hpp +++ b/src/mqtt/mqtt_server_impl.hpp @@ -115,10 +115,10 @@ namespace mtconnect { // including close_handler and error_handler. ep.start_session(std::make_tuple(std::move(spep), std::move(g))); ep.set_connect_handler([this, wp](MQTT_NS::buffer client_id, - MQTT_NS::optional username, - MQTT_NS::optional password, - MQTT_NS::optional, - bool clean_session, std::uint16_t keep_alive) { + MQTT_NS::optional username, + MQTT_NS::optional password, + MQTT_NS::optional, bool clean_session, + std::uint16_t keep_alive) { using namespace MQTT_NS::literals; LOG(info) << "Server: Client_id : " << client_id << std::endl; LOG(info) << "Server: User Name : " << (username ? username.value() : "none"_mb) @@ -303,9 +303,9 @@ namespace mtconnect { auto serverPrivateKey = GetOption(m_options, configuration::TlsPrivateKey); auto serverCert = GetOption(m_options, configuration::TlsCertificateChain); ctx.use_certificate_chain_file(*serverCert); - //ctx.use_tmp_dh_file(*GetOption(m_options, configuration::TlsDHKey)); + // ctx.use_tmp_dh_file(*GetOption(m_options, configuration::TlsDHKey)); ctx.use_private_key_file(*serverPrivateKey, boost::asio::ssl::context::pem); - + if (HasOption(m_options, configuration::TlsCertificatePassword)) { ctx.set_password_callback( @@ -349,7 +349,7 @@ namespace mtconnect { auto serverPrivateKey = GetOption(m_options, configuration::TlsPrivateKey); auto serverCert = GetOption(m_options, configuration::TlsCertificateChain); ctx.use_certificate_chain_file(*serverCert); - //ctx.use_tmp_dh_file(*GetOption(m_options, configuration::TlsDHKey)); + // ctx.use_tmp_dh_file(*GetOption(m_options, configuration::TlsDHKey)); ctx.use_private_key_file(*serverPrivateKey, boost::asio::ssl::context::pem); /*if (IsOptionSet(m_options, configuration::TlsVerifyClientCertificate)) diff --git a/src/parser/xml_parser.cpp b/src/parser/xml_parser.cpp index 3fe52222d..773bbb5e2 100644 --- a/src/parser/xml_parser.cpp +++ b/src/parser/xml_parser.cpp @@ -137,7 +137,7 @@ namespace mtconnect::parser { { auto version = ns.substr(colon + 1); LOG(info) << "MTConnect Schema Version of file: " << filePath << " = " << version; - m_schemaVersion.emplace(version); + m_schemaVersion.emplace(version); } } diff --git a/src/parser/xml_parser.hpp b/src/parser/xml_parser.hpp index 23871c2b2..932052caa 100644 --- a/src/parser/xml_parser.hpp +++ b/src/parser/xml_parser.hpp @@ -53,7 +53,7 @@ namespace mtconnect::parser { // Get std::list of data items in path void getDataItems(FilterSet &filterSet, const std::string &path, xmlNodePtr node = nullptr); const auto &getSchemaVersion() const { return m_schemaVersion; } - + protected: // LibXML XML Doc xmlDocPtr m_doc = nullptr; diff --git a/src/printer/json_printer.cpp b/src/printer/json_printer.cpp index 3c805993d..86af54bc1 100644 --- a/src/printer/json_printer.cpp +++ b/src/printer/json_printer.cpp @@ -441,7 +441,7 @@ namespace mtconnect::printer { const asset::AssetList &asset) const { defaultSchemaVersion(); - + entity::JsonPrinter printer(m_jsonVersion); json assetDoc; if (m_jsonVersion == 1) diff --git a/src/printer/printer.hpp b/src/printer/printer.hpp index 6a9b87c5e..e658029d8 100644 --- a/src/printer/printer.hpp +++ b/src/printer/printer.hpp @@ -73,16 +73,17 @@ namespace mtconnect { void setModelChangeTime(const std::string &t) { m_modelChangeTime = t; } const std::string &getModelChangeTime() { return m_modelChangeTime; } - + void setSchemaVersion(const std::string &s) { m_schemaVersion = s; } const auto &getSchemaVersion() const { return m_schemaVersion; } - - void defaultSchemaVersion() const { + + void defaultSchemaVersion() const + { if (!m_schemaVersion) { - std::string ver = std::to_string(AGENT_VERSION_MAJOR) + "." - + std::to_string(AGENT_VERSION_MINOR); - const_cast(this)->m_schemaVersion.emplace(ver); + std::string ver = + std::to_string(AGENT_VERSION_MAJOR) + "." + std::to_string(AGENT_VERSION_MINOR); + const_cast(this)->m_schemaVersion.emplace(ver); } } diff --git a/src/printer/xml_printer.cpp b/src/printer/xml_printer.cpp index 070383f7f..5dfaf2672 100644 --- a/src/printer/xml_printer.cpp +++ b/src/printer/xml_printer.cpp @@ -100,11 +100,7 @@ namespace mtconnect::printer { xmlBufferPtr m_buf; }; - XmlPrinter::XmlPrinter(bool pretty) - : Printer(pretty) - { - NAMED_SCOPE("xml.printer"); - } + XmlPrinter::XmlPrinter(bool pretty) : Printer(pretty) { NAMED_SCOPE("xml.printer"); } void XmlPrinter::addDevicesNamespace(const std::string &urn, const std::string &location, const std::string &prefix) @@ -617,8 +613,6 @@ namespace mtconnect::printer { mtcLocation = xmlns + " " + ns.second.mSchemaLocation; } } - - // Write the schema location if (location.empty() && !mtcLocation.empty()) diff --git a/src/utilities.hpp b/src/utilities.hpp index 23d7b580d..7e0c29e83 100644 --- a/src/utilities.hpp +++ b/src/utilities.hpp @@ -576,19 +576,19 @@ namespace mtconnect { return camel; } - + #define SCHEMA_VERSION(major, minor) (major * 100 + minor) - + inline std::string StrDefaultSchemaVersion() { return std::to_string(AGENT_VERSION_MAJOR) + "." + std::to_string(AGENT_VERSION_MINOR); } - + inline constexpr int32_t IntDefaultSchemaVersion() { return SCHEMA_VERSION(AGENT_VERSION_MAJOR, AGENT_VERSION_MINOR); } - + inline int32_t IntSchemaVersion(const std::string &s) { int major, minor; @@ -596,6 +596,5 @@ namespace mtconnect { std::stringstream vstr(s); vstr >> major >> c >> minor; return SCHEMA_VERSION(major, minor); - } } // namespace mtconnect diff --git a/test/agent_test.cpp b/test/agent_test.cpp index 3dafb268d..d96807260 100644 --- a/test/agent_test.cpp +++ b/test/agent_test.cpp @@ -2497,19 +2497,18 @@ TEST_F(AgentTest, ResponseToHTTPAssetPutErrors) TEST_F(AgentTest, update_asset_count_data_item_v2_0) { - auto agent = m_agentTestHelper->createAgent("/samples/test_config.xml", 8, 10, "2.0", 4, true); + m_agentTestHelper->createAgent("/samples/test_config.xml", 8, 10, "2.0", 4, true); addAdapter(); - const auto &storage = agent->getAssetStorage(); - + m_agentTestHelper->m_adapter->processData( "2021-02-01T12:00:00Z|@ASSET@|P1|Part|TEST 1"); - + { PARSE_XML_RESPONSE("/LinuxCNC/current"); ASSERT_XML_PATH_EQUAL(doc, "//m:AssetCountDataSet/m:Entry@key", "Part"); ASSERT_XML_PATH_EQUAL(doc, "//m:AssetCountDataSet/m:Entry[@key='Part']", "1"); } - + m_agentTestHelper->m_adapter->processData( "2021-02-01T12:00:00Z|@ASSET@|P2|Part|TEST 1"); @@ -2518,7 +2517,7 @@ TEST_F(AgentTest, update_asset_count_data_item_v2_0) ASSERT_XML_PATH_EQUAL(doc, "//m:AssetCountDataSet/m:Entry@key", "Part"); ASSERT_XML_PATH_EQUAL(doc, "//m:AssetCountDataSet/m:Entry[@key='Part']", "2"); } - + m_agentTestHelper->m_adapter->processData( "2021-02-01T12:00:00Z|@ASSET@|T1|Tool|TEST 1"); @@ -2561,15 +2560,13 @@ TEST_F(AgentTest, update_asset_count_data_item_v2_0) ASSERT_XML_PATH_COUNT(doc, "//m:AssetCountDataSet/m:Entry[@key='Part']", 0); ASSERT_XML_PATH_EQUAL(doc, "//m:AssetCountDataSet/m:Entry[@key='Tool']", "3"); } - - m_agentTestHelper->m_adapter->processData("2021-02-01T12:00:00Z|@REMOVE_ALL_ASSETS@|"); + m_agentTestHelper->m_adapter->processData("2021-02-01T12:00:00Z|@REMOVE_ALL_ASSETS@|"); { PARSE_XML_RESPONSE("/LinuxCNC/current"); ASSERT_XML_PATH_COUNT(doc, "//m:AssetCountDataSet/*", 0); } - } // ---------------- Srreaming Tests --------------------- diff --git a/test/config_test.cpp b/test/config_test.cpp index 5e4cd877a..d1f888110 100644 --- a/test/config_test.cpp +++ b/test/config_test.cpp @@ -54,7 +54,7 @@ namespace { m_config = std::make_unique(); m_config->setDebug(true); m_cwd = std::filesystem::current_path(); - + chdir(TEST_BIN_ROOT_DIR); m_config->updateWorkingDirectory(); } @@ -64,35 +64,32 @@ namespace { m_config.reset(); chdir(m_cwd.string().c_str()); } - + fs::path createTempDirectory(const string &ext) { - fs::path root { fs::path(TEST_BIN_ROOT_DIR) / ("config_test_" + ext) }; + fs::path root {fs::path(TEST_BIN_ROOT_DIR) / ("config_test_" + ext)}; if (!fs::exists(root)) fs::create_directory(root); chdir(root.string().c_str()); m_config->updateWorkingDirectory(); - //m_config->setDebug(false); + // m_config->setDebug(false); return root; } - - fs::path copyFile(const std::string &src, - fs::path target, - chrono::seconds delta) + + fs::path copyFile(const std::string &src, fs::path target, chrono::seconds delta) { - fs::path file { fs::path(PROJECT_ROOT_DIR) / "samples" / src }; + fs::path file {fs::path(PROJECT_ROOT_DIR) / "samples" / src}; fs::copy_file(file, target, fs::copy_options::overwrite_existing); auto t = fs::last_write_time(target); if (delta.count() != 0) fs::last_write_time(target, t - delta); - + return target; } - - void replaceTextInFile(fs::path file, const std::string &from, - const std::string &to) + + void replaceTextInFile(fs::path file, const std::string &from, const std::string &to) { ifstream is {file.string(), ios::binary | ios::ate}; auto size = is.tellg(); @@ -954,13 +951,11 @@ logger_config { m_config->setLoggingLevel("FATAL"); EXPECT_EQ(severity_level::fatal, m_config->getLogLevel()); } - - TEST_F(ConfigTest, should_reload_device_xml_file) { - auto root { createTempDirectory("1") }; - + auto root {createTempDirectory("1")}; + fs::path devices(root / "Devices.xml"); fs::path config {root / "agent.cfg"}; { @@ -973,7 +968,7 @@ Port = 0 )DOC"; cfg << "Devices = " << devices << endl; } - + copyFile("min_config.xml", devices, 60min); boost::program_options::variables_map options; @@ -1038,7 +1033,7 @@ Port = 0 TEST_F(ConfigTest, should_reload_device_xml_and_skip_unchanged_devices) { - fs::path root { createTempDirectory("2") }; + fs::path root {createTempDirectory("2")}; fs::path devices(root / "Devices.xml"); fs::path config {root / "agent.cfg"}; @@ -1052,7 +1047,7 @@ Port = 0 )DOC"; cfg << "Devices = " << devices << endl; } - + copyFile("min_config.xml", devices, 1min); boost::program_options::variables_map options; @@ -1104,7 +1099,7 @@ Port = 0 TEST_F(ConfigTest, should_restart_agent_when_config_file_changes) { - fs::path root { createTempDirectory("3") }; + fs::path root {createTempDirectory("3")}; auto &context = m_config->getAsyncContext(); fs::path devices(root / "Devices.xml"); @@ -1119,7 +1114,7 @@ Port = 0 )DOC"; cfg << "Devices = " << devices << endl; } - + copyFile("min_config.xml", devices, 0s); boost::program_options::variables_map options; @@ -1179,7 +1174,7 @@ Port = 0 TEST_F(ConfigTest, should_reload_device_xml_and_add_new_devices) { - fs::path root { createTempDirectory("4") }; + fs::path root {createTempDirectory("4")}; fs::path devices(root / "Devices.xml"); fs::path config {root / "agent.cfg"}; @@ -1193,7 +1188,7 @@ Port = 0 )DOC"; cfg << "Devices = " << devices << endl; } - + copyFile("min_config.xml", devices, 1min); boost::program_options::variables_map options; @@ -1293,10 +1288,10 @@ Port = 0 auto device = devices.front(); ASSERT_EQ("Agent", device->getName()); } - + TEST_F(ConfigTest, should_update_schema_version_when_device_file_updates) { - auto root { createTempDirectory("5") }; + auto root {createTempDirectory("5")}; fs::path devices(root / "Devices.xml"); fs::path config {root / "agent.cfg"}; @@ -1310,7 +1305,7 @@ Port = 0 )DOC"; cfg << "Devices = " << devices << endl; } - + copyFile("min_config.xml", devices, 10min); replaceTextInFile(devices, "2.0", "1.2"); @@ -1324,7 +1319,7 @@ Port = 0 auto sink = agent->findSink("RestService"); auto rest = dynamic_pointer_cast(sink); ASSERT_TRUE(rest); - + auto instance = rest->instanceId(); sink.reset(); rest.reset(); @@ -1352,7 +1347,7 @@ Port = 0 replaceTextInFile(devices, "1.2", "1.3"); } }); - + auto th = thread([this, agent, instance, &context]() { this_thread::sleep_for(5s); @@ -1369,7 +1364,7 @@ Port = 0 EXPECT_NE(agent, agent2); EXPECT_NE(instance, rest->instanceId()); - + auto dataItem = agent2->getDataItemById("c1"); EXPECT_TRUE(dataItem); EXPECT_EQ("ROTARY_VELOCITY", dataItem->getType()); @@ -1377,10 +1372,9 @@ Port = 0 const auto &printer = agent2->getPrinter("xml"); EXPECT_NE(nullptr, printer); ASSERT_EQ("1.3", *printer->getSchemaVersion()); - } }); - + m_config->stop(); }); @@ -1388,5 +1382,4 @@ Port = 0 th.join(); } - } // namespace diff --git a/test/mqtt_isolated_test.cpp b/test/mqtt_isolated_test.cpp index d7e4eaa4f..e626c8702 100644 --- a/test/mqtt_isolated_test.cpp +++ b/test/mqtt_isolated_test.cpp @@ -76,16 +76,16 @@ class MqttIsolatedUnitTest : public testing::Test } void createServer(const ConfigOptions &options) - { + { bool withTlsOption = IsOptionSet(options, configuration::MqttTls); ConfigOptions opts(options); MergeOptions(opts, {{ServerIp, "127.0.0.1"s}, {MqttPort, 0}, {MqttTls, withTlsOption}, - {AutoAvailable, false}, + {AutoAvailable, false}, {TlsCertificateChain, ServerCertFile}, - {TlsPrivateKey, ServerKeyFile}, + {TlsPrivateKey, ServerKeyFile}, {TlsCertificatePassword, "mtconnect"s}, {RealTime, false}}); @@ -138,7 +138,7 @@ class MqttIsolatedUnitTest : public testing::Test void createClient(const ConfigOptions &options, unique_ptr &&handler) { - bool withTlsOption = IsOptionSet(options, configuration::MqttTls); + bool withTlsOption = IsOptionSet(options, configuration::MqttTls); ConfigOptions opts(options); MergeOptions(opts, {{MqttHost, "127.0.0.1"s}, @@ -147,7 +147,7 @@ class MqttIsolatedUnitTest : public testing::Test {AutoAvailable, false}, {MqttCaCert, MqttClientCACert}, {MqttCert, MqttClientCert}, - {MqttPrivateKey, MqttClientKey}, + {MqttPrivateKey, MqttClientKey}, {RealTime, false}}); if (withTlsOption) @@ -163,7 +163,7 @@ class MqttIsolatedUnitTest : public testing::Test } bool startClient() - { + { bool started = m_client && m_client->start(); if (started) { @@ -180,7 +180,6 @@ class MqttIsolatedUnitTest : public testing::Test uint16_t m_port {0}; }; - TEST_F(MqttIsolatedUnitTest, mqtt_client_should_connect_to_broker) { ConfigOptions options; @@ -216,75 +215,77 @@ TEST_F(MqttIsolatedUnitTest, mqtt_tcp_client_should_receive_loopback_publication client->set_clean_session(true); client->set_keep_alive_sec(30); - client->set_connack_handler( - [&client, &pid_sub1](bool sp, mqtt::connect_return_code connack_return_code) { - std::cout << "Connack handler called" << std::endl; - std::cout << "Session Present: " << std::boolalpha << sp << std::endl; - std::cout << "Connack Return Code: " << connack_return_code << std::endl; - if (connack_return_code == mqtt::connect_return_code::accepted) - { - pid_sub1 = client->acquire_unique_packet_id(); - - client->async_subscribe(pid_sub1, "mqtt_tcp_client_cpp/topic1", MQTT_NS::qos::at_most_once, - //[optional] checking async_subscribe completion code - [](MQTT_NS::error_code ec) { - EXPECT_FALSE(ec); - std::cout << "async_tcp_subscribe callback: " << ec.message() - << std::endl; - }); - } - return true; - }); - client->set_close_handler([] { std::cout << "closed" << std::endl; }); - - client->set_suback_handler([&client, &pid_sub1](std::uint16_t packet_id, - std::vector results) { - std::cout << "suback received. packet_id: " << packet_id << std::endl; - for (auto const &e : results) + client->set_connack_handler([&client, &pid_sub1](bool sp, + mqtt::connect_return_code connack_return_code) { + std::cout << "Connack handler called" << std::endl; + std::cout << "Session Present: " << std::boolalpha << sp << std::endl; + std::cout << "Connack Return Code: " << connack_return_code << std::endl; + if (connack_return_code == mqtt::connect_return_code::accepted) { - std::cout << "subscribe result: " << e << std::endl; + pid_sub1 = client->acquire_unique_packet_id(); + + client->async_subscribe(pid_sub1, "mqtt_tcp_client_cpp/topic1", MQTT_NS::qos::at_most_once, + //[optional] checking async_subscribe completion code + [](MQTT_NS::error_code ec) { + EXPECT_FALSE(ec); + std::cout << "async_tcp_subscribe callback: " << ec.message() + << std::endl; + }); } - - if (packet_id == pid_sub1) - { - client->async_publish("mqtt_tcp_client_cpp/topic1", "test1", MQTT_NS::qos::at_most_once, - //[optional] checking async_publish completion code - [](MQTT_NS::error_code ec) { - EXPECT_FALSE(ec); - - std::cout << "async_tcp_publish callback: " << ec.message() << std::endl; - EXPECT_EQ(ec.message(), "Success"); - }); - return true; - } - return true; }); + client->set_close_handler([] { std::cout << "closed" << std::endl; }); + + client->set_suback_handler( + [&client, &pid_sub1](std::uint16_t packet_id, std::vector results) { + std::cout << "suback received. packet_id: " << packet_id << std::endl; + for (auto const &e : results) + { + std::cout << "subscribe result: " << e << std::endl; + } + + if (packet_id == pid_sub1) + { + client->async_publish("mqtt_tcp_client_cpp/topic1", "test1", MQTT_NS::qos::at_most_once, + //[optional] checking async_publish completion code + [](MQTT_NS::error_code ec) { + EXPECT_FALSE(ec); + + std::cout << "async_tcp_publish callback: " << ec.message() + << std::endl; + EXPECT_EQ(ec.message(), "Success"); + }); + return true; + } + + return true; + }); client->set_close_handler([] { std::cout << "closed" << std::endl; }); - client->set_suback_handler([&client, &pid_sub1](std::uint16_t packet_id, - std::vector results) { - std::cout << "suback received. packet_id: " << packet_id << std::endl; - for (auto const &e : results) - { - std::cout << "subscribe result: " << e << std::endl; - } + client->set_suback_handler( + [&client, &pid_sub1](std::uint16_t packet_id, std::vector results) { + std::cout << "suback received. packet_id: " << packet_id << std::endl; + for (auto const &e : results) + { + std::cout << "subscribe result: " << e << std::endl; + } - if (packet_id == pid_sub1) - { - client->async_publish("mqtt_tcp_client_cpp/topic1", "test1", MQTT_NS::qos::at_most_once, - //[optional] checking async_publish completion code - [packet_id](MQTT_NS::error_code ec) { - EXPECT_FALSE(ec); - - std::cout << "async_tcp_publish callback: " << ec.message() << std::endl; - ASSERT_TRUE(packet_id); - }); - } + if (packet_id == pid_sub1) + { + client->async_publish("mqtt_tcp_client_cpp/topic1", "test1", MQTT_NS::qos::at_most_once, + //[optional] checking async_publish completion code + [packet_id](MQTT_NS::error_code ec) { + EXPECT_FALSE(ec); + + std::cout << "async_tcp_publish callback: " << ec.message() + << std::endl; + ASSERT_TRUE(packet_id); + }); + } - return true; - }); + return true; + }); bool received = false; client->set_publish_handler([&client, &received](mqtt::optional packet_id, @@ -340,12 +341,12 @@ TEST_F(MqttIsolatedUnitTest, should_connect_using_tls_ws) ConfigOptions options; MergeOptions(options, {{ServerIp, "127.0.0.1"s}, - {MqttPort, 0}, - {MqttTls, true}, - {AutoAvailable, false}, - {TlsCertificateChain, ServerCertFile}, - {TlsPrivateKey, ServerKeyFile}, - {RealTime, false}}); + {MqttPort, 0}, + {MqttTls, true}, + {AutoAvailable, false}, + {TlsCertificateChain, ServerCertFile}, + {TlsPrivateKey, ServerKeyFile}, + {RealTime, false}}); m_server = make_shared(m_agentTestHelper->m_ioContext, options); @@ -368,7 +369,7 @@ TEST_F(MqttIsolatedUnitTest, should_connect_using_tls_ws) m_client = make_shared(m_agentTestHelper->m_ioContext, opts, move(handler)); - + ASSERT_TRUE(startClient()); ASSERT_TRUE(m_client->isConnected()); diff --git a/test/mqtt_sink_test.cpp b/test/mqtt_sink_test.cpp index 79f61fff3..6665b27d3 100644 --- a/test/mqtt_sink_test.cpp +++ b/test/mqtt_sink_test.cpp @@ -81,7 +81,7 @@ class MqttSinkTest : public testing::Test ConfigOptions opts(options); MergeOptions(opts, {{"MqttSink", true}, - {configuration::MqttPort, m_port}, + {configuration::MqttPort, m_port}, {configuration::MqttHost, "127.0.0.1"s}}); m_agentTestHelper->createAgent("/samples/test_config.xml", 8, 4, "2.0", 25, false, true, opts); addAdapter(); @@ -96,7 +96,7 @@ class MqttSinkTest : public testing::Test MergeOptions(opts, {{ServerIp, "127.0.0.1"s}, {MqttPort, 0}, {MqttTls, false}, - {AutoAvailable, false}, + {AutoAvailable, false}, {RealTime, false}}); m_server = @@ -139,12 +139,12 @@ class MqttSinkTest : public testing::Test } void createClient(const ConfigOptions &options, unique_ptr &&handler) - { + { ConfigOptions opts(options); MergeOptions(opts, {{MqttHost, "127.0.0.1"s}, {MqttPort, m_port}, {MqttTls, false}, - {AutoAvailable, false}, + {AutoAvailable, false}, {RealTime, false}}); m_client = make_shared(m_agentTestHelper->m_ioContext, opts, move(handler)); @@ -198,8 +198,7 @@ TEST_F(MqttSinkTest, mqtt_sink_should_connect_to_broker) TEST_F(MqttSinkTest, mqtt_sink_should_connect_to_broker_with_UserNameandPassword) { - ConfigOptions options {{MqttUserName, "MQTT-SINK"s}, - {MqttPassword, "mtconnect"s}}; + ConfigOptions options {{MqttUserName, "MQTT-SINK"s}, {MqttPassword, "mtconnect"s}}; createServer(options); startServer(); @@ -276,8 +275,7 @@ TEST_F(MqttSinkTest, mqtt_sink_should_publish_Streams) auto handler = make_unique(); bool foundLineDataItem = false; handler->m_receive = [&foundLineDataItem](std::shared_ptr client, - const std::string &topic, - const std::string &payload) { + const std::string &topic, const std::string &payload) { EXPECT_EQ("MTConnect/Observation/000/Controller[Controller]/Path/Line[line]", topic); auto jdoc = json::parse(payload); @@ -286,7 +284,7 @@ TEST_F(MqttSinkTest, mqtt_sink_should_publish_Streams) { EXPECT_TRUE(true); foundLineDataItem = true; - } + } }; createClient(options, move(handler)); ASSERT_TRUE(startClient()); @@ -298,7 +296,7 @@ TEST_F(MqttSinkTest, mqtt_sink_should_publish_Streams) m_agentTestHelper->m_adapter->processData("2021-02-01T12:00:00Z|line|204"); m_client->subscribe("MTConnect/Observation/000/Controller[Controller]/Path/Line[line]"); - + waitFor(2s, [&foundLineDataItem]() { return foundLineDataItem; }); } @@ -314,8 +312,8 @@ TEST_F(MqttSinkTest, mqtt_sink_should_publish_Asset) auto handler = make_unique(); bool gotControllerDataItem = false; handler->m_receive = [&gotControllerDataItem](std::shared_ptr, - const std::string &topic, - const std::string &payload) { + const std::string &topic, + const std::string &payload) { EXPECT_EQ("MTConnect/Asset/0001", topic); auto jdoc = json::parse(payload); string id = jdoc.at("/Part/assetId"_json_pointer).get(); @@ -323,7 +321,7 @@ TEST_F(MqttSinkTest, mqtt_sink_should_publish_Asset) { EXPECT_TRUE(true); gotControllerDataItem = true; - } + } }; createClient(options, move(handler)); ASSERT_TRUE(startClient()); @@ -351,9 +349,8 @@ TEST_F(MqttSinkTest, mqtt_sink_should_publish_RotaryMode) auto handler = make_unique(); bool gotRotaryMode = false; - handler->m_receive = [&gotRotaryMode, &parser](std::shared_ptr, - const std::string &topic, - const std::string &payload) { + handler->m_receive = [&gotRotaryMode](std::shared_ptr, const std::string &topic, + const std::string &payload) { EXPECT_EQ("MTConnect/Observation/000/Axes[Axes]/Rotary[C]/Events/RotaryMode[Smode]", topic); auto jdoc = json::parse(payload); @@ -381,7 +378,7 @@ TEST_F(MqttSinkTest, mqtt_sink_should_publish_RotaryMode) } TEST_F(MqttSinkTest, mqtt_sink_should_publish_Dataset) -{ +{ ConfigOptions options; createServer(options); startServer(); @@ -389,13 +386,13 @@ TEST_F(MqttSinkTest, mqtt_sink_should_publish_Dataset) entity::JsonParser parser; auto handler = make_unique(); bool gotControllerDataItem = false; - handler->m_receive = [&gotControllerDataItem, &parser](std::shared_ptr, - const std::string &topic, - const std::string &payload) { + handler->m_receive = [&gotControllerDataItem](std::shared_ptr, + const std::string &topic, + const std::string &payload) { EXPECT_EQ("MTConnect/Observation/000/Controller[Controller]/Path/VARIABLE[vars]", topic); auto jdoc = json::parse(payload); string id = jdoc.at("/Part/a"_json_pointer).get(); - + if (id == string("1")) { EXPECT_TRUE(true); @@ -407,7 +404,6 @@ TEST_F(MqttSinkTest, mqtt_sink_should_publish_Dataset) createAgent("/samples/data_set.xml"); auto service = m_agentTestHelper->getMqttService(); ASSERT_TRUE(waitFor(1s, [&service]() { return service->isConnected(); })); - auto time = chrono::system_clock::now(); m_agentTestHelper->m_adapter->processData("TIME|vars|a=1 b=2 c=3"); m_client->subscribe("MTConnect/Observation/000/Controller[Controller]/Path/VARIABLE[vars]"); waitFor(3s, [&gotControllerDataItem]() { return gotControllerDataItem; }); @@ -422,9 +418,9 @@ TEST_F(MqttSinkTest, mqtt_sink_should_publish_Table) entity::JsonParser parser; auto handler = make_unique(); bool gotControllerDataItem = false; - handler->m_receive = [&gotControllerDataItem, &parser](std::shared_ptr, - const std::string &topic, - const std::string &payload) { + handler->m_receive = [&gotControllerDataItem](std::shared_ptr, + const std::string &topic, + const std::string &payload) { EXPECT_EQ( "MTConnect/Observation/000/Controller[Controller]/Path[path]/Events/WorkOffsetTable[wpo]", topic); @@ -440,22 +436,22 @@ TEST_F(MqttSinkTest, mqtt_sink_should_publish_Table) { for (auto &[subKey, subValue] : value.items()) { - if (key == "G53.1" && (subKey == "X" && subValue.get() == 1 || - subKey == "Y" && subValue.get() == 2 || - subKey == "Z" && subValue.get() == 3)) + if (key == "G53.1" && ((subKey == "X" && subValue.get() == 1) || + (subKey == "Y" && subValue.get() == 2) || + (subKey == "Z" && subValue.get() == 3))) { count++; } - else if (key == "G53.2" && (subKey == "X" && subValue.get() == 4 || - subKey == "Y" && subValue.get() == 5 || - subKey == "Z" && subValue.get() == 6)) + else if (key == "G53.2" && ((subKey == "X" && subValue.get() == 4) || + (subKey == "Y" && subValue.get() == 5) || + (subKey == "Z" && subValue.get() == 6))) { count++; } - else if (key == "G53.3" && (subKey == "X" && subValue.get() == 7.0 || - subKey == "Y" && subValue.get() == 8.0 || - subKey == "Z" && subValue.get() == 9.0 || - subKey == "U" && subValue.get() == 10.0)) + else if (key == "G53.3" && ((subKey == "X" && subValue.get() == 7.0) || + (subKey == "Y" && subValue.get() == 8.0) || + (subKey == "Z" && subValue.get() == 9.0) || + (subKey == "U" && subValue.get() == 10.0))) { count++; } @@ -474,7 +470,6 @@ TEST_F(MqttSinkTest, mqtt_sink_should_publish_Table) createAgent("/samples/data_set.xml"); auto service = m_agentTestHelper->getMqttService(); ASSERT_TRUE(waitFor(1s, [&service]() { return service->isConnected(); })); - auto time = chrono::system_clock::now(); m_agentTestHelper->m_adapter->processData( "2021-02-01T12:00:00Z|wpo|G53.1={X=1.0 Y=2.0 Z=3.0} G53.2={X=4.0 Y=5.0 Z=6.0}" @@ -498,9 +493,8 @@ TEST_F(MqttSinkTest, mqtt_sink_should_publish_Temperature) auto handler = make_unique(); bool gotTemperature = false; - handler->m_receive = [&gotTemperature, &parser](std::shared_ptr, - const std::string &topic, - const std::string &payload) { + handler->m_receive = [&gotTemperature](std::shared_ptr, const std::string &topic, + const std::string &payload) { EXPECT_EQ( "MTConnect/Observation/000/Axes[Axes]/Linear[Z]/Motor[motor_name]/Samples/" "Temperature[z_motor_temp]", @@ -544,9 +538,8 @@ TEST_F(MqttSinkTest, mqtt_sink_should_publish_LinearLoad) entity::JsonParser parser; auto handler = make_unique(); bool gotLinearLoad = false; - handler->m_receive = [&gotLinearLoad, &parser](std::shared_ptr, - const std::string &topic, - const std::string &payload) { + handler->m_receive = [&gotLinearLoad](std::shared_ptr, const std::string &topic, + const std::string &payload) { EXPECT_EQ("MTConnect/Observation/000/Axes[Axes]/Linear[X]/Load[Xload]", topic); auto jdoc = json::parse(payload); auto value = jdoc.at("/value"_json_pointer); @@ -581,9 +574,8 @@ TEST_F(MqttSinkTest, mqtt_sink_should_publish_DynamicCalibration) auto handler = make_unique(); bool gotCalibration = false; - handler->m_receive = [&gotCalibration, &parser](std::shared_ptr, - const std::string &topic, - const std::string &payload) { + handler->m_receive = [&gotCalibration](std::shared_ptr, const std::string &topic, + const std::string &payload) { EXPECT_EQ( "MTConnect/Observation/000/Axes[Axes]/Linear[X]/Samples/PositionTimeSeries.Actual[Xts]", topic); diff --git a/test/test_utilities.hpp b/test/test_utilities.hpp index b6dbdb298..35fb3a349 100644 --- a/test/test_utilities.hpp +++ b/test/test_utilities.hpp @@ -44,8 +44,8 @@ std::string &trim(std::string &str); void xpathTest(xmlDocPtr doc, const char *xpath, const char *expected, const std::string &file, int line); -#define PARSE_XML(expr) \ - string result = expr; \ +#define PARSE_XML(expr) \ + string result = expr; \ auto doc = xmlParseMemory(result.c_str(), static_cast(result.length())); \ ASSERT_TRUE(doc); diff --git a/test/xml_printer_test.cpp b/test/xml_printer_test.cpp index 946a53725..f87e2ad8d 100644 --- a/test/xml_printer_test.cpp +++ b/test/xml_printer_test.cpp @@ -239,8 +239,7 @@ TEST_F(XmlPrinterTest, ChangeDevicesNamespace) { // Devices m_printer->clearDevicesNamespaces(); - - + { PARSE_XML(m_printer->printProbe(123, 9999, 1024, 10, 1, m_devices)); ASSERT_XML_PATH_EQUAL(doc, "/m:MTConnectDevices@schemaLocation",