This is an automated email from the ASF dual-hosted git repository. szaszm pushed a commit to branch main in repository https://gitbox.apache.org/repos/asf/nifi-minifi-cpp.git
commit 68deb181a619fee9cd07291d12e19a0229a0f9e4 Author: Gabor Gyimesi <[email protected]> AuthorDate: Thu Oct 26 16:17:22 2023 +0200 MINIFICPP-1891 Integrate google clang-tidy checks in CI Closes #1671 Signed-off-by: Marton Szasz <[email protected]> --- .clang-tidy | 16 ++++++- .../tests/ExpressionLanguageTests.cpp | 2 +- extensions/http-curl/client/HTTPClient.cpp | 2 +- extensions/http-curl/tests/unit/AlertTests.cpp | 2 +- extensions/librdkafka/ConsumeKafka.cpp | 2 +- extensions/python/tests/PythonManifestTests.cpp | 2 +- extensions/rocksdb-repos/RocksDbRepository.cpp | 2 +- extensions/rocksdb-repos/RocksDbStream.cpp | 2 +- extensions/sftp/client/SFTPClient.cpp | 10 ++-- extensions/sftp/tests/PutSFTPTests.cpp | 5 +- .../tests/QuerySplunkIndexingStatusTests.cpp | 2 +- extensions/sql/data/JSONSQLWriter.cpp | 4 +- extensions/sql/data/SociConnectors.cpp | 8 ++-- .../standard-processors/tests/unit/PutTCPTests.cpp | 2 +- extensions/systemd/libwrapper/DlopenWrapper.cpp | 10 +--- extensions/systemd/libwrapper/DlopenWrapper.h | 10 +--- libminifi/include/core/ProcessSession.h | 4 +- libminifi/src/c2/C2Agent.cpp | 2 +- libminifi/src/core/ProcessSession.cpp | 21 ++++---- .../src/core/flow/StructuredConfiguration.cpp | 10 ++-- libminifi/src/provenance/Provenance.cpp | 23 +++++---- libminifi/src/sitetosite/RawSocketProtocol.cpp | 56 ++++++++++++---------- libminifi/src/sitetosite/SiteToSiteClient.cpp | 28 +++++------ libminifi/src/utils/Cron.cpp | 6 +-- libminifi/src/utils/TimeUtil.cpp | 2 +- libminifi/src/utils/file/FileUtils.cpp | 18 ++++--- libminifi/test/unit/CronTests.cpp | 4 +- libminifi/test/unit/ExtensionVerificationTests.cpp | 2 +- libminifi/test/unit/FileUtilsTests.cpp | 51 ++++++++++---------- libminifi/test/unit/LoggerTests.cpp | 8 ++-- libminifi/test/unit/MinifiConcurrentQueueTests.cpp | 47 ++++++++---------- libminifi/test/unit/NetUtilsTest.cpp | 6 +-- libminifi/test/unit/PropertyValidationTests.cpp | 45 +++++++++-------- libminifi/test/unit/StreamTests.cpp | 8 ++-- libminifi/test/unit/TimeUtilTests.cpp | 21 ++++---- 35 files changed, 222 insertions(+), 221 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index cef17b1ab..de57fee56 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -188,5 +188,19 @@ Checks: > cppcoreguidelines-rvalue-reference-param-not-moved, cppcoreguidelines-slicing, cppcoreguidelines-virtual-class-destructor, - cppcoreguidelines-macro-usage + cppcoreguidelines-macro-usage, + google-build-explicit-make-pair, + google-build-namespaces, + google-build-using-namespace, + google-explicit-constructor, + google-global-names-in-headers, + google-objc-avoid-nsobject-new, + google-objc-avoid-throwing-exception, + google-objc-function-naming, + google-objc-global-variable-declaration, + google-readability-avoid-underscore-in-googletest-name, + google-readability-todo, + google-runtime-int, + google-runtime-operator, + google-upgrade-googletest-case FormatStyle: 'file' diff --git a/extensions/expression-language/tests/ExpressionLanguageTests.cpp b/extensions/expression-language/tests/ExpressionLanguageTests.cpp index d17f728db..8992a647d 100644 --- a/extensions/expression-language/tests/ExpressionLanguageTests.cpp +++ b/extensions/expression-language/tests/ExpressionLanguageTests.cpp @@ -1321,7 +1321,7 @@ TEST_CASE("Now Date", "[expressionNowDate]") { TEST_CASE("Parse RFC3339 with Expression Language toDate") { using date::sys_days; using org::apache::nifi::minifi::utils::timeutils::parseRfc3339; - using namespace date::literals; + using namespace date::literals; // NOLINT(google-build-using-namespace) using namespace std::literals::chrono_literals; using std::chrono::milliseconds; diff --git a/extensions/http-curl/client/HTTPClient.cpp b/extensions/http-curl/client/HTTPClient.cpp index d62c30765..b9933ea09 100644 --- a/extensions/http-curl/client/HTTPClient.cpp +++ b/extensions/http-curl/client/HTTPClient.cpp @@ -389,7 +389,7 @@ bool HTTPClient::submit() { if (read_callback_ == nullptr) { content_.close(); } - long http_code = 0; // NOLINT(runtime/int) long due to libcurl API + long http_code = 0; // NOLINT(runtime/int,google-runtime-int) long due to libcurl API curl_easy_getinfo(http_session_.get(), CURLINFO_RESPONSE_CODE, &http_code); response_data_.response_code = http_code; curl_easy_getinfo(http_session_.get(), CURLINFO_CONTENT_TYPE, &response_data_.response_content_type); diff --git a/extensions/http-curl/tests/unit/AlertTests.cpp b/extensions/http-curl/tests/unit/AlertTests.cpp index 20774156b..5a573fedf 100644 --- a/extensions/http-curl/tests/unit/AlertTests.cpp +++ b/extensions/http-curl/tests/unit/AlertTests.cpp @@ -73,7 +73,7 @@ TEST_CASE("Alert system forwards logs") { utils::timeutils::setClock(clock); TempDirectory dir; - auto flow_config_file = std::filesystem::path(dir.getPath()) / "config.yml"; + auto flow_config_file = dir.getPath() / "config.yml"; std::ofstream(flow_config_file) << empty_flow; std::string agent_id = "test-agent-1"; diff --git a/extensions/librdkafka/ConsumeKafka.cpp b/extensions/librdkafka/ConsumeKafka.cpp index 785b8bf7c..3b84869b5 100644 --- a/extensions/librdkafka/ConsumeKafka.cpp +++ b/extensions/librdkafka/ConsumeKafka.cpp @@ -293,7 +293,7 @@ std::vector<std::string> ConsumeKafka::get_matching_headers(const rd_kafka_messa for (std::size_t header_idx = 0;; ++header_idx) { const char* value = nullptr; // Not to be freed std::size_t size = 0; - if (RD_KAFKA_RESP_ERR_NO_ERROR != rd_kafka_header_get(headers_raw, header_idx, header_name.c_str(), (const void**)(&value), &size)) { + if (RD_KAFKA_RESP_ERR_NO_ERROR != rd_kafka_header_get(headers_raw, header_idx, header_name.c_str(), reinterpret_cast<const void**>(&value), &size)) { break; } if (size < 200) { diff --git a/extensions/python/tests/PythonManifestTests.cpp b/extensions/python/tests/PythonManifestTests.cpp index 5ec989ae9..e6e2185eb 100644 --- a/extensions/python/tests/PythonManifestTests.cpp +++ b/extensions/python/tests/PythonManifestTests.cpp @@ -47,7 +47,7 @@ const SerializedResponseNode& getNode(const std::vector<SerializedResponseNode>& TEST_CASE("Python processor's description is part of the manifest") { TestControllerWithFlow controller(empty_flow, false /* DEFER FLOW SETUP */); - auto python_dir = std::filesystem::path(controller.configuration_->getHome()) / "minifi-python"; + auto python_dir = controller.configuration_->getHome() / "minifi-python"; utils::file::create_dir(python_dir); std::ofstream{python_dir / "MyPyProc.py"} << "def describe(proc):\n" diff --git a/extensions/rocksdb-repos/RocksDbRepository.cpp b/extensions/rocksdb-repos/RocksDbRepository.cpp index 409388327..5f44050f1 100644 --- a/extensions/rocksdb-repos/RocksDbRepository.cpp +++ b/extensions/rocksdb-repos/RocksDbRepository.cpp @@ -51,7 +51,7 @@ bool RocksDbRepository::Put(const std::string& key, const uint8_t *buf, size_t b if (!opendb) { return false; } - rocksdb::Slice value((const char *) buf, bufLen); + rocksdb::Slice value(reinterpret_cast<const char *>(buf), bufLen); auto operation = [&key, &value, &opendb]() { return opendb->Put(rocksdb::WriteOptions(), key, value); }; return ExecuteWithRetry(operation); } diff --git a/extensions/rocksdb-repos/RocksDbStream.cpp b/extensions/rocksdb-repos/RocksDbStream.cpp index a0bbcde41..2dfaa0e4f 100644 --- a/extensions/rocksdb-repos/RocksDbStream.cpp +++ b/extensions/rocksdb-repos/RocksDbStream.cpp @@ -60,7 +60,7 @@ size_t RocksDbStream::write(const uint8_t *value, size_t size) { if (!opendb) { return STREAM_ERROR; } - rocksdb::Slice slice_value((const char*)value, size); + rocksdb::Slice slice_value(reinterpret_cast<const char*>(value), size); rocksdb::Status status; size_ += size; if (batch_ != nullptr) { diff --git a/extensions/sftp/client/SFTPClient.cpp b/extensions/sftp/client/SFTPClient.cpp index badea3ae9..d9ee21069 100644 --- a/extensions/sftp/client/SFTPClient.cpp +++ b/extensions/sftp/client/SFTPClient.cpp @@ -32,7 +32,7 @@ namespace org::apache::nifi::minifi::utils { -static const char* sftp_strerror(unsigned long err) { // NOLINT(runtime/int) unsigned long comes from libssh2 API +static const char* sftp_strerror(unsigned long err) { // NOLINT(runtime/int,google-runtime-int) unsigned long comes from libssh2 API switch (err) { case LIBSSH2_FX_OK: return "LIBSSH2_FX_OK"; @@ -83,7 +83,7 @@ static const char* sftp_strerror(unsigned long err) { // NOLINT(runtime/int) un } } -static SFTPError libssh2_sftp_error_to_sftp_error(unsigned long libssh2_sftp_error) { // NOLINT(runtime/int) unsigned long comes from libssh2 API +static SFTPError libssh2_sftp_error_to_sftp_error(unsigned long libssh2_sftp_error) { // NOLINT(runtime/int,google-runtime-int) unsigned long comes from libssh2 API switch (libssh2_sftp_error) { case LIBSSH2_FX_OK: return SFTPError::Ok; @@ -123,7 +123,7 @@ LastSFTPError::LastSFTPError() , sftp_error_(SFTPError::Ok) { } -LastSFTPError& LastSFTPError::setLibssh2Error(unsigned long libssh2_sftp_error) { // NOLINT(runtime/int) unsigned long comes from libssh2 API +LastSFTPError& LastSFTPError::setLibssh2Error(unsigned long libssh2_sftp_error) { // NOLINT(runtime/int,google-runtime-int) unsigned long comes from libssh2 API sftp_error_set_ = false; libssh2_sftp_error_ = libssh2_sftp_error; return *this; @@ -135,7 +135,7 @@ LastSFTPError& LastSFTPError::setSftpError(const SFTPError& sftp_error) { return *this; } -LastSFTPError::operator unsigned long() const { // NOLINT(runtime/int) unsigned long comes from libssh2 API +LastSFTPError::operator unsigned long() const { // NOLINT(runtime/int,google-runtime-int) unsigned long comes from libssh2 API if (sftp_error_set_) { return LIBSSH2_FX_OK; } else { @@ -300,7 +300,7 @@ bool SFTPClient::connect() { #ifdef WIN32 curl_socket_t sockfd; #else - long sockfd = 0; // NOLINT(runtime/int) long due to libcurl API + long sockfd = 0; // NOLINT(runtime/int,google-runtime-int) long due to libcurl API #endif curl_res = curl_easy_getinfo(easy_, CURLINFO_ACTIVESOCKET, &sockfd); if (curl_res != CURLE_OK) { diff --git a/extensions/sftp/tests/PutSFTPTests.cpp b/extensions/sftp/tests/PutSFTPTests.cpp index 3cf38f437..e7904873f 100644 --- a/extensions/sftp/tests/PutSFTPTests.cpp +++ b/extensions/sftp/tests/PutSFTPTests.cpp @@ -201,7 +201,7 @@ class PutSFTPTestsFixture { namespace { std::size_t directoryContentCount(const std::filesystem::path& dir) { - return (std::size_t)std::distance(std::filesystem::directory_iterator{dir}, std::filesystem::directory_iterator{}); + return gsl::narrow<std::size_t>(std::distance(std::filesystem::directory_iterator{dir}, std::filesystem::directory_iterator{})); } } // namespace @@ -501,8 +501,7 @@ TEST_CASE_METHOD(PutSFTPTestsFixture, "PutSFTP set mtime", "[PutSFTP]") { testController.runSession(plan, true); testFile("nifi_test/tstFile1.ext", "content 1"); - using namespace std::chrono; // NOLINT(build/namespaces) - system_clock::time_point modification_time = date::sys_days(date::January / 24 / 2065) + 5h + 20min; + std::chrono::system_clock::time_point modification_time = date::sys_days(date::January / 24 / 2065) + 5h + 20min; testModificationTime("nifi_test/tstFile1.ext", utils::file::from_sys(modification_time)); } diff --git a/extensions/splunk/tests/QuerySplunkIndexingStatusTests.cpp b/extensions/splunk/tests/QuerySplunkIndexingStatusTests.cpp index 49a025b97..29716ad9e 100644 --- a/extensions/splunk/tests/QuerySplunkIndexingStatusTests.cpp +++ b/extensions/splunk/tests/QuerySplunkIndexingStatusTests.cpp @@ -87,7 +87,7 @@ TEST_CASE("QuerySplunkIndexingStatus tests", "[querysplunkindexingstatus]") { write_to_flow_file->setContent(""); plan->reset(); - std::this_thread::sleep_for(std::chrono::milliseconds(100ms)); + std::this_thread::sleep_for(100ms); test_controller.runSession(plan); CHECK(read_from_failure->numberOfFlowFilesRead() == 0); diff --git a/extensions/sql/data/JSONSQLWriter.cpp b/extensions/sql/data/JSONSQLWriter.cpp index d77ff2741..2a2df6912 100644 --- a/extensions/sql/data/JSONSQLWriter.cpp +++ b/extensions/sql/data/JSONSQLWriter.cpp @@ -58,11 +58,11 @@ void JSONSQLWriter::processColumn(const std::string& name, int value) { addToJSONRow(name, rapidjson::Value(value)); } -void JSONSQLWriter::processColumn(const std::string& name, long long value) { +void JSONSQLWriter::processColumn(const std::string& name, long long value) { // NOLINT(google-runtime-int) addToJSONRow(name, rapidjson::Value(gsl::narrow<int64_t>(value))); } -void JSONSQLWriter::processColumn(const std::string& name, unsigned long long value) { +void JSONSQLWriter::processColumn(const std::string& name, unsigned long long value) { // NOLINT(google-runtime-int) addToJSONRow(name, rapidjson::Value(gsl::narrow<uint64_t>(value))); } diff --git a/extensions/sql/data/SociConnectors.cpp b/extensions/sql/data/SociConnectors.cpp index 7b6c371e4..9bdc626e8 100644 --- a/extensions/sql/data/SociConnectors.cpp +++ b/extensions/sql/data/SociConnectors.cpp @@ -83,12 +83,12 @@ int SociRow::getInteger(std::size_t index) const { return current_->get<int>(index); } -long long SociRow::getLongLong(std::size_t index) const { - return current_->get<long long>(index); +long long SociRow::getLongLong(std::size_t index) const { // NOLINT(google-runtime-int) + return current_->get<long long>(index); // NOLINT(google-runtime-int) } -unsigned long long SociRow::getUnsignedLongLong(std::size_t index) const { - return current_->get<unsigned long long>(index); +unsigned long long SociRow::getUnsignedLongLong(std::size_t index) const { // NOLINT(google-runtime-int) + return current_->get<unsigned long long>(index); // NOLINT(google-runtime-int) } std::tm SociRow::getDate(std::size_t index) const { diff --git a/extensions/standard-processors/tests/unit/PutTCPTests.cpp b/extensions/standard-processors/tests/unit/PutTCPTests.cpp index 9a38a146a..9956527bc 100644 --- a/extensions/standard-processors/tests/unit/PutTCPTests.cpp +++ b/extensions/standard-processors/tests/unit/PutTCPTests.cpp @@ -166,7 +166,7 @@ class PutTCPTestFixture { } void addSSLContextToPutTCP(const std::filesystem::path& ca_cert, const std::optional<std::filesystem::path>& client_cert, const std::optional<std::filesystem::path>& client_cert_key) { - const std::filesystem::path ca_dir = std::filesystem::path(minifi::utils::file::FileUtils::get_executable_dir()) / "resources"; + const std::filesystem::path ca_dir = minifi::utils::file::FileUtils::get_executable_dir() / "resources"; auto ssl_context_service_node = controller_.plan->addController("SSLContextService", "SSLContextService"); REQUIRE(controller_.plan->setProperty(ssl_context_service_node, SSLContextService::CACertificate, (ca_dir / ca_cert).string())); if (client_cert) { diff --git a/extensions/systemd/libwrapper/DlopenWrapper.cpp b/extensions/systemd/libwrapper/DlopenWrapper.cpp index 355370f64..b4e6e90e4 100644 --- a/extensions/systemd/libwrapper/DlopenWrapper.cpp +++ b/extensions/systemd/libwrapper/DlopenWrapper.cpp @@ -24,7 +24,7 @@ struct sd_journal; -namespace org { namespace apache { namespace nifi { namespace minifi { namespace extensions { namespace systemd { namespace libwrapper { +namespace org::apache::nifi::minifi::extensions::systemd::libwrapper { namespace { struct dlclose_deleter { @@ -101,10 +101,4 @@ std::unique_ptr<Journal> DlopenWrapper::openJournal(const JournalType type) { return std::make_unique<DlopenJournal>(type); } -} // namespace libwrapper -} // namespace systemd -} // namespace extensions -} // namespace minifi -} // namespace nifi -} // namespace apache -} // namespace org +} // namespace org::apache::nifi::minifi::extensions::systemd::libwrapper diff --git a/extensions/systemd/libwrapper/DlopenWrapper.h b/extensions/systemd/libwrapper/DlopenWrapper.h index 88ae6901a..82267eab6 100644 --- a/extensions/systemd/libwrapper/DlopenWrapper.h +++ b/extensions/systemd/libwrapper/DlopenWrapper.h @@ -19,16 +19,10 @@ #include "LibWrapper.h" #include <memory> -namespace org { namespace apache { namespace nifi { namespace minifi { namespace extensions { namespace systemd { namespace libwrapper { +namespace org::apache::nifi::minifi::extensions::systemd::libwrapper { struct DlopenWrapper : LibWrapper { std::unique_ptr<Journal> openJournal(JournalType) override; }; -} // namespace libwrapper -} // namespace systemd -} // namespace extensions -} // namespace minifi -} // namespace nifi -} // namespace apache -} // namespace org +} // namespace org::apache::nifi::minifi::extensions::systemd::libwrapper diff --git a/libminifi/include/core/ProcessSession.h b/libminifi/include/core/ProcessSession.h index 86fe5cf9e..85a25ad76 100644 --- a/libminifi/include/core/ProcessSession.h +++ b/libminifi/include/core/ProcessSession.h @@ -124,8 +124,8 @@ class ProcessSession : public ReferenceContainer { void importFrom(io::InputStream&& stream, const std::shared_ptr<core::FlowFile> &flow); // import from the data source. - void import(std::string source, const std::shared_ptr<core::FlowFile> &flow, bool keepSource = true, uint64_t offset = 0); - DEPRECATED(/*deprecated in*/ 0.7.0, /*will remove in */ 2.0) void import(std::string source, std::vector<std::shared_ptr<FlowFile>> &flows, bool keepSource, uint64_t offset, char inputDelimiter); // NOLINT + void import(const std::string& source, const std::shared_ptr<core::FlowFile> &flow, bool keepSource = true, uint64_t offset = 0); + DEPRECATED(/*deprecated in*/ 0.7.0, /*will remove in */ 2.0) void import(const std::string& source, std::vector<std::shared_ptr<FlowFile>> &flows, bool keepSource, uint64_t offset, char inputDelimiter); // NOLINT DEPRECATED(/*deprecated in*/ 0.8.0, /*will remove in */ 2.0) void import(const std::string& source, std::vector<std::shared_ptr<FlowFile>> &flows, uint64_t offset, char inputDelimiter); /** diff --git a/libminifi/src/c2/C2Agent.cpp b/libminifi/src/c2/C2Agent.cpp index 3bd7bc0e5..bfb12cf09 100644 --- a/libminifi/src/c2/C2Agent.cpp +++ b/libminifi/src/c2/C2Agent.cpp @@ -941,7 +941,7 @@ void C2Agent::handleAssetUpdate(const C2ContentResponse& resp) { response.setRawData(as_bytes(std::span(error.begin(), error.end()))); enqueue_c2_response(std::move(response)); }; - std::filesystem::path asset_dir = std::filesystem::path(configuration_->getHome()) / "asset"; + std::filesystem::path asset_dir = configuration_->getHome() / "asset"; if (auto asset_dir_str = configuration_->get(Configuration::nifi_asset_directory)) { asset_dir = asset_dir_str.value(); } diff --git a/libminifi/src/core/ProcessSession.cpp b/libminifi/src/core/ProcessSession.cpp index a2e733c35..4b7507234 100644 --- a/libminifi/src/core/ProcessSession.cpp +++ b/libminifi/src/core/ProcessSession.cpp @@ -175,7 +175,7 @@ std::shared_ptr<core::FlowFile> ProcessSession::cloneDuringTransfer(const std::s } std::shared_ptr<core::FlowFile> ProcessSession::clone(const std::shared_ptr<core::FlowFile> &parent, int64_t offset, int64_t size) { - if ((uint64_t) (offset + size) > parent->getSize()) { + if (gsl::narrow<uint64_t>(offset + size) > parent->getSize()) { // Set offset and size logger_->log_error("clone offset {} and size {} exceed parent size {}", offset, size, parent->getSize()); return nullptr; @@ -484,7 +484,7 @@ void ProcessSession::importFrom(io::InputStream &stream, const std::shared_ptr<c } } -void ProcessSession::import(std::string source, const std::shared_ptr<FlowFile> &flow, bool keepSource, uint64_t offset) { +void ProcessSession::import(const std::string& source, const std::shared_ptr<FlowFile> &flow, bool keepSource, uint64_t offset) { std::shared_ptr<ResourceClaim> claim = content_session_->create(); size_t size = getpagesize(); std::vector<uint8_t> charBuffer(size); @@ -502,14 +502,14 @@ void ProcessSession::import(std::string source, const std::shared_ptr<FlowFile> bool invalidWrite = false; // Open the source file and stream to the flow file if (offset != 0) { - input.seekg(offset); + input.seekg(gsl::narrow<std::streamoff>(offset)); if (!input.good()) { logger_->log_error("Seeking to {} failed for file {} (does file/filesystem support seeking?)", offset, source); invalidWrite = true; } } while (input.good()) { - input.read(reinterpret_cast<char*>(charBuffer.data()), size); + input.read(reinterpret_cast<char*>(charBuffer.data()), gsl::narrow<std::streamsize>(size)); if (input) { if (io::isError(stream->write(charBuffer.data(), size))) { invalidWrite = true; @@ -533,8 +533,9 @@ void ProcessSession::import(std::string source, const std::shared_ptr<FlowFile> stream->close(); input.close(); - if (!keepSource) - std::remove(source.c_str()); + if (!keepSource) { + (void)std::remove(source.c_str()); + } std::stringstream details; details << process_context_->getProcessorNode()->getName() << " modify flow record content " << flow->getUUIDStr(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_time); @@ -569,14 +570,14 @@ void ProcessSession::import(const std::string& source, std::vector<std::shared_p throw Exception(FILE_OPERATION_EXCEPTION, utils::StringUtils::join_pack("File Import Error: failed to open file \'", source, "\'")); } if (offset != 0U) { - input.seekg(offset, std::ifstream::beg); + input.seekg(gsl::narrow<std::streamoff>(offset), std::ifstream::beg); if (!input.good()) { logger_->log_error("Seeking to {} failed for file {} (does file/filesystem support seeking?)", offset, source); throw Exception(FILE_OPERATION_EXCEPTION, utils::StringUtils::join_pack("File Import Error: Couldn't seek to offset ", std::to_string(offset))); } } while (input.good()) { - input.read(reinterpret_cast<char*>(buffer.data()), buffer.size()); + input.read(reinterpret_cast<char*>(buffer.data()), gsl::narrow<std::streamsize>(buffer.size())); std::streamsize read = input.gcount(); if (read < 0) { throw Exception(FILE_OPERATION_EXCEPTION, "std::ifstream::gcount returned negative value"); @@ -656,7 +657,7 @@ void ProcessSession::import(const std::string& source, std::vector<std::shared_p } } -void ProcessSession::import(std::string source, std::vector<std::shared_ptr<FlowFile>> &flows, bool keepSource, uint64_t offset, char inputDelimiter) { +void ProcessSession::import(const std::string& source, std::vector<std::shared_ptr<FlowFile>> &flows, bool keepSource, uint64_t offset, char inputDelimiter) { // this function calls a deprecated function, but it is itself deprecated, so suppress warnings #if defined(__clang__) #pragma clang diagnostic push @@ -678,7 +679,7 @@ void ProcessSession::import(std::string source, std::vector<std::shared_ptr<Flow #endif logger_->log_trace("Closed input {}, keeping source ? {}", source, keepSource); if (!keepSource) { - std::remove(source.c_str()); + (void)std::remove(source.c_str()); } } diff --git a/libminifi/src/core/flow/StructuredConfiguration.cpp b/libminifi/src/core/flow/StructuredConfiguration.cpp index 5435e4143..1234b634d 100644 --- a/libminifi/src/core/flow/StructuredConfiguration.cpp +++ b/libminifi/src/core/flow/StructuredConfiguration.cpp @@ -266,10 +266,10 @@ void StructuredConfiguration::parseProcessorNode(const Node& processors_node, co logger_->log_debug("setting scheduling strategy as {}", procCfg.schedulingStrategy); } - int32_t maxConcurrentTasks; + uint8_t maxConcurrentTasks = 0; if (core::Property::StringToInt(procCfg.maxConcurrentTasks, maxConcurrentTasks)) { logger_->log_debug("parseProcessorNode: maxConcurrentTasks => [{}]", maxConcurrentTasks); - processor->setMaxConcurrentTasks((uint8_t) maxConcurrentTasks); + processor->setMaxConcurrentTasks(maxConcurrentTasks); } if (core::Property::StringToInt(procCfg.runDurationNanos, runDurationNanos)) { @@ -366,7 +366,7 @@ void StructuredConfiguration::parseRemoteProcessGroup(const Node& rpg_node_seq, } if (currRpgNode[schema_.rpg_proxy_port]) { auto http_proxy_port = currRpgNode[schema_.rpg_proxy_port].getIntegerAsString().value(); - int32_t port; + int32_t port = 0; if (core::Property::StringToInt(http_proxy_port, port)) { logger_->log_debug("parseRemoteProcessGroup: proxy port => [{}]", port); group->setHttpProxyPort(port); @@ -436,7 +436,7 @@ void StructuredConfiguration::parseProvenanceReporting(const Node& node, core::P throw std::invalid_argument("Invalid scheduling strategy " + schedulingStrategyStr); } - int64_t lvalue; + int64_t lvalue = 0; if (node["host"] && node["port"]) { auto hostStr = node["host"].getString().value(); @@ -610,7 +610,7 @@ void StructuredConfiguration::parseRPGPort(const Node& port_node, core::ProcessG if (auto tasksNode = port_node[schema_.max_concurrent_tasks]) { std::string rawMaxConcurrentTasks = tasksNode.getIntegerAsString().value(); - int32_t maxConcurrentTasks; + int32_t maxConcurrentTasks = 0; if (core::Property::StringToInt(rawMaxConcurrentTasks, maxConcurrentTasks)) { processor.setMaxConcurrentTasks(maxConcurrentTasks); } diff --git a/libminifi/src/provenance/Provenance.cpp b/libminifi/src/provenance/Provenance.cpp index 163a1ee69..aaa98c704 100644 --- a/libminifi/src/provenance/Provenance.cpp +++ b/libminifi/src/provenance/Provenance.cpp @@ -37,8 +37,8 @@ namespace org::apache::nifi::minifi::provenance { std::shared_ptr<utils::IdGenerator> ProvenanceEventRecord::id_generator_ = utils::IdGenerator::getIdGenerator(); std::shared_ptr<core::logging::Logger> ProvenanceEventRecord::logger_ = core::logging::LoggerFactory<ProvenanceEventRecord>::getLogger(); -const char *ProvenanceEventRecord::ProvenanceEventTypeStr[REPLAY + 1] = { "CREATE", "RECEIVE", "FETCH", "SEND", "DOWNLOAD", "DROP", "EXPIRE", "FORK", "JOIN", "CLONE", "CONTENT_MODIFIED", - "ATTRIBUTES_MODIFIED", "ROUTE", "ADDINFO", "REPLAY" }; +const char *ProvenanceEventRecord::ProvenanceEventTypeStr[REPLAY + 1] = { "CREATE", "RECEIVE", "FETCH", "SEND", "DOWNLOAD", // NOLINT(cppcoreguidelines-avoid-c-arrays) + "DROP", "EXPIRE", "FORK", "JOIN", "CLONE", "CONTENT_MODIFIED", "ATTRIBUTES_MODIFIED", "ROUTE", "ADDINFO", "REPLAY" }; ProvenanceEventRecord::ProvenanceEventRecord(ProvenanceEventRecord::ProvenanceEventType event, std::string componentId, std::string componentType) : core::SerializableComponent(core::className<ProvenanceEventRecord>()), @@ -50,7 +50,7 @@ ProvenanceEventRecord::ProvenanceEventRecord(ProvenanceEventRecord::ProvenanceEv bool ProvenanceEventRecord::loadFromRepository(const std::shared_ptr<core::Repository> &repo) { std::string value; - bool ret; + bool ret = false; if (nullptr == repo || uuid_.isNil()) { logger_->log_error("Repo could not be assigned"); @@ -249,7 +249,7 @@ bool ProvenanceEventRecord::deserialize(io::InputStream &input_stream) { } } - uint32_t eventType; + uint32_t eventType = 0; { const auto ret = input_stream.read(eventType); if (ret != 4) { @@ -257,9 +257,14 @@ bool ProvenanceEventRecord::deserialize(io::InputStream &input_stream) { } } - this->_eventType = (ProvenanceEventRecord::ProvenanceEventType) eventType; + if (auto event_type_opt = magic_enum::enum_cast<ProvenanceEventRecord::ProvenanceEventType>(eventType)) { + _eventType = *event_type_opt; + } else { + return false; + } + { - uint64_t event_time_in_ms; + uint64_t event_time_in_ms = 0; const auto ret = input_stream.read(event_time_in_ms); if (ret != 8) { return false; @@ -268,7 +273,7 @@ bool ProvenanceEventRecord::deserialize(io::InputStream &input_stream) { } { - uint64_t entry_date_in_ms; + uint64_t entry_date_in_ms = 0; const auto ret = input_stream.read(entry_date_in_ms); if (ret != 8) { return false; @@ -277,7 +282,7 @@ bool ProvenanceEventRecord::deserialize(io::InputStream &input_stream) { } { - uint64_t event_duration_ms; + uint64_t event_duration_ms = 0; const auto ret = input_stream.read(event_duration_ms); if (ret != 8) { return false; @@ -286,7 +291,7 @@ bool ProvenanceEventRecord::deserialize(io::InputStream &input_stream) { } { - uint64_t lineage_start_date_in_ms; + uint64_t lineage_start_date_in_ms = 0; const auto ret = input_stream.read(lineage_start_date_in_ms); if (ret != 8) { return false; diff --git a/libminifi/src/sitetosite/RawSocketProtocol.cpp b/libminifi/src/sitetosite/RawSocketProtocol.cpp index 3e8ec0bb8..307a9092c 100644 --- a/libminifi/src/sitetosite/RawSocketProtocol.cpp +++ b/libminifi/src/sitetosite/RawSocketProtocol.cpp @@ -36,7 +36,7 @@ namespace org::apache::nifi::minifi::sitetosite { std::shared_ptr<utils::IdGenerator> RawSiteToSiteClient::id_generator_ = utils::IdGenerator::getIdGenerator(); std::shared_ptr<utils::IdGenerator> Transaction::id_generator_ = utils::IdGenerator::getIdGenerator(); -const char *RawSiteToSiteClient::HandShakePropertyStr[MAX_HANDSHAKE_PROPERTY] = { +const char *RawSiteToSiteClient::HandShakePropertyStr[MAX_HANDSHAKE_PROPERTY] = { // NOLINT(cppcoreguidelines-avoid-c-arrays) /** * Boolean value indicating whether or not the contents of a FlowFile should * be GZipped when transferred. @@ -126,7 +126,7 @@ bool RawSiteToSiteClient::initiateResourceNegotiation() { } } - uint8_t statusCode; + uint8_t statusCode = 0; { const auto ret = peer_->read(statusCode); if (ret == 0 || io::isError(ret)) { @@ -136,11 +136,12 @@ bool RawSiteToSiteClient::initiateResourceNegotiation() { } logger_->log_debug("status code is {}", statusCode); switch (statusCode) { - case RESOURCE_OK: + case RESOURCE_OK: { logger_->log_debug("Site2Site Protocol Negotiate protocol version OK"); return true; - case DIFFERENT_RESOURCE_VERSION: - uint32_t serverVersion; + } + case DIFFERENT_RESOURCE_VERSION: { + uint32_t serverVersion = 0; { const auto ret = peer_->read(serverVersion); if (ret == 0 || io::isError(ret)) { @@ -153,18 +154,21 @@ bool RawSiteToSiteClient::initiateResourceNegotiation() { for (unsigned int i = (_currentVersionIndex + 1); i < sizeof(_supportedVersion) / sizeof(uint32_t); i++) { if (serverVersion >= _supportedVersion[i]) { _currentVersion = _supportedVersion[i]; - _currentVersionIndex = i; + _currentVersionIndex = gsl::narrow<int>(i); return initiateResourceNegotiation(); } } logger_->log_error("Site2Site Negotiate protocol failed to find a common version with server"); return false; - case NEGOTIATED_ABORT: + } + case NEGOTIATED_ABORT: { logger_->log_error("Site2Site Negotiate protocol response ABORT"); return false; - default: + } + default: { logger_->log_error("Negotiate protocol response unknown code {}", statusCode); return false; + } } } @@ -193,7 +197,7 @@ bool RawSiteToSiteClient::initiateCodecResourceNegotiation() { } } - uint8_t statusCode; + uint8_t statusCode = 0; { const auto ret = peer_->read(statusCode); if (ret == 0 || io::isError(ret)) { @@ -201,11 +205,12 @@ bool RawSiteToSiteClient::initiateCodecResourceNegotiation() { } } switch (statusCode) { - case RESOURCE_OK: + case RESOURCE_OK: { logger_->log_trace("Site2Site Codec Negotiate version OK"); return true; - case DIFFERENT_RESOURCE_VERSION: - uint32_t serverVersion; + } + case DIFFERENT_RESOURCE_VERSION: { + uint32_t serverVersion = 0; { const auto ret = peer_->read(serverVersion); if (ret == 0 || io::isError(ret)) { @@ -217,18 +222,21 @@ bool RawSiteToSiteClient::initiateCodecResourceNegotiation() { for (unsigned int i = (_currentCodecVersionIndex + 1); i < sizeof(_supportedCodecVersion) / sizeof(uint32_t); i++) { if (serverVersion >= _supportedCodecVersion[i]) { _currentCodecVersion = _supportedCodecVersion[i]; - _currentCodecVersionIndex = i; + _currentCodecVersionIndex = gsl::narrow<int>(i); return initiateCodecResourceNegotiation(); } } logger_->log_error("Site2Site Negotiate codec failed to find a common version with server"); return false; - case NEGOTIATED_ABORT: + } + case NEGOTIATED_ABORT: { logger_->log_error("Site2Site Codec Negotiate response ABORT"); return false; - default: + } + default: { logger_->log_error("Negotiate Codec response unknown code {}", statusCode); return false; + } } } @@ -292,7 +300,7 @@ bool RawSiteToSiteClient::handShake() { logger_->log_debug("Site2Site Protocol Send handshake properties {} {}", it->first, it->second); } - RespondCode code; + RespondCode code = RESERVED; std::string message; { @@ -348,7 +356,7 @@ bool RawSiteToSiteClient::getPeerList(std::vector<PeerStatus> &peers) { return false; } - uint32_t number_of_peers; + uint32_t number_of_peers = 0; { const auto ret = peer_->read(number_of_peers); if (ret == 0 || io::isError(ret)) { @@ -366,7 +374,7 @@ bool RawSiteToSiteClient::getPeerList(std::vector<PeerStatus> &peers) { return false; } } - uint32_t port; + uint32_t port = 0; { const auto ret = peer_->read(port); if (ret == 0 || io::isError(ret)) { @@ -374,7 +382,7 @@ bool RawSiteToSiteClient::getPeerList(std::vector<PeerStatus> &peers) { return false; } } - uint8_t secure; + uint8_t secure = 0; { const auto ret = peer_->read(secure); if (ret == 0 || io::isError(ret)) { @@ -382,7 +390,7 @@ bool RawSiteToSiteClient::getPeerList(std::vector<PeerStatus> &peers) { return false; } } - uint32_t count; + uint32_t count = 0; { const auto ret = peer_->read(count); if (ret == 0 || io::isError(ret)) { @@ -419,7 +427,7 @@ bool RawSiteToSiteClient::getPeerList(std::vector<PeerStatus> &peers) { for (int i = NEGOTIATE_FLOWFILE_CODEC; i <= SHUTDOWN; i++) { if (SiteToSiteRequest::RequestTypeStr[i] == requestTypeStr) { - type = (RequestType) i; + type = static_cast<RequestType>(i); return static_cast<int>(ret); } } @@ -480,8 +488,8 @@ bool RawSiteToSiteClient::bootstrap() { } std::shared_ptr<Transaction> RawSiteToSiteClient::createTransaction(TransferDirection direction) { - int ret; - bool dataAvailable; + int ret = 0; + bool dataAvailable = false; std::shared_ptr<Transaction> transaction = nullptr; if (peer_state_ != READY) { @@ -499,7 +507,7 @@ std::shared_ptr<Transaction> RawSiteToSiteClient::createTransaction(TransferDire return transaction; } - RespondCode code; + RespondCode code = RESERVED; std::string message; ret = readRespond(nullptr, code, message); diff --git a/libminifi/src/sitetosite/SiteToSiteClient.cpp b/libminifi/src/sitetosite/SiteToSiteClient.cpp index d7d37dced..3eb000af0 100644 --- a/libminifi/src/sitetosite/SiteToSiteClient.cpp +++ b/libminifi/src/sitetosite/SiteToSiteClient.cpp @@ -27,28 +27,28 @@ namespace org::apache::nifi::minifi::sitetosite { int SiteToSiteClient::readResponse(const std::shared_ptr<Transaction>& /*transaction*/, RespondCode &code, std::string &message) { - uint8_t firstByte; + uint8_t firstByte = 0; { const auto ret = peer_->read(firstByte); if (ret == 0 || io::isError(ret) || firstByte != CODE_SEQUENCE_VALUE_1) return -1; } - uint8_t secondByte; + uint8_t secondByte = 0; { const auto ret = peer_->read(secondByte); if (ret == 0 || io::isError(ret) || secondByte != CODE_SEQUENCE_VALUE_2) return -1; } - uint8_t thirdByte; + uint8_t thirdByte = 0; { const auto ret = peer_->read(thirdByte); if (ret == 0 || io::isError(ret)) return static_cast<int>(ret); } - code = (RespondCode) thirdByte; + code = static_cast<RespondCode>(thirdByte); RespondCodeContext *resCode = this->getRespondCodeContext(code); if (!resCode) { return -1; @@ -82,8 +82,8 @@ int SiteToSiteClient::writeResponse(const std::shared_ptr<Transaction>& /*transa } { - const uint8_t codeSeq[3] { CODE_SEQUENCE_VALUE_1, CODE_SEQUENCE_VALUE_2, static_cast<uint8_t>(code) }; - const auto ret = peer_->write(codeSeq, 3); + const std::array<uint8_t, 3> codeSeq = { CODE_SEQUENCE_VALUE_1, CODE_SEQUENCE_VALUE_2, static_cast<uint8_t>(code) }; + const auto ret = peer_->write(codeSeq.data(), 3); if (ret != 3) return -1; } @@ -190,7 +190,7 @@ bool SiteToSiteClient::transferFlowFiles(const std::shared_ptr<core::ProcessCont } bool SiteToSiteClient::confirm(const utils::Identifier& transactionID) { - int ret; + int ret = 0; std::shared_ptr<Transaction> transaction; if (peer_state_ != READY) { @@ -236,7 +236,7 @@ bool SiteToSiteClient::confirm(const utils::Identifier& transactionID) { ret = writeResponse(transaction, CONFIRM_TRANSACTION, crc); if (ret <= 0) return false; - RespondCode code; + RespondCode code = RESERVED; std::string message; readResponse(transaction, code, message); if (ret <= 0) @@ -259,7 +259,7 @@ bool SiteToSiteClient::confirm(const utils::Identifier& transactionID) { if (ret <= 0) { return false; } - RespondCode code; + RespondCode code = RESERVED; std::string message; readResponse(transaction, code, message); @@ -337,7 +337,7 @@ void SiteToSiteClient::error(const utils::Identifier& transactionID) { // Complete the transaction bool SiteToSiteClient::complete(const utils::Identifier& transactionID) { - int ret; + int ret = 0; std::shared_ptr<Transaction> transaction = nullptr; if (peer_state_ != READY) { @@ -374,7 +374,7 @@ bool SiteToSiteClient::complete(const utils::Identifier& transactionID) { } } } else { - RespondCode code; + RespondCode code = RESERVED; std::string message; ret = readResponse(transaction, code, message); @@ -553,7 +553,7 @@ bool SiteToSiteClient::receive(const utils::Identifier& transactionID, DataPacke if (transaction->current_transfers_ > 0) { // if we already has transfer before, check to see whether another one is available - RespondCode code; + RespondCode code = RESERVED; std::string message; if (readResponse(transaction, code, message) <= 0) { @@ -580,7 +580,7 @@ bool SiteToSiteClient::receive(const utils::Identifier& transactionID, DataPacke } // start to read the packet - uint32_t numAttributes; + uint32_t numAttributes = 0; { const auto ret = transaction->getStream().read(numAttributes); if (ret == 0 || io::isError(ret) || numAttributes > MAX_NUM_ATTRIBUTES) { @@ -609,7 +609,7 @@ bool SiteToSiteClient::receive(const utils::Identifier& transactionID, DataPacke logger_->log_debug("Site2Site transaction {} receives attribute key {} value {}", transactionID.to_string(), key, value); } - uint64_t len; + uint64_t len = 0; { const auto ret = transaction->getStream().read(len); if (ret == 0 || io::isError(ret)) { diff --git a/libminifi/src/utils/Cron.cpp b/libminifi/src/utils/Cron.cpp index 5fa8d9ecd..44e51e451 100644 --- a/libminifi/src/utils/Cron.cpp +++ b/libminifi/src/utils/Cron.cpp @@ -292,8 +292,8 @@ class LastNthDayInMonthField : public CronField { [[nodiscard]] bool matches(local_seconds tp) const override { year_month_day date(floor<days>(tp)); - auto last_day = date.year()/date.month()/last; - auto target_date = local_days(last_day)-offset_; + auto last_day = date.year() / date.month() / last; + auto target_date = local_days(last_day) - offset_; return local_days(date) == target_date; } @@ -307,7 +307,7 @@ class NthWeekdayField : public CronField { [[nodiscard]] bool matches(local_seconds tp) const override { year_month_day date(floor<days>(tp)); - auto target_date = date.year()/date.month()/(weekday_[n_]); + auto target_date = date.year() / date.month() / (weekday_[n_]); return local_days(date) == local_days(target_date); } diff --git a/libminifi/src/utils/TimeUtil.cpp b/libminifi/src/utils/TimeUtil.cpp index 1bde905d2..0ae167e62 100644 --- a/libminifi/src/utils/TimeUtil.cpp +++ b/libminifi/src/utils/TimeUtil.cpp @@ -44,7 +44,7 @@ std::optional<std::chrono::system_clock::time_point> parseRfc3339(const std::str return std::nullopt; constexpr std::string_view accepted_delimiters = "tT_ "; - char delimiter_char; + char delimiter_char = 0; stream.get(delimiter_char); if (stream.fail() || !ranges::contains(accepted_delimiters, delimiter_char)) diff --git a/libminifi/src/utils/file/FileUtils.cpp b/libminifi/src/utils/file/FileUtils.cpp index a011802f7..55db62364 100644 --- a/libminifi/src/utils/file/FileUtils.cpp +++ b/libminifi/src/utils/file/FileUtils.cpp @@ -71,32 +71,30 @@ bool contains(const std::filesystem::path& file_path, std::string_view text_to_s } std::chrono::system_clock::time_point to_sys(std::chrono::file_clock::time_point file_time) { - using namespace std::chrono; // NOLINT(build/namespaces) #if defined(WIN32) // workaround for https://github.com/microsoft/STL/issues/2446 // clock_cast can fail on older windows versions - constexpr file_clock::duration clock_epoch_diff{std::filesystem::__std_fs_file_time_epoch_adjustment}; - return system_clock::time_point(file_time.time_since_epoch() - clock_epoch_diff); + constexpr std::chrono::file_clock::duration clock_epoch_diff{std::filesystem::__std_fs_file_time_epoch_adjustment}; + return std::chrono::system_clock::time_point(file_time.time_since_epoch() - clock_epoch_diff); #elif(defined(_LIBCPP_VERSION) && (_LIBCPP_VERSION < 14000)) // relies on file_clock and system_clock having the same epoch - return system_clock::time_point(duration_cast<system_clock::duration>(file_time.time_since_epoch())); + return std::chrono::system_clock::time_point(duration_cast<std::chrono::system_clock::duration>(file_time.time_since_epoch())); #else - return time_point_cast<system_clock::duration>(file_clock::to_sys(file_time)); + return time_point_cast<std::chrono::system_clock::duration>(std::chrono::file_clock::to_sys(file_time)); #endif } std::chrono::file_clock::time_point from_sys(std::chrono::system_clock::time_point sys_time) { - using namespace std::chrono; // NOLINT(build/namespaces) #if defined(WIN32) // workaround for https://github.com/microsoft/STL/issues/2446 // clock_cast can fail on older windows versions - constexpr file_clock::duration clock_epoch_diff{std::filesystem::__std_fs_file_time_epoch_adjustment}; - return file_clock::time_point(sys_time.time_since_epoch() + clock_epoch_diff); + constexpr std::chrono::file_clock::duration clock_epoch_diff{std::filesystem::__std_fs_file_time_epoch_adjustment}; + return std::chrono::file_clock::time_point(sys_time.time_since_epoch() + clock_epoch_diff); #elif(defined(_LIBCPP_VERSION) && (_LIBCPP_VERSION < 14000)) // relies on file_clock and system_clock having the same epoch - return file_clock::time_point(duration_cast<file_clock::duration>(sys_time.time_since_epoch())); + return std::chrono::file_clock::time_point(duration_cast<std::chrono::file_clock::duration>(sys_time.time_since_epoch())); #else - return time_point_cast<file_clock::duration>(file_clock::from_sys(sys_time)); + return time_point_cast<std::chrono::file_clock::duration>(std::chrono::file_clock::from_sys(sys_time)); #endif } diff --git a/libminifi/test/unit/CronTests.cpp b/libminifi/test/unit/CronTests.cpp index 4d8fa5669..3b7c6118a 100644 --- a/libminifi/test/unit/CronTests.cpp +++ b/libminifi/test/unit/CronTests.cpp @@ -129,7 +129,7 @@ TEST_CASE("Cron allowed nonnumerical inputs", "[cron]") { TEST_CASE("Cron::calculateNextTrigger", "[cron]") { using date::sys_days; - using namespace date::literals; + using namespace date::literals; // NOLINT(google-build-using-namespace) using namespace std::literals::chrono_literals; #ifdef WIN32 date::set_install(TZ_DATA_DIR); @@ -415,7 +415,7 @@ TEST_CASE("Cron::calculateNextTrigger with timezones", "[cron]") { using date::local_days; using date::locate_zone; using date::zoned_time; - using namespace date::literals; + using namespace date::literals; // NOLINT(google-build-using-namespace) using namespace std::literals::chrono_literals; #ifdef WIN32 date::set_install(TZ_DATA_DIR); diff --git a/libminifi/test/unit/ExtensionVerificationTests.cpp b/libminifi/test/unit/ExtensionVerificationTests.cpp index f05b71c3a..9fdd06a5b 100644 --- a/libminifi/test/unit/ExtensionVerificationTests.cpp +++ b/libminifi/test/unit/ExtensionVerificationTests.cpp @@ -40,7 +40,7 @@ const std::string extension_file = "libextension.so"; struct Fixture : public TestController { Fixture() { - extension_ = std::filesystem::path(createTempDirectory()) / extension_file; + extension_ = createTempDirectory() / extension_file; } std::filesystem::path extension_; }; diff --git a/libminifi/test/unit/FileUtilsTests.cpp b/libminifi/test/unit/FileUtilsTests.cpp index 0a1420068..5e9af4f67 100644 --- a/libminifi/test/unit/FileUtilsTests.cpp +++ b/libminifi/test/unit/FileUtilsTests.cpp @@ -30,6 +30,8 @@ #include "utils/gsl.h" #include "utils/TimeUtil.h" +using namespace std::literals::chrono_literals; + namespace FileUtils = org::apache::nifi::minifi::utils::file; TEST_CASE("TestFileUtils::get_executable_path", "[TestGetExecutablePath]") { @@ -183,10 +185,8 @@ TEST_CASE("TestFileUtils::addFilesMatchingExtension", "[TestAddFilesMatchingExte } TEST_CASE("FileUtils::last_write_time and last_write_time_point work", "[last_write_time][last_write_time_point]") { - using namespace std::chrono; - - auto time_before_write = file_clock::now(); - auto time_point_before_write = time_point_cast<seconds>(file_clock::now()); + auto time_before_write = std::chrono::file_clock::now(); + auto time_point_before_write = std::chrono::time_point_cast<std::chrono::seconds>(std::chrono::file_clock::now()); TestController testController; @@ -194,15 +194,15 @@ TEST_CASE("FileUtils::last_write_time and last_write_time_point work", "[last_wr auto test_file = dir / "test.txt"; REQUIRE_FALSE(FileUtils::last_write_time(test_file).has_value()); // non existent file should not return last w.t. - REQUIRE(FileUtils::last_write_time_point(test_file) == (time_point<file_clock, seconds>{})); + REQUIRE(FileUtils::last_write_time_point(test_file) == (std::chrono::time_point<std::chrono::file_clock, std::chrono::seconds>{})); std::this_thread::sleep_for(std::chrono::milliseconds(10)); std::ofstream test_file_stream(test_file); test_file_stream << "foo\n"; test_file_stream.flush(); - auto time_after_first_write = file_clock::now(); - auto time_point_after_first_write = time_point_cast<seconds>(file_clock::now()); + auto time_after_first_write = std::chrono::file_clock::now(); + auto time_point_after_first_write = std::chrono::time_point_cast<std::chrono::seconds>(std::chrono::file_clock::now()); auto first_mtime = FileUtils::last_write_time(test_file).value(); REQUIRE(first_mtime >= time_before_write); @@ -216,8 +216,8 @@ TEST_CASE("FileUtils::last_write_time and last_write_time_point work", "[last_wr test_file_stream << "bar\n"; test_file_stream.flush(); - auto time_after_second_write = file_clock::now(); - auto time_point_after_second_write = time_point_cast<seconds>(file_clock::now()); + auto time_after_second_write = std::chrono::file_clock::now(); + auto time_point_after_second_write = time_point_cast<std::chrono::seconds>(std::chrono::file_clock::now()); auto second_mtime = FileUtils::last_write_time(test_file).value(); REQUIRE(second_mtime >= first_mtime); @@ -365,7 +365,7 @@ TEST_CASE("FileUtils::set_permissions and get_permissions", "[TestSetPermissions std::ofstream outfile(path, std::ios::out | std::ios::binary); REQUIRE(FileUtils::set_permissions(path, 0644) == 0); - uint32_t perms; + uint32_t perms = 0; REQUIRE(FileUtils::get_permissions(path, perms)); REQUIRE(perms == 0644); } @@ -515,32 +515,33 @@ TEST_CASE("FileUtils::path_size", "[TestPathSize]") { } TEST_CASE("file_clock to system_clock conversion tests") { - using namespace std::chrono; - - static_assert(system_clock::period::num == file_clock::period::num); - constexpr auto lowest_den = std::min(file_clock::period::den, system_clock::period::den); - using LeastPreciseDurationType = duration<std::common_type_t<system_clock::duration::rep, file_clock::duration::rep>, std::ratio<system_clock::period::num, lowest_den>>; + static_assert(std::chrono::system_clock::period::num == std::chrono::file_clock::period::num); + constexpr auto lowest_den = std::min(std::chrono::file_clock::period::den, std::chrono::system_clock::period::den); + using LeastPreciseDurationType = std::chrono::duration<std::common_type_t<std::chrono::system_clock::duration::rep, std::chrono::file_clock::duration::rep>, + std::ratio<std::chrono::system_clock::period::num, lowest_den>>; { - system_clock::time_point system_now = system_clock::now(); - file_clock::time_point converted_system_now = FileUtils::from_sys(system_now); - system_clock::time_point double_converted_system_now = FileUtils::to_sys(converted_system_now); + std::chrono::system_clock::time_point system_now = std::chrono::system_clock::now(); + std::chrono::file_clock::time_point converted_system_now = FileUtils::from_sys(system_now); + std::chrono::system_clock::time_point double_converted_system_now = FileUtils::to_sys(converted_system_now); - CHECK(time_point_cast<LeastPreciseDurationType>(system_now).time_since_epoch().count() == time_point_cast<LeastPreciseDurationType>(double_converted_system_now).time_since_epoch().count()); + CHECK(std::chrono::time_point_cast<LeastPreciseDurationType>(system_now).time_since_epoch().count() == + std::chrono::time_point_cast<LeastPreciseDurationType>(double_converted_system_now).time_since_epoch().count()); } { - file_clock::time_point file_now = file_clock ::now(); - system_clock::time_point converted_file_now = FileUtils::to_sys(file_now); - file_clock::time_point double_converted_file_now = FileUtils::from_sys(converted_file_now); + std::chrono::file_clock::time_point file_now = std::chrono::file_clock ::now(); + std::chrono::system_clock::time_point converted_file_now = FileUtils::to_sys(file_now); + std::chrono::file_clock::time_point double_converted_file_now = FileUtils::from_sys(converted_file_now); - CHECK(time_point_cast<LeastPreciseDurationType>(file_now).time_since_epoch().count() == time_point_cast<LeastPreciseDurationType>(double_converted_file_now).time_since_epoch().count()); + CHECK(std::chrono::time_point_cast<LeastPreciseDurationType>(file_now).time_since_epoch().count() == + std::chrono::time_point_cast<LeastPreciseDurationType>(double_converted_file_now).time_since_epoch().count()); } { // t0 <= t1 - auto sys_time_t0 = system_clock::now(); - auto file_time_t1 = file_clock ::now(); + auto sys_time_t0 = std::chrono::system_clock::now(); + auto file_time_t1 = std::chrono::file_clock ::now(); auto file_time_from_t0 = FileUtils::from_sys(sys_time_t0); auto sys_time_from_t1 = FileUtils::to_sys(file_time_t1); diff --git a/libminifi/test/unit/LoggerTests.cpp b/libminifi/test/unit/LoggerTests.cpp index bd270325c..beb06c706 100644 --- a/libminifi/test/unit/LoggerTests.cpp +++ b/libminifi/test/unit/LoggerTests.cpp @@ -201,12 +201,10 @@ TEST_CASE("Test ShortenNames", "[ttl8]") { LogTestController::getInstance().reset(); } -using namespace minifi::io; - -std::string decompress(const std::unique_ptr<InputStream>& input) { +std::string decompress(const std::unique_ptr<minifi::io::InputStream>& input) { input->seek(0); - auto output = std::make_unique<BufferStream>(); - auto decompressor = std::make_shared<ZlibDecompressStream>(gsl::make_not_null(output.get())); + auto output = std::make_unique<minifi::io::BufferStream>(); + auto decompressor = std::make_shared<minifi::io::ZlibDecompressStream>(gsl::make_not_null(output.get())); minifi::internal::pipe(*input, *decompressor); decompressor->close(); return utils::span_to<std::string>(utils::as_span<const char>(output->getBuffer())); diff --git a/libminifi/test/unit/MinifiConcurrentQueueTests.cpp b/libminifi/test/unit/MinifiConcurrentQueueTests.cpp index a0decc244..d152aecdf 100644 --- a/libminifi/test/unit/MinifiConcurrentQueueTests.cpp +++ b/libminifi/test/unit/MinifiConcurrentQueueTests.cpp @@ -168,8 +168,6 @@ namespace MinifiConcurrentQueueTestProducersConsumers { } // namespace MinifiConcurrentQueueTestProducersConsumers TEST_CASE("TestConcurrentQueue", "[TestConcurrentQueue]") { - using namespace MinifiConcurrentQueueTestProducersConsumers; - utils::ConcurrentQueue<std::string> queue; SECTION("empty queue") { @@ -228,7 +226,6 @@ TEST_CASE("TestConcurrentQueue", "[TestConcurrentQueue]") { } TEST_CASE("TestConcurrentQueue: test simple producer and consumer", "[ProducerConsumer]") { - using namespace MinifiConcurrentQueueTestProducersConsumers; utils::ConcurrentQueue<std::string> queue; std::vector<std::string> results; @@ -236,18 +233,18 @@ TEST_CASE("TestConcurrentQueue: test simple producer and consumer", "[ProducerCo std::thread producer; std::thread consumer; SECTION("using tryDequeue") { - producer = getSimpleProducerThread(queue); - consumer = getSimpleTryDequeConsumerThread(queue, results); + producer = MinifiConcurrentQueueTestProducersConsumers::getSimpleProducerThread(queue); + consumer = MinifiConcurrentQueueTestProducersConsumers::getSimpleTryDequeConsumerThread(queue, results); } SECTION("using consume") { - producer = getSimpleProducerThread(queue); - consumer = getSimpleConsumeConsumerThread(queue, results); + producer = MinifiConcurrentQueueTestProducersConsumers::getSimpleProducerThread(queue); + consumer = MinifiConcurrentQueueTestProducersConsumers::getSimpleConsumeConsumerThread(queue, results); } /* In this testcase the consumer thread puts back all items to the queue to consume again * Even in this case the ones inserted later by the producer should be consumed */ SECTION("with readd") { - producer = getSimpleProducerThread(queue); - consumer = getSpinningReaddingDequeueConsumerThread(queue, results); + producer = MinifiConcurrentQueueTestProducersConsumers::getSimpleProducerThread(queue); + consumer = MinifiConcurrentQueueTestProducersConsumers::getSpinningReaddingDequeueConsumerThread(queue, results); } producer.join(); consumer.join(); @@ -257,21 +254,20 @@ TEST_CASE("TestConcurrentQueue: test simple producer and consumer", "[ProducerCo } TEST_CASE("TestConcurrentQueue: test timed waiting consumers", "[ProducerConsumer]") { - using namespace MinifiConcurrentQueueTestProducersConsumers; utils::ConditionConcurrentQueue<std::string> queue(true); std::vector<std::string> results; - std::thread producer { getSimpleProducerThread(queue) }; + std::thread producer { MinifiConcurrentQueueTestProducersConsumers::getSimpleProducerThread(queue) }; std::thread consumer; SECTION("using dequeueWaitFor") { - consumer = getDequeueWaitForConsumerThread(queue, results); + consumer = MinifiConcurrentQueueTestProducersConsumers::getDequeueWaitForConsumerThread(queue, results); } SECTION("using dequeueWaitUntil") { - consumer = getDequeueWaitUntilConsumerThread(queue, results); + consumer = MinifiConcurrentQueueTestProducersConsumers::getDequeueWaitUntilConsumerThread(queue, results); } SECTION("using consumeWaitFor") { - consumer = getConsumeWaitForConsumerThread(queue, results); + consumer = MinifiConcurrentQueueTestProducersConsumers::getConsumeWaitForConsumerThread(queue, results); } producer.join(); @@ -281,18 +277,17 @@ TEST_CASE("TestConcurrentQueue: test timed waiting consumers", "[ProducerConsume } TEST_CASE("TestConcurrentQueue: test untimed waiting consumers", "[ProducerConsumer]") { - using namespace MinifiConcurrentQueueTestProducersConsumers; utils::ConditionConcurrentQueue<std::string> queue(true); std::vector<std::string> results; - std::thread producer { getSimpleProducerThread(queue) }; + std::thread producer { MinifiConcurrentQueueTestProducersConsumers::getSimpleProducerThread(queue) }; std::thread consumer; SECTION("using dequeueWait") { - consumer = getDequeueWaitConsumerThread(queue, results); + consumer = MinifiConcurrentQueueTestProducersConsumers::getDequeueWaitConsumerThread(queue, results); } SECTION("using consumeWait") { - consumer = getConsumeWaitConsumerThread(queue, results); + consumer = MinifiConcurrentQueueTestProducersConsumers::getConsumeWaitConsumerThread(queue, results); } producer.join(); @@ -307,14 +302,13 @@ TEST_CASE("TestConcurrentQueue: test untimed waiting consumers", "[ProducerConsu } TEST_CASE("TestConcurrentQueue: test the readding dequeue consumer", "[ProducerConsumer]") { - using namespace MinifiConcurrentQueueTestProducersConsumers; utils::ConditionConcurrentQueue<std::string> queue(true); std::vector<std::string> results; std::atomic_int results_size{0}; - std::thread consumer { getReaddingDequeueConsumerThread(queue, results, results_size) }; + std::thread consumer { MinifiConcurrentQueueTestProducersConsumers::getReaddingDequeueConsumerThread(queue, results, results_size) }; std::this_thread::sleep_for(std::chrono::milliseconds(1)); - std::thread producer { getSimpleProducerThread(queue) }; + std::thread producer { MinifiConcurrentQueueTestProducersConsumers::getSimpleProducerThread(queue) }; auto we_have_all_results = [&results_size]() { return results_size >= 3; }; REQUIRE(utils::verifyEventHappenedInPollTime(std::chrono::seconds(1), we_have_all_results)); @@ -327,19 +321,18 @@ TEST_CASE("TestConcurrentQueue: test the readding dequeue consumer", "[ProducerC } TEST_CASE("TestConcurrentQueue: test waiting consumers with blocked producer", "[ProducerConsumer]") { - using namespace MinifiConcurrentQueueTestProducersConsumers; utils::ConditionConcurrentQueue<std::string> queue(true); std::vector<std::string> results; std::mutex mutex; std::unique_lock<std::mutex> lock(mutex); - std::thread producer{ getBlockedProducerThread(queue, mutex) }; + std::thread producer{ MinifiConcurrentQueueTestProducersConsumers::getBlockedProducerThread(queue, mutex) }; std::thread consumer; SECTION("using dequeueWaitFor") { - consumer = getDequeueWaitForConsumerThread(queue, results); + consumer = MinifiConcurrentQueueTestProducersConsumers::getDequeueWaitForConsumerThread(queue, results); } SECTION("using consumeWaitFor") { - consumer = getConsumeWaitForConsumerThread(queue, results); + consumer = MinifiConcurrentQueueTestProducersConsumers::getConsumeWaitForConsumerThread(queue, results); } consumer.join(); lock.unlock(); @@ -368,7 +361,7 @@ TEST_CASE("TestConcurrentQueues::highLoad", "[TestConcurrentQueuesHighLoad]") { std::thread relay([&queue, &cqueue]() { size_t cnt = 0; while (cnt < 50000) { - int i; + int i = 0; if (queue.tryDequeue(i)) { cnt++; cqueue.enqueue(i); @@ -377,7 +370,7 @@ TEST_CASE("TestConcurrentQueues::highLoad", "[TestConcurrentQueuesHighLoad]") { }); std::thread consumer([&cqueue, &target]() { - int i; + int i = 0; while (cqueue.dequeueWait(i)) { target.push_back(i); } diff --git a/libminifi/test/unit/NetUtilsTest.cpp b/libminifi/test/unit/NetUtilsTest.cpp index 17403eab3..10b7b2cb0 100644 --- a/libminifi/test/unit/NetUtilsTest.cpp +++ b/libminifi/test/unit/NetUtilsTest.cpp @@ -66,7 +66,7 @@ TEST_CASE("utils::net::getSslContext") { auto ssl_context_node = plan->addController("SSLContextService", "ssl_context_service"); auto ssl_context_service = std::dynamic_pointer_cast<minifi::controllers::SSLContextService>(ssl_context_node->getControllerServiceImplementation()); - const std::filesystem::path cert_dir = std::filesystem::path(minifi::utils::file::FileUtils::get_executable_dir()) / "resources"; + const std::filesystem::path cert_dir = minifi::utils::file::FileUtils::get_executable_dir() / "resources"; REQUIRE(ssl_context_service->setProperty(minifi::controllers::SSLContextService::CACertificate, (cert_dir / "ca_A.crt").string())); @@ -107,7 +107,7 @@ TEST_CASE("utils::net::getSslContext passphrase problems") { auto ssl_context_node = plan->addController("SSLContextService", "ssl_context_service"); auto ssl_context_service = std::dynamic_pointer_cast<minifi::controllers::SSLContextService>(ssl_context_node->getControllerServiceImplementation()); - const std::filesystem::path cert_dir = std::filesystem::path(minifi::utils::file::FileUtils::get_executable_dir()) / "resources"; + const std::filesystem::path cert_dir = minifi::utils::file::FileUtils::get_executable_dir() / "resources"; REQUIRE(ssl_context_service->setProperty(minifi::controllers::SSLContextService::CACertificate, (cert_dir / "ca_A.crt").string())); REQUIRE(ssl_context_service->setProperty(minifi::controllers::SSLContextService::ClientCertificate, (cert_dir / "alice_by_A.pem").string())); @@ -138,7 +138,7 @@ TEST_CASE("utils::net::getSslContext missing CA") { auto ssl_context_node = plan->addController("SSLContextService", "ssl_context_service"); auto ssl_context_service = std::dynamic_pointer_cast<minifi::controllers::SSLContextService>(ssl_context_node->getControllerServiceImplementation()); - const std::filesystem::path cert_dir = std::filesystem::path(minifi::utils::file::FileUtils::get_executable_dir()) / "resources"; + const std::filesystem::path cert_dir = minifi::utils::file::FileUtils::get_executable_dir() / "resources"; REQUIRE(ssl_context_service->setProperty(minifi::controllers::SSLContextService::ClientCertificate, (cert_dir / "alice_by_A.pem").string())); REQUIRE(ssl_context_service->setProperty(minifi::controllers::SSLContextService::PrivateKey, (cert_dir / "alice.key").string())); diff --git a/libminifi/test/unit/PropertyValidationTests.cpp b/libminifi/test/unit/PropertyValidationTests.cpp index 348114965..8e56101a9 100644 --- a/libminifi/test/unit/PropertyValidationTests.cpp +++ b/libminifi/test/unit/PropertyValidationTests.cpp @@ -24,14 +24,13 @@ namespace org::apache::nifi::minifi::core { -using namespace utils::internal; /** * This Tests checks a deprecated behavior that should be removed * in the next major release. */ TEST_CASE("Some default values get coerced to typed variants") { auto prop = Property("prop", "d", "true"); - REQUIRE_THROWS_AS(prop.setValue("banana"), ConversionException); + REQUIRE_THROWS_AS(prop.setValue("banana"), utils::internal::ConversionException); const std::string SPACE = " "; auto prop2 = Property("prop", "d", SPACE + "true"); @@ -44,9 +43,9 @@ TEST_CASE("Converting invalid PropertyValue") { .withDefaultValue("0") .build(); Property property{property_definition}; - REQUIRE_THROWS_AS(property.setValue("not int"), ParseException); + REQUIRE_THROWS_AS(property.setValue("not int"), utils::internal::ParseException); auto cast_check = [&]{ return static_cast<int>(property.getValue()) == 0; }; // To avoid unused-value warning - REQUIRE_THROWS_AS(cast_check(), InvalidValueException); + REQUIRE_THROWS_AS(cast_check(), utils::internal::InvalidValueException); } TEST_CASE("Parsing int has baggage after") { @@ -55,7 +54,7 @@ TEST_CASE("Parsing int has baggage after") { .withDefaultValue("0") .build(); Property property{property_definition}; - REQUIRE_THROWS_AS(property.setValue("55almost int"), ParseException); + REQUIRE_THROWS_AS(property.setValue("55almost int"), utils::internal::ParseException); } TEST_CASE("Parsing int has spaces") { @@ -74,7 +73,7 @@ TEST_CASE("Parsing int out of range") { .withDefaultValue("0") .build(); Property property{property_definition}; - REQUIRE_THROWS_AS(property.setValue(" 5000000000 "), ParseException); + REQUIRE_THROWS_AS(property.setValue(" 5000000000 "), utils::internal::ParseException); } TEST_CASE("Parsing bool has baggage after") { @@ -83,7 +82,7 @@ TEST_CASE("Parsing bool has baggage after") { .withDefaultValue("true") .build(); Property property{property_definition}; - REQUIRE_THROWS_AS(property.setValue("false almost bool"), ParseException); + REQUIRE_THROWS_AS(property.setValue("false almost bool"), utils::internal::ParseException); } class TestConfigurableComponent : public ConfigurableComponent { @@ -144,7 +143,7 @@ TEST_CASE("Missing Required Without Default") { TestConfigurableComponent component; component.setSupportedProperties(std::array<PropertyReference, 1>{property_definition}); std::string value; - REQUIRE_THROWS_AS(component.getProperty(property.getName(), value), RequiredPropertyMissingException); + REQUIRE_THROWS_AS(component.getProperty(property.getName(), value), utils::internal::RequiredPropertyMissingException); } TEST_CASE("Missing Optional Without Default") { @@ -180,9 +179,9 @@ TEST_CASE("Invalid With Default") { Property property{property_definition}; TestConfigurableComponent component; component.setSupportedProperties(std::array<PropertyReference, 1>{property_definition}); - REQUIRE_THROWS_AS(component.setProperty("prop", "banana"), ParseException); + REQUIRE_THROWS_AS(component.setProperty("prop", "banana"), utils::internal::ParseException); std::string value; - REQUIRE_THROWS_AS(component.getProperty(property.getName(), value), InvalidValueException); + REQUIRE_THROWS_AS(component.getProperty(property.getName(), value), utils::internal::InvalidValueException); } TEST_CASE("Valid With Default") { @@ -207,7 +206,7 @@ TEST_CASE("Invalid conversion") { TestConfigurableComponent component; component.setSupportedProperties(std::array<PropertyReference, 1>{property_definition}); bool value = false; - REQUIRE_THROWS_AS(component.getProperty(property.getName(), value), ConversionException); + REQUIRE_THROWS_AS(component.getProperty(property.getName(), value), utils::internal::ConversionException); } TEST_CASE("Write Invalid Then Override With Valid") { @@ -219,7 +218,7 @@ TEST_CASE("Write Invalid Then Override With Valid") { Property property{property_definition}; TestConfigurableComponent component; component.setSupportedProperties(std::array<PropertyReference, 1>{property_definition}); - REQUIRE_THROWS_AS(component.setProperty(property.getName(), "banana"), ConversionException); + REQUIRE_THROWS_AS(component.setProperty(property.getName(), "banana"), utils::internal::ConversionException); component.setProperty(property.getName(), "98"); int value = 0; REQUIRE(component.getProperty(property.getName(), value)); @@ -238,7 +237,7 @@ TEST_CASE("Property Change notification gets called even on erroneous assignment component.setPropertyModifiedCallback([&](const Property &, const Property &) { ++callbackCount; }); - REQUIRE_THROWS_AS(component.setProperty(property.getName(), "banana"), ConversionException); + REQUIRE_THROWS_AS(component.setProperty(property.getName(), "banana"), utils::internal::ConversionException); REQUIRE(callbackCount == 1); } @@ -255,7 +254,7 @@ TEST_CASE("Correctly Typed Property With Invalid Validation") { component.setPropertyModifiedCallback([&](const Property &, const Property &) { ++callbackCount; }); - REQUIRE_THROWS_AS(component.setProperty(property.getName(), "20"), InvalidValueException); + REQUIRE_THROWS_AS(component.setProperty(property.getName(), "20"), utils::internal::InvalidValueException); REQUIRE(callbackCount == 1); } @@ -271,7 +270,7 @@ TEST_CASE("TimePeriodValue Property") { TimePeriodValue time_period_value; REQUIRE(component.getProperty(property.getName(), time_period_value)); CHECK(time_period_value.getMilliseconds() == 10min); - REQUIRE_THROWS_AS(component.setProperty(property.getName(), "20"), ParseException); + REQUIRE_THROWS_AS(component.setProperty(property.getName(), "20"), utils::internal::ParseException); } TEST_CASE("TimePeriodValue Property without validator") { @@ -286,7 +285,7 @@ TEST_CASE("TimePeriodValue Property without validator") { REQUIRE(component.getProperty(property.getName(), time_period_value)); CHECK(time_period_value.getMilliseconds() == 1h); REQUIRE_NOTHROW(component.setProperty(property.getName(), "20")); - REQUIRE_THROWS_AS(component.getProperty(property.getName(), time_period_value), ValueException); + REQUIRE_THROWS_AS(component.getProperty(property.getName(), time_period_value), utils::internal::ValueException); } TEST_CASE("Validating listener port property") { @@ -295,9 +294,9 @@ TEST_CASE("Validating listener port property") { .build(); Property property{property_definition}; REQUIRE_NOTHROW(property.setValue("1234")); - REQUIRE_THROWS_AS(property.setValue("banana"), InvalidValueException); - REQUIRE_THROWS_AS(property.setValue("65536"), InvalidValueException); - REQUIRE_THROWS_AS(property.setValue("-1"), InvalidValueException); + REQUIRE_THROWS_AS(property.setValue("banana"), utils::internal::InvalidValueException); + REQUIRE_THROWS_AS(property.setValue("65536"), utils::internal::InvalidValueException); + REQUIRE_THROWS_AS(property.setValue("-1"), utils::internal::InvalidValueException); } TEST_CASE("Validating data transfer speed property with default value") { @@ -318,9 +317,9 @@ TEST_CASE("Validating data transfer speed property with default value") { REQUIRE(component.getProperty(property.getName(), data_transfer_speed_value)); CHECK(data_transfer_speed_value.getValue() == 1_TiB); REQUIRE_NOTHROW(component.setProperty(property.getName(), "1KBinvalidsuffix")); - REQUIRE_THROWS_AS(component.getProperty(property.getName(), data_transfer_speed_value), ValueException); + REQUIRE_THROWS_AS(component.getProperty(property.getName(), data_transfer_speed_value), utils::internal::ValueException); REQUIRE_NOTHROW(component.setProperty(property.getName(), "1KB")); - REQUIRE_THROWS_AS(component.getProperty(property.getName(), data_transfer_speed_value), ValueException); + REQUIRE_THROWS_AS(component.getProperty(property.getName(), data_transfer_speed_value), utils::internal::ValueException); } TEST_CASE("Validating data transfer speed property without default value") { @@ -336,8 +335,8 @@ TEST_CASE("Validating data transfer speed property without default value") { REQUIRE_NOTHROW(component.setProperty(property.getName(), "1TB/S ")); REQUIRE(component.getProperty(property.getName(), data_transfer_speed_value)); CHECK(data_transfer_speed_value.getValue() == 1_TiB); - REQUIRE_THROWS_AS(component.setProperty(property.getName(), "1KBinvalidsuffix"), ValueException); - REQUIRE_THROWS_AS(component.setProperty(property.getName(), "1KB"), ValueException); + REQUIRE_THROWS_AS(component.setProperty(property.getName(), "1KBinvalidsuffix"), utils::internal::ValueException); + REQUIRE_THROWS_AS(component.setProperty(property.getName(), "1KB"), utils::internal::ValueException); } } // namespace org::apache::nifi::minifi::core diff --git a/libminifi/test/unit/StreamTests.cpp b/libminifi/test/unit/StreamTests.cpp index 420ee3b0d..f68872cba 100644 --- a/libminifi/test/unit/StreamTests.cpp +++ b/libminifi/test/unit/StreamTests.cpp @@ -31,7 +31,7 @@ TEST_CASE("TestReadData", "[testread]") { auto base = std::make_shared<minifi::io::BufferStream>(); - base->write((const uint8_t*)"\x01\x02\x03\x04\x05\x06\x07\x08", 8); + base->write(reinterpret_cast<const uint8_t*>("\x01\x02\x03\x04\x05\x06\x07\x08"), 8); uint64_t c = 0; REQUIRE(8 == base->read(c)); REQUIRE(c == 0x0102030405060708); @@ -75,7 +75,7 @@ TEST_CASE("TestRead4", "[testread]") { TEST_CASE("TestWrite1", "[testwrite]") { auto base = std::make_shared<minifi::io::BufferStream>(); - base->write((uint64_t)0x0102030405060708); + base->write(static_cast<uint64_t>(0x0102030405060708)); std::string bytes(8, '\0'); REQUIRE(8 == base->read(as_writable_bytes(std::span(bytes)))); REQUIRE(bytes == "\x01\x02\x03\x04\x05\x06\x07\x08"); @@ -83,7 +83,7 @@ TEST_CASE("TestWrite1", "[testwrite]") { TEST_CASE("InvalidStreamSliceTest", "[teststreamslice]") { std::shared_ptr<minifi::io::BaseStream> base = std::make_shared<minifi::io::BufferStream>(); - base->write((const uint8_t*)"\x01\x02\x03\x04\x05\x06\x07\x08", 8); + base->write(reinterpret_cast<const uint8_t*>("\x01\x02\x03\x04\x05\x06\x07\x08"), 8); auto input_stream = std::static_pointer_cast<minifi::io::InputStream>(base); REQUIRE_THROWS_WITH(std::make_shared<minifi::io::StreamSlice>(input_stream, 0, 9), "StreamSlice is bigger than the Stream, Stream size: 8, StreamSlice size: 9, offset: 0"); REQUIRE_THROWS_WITH(std::make_shared<minifi::io::StreamSlice>(input_stream, 7, 3), "StreamSlice is bigger than the Stream, Stream size: 8, StreamSlice size: 3, offset: 7"); @@ -91,7 +91,7 @@ TEST_CASE("InvalidStreamSliceTest", "[teststreamslice]") { TEST_CASE("StreamSliceTest1", "[teststreamslice]") { std::shared_ptr<minifi::io::BaseStream> base = std::make_shared<minifi::io::BufferStream>(); - base->write((const uint8_t*)"\x01\x02\x03\x04\x05\x06\x07\x08", 8); + base->write(reinterpret_cast<const uint8_t*>("\x01\x02\x03\x04\x05\x06\x07\x08"), 8); auto input_stream = std::static_pointer_cast<minifi::io::InputStream>(base); std::shared_ptr<minifi::io::InputStream> stream_slice = std::make_shared<minifi::io::StreamSlice>(input_stream, 2, 4); std::vector<std::byte> buffer; diff --git a/libminifi/test/unit/TimeUtilTests.cpp b/libminifi/test/unit/TimeUtilTests.cpp index 9b9eb727f..cd7c6f344 100644 --- a/libminifi/test/unit/TimeUtilTests.cpp +++ b/libminifi/test/unit/TimeUtilTests.cpp @@ -70,7 +70,7 @@ TEST_CASE("getDateTimeStr() works correctly", "[getDateTimeStr]") { } TEST_CASE("getRFC2616Format() works correctly", "[getRFC2616Format]") { - using namespace date::literals; + using namespace date::literals; // NOLINT(google-build-using-namespace) using namespace std::literals::chrono_literals; using date::year_month_day; using date::sys_days; @@ -89,7 +89,7 @@ TEST_CASE("Test time conversion", "[testtimeconversion]") { } TEST_CASE("Test DateTime Conversion", "[testDateTime]") { - using namespace date::literals; + using namespace date::literals; // NOLINT(google-build-using-namespace) using namespace std::literals::chrono_literals; using date::year_month_day; using date::sys_days; @@ -110,20 +110,18 @@ TEST_CASE("Test DateTime Conversion", "[testDateTime]") { } TEST_CASE("Test system_clock epoch", "[systemclockepoch]") { - using namespace std::chrono; - time_point<system_clock> epoch; - time_point<system_clock> unix_epoch_plus_3e9_sec = date::sys_days(date::January / 24 / 2065) + 5h + 20min; + std::chrono::time_point<std::chrono::system_clock> epoch; + std::chrono::time_point<std::chrono::system_clock> unix_epoch_plus_3e9_sec = date::sys_days(date::January / 24 / 2065) + 5h + 20min; REQUIRE(epoch.time_since_epoch() == 0s); REQUIRE(unix_epoch_plus_3e9_sec.time_since_epoch() == 3000000000s); } #ifdef WIN32 TEST_CASE("Test windows file_clock duration period and epoch") { - using namespace std::chrono; static_assert(std::ratio_equal_v<std::chrono::file_clock::duration::period, std::ratio<1, 10000000>>, "file_clock duration tick period must be 100 nanoseconds"); auto file_clock_epoch = std::chrono::file_clock::time_point{}; auto file_clock_epoch_as_sys_time = utils::file::to_sys(file_clock_epoch); - system_clock::time_point expected_windows_file_epoch = date::sys_days(date::January / 1 / 1601); + std::chrono::system_clock::time_point expected_windows_file_epoch = date::sys_days(date::January / 1 / 1601); CHECK(file_clock_epoch_as_sys_time == expected_windows_file_epoch); } @@ -142,10 +140,9 @@ TEST_CASE("Test windows FILETIME epoch") { #endif TEST_CASE("Test clock resolutions", "[clockresolutiontests]") { - using namespace std::chrono; - CHECK(std::is_constructible<system_clock::duration, std::chrono::microseconds>::value); // The resolution of the system_clock is at least microseconds - CHECK(std::is_constructible<steady_clock::duration, std::chrono::microseconds>::value); // The resolution of the steady_clock is at least microseconds - CHECK(std::is_constructible<high_resolution_clock::duration, std::chrono::nanoseconds>::value); // The resolution of the high_resolution_clock is at least nanoseconds + CHECK(std::is_constructible<std::chrono::system_clock::duration, std::chrono::microseconds>::value); // The resolution of the system_clock is at least microseconds + CHECK(std::is_constructible<std::chrono::steady_clock::duration, std::chrono::microseconds>::value); // The resolution of the steady_clock is at least microseconds + CHECK(std::is_constructible<std::chrono::high_resolution_clock::duration, std::chrono::nanoseconds>::value); // The resolution of the high_resolution_clock is at least nanoseconds } TEST_CASE("Test string to duration conversion", "[timedurationtests]") { @@ -292,7 +289,7 @@ TEST_CASE("Test roundToNextSecond", "[roundingTests]") { TEST_CASE("Parse RFC3339", "[parseRfc3339]") { using date::sys_days; using org::apache::nifi::minifi::utils::timeutils::parseRfc3339; - using namespace date::literals; + using namespace date::literals; // NOLINT(google-build-using-namespace) using namespace std::literals::chrono_literals; auto expected_second = sys_days(2023_y / 03 / 01) + 19h + 04min + 55s;
