From 53a7ffc3486cdd60c89795323dd048ff0a96d657 Mon Sep 17 00:00:00 2001 From: Lennart Date: Wed, 16 Apr 2025 21:00:02 +0200 Subject: [PATCH 1/6] Resolve clang-tidy warnings in test files (#316) --- lint/clang-tidy.sh | 2 +- src/communication/RpcClient.cpp | 1 - src/datamodel/validator/UMessage.cpp | 1 - .../client/usubscription/v3/ConsumerTest.cpp | 139 +- .../communication/NotificationSinkTest.cpp | 152 ++- .../communication/NotificationSourceTest.cpp | 175 +-- test/coverage/communication/PublisherTest.cpp | 132 +- test/coverage/communication/RpcClientTest.cpp | 1197 +++++++++-------- test/coverage/communication/RpcServerTest.cpp | 381 +++--- .../coverage/communication/SubscriberTest.cpp | 150 ++- .../coverage/datamodel/PayloadBuilderTest.cpp | 395 +++--- .../datamodel/UMessageBuilderTest.cpp | 562 ++++---- .../datamodel/UMessageValidatorTest.cpp | 810 +++++++---- .../coverage/datamodel/UUriSerializerTest.cpp | 431 +++--- test/coverage/datamodel/UUriValidatorTest.cpp | 266 ++-- test/coverage/datamodel/UuidBuilderTest.cpp | 62 +- .../coverage/datamodel/UuidSerializerTest.cpp | 214 +-- test/coverage/datamodel/UuidValidatorTest.cpp | 180 +-- test/coverage/transport/UTransportTest.cpp | 331 +++-- .../coverage/utils/CallbackConnectionTest.cpp | 187 ++- test/coverage/utils/CyclicQueueTest.cpp | 8 +- test/coverage/utils/ExpectedTest.cpp | 138 +- test/coverage/utils/IpAddressTest.cpp | 8 +- test/coverage/utils/ThreadPoolTest.cpp | 8 +- test/coverage/utils/base64Test.cpp | 8 +- test/extra/NotificationTest.cpp | 113 +- test/extra/PublisherSubscriberTest.cpp | 97 +- test/extra/RpcClientServerTest.cpp | 91 +- test/extra/UTransportMockTest.cpp | 99 +- test/include/UTransportMock.h | 36 +- 30 files changed, 3558 insertions(+), 2816 deletions(-) diff --git a/lint/clang-tidy.sh b/lint/clang-tidy.sh index e2b490758..19e9ddc80 100755 --- a/lint/clang-tidy.sh +++ b/lint/clang-tidy.sh @@ -58,7 +58,7 @@ if [ -z "$target_source" ]; then shopt -s globstar pushd "$PROJECT_ROOT" > /dev/null - for f in include/**/*.h src/**/*.cpp; do # test/coverage/**/*.cpp test/extra/**/*.cpp test/include/**/*.h; do + for f in include/**/*.h src/**/*.cpp test/coverage/**/*.cpp test/extra/**/*.cpp test/include/**/*.h; do if [[ ! ("$f" =~ "build/") ]]; then echo echo "Checking file '$f'" diff --git a/src/communication/RpcClient.cpp b/src/communication/RpcClient.cpp index 87239a71f..469b51316 100644 --- a/src/communication/RpcClient.cpp +++ b/src/communication/RpcClient.cpp @@ -265,7 +265,6 @@ namespace detail { using uprotocol::v1::UCode; using uprotocol::v1::UStatus; -// using namespace std::chrono_literals; using ListenHandle = uprotocol::transport::UTransport::ListenHandle; auto PendingRequest::operator>(const PendingRequest& other) const { diff --git a/src/datamodel/validator/UMessage.cpp b/src/datamodel/validator/UMessage.cpp index 6a9db80c7..5a611bc2b 100644 --- a/src/datamodel/validator/UMessage.cpp +++ b/src/datamodel/validator/UMessage.cpp @@ -19,7 +19,6 @@ namespace uprotocol::datamodel::validator::message { using uprotocol::v1::UPRIORITY_CS4; -// using uprotocol::datamodel::validator; std::string_view message(Reason reason) { switch (reason) { diff --git a/test/coverage/client/usubscription/v3/ConsumerTest.cpp b/test/coverage/client/usubscription/v3/ConsumerTest.cpp index 17ba73169..6c6c133e4 100644 --- a/test/coverage/client/usubscription/v3/ConsumerTest.cpp +++ b/test/coverage/client/usubscription/v3/ConsumerTest.cpp @@ -14,7 +14,6 @@ #include #include -#include #include #include "UTransportMock.h" @@ -28,19 +27,37 @@ void someCallBack(const uprotocol::v1::UMessage& message) { } class ConsumerTest : public testing::Test { -protected: - // Run once per TEST_F. - // Used to set up clean environments per test. +private: std::shared_ptr mockTransportClient_; std::shared_ptr mockTransportServer_; uprotocol::v1::UUri client_uuri; uprotocol::v1::UUri server_uuri; - uprotocol::v1::UUri subcription_uuri; + uprotocol::v1::UUri subscription_uuri; + +protected: + // Run once per TEST_F. + // Used to set up clean environments per test. + + std::shared_ptr getMockTransportClient() + const { + return mockTransportClient_; + } + std::shared_ptr getMockTransportServer() + const { + return mockTransportServer_; + } + uprotocol::v1::UUri& getClientUUri() { return client_uuri; } + const uprotocol::v1::UUri& getServerUUri() const { return server_uuri; } + const uprotocol::v1::UUri& getSubscriptionUUri() const { + return subscription_uuri; + } void SetUp() override { + constexpr uint32_t TEST_UE_ID = 0x18000; + constexpr uint32_t DEFAULT_RESOURCE_ID = 0x8000; // Create a generic transport uri client_uuri.set_authority_name("random_string"); - client_uuri.set_ue_id(0x18000); + client_uuri.set_ue_id(TEST_UE_ID); client_uuri.set_ue_version_major(3); client_uuri.set_resource_id(0); @@ -58,17 +75,16 @@ class ConsumerTest : public testing::Test { std::make_shared(server_uuri); // Create a generic subscription uri - subcription_uuri.set_authority_name("10.0.0.2"); - subcription_uuri.set_ue_id(0x18000); - subcription_uuri.set_ue_version_major(3); - subcription_uuri.set_resource_id(0x8000); + subscription_uuri.set_authority_name("10.0.0.2"); + subscription_uuri.set_ue_id(TEST_UE_ID); + subscription_uuri.set_ue_version_major(3); + subscription_uuri.set_resource_id(DEFAULT_RESOURCE_ID); }; void TearDown() override {} // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. ConsumerTest() = default; - ~ConsumerTest() = default; void buildDefaultSourceURI(); void buildValidNotificationURI(); @@ -78,125 +94,130 @@ class ConsumerTest : public testing::Test { // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} + +public: + ~ConsumerTest() override = default; }; // Negative test case with no source filter -TEST_F(ConsumerTest, ConstructorTestSuccess) { - auto subcriptionCallback = someCallBack; - auto subscribe_request_ttl = std::chrono::milliseconds(1000); +TEST_F(ConsumerTest, ConstructorTestSuccess) { // NOLINT + constexpr int REQUEST_TTL_TIME = 0x8000; + auto subscription_callback = someCallBack; + auto subscribe_request_ttl = std::chrono::milliseconds(REQUEST_TTL_TIME); auto priority = uprotocol::v1::UPriority::UPRIORITY_CS4; auto options = uprotocol::client::usubscription::v3::ConsumerOptions(); - auto consumerOrSatus = + auto consumer_or_status = uprotocol::client::usubscription::v3::Consumer::create( - mockTransportClient_, subcription_uuri, - std::move(subcriptionCallback), priority, - std::move(subscribe_request_ttl), options); + getMockTransportClient(), getSubscriptionUUri(), + subscription_callback, priority, subscribe_request_ttl, options); // Ensure that the consumer creation was successful - ASSERT_TRUE(consumerOrSatus.has_value()); + ASSERT_TRUE(consumer_or_status.has_value()); // Obtain a pointer to the created consumer instance - auto& consumerPtr = consumerOrSatus.value(); + const auto& consumer_ptr = consumer_or_status.value(); // Verify that the consumer pointer is not null, indicating successful // creation - ASSERT_NE(consumerPtr, nullptr); + ASSERT_NE(consumer_ptr, nullptr); } -TEST_F(ConsumerTest, SubscribeTestSuccess) { - auto subcriptionCallback = someCallBack; - auto subscribe_request_ttl = std::chrono::milliseconds(1000); +TEST_F(ConsumerTest, SubscribeTestSuccess) { // NOLINT + constexpr uint32_t DEFAULT_RESOURCE_ID = 0x8000; + constexpr int REQUEST_TTL_TIME = 0x8000; + auto subscription_callback = someCallBack; + auto subscribe_request_ttl = std::chrono::milliseconds(REQUEST_TTL_TIME); auto priority = uprotocol::v1::UPriority::UPRIORITY_CS4; auto options = uprotocol::client::usubscription::v3::ConsumerOptions(); - auto consumerOrSatus = + auto consumer_or_status = uprotocol::client::usubscription::v3::Consumer::create( - mockTransportClient_, subcription_uuri, - std::move(subcriptionCallback), priority, - std::move(subscribe_request_ttl), options); + getMockTransportClient(), getSubscriptionUUri(), + subscription_callback, priority, subscribe_request_ttl, options); // Ensure that the consumer creation was successful - ASSERT_TRUE(consumerOrSatus.has_value()); + ASSERT_TRUE(consumer_or_status.has_value()); // Obtain a pointer to the created consumer instance - auto& consumerPtr = consumerOrSatus.value(); + const auto& consumer_ptr = consumer_or_status.value(); // Verify that the consumer pointer is not null, indicating successful // creation - ASSERT_NE(consumerPtr, nullptr); + ASSERT_NE(consumer_ptr, nullptr); // Create notification source sink uri to match resource id of sink - auto notification_uuri = server_uuri; - notification_uuri.set_resource_id(0x8000); + auto notification_uuri = getServerUUri(); + notification_uuri.set_resource_id(DEFAULT_RESOURCE_ID); // set format UPAYLOAD_FORMAT_PROTOBUF_WRAPPED_IN_ANY auto format = uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_PROTOBUF_WRAPPED_IN_ANY; - auto norificationSource = uprotocol::communication::NotificationSource( - mockTransportServer_, std::move(notification_uuri), - std::move(client_uuri), format); + auto notification_source = uprotocol::communication::NotificationSource( + getMockTransportServer(), std::move(notification_uuri), + std::move(getClientUUri()), format); // Build payload const std::string data = "test"; auto payload = uprotocol::datamodel::builder::Payload(data, format); - norificationSource.notify(std::move(payload)); + notification_source.notify(std::move(payload)); // Check send count - EXPECT_TRUE(mockTransportServer_->send_count_ == 1); - EXPECT_TRUE(mockTransportClient_->send_count_ == 1); + EXPECT_TRUE(getMockTransportServer()->getSendCount() == 1); + EXPECT_TRUE(getMockTransportClient()->getSendCount() == 1); } -TEST_F(ConsumerTest, UnsubscribeTestSuccess) { - auto subcriptionCallback = someCallBack; - auto subscribe_request_ttl = std::chrono::milliseconds(1000); +TEST_F(ConsumerTest, UnsubscribeTestSuccess) { // NOLINT + constexpr uint32_t DEFAULT_RESOURCE_ID = 0x8000; + constexpr int REQUEST_TTL_TIME = 0x8000; + auto subscription_callback = someCallBack; + auto subscribe_request_ttl = std::chrono::milliseconds(REQUEST_TTL_TIME); auto priority = uprotocol::v1::UPriority::UPRIORITY_CS4; auto options = uprotocol::client::usubscription::v3::ConsumerOptions(); - auto consumerOrSatus = + auto consumer_or_status = uprotocol::client::usubscription::v3::Consumer::create( - mockTransportClient_, subcription_uuri, - std::move(subcriptionCallback), priority, - std::move(subscribe_request_ttl), options); + getMockTransportClient(), getSubscriptionUUri(), + subscription_callback, priority, subscribe_request_ttl, options); // Ensure that the consumer creation was successful - ASSERT_TRUE(consumerOrSatus.has_value()); + ASSERT_TRUE(consumer_or_status.has_value()); // Obtain a pointer to the created consumer instance - auto& consumerPtr = consumerOrSatus.value(); + const auto& consumer_ptr = consumer_or_status.value(); // Verify that the consumer pointer is not null, indicating successful // creation - ASSERT_NE(consumerPtr, nullptr); + ASSERT_NE(consumer_ptr, nullptr); // Create notification source sink uri to match resource id of sink - auto notification_uuri = server_uuri; - notification_uuri.set_resource_id(0x8000); + auto notification_uuri = getServerUUri(); + notification_uuri.set_resource_id(DEFAULT_RESOURCE_ID); // set format UPAYLOAD_FORMAT_PROTOBUF_WRAPPED_IN_ANY auto format = uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_PROTOBUF_WRAPPED_IN_ANY; - auto norificationSource = uprotocol::communication::NotificationSource( - mockTransportServer_, std::move(notification_uuri), - std::move(client_uuri), format); + auto notification_source = uprotocol::communication::NotificationSource( + getMockTransportServer(), std::move(notification_uuri), + std::move(getClientUUri()), format); // Build payload const std::string data = "test"; auto payload = uprotocol::datamodel::builder::Payload(data, format); - norificationSource.notify(std::move(payload)); + notification_source.notify(std::move(payload)); // Check send count - EXPECT_TRUE(mockTransportServer_->send_count_ == 1); - EXPECT_TRUE(mockTransportClient_->send_count_ == 1); + EXPECT_TRUE(getMockTransportServer()->getSendCount() == 1); + EXPECT_TRUE(getMockTransportClient()->getSendCount() == 1); - consumerPtr->unsubscribe(priority, subscribe_request_ttl); + consumer_ptr->unsubscribe(priority, subscribe_request_ttl); - EXPECT_TRUE(mockTransportClient_->send_count_ == 2); + EXPECT_TRUE(getMockTransportClient()->getSendCount() == 2); } } // namespace diff --git a/test/coverage/communication/NotificationSinkTest.cpp b/test/coverage/communication/NotificationSinkTest.cpp index 2a545e36b..ecef04d3c 100644 --- a/test/coverage/communication/NotificationSinkTest.cpp +++ b/test/coverage/communication/NotificationSinkTest.cpp @@ -19,12 +19,18 @@ #include "UTransportMock.h" #include "up-cpp/datamodel/validator/UUri.h" -namespace { using MsgDiff = google::protobuf::util::MessageDifferencer; -using namespace uprotocol::communication; +namespace uprotocol::communication { namespace UriValidator = uprotocol::datamodel::validator::uri; class NotificationSinkTest : public testing::Test { +private: + uprotocol::v1::UUri testTopicUUri_; + uprotocol::v1::UUri testInvalidTopicUUri_; + uprotocol::v1::UUri testDefaultSourceUUri_; + size_t capture_count_ = 0; + uprotocol::v1::UMessage capture_msg_; + protected: // Run once per TEST_F. // Used to set up clean environments per test. @@ -34,7 +40,6 @@ class NotificationSinkTest : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. NotificationSinkTest() = default; - ~NotificationSinkTest() = default; void buildDefaultSourceURI(); void buildValidNotificationURI(); @@ -45,14 +50,23 @@ class NotificationSinkTest : public testing::Test { static void SetUpTestSuite() {} static void TearDownTestSuite() {} - uprotocol::v1::UUri testTopicUUri_; - uprotocol::v1::UUri testInvalidTopicUUri_; - uprotocol::v1::UUri testDefaultSourceUUri_; - size_t capture_count_ = 0; - uprotocol::v1::UMessage capture_msg_; + const uprotocol::v1::UUri& getTestTopicUUri() const { + return testTopicUUri_; + } + const uprotocol::v1::UUri& getTestInvalidTopicUUri() const { + return testInvalidTopicUUri_; + } + const uprotocol::v1::UUri& getTestDefaultSourceUUri() const { + return testDefaultSourceUUri_; + } + size_t getCaptureCount() const { return capture_count_; } + const uprotocol::v1::UMessage& getCaptureMsg() const { + return capture_msg_; + } public: void handleCallbackMessage(const uprotocol::v1::UMessage& message); + ~NotificationSinkTest() override = default; }; void NotificationSinkTest::SetUp() { @@ -62,25 +76,30 @@ void NotificationSinkTest::SetUp() { } void NotificationSinkTest::buildDefaultSourceURI() { + constexpr uint32_t DEFAULT_SOURCE_UURI_UE_ID = 0x00011102; testDefaultSourceUUri_.set_authority_name("192.168.1.10"); - testDefaultSourceUUri_.set_ue_id(0x00011102); + testDefaultSourceUUri_.set_ue_id(DEFAULT_SOURCE_UURI_UE_ID); testDefaultSourceUUri_.set_ue_version_major(0x1); testDefaultSourceUUri_.set_resource_id(0x0); } void NotificationSinkTest::buildValidNotificationURI() { + constexpr uint32_t TOPIC_UURI_UE_ID = 0x00011101; + constexpr uint32_t TOPIC_UURI_RESOURCE_ID = 0x8001; testTopicUUri_.set_authority_name("192.168.1.10"); - testTopicUUri_.set_ue_id(0x00011101); + testTopicUUri_.set_ue_id(TOPIC_UURI_UE_ID); testTopicUUri_.set_ue_version_major(0x1); - testTopicUUri_.set_resource_id(0x8001); + testTopicUUri_.set_resource_id(TOPIC_UURI_RESOURCE_ID); } void NotificationSinkTest::buildInValidNotificationURI() { + constexpr uint32_t TOPIC_UURI_UE_ID = 0x00011101; + constexpr uint32_t TOPIC_UURI_RESOURCE_ID = 0x1200; testInvalidTopicUUri_.set_authority_name("192.168.1.10"); - testInvalidTopicUUri_.set_ue_id(0x00011101); + testInvalidTopicUUri_.set_ue_id(TOPIC_UURI_UE_ID); testInvalidTopicUUri_.set_ue_version_major(0x1); // Resource ID should be in the range of 0x8000 to 0xFFFF - testInvalidTopicUUri_.set_resource_id(0x1200); + testInvalidTopicUUri_.set_resource_id(TOPIC_UURI_RESOURCE_ID); } void NotificationSinkTest::handleCallbackMessage( @@ -91,12 +110,16 @@ void NotificationSinkTest::handleCallbackMessage( std::string get_random_string(size_t length) { auto randchar = []() -> char { - const char charset[] = - "0123456789" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz"; - const size_t max_index = (sizeof(charset) - 1); - return charset[rand() % max_index]; + constexpr std::array CHARSET = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', + 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', + 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', + 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; + std::random_device rd; + std::mt19937 gen(rd()); + std::uniform_int_distribution<> distr(0, CHARSET.size() - 1); + return CHARSET.at(static_cast(distr(gen))); }; std::string str(length, 0); std::generate_n(str.begin(), length, randchar); @@ -104,9 +127,9 @@ std::string get_random_string(size_t length) { } // Negative test case with no source filter -TEST_F(NotificationSinkTest, FailWithoutSourceFilter) { +TEST_F(NotificationSinkTest, FailWithoutSourceFilter) { // NOLINT auto transport = std::make_shared( - testDefaultSourceUUri_); + getTestDefaultSourceUUri()); auto callback = [this](const auto& arg) { return this->handleCallbackMessage(arg); @@ -114,19 +137,19 @@ TEST_F(NotificationSinkTest, FailWithoutSourceFilter) { std::optional source_filter; - EXPECT_THROW( + EXPECT_THROW( // NOLINT { - auto result = NotificationSink::create(transport, testTopicUUri_, - std::move(callback), - std::move(source_filter)); + auto result = NotificationSink::create( + transport, getTestTopicUUri(), std::move(callback), + std::move(source_filter)); }, UriValidator::InvalidUUri); } // Negative test case with invalid notification resource ID -TEST_F(NotificationSinkTest, FailWithInvalidResourceID) { +TEST_F(NotificationSinkTest, FailWithInvalidResourceID) { // NOLINT auto transport = std::make_shared( - testDefaultSourceUUri_); + getTestDefaultSourceUUri()); auto callback = [this](const auto& arg) { return this->handleCallbackMessage(arg); @@ -135,67 +158,71 @@ TEST_F(NotificationSinkTest, FailWithInvalidResourceID) { std::optional source_filter; // Notification to invalid UUri topic with resource ID not in correct range - EXPECT_THROW(auto result = NotificationSink::create( - transport, testInvalidTopicUUri_, std::move(callback), + EXPECT_THROW(auto result = NotificationSink::create( // NOLINT + transport, getTestInvalidTopicUUri(), std::move(callback), std::move(source_filter)), UriValidator::InvalidUUri); } // Positive test case with source filter -TEST_F(NotificationSinkTest, SuccessWithSourceFilter) { +TEST_F(NotificationSinkTest, SuccessWithSourceFilter) { // NOLINT + constexpr uint16_t RANDOM_STRING_LENGTH = 1400; auto transport = std::make_shared( - testDefaultSourceUUri_); + getTestDefaultSourceUUri()); auto callback = [this](const auto& arg) { return this->handleCallbackMessage(arg); }; - auto result = NotificationSink::create(transport, transport->getEntityUri(), - std::move(callback), testTopicUUri_); + auto result = + NotificationSink::create(transport, transport->getEntityUri(), + std::move(callback), getTestTopicUUri()); - EXPECT_TRUE(transport->listener_); + EXPECT_TRUE(transport->getListener()); EXPECT_TRUE(result.has_value()); auto handle = std::move(result).value(); EXPECT_TRUE(handle); - EXPECT_TRUE(MsgDiff::Equals(testTopicUUri_, transport->source_filter_)); EXPECT_TRUE( - MsgDiff::Equals(transport->getEntityUri(), *transport->sink_filter_)); + MsgDiff::Equals(getTestTopicUUri(), transport->getSourceFilter())); + EXPECT_TRUE(MsgDiff::Equals(transport->getEntityUri(), + *transport->getSinkFilter())); const size_t max_count = 100; for (size_t i = 0; i < max_count; i++) { uprotocol::v1::UMessage msg; auto attr = std::make_shared(); *msg.mutable_attributes() = *attr; - msg.set_payload(get_random_string(1400)); + msg.set_payload(get_random_string(RANDOM_STRING_LENGTH)); transport->mockMessage(msg); - EXPECT_EQ(i + 1, capture_count_); - EXPECT_TRUE(MsgDiff::Equals(msg, capture_msg_)); + EXPECT_EQ(i + 1, getCaptureCount()); + EXPECT_TRUE(MsgDiff::Equals(msg, getCaptureMsg())); } } // Simulate Error code from transport mock -TEST_F(NotificationSinkTest, FailWithErrorCode) { +TEST_F(NotificationSinkTest, FailWithErrorCode) { // NOLINT auto transport = std::make_shared( - testDefaultSourceUUri_); + getTestDefaultSourceUUri()); auto callback = [this](const auto& arg) { return this->handleCallbackMessage(arg); }; - uprotocol::v1::UStatus expectedStatus; - expectedStatus.set_code(uprotocol::v1::UCode::ABORTED); - transport->registerListener_status_ = expectedStatus; + uprotocol::v1::UStatus expected_status; + expected_status.set_code(uprotocol::v1::UCode::ABORTED); + transport->getRegisterListenerStatus() = expected_status; - auto result = NotificationSink::create(transport, transport->getEntityUri(), - std::move(callback), testTopicUUri_); + auto result = + NotificationSink::create(transport, transport->getEntityUri(), + std::move(callback), getTestTopicUUri()); - auto actualStatus = std::move(result).error(); - EXPECT_EQ(actualStatus.code(), expectedStatus.code()); + auto actual_status = std::move(result).error(); + EXPECT_EQ(actual_status.code(), expected_status.code()); } // Notification sink with null transport -TEST_F(NotificationSinkTest, NullTransport) { +TEST_F(NotificationSinkTest, NullTransport) { // NOLINT // set transport to null auto transport = nullptr; std::optional source_filter; @@ -204,35 +231,34 @@ TEST_F(NotificationSinkTest, NullTransport) { return this->handleCallbackMessage(arg); }; - EXPECT_THROW(auto result = NotificationSink::create( - transport, testDefaultSourceUUri_, std::move(callback), - testTopicUUri_), + EXPECT_THROW(auto result = NotificationSink::create( // NOLINT + transport, getTestDefaultSourceUUri(), std::move(callback), + getTestTopicUUri()), uprotocol::transport::NullTransport); } // notification sink with null callback -TEST_F(NotificationSinkTest, NullCallback) { +TEST_F(NotificationSinkTest, NullCallback) { // NOLINT auto transport = std::make_shared( - testDefaultSourceUUri_); + getTestDefaultSourceUUri()); // bind to null callback auto test_create_nullptr = [transport, this]() { - std::ignore = - NotificationSink::create(transport, transport->getEntityUri(), - std::move(nullptr), testTopicUUri_); + std::ignore = NotificationSink::create( + transport, transport->getEntityUri(), nullptr, getTestTopicUUri()); }; - using namespace uprotocol::utils; - - EXPECT_THROW(test_create_nullptr(), callbacks::EmptyFunctionObject); + EXPECT_THROW(test_create_nullptr(), // NOLINT + utils::callbacks::EmptyFunctionObject); // Default construct a function object auto test_create_empty = [transport, this]() { std::ignore = NotificationSink::create( - transport, transport->getEntityUri(), {}, testTopicUUri_); + transport, transport->getEntityUri(), {}, getTestTopicUUri()); }; - EXPECT_THROW(test_create_empty(), callbacks::EmptyFunctionObject); + EXPECT_THROW(test_create_empty(), // NOLINT + utils::callbacks::EmptyFunctionObject); } -} // namespace +} // namespace uprotocol::communication diff --git a/test/coverage/communication/NotificationSourceTest.cpp b/test/coverage/communication/NotificationSourceTest.cpp index 1463876ef..724ac9e74 100644 --- a/test/coverage/communication/NotificationSourceTest.cpp +++ b/test/coverage/communication/NotificationSourceTest.cpp @@ -16,183 +16,198 @@ #include #include "UTransportMock.h" -#include "up-cpp/datamodel/builder/UMessage.h" #include "up-cpp/datamodel/validator/UMessage.h" #include "up-cpp/transport/UTransport.h" -using namespace uprotocol::communication; -using namespace uprotocol::datamodel::builder; -using namespace uprotocol::v1; -using ::testing::_; -using ::testing::Return; - -namespace { +namespace uprotocol::communication { class TestNotificationSource : public testing::Test { +private: + std::shared_ptr transportMock_; + uprotocol::v1::UUri source_; + uprotocol::v1::UUri sink_; + uprotocol::v1::UPayloadFormat format_ = + uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT; + std::optional priority_; + std::optional ttl_; + protected: // Run once per TEST_F. // Used to set up clean environments per test. void SetUp() override { + constexpr uint32_t DEFAULT_UE_ID = 0x00011101; + constexpr uint32_t DEFAULT_RESOURCE_ID = 0x8101; + constexpr uint32_t SOURCE_VERSION_MAJOR = 0xF1; + constexpr uint32_t TOPIC_VERSION_MAJOR = 0xF8; + constexpr uint16_t DEFAULT_TTL_TIME = 1000; + source_.set_authority_name("10.0.0.1"); - source_.set_ue_id(0x00011101); - source_.set_ue_version_major(0xF1); + source_.set_ue_id(DEFAULT_UE_ID); + source_.set_ue_version_major(SOURCE_VERSION_MAJOR); source_.set_resource_id(0x0); sink_.set_authority_name("10.0.0.1"); - sink_.set_ue_id(0x00011101); - sink_.set_ue_version_major(0xF8); - sink_.set_resource_id(0x8101); + sink_.set_ue_id(DEFAULT_UE_ID); + sink_.set_ue_version_major(TOPIC_VERSION_MAJOR); + sink_.set_resource_id(DEFAULT_RESOURCE_ID); transportMock_ = std::make_shared(source_); - source_.set_resource_id(0x8101); + source_.set_resource_id(DEFAULT_RESOURCE_ID); sink_.set_resource_id(0x0); - - format_ = UPayloadFormat::UPAYLOAD_FORMAT_TEXT; - priority_ = UPriority::UPRIORITY_CS1; - ttl_ = std::chrono::milliseconds(1000); + priority_ = uprotocol::v1::UPriority::UPRIORITY_CS1; + ttl_ = std::chrono::milliseconds(DEFAULT_TTL_TIME); } void TearDown() override {} // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. TestNotificationSource() = default; - ~TestNotificationSource() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} - std::shared_ptr transportMock_; - UUri source_; - UUri sink_; - UPayloadFormat format_; - std::optional priority_; - std::optional ttl_; + std::shared_ptr getTransportMock() const { + return transportMock_; + } + uprotocol::v1::UUri getSource() const { return source_; } + uprotocol::v1::UUri getSink() const { return sink_; } + uprotocol::v1::UPayloadFormat getFormat() const { return format_; } + std::optional& getPriority() { return priority_; } + std::optional getTTL() const { return ttl_; } + +public: + ~TestNotificationSource() override = default; }; -TEST_F(TestNotificationSource, NotifyWithPayloadSuccess) { - std::string testPayloadStr = "test_payload"; - NotificationSource notificationSource(transportMock_, std::move(source_), - std::move(sink_), format_, priority_, - ttl_); - Payload testPayload(testPayloadStr, format_); +TEST_F(TestNotificationSource, NotifyWithPayloadSuccess) { // NOLINT + std::string test_payload_str = "test_payload"; + NotificationSource notification_source(getTransportMock(), getSource(), + getSink(), getFormat(), + getPriority(), getTTL()); + uprotocol::datamodel::builder::Payload test_payload(test_payload_str, + getFormat()); uprotocol::v1::UStatus retval; retval.set_code(uprotocol::v1::UCode::OK); - transportMock_->send_status_ = retval; + getTransportMock()->getSendStatus() = retval; - auto status = notificationSource.notify(std::move(testPayload)); + auto status = notification_source.notify(std::move(test_payload)); EXPECT_EQ(status.code(), retval.code()); auto [valid, reason] = uprotocol::datamodel::validator::message::isValidNotification( - transportMock_->message_); + getTransportMock()->getMessage()); EXPECT_EQ(valid, true); } -TEST_F(TestNotificationSource, NotifyWithPayloadSuccessWithoutTTL) { - std::string testPayloadStr = "test_payload"; - NotificationSource notificationSource(transportMock_, std::move(source_), - std::move(sink_), format_, priority_); - Payload testPayload(testPayloadStr, format_); +TEST_F(TestNotificationSource, NotifyWithPayloadSuccessWithoutTTL) { // NOLINT + std::string test_payload_str = "test_payload"; + NotificationSource notification_source( + getTransportMock(), getSource(), getSink(), getFormat(), getPriority()); + uprotocol::datamodel::builder::Payload test_payload(test_payload_str, + getFormat()); uprotocol::v1::UStatus retval; retval.set_code(uprotocol::v1::UCode::OK); - transportMock_->send_status_ = retval; + getTransportMock()->getSendStatus() = retval; - auto status = notificationSource.notify(std::move(testPayload)); + auto status = notification_source.notify(std::move(test_payload)); EXPECT_EQ(status.code(), retval.code()); auto [valid, reason] = uprotocol::datamodel::validator::message::isValidNotification( - transportMock_->message_); + getTransportMock()->getMessage()); EXPECT_EQ(valid, true); - EXPECT_EQ(transportMock_->message_.attributes().ttl(), 0); + EXPECT_EQ(getTransportMock()->getMessage().attributes().ttl(), 0); } -TEST_F(TestNotificationSource, NotifyWithPayloadSuccessWithoutPriority) { - std::string testPayloadStr = "test_payload"; - priority_.reset(); - NotificationSource notificationSource(transportMock_, std::move(source_), - std::move(sink_), format_, priority_); - Payload testPayload(testPayloadStr, format_); +TEST_F(TestNotificationSource, // NOLINT + NotifyWithPayloadSuccessWithoutPriority) { + std::string test_payload_str = "test_payload"; + getPriority().reset(); + NotificationSource notification_source( + getTransportMock(), getSource(), getSink(), getFormat(), getPriority()); + uprotocol::datamodel::builder::Payload test_payload(test_payload_str, + getFormat()); uprotocol::v1::UStatus retval; retval.set_code(uprotocol::v1::UCode::OK); - transportMock_->send_status_ = retval; + getTransportMock()->getSendStatus() = retval; - auto status = notificationSource.notify(std::move(testPayload)); + auto status = notification_source.notify(std::move(test_payload)); EXPECT_EQ(status.code(), retval.code()); auto [valid, reason] = uprotocol::datamodel::validator::message::isValidNotification( - transportMock_->message_); + getTransportMock()->getMessage()); EXPECT_EQ(valid, true); - EXPECT_EQ(transportMock_->message_.attributes().priority(), - UPriority::UPRIORITY_CS1); + EXPECT_EQ(getTransportMock()->getMessage().attributes().priority(), + uprotocol::v1::UPriority::UPRIORITY_CS1); } -TEST_F(TestNotificationSource, NotifyWithPayloadFailure) { - std::string testPayloadStr = "test_payload"; - NotificationSource notificationSource(transportMock_, std::move(source_), - std::move(sink_), format_, priority_, - ttl_); - Payload testPayload(testPayloadStr, format_); +TEST_F(TestNotificationSource, NotifyWithPayloadFailure) { // NOLINT + std::string test_payload_str = "test_payload"; + NotificationSource notification_source(getTransportMock(), getSource(), + getSink(), getFormat(), + getPriority(), getTTL()); + uprotocol::datamodel::builder::Payload test_payload(test_payload_str, + getFormat()); uprotocol::v1::UStatus retval; retval.set_code(uprotocol::v1::UCode::DATA_LOSS); - transportMock_->send_status_ = retval; + getTransportMock()->getSendStatus() = retval; - auto status = notificationSource.notify(std::move(testPayload)); + auto status = notification_source.notify(std::move(test_payload)); EXPECT_EQ(status.code(), retval.code()); } -TEST_F(TestNotificationSource, NotifyWithoutPayloadSuccess) { - NotificationSource notificationSource(transportMock_, std::move(source_), - std::move(sink_)); +TEST_F(TestNotificationSource, NotifyWithoutPayloadSuccess) { // NOLINT + NotificationSource notification_source(getTransportMock(), getSource(), + getSink()); uprotocol::v1::UStatus retval; retval.set_code(uprotocol::v1::UCode::OK); - transportMock_->send_status_ = retval; + getTransportMock()->getSendStatus() = retval; - auto status = notificationSource.notify(); + auto status = notification_source.notify(); EXPECT_EQ(status.code(), retval.code()); - EXPECT_EQ(transportMock_->message_.attributes().ttl(), 0); - EXPECT_EQ(transportMock_->message_.attributes().priority(), - UPriority::UPRIORITY_CS1); + EXPECT_EQ(getTransportMock()->getMessage().attributes().ttl(), 0); + EXPECT_EQ(getTransportMock()->getMessage().attributes().priority(), + uprotocol::v1::UPriority::UPRIORITY_CS1); } -TEST_F(TestNotificationSource, NotifyWithoutPayloadFailure) { - NotificationSource notificationSource(transportMock_, std::move(source_), - std::move(sink_)); +TEST_F(TestNotificationSource, NotifyWithoutPayloadFailure) { // NOLINT + NotificationSource notification_source(getTransportMock(), getSource(), + getSink()); uprotocol::v1::UStatus retval; retval.set_code(uprotocol::v1::UCode::DATA_LOSS); - transportMock_->send_status_ = retval; + getTransportMock()->getSendStatus() = retval; - auto status = notificationSource.notify(); + auto status = notification_source.notify(); EXPECT_EQ(status.code(), retval.code()); } // Test with Null transport -TEST_F(TestNotificationSource, NullTransport) { +TEST_F(TestNotificationSource, NullTransport) { // NOLINT auto transport = nullptr; - EXPECT_THROW(NotificationSource notificationSource( - transport, std::move(source_), std::move(sink_), format_, - priority_, ttl_), + EXPECT_THROW(NotificationSource notification_source( // NOLINT + transport, getSource(), getSink(), getFormat(), + getPriority(), getTTL()), uprotocol::transport::NullTransport); } -} // namespace +} // namespace uprotocol::communication diff --git a/test/coverage/communication/PublisherTest.cpp b/test/coverage/communication/PublisherTest.cpp index cea1943ff..fb350f52c 100644 --- a/test/coverage/communication/PublisherTest.cpp +++ b/test/coverage/communication/PublisherTest.cpp @@ -16,32 +16,52 @@ #include "UTransportMock.h" -using namespace uprotocol::communication; -using namespace uprotocol; - -namespace { -using namespace uprotocol::datamodel::builder; +namespace uprotocol { class TestPublisher : public testing::Test { +private: + std::shared_ptr transportMock_; + v1::UUri source_; + v1::UUri topic_; + v1::UPayloadFormat format_ = v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT; + std::optional priority_; + std::optional ttl_; + uprotocol::v1::UMessage capture_msg_; + protected: + std::shared_ptr getTransportMock() const { + return transportMock_; + } + v1::UUri getSource() const { return source_; } + v1::UUri getTopic() const { return topic_; } + v1::UPayloadFormat getFormat() const { return format_; } + std::optional& getPriority() { return priority_; } + std::optional getTTL() const { return ttl_; } + uprotocol::v1::UMessage getCaptureMsg() const { return capture_msg_; } + // Run once per TEST_F. // Used to set up clean environments per test. void SetUp() override { + constexpr uint32_t DEFAULT_UE_ID = 0x00011101; + constexpr uint32_t DEFAULT_RESOURCE_ID = 0x8101; + constexpr uint32_t SOURCE_VERSION_MAJOR = 0xF1; + constexpr uint32_t TOPIC_VERSION_MAJOR = 0xF8; + constexpr uint16_t DEFAULT_TTL_TIME = 1000; + source_.set_authority_name("10.0.0.1"); - source_.set_ue_id(0x00011101); - source_.set_ue_version_major(0xF1); + source_.set_ue_id(DEFAULT_UE_ID); + source_.set_ue_version_major(SOURCE_VERSION_MAJOR); source_.set_resource_id(0x0); topic_.set_authority_name("10.0.0.1"); - topic_.set_ue_id(0x00011101); - topic_.set_ue_version_major(0xF8); - topic_.set_resource_id(0x8101); + topic_.set_ue_id(DEFAULT_UE_ID); + topic_.set_ue_version_major(TOPIC_VERSION_MAJOR); + topic_.set_resource_id(DEFAULT_RESOURCE_ID); transportMock_ = std::make_shared(source_); - format_ = v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT; priority_ = v1::UPriority::UPRIORITY_CS2; - ttl_ = std::chrono::milliseconds(1000); + ttl_ = std::chrono::milliseconds(DEFAULT_TTL_TIME); } void TearDown() override {} @@ -49,108 +69,104 @@ class TestPublisher : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. TestPublisher() = default; - ~TestPublisher() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} - std::shared_ptr transportMock_; - v1::UUri source_; - v1::UUri topic_; - v1::UPayloadFormat format_; - std::optional priority_; - std::optional ttl_; - uprotocol::v1::UMessage capture_msg_; +public: + ~TestPublisher() override = default; }; -TEST_F(TestPublisher, PublisherSuccess) { - std::string testPayloadStr = "test_payload"; - Publisher publisher(transportMock_, std::move(topic_), format_, priority_, - ttl_); +TEST_F(TestPublisher, PublisherSuccess) { // NOLINT + std::string test_payload_str = "test_payload"; + communication::Publisher publisher(getTransportMock(), getTopic(), + getFormat(), getPriority(), getTTL()); uprotocol::v1::UStatus retval; retval.set_code(uprotocol::v1::UCode::OK); - transportMock_->send_status_ = retval; + getTransportMock()->getSendStatus() = retval; - Payload testPayload(testPayloadStr, format_); - auto status = publisher.publish(std::move(testPayload)); + datamodel::builder::Payload test_payload(test_payload_str, getFormat()); + auto status = publisher.publish(std::move(test_payload)); EXPECT_EQ(status.code(), retval.code()); auto [valid, reason] = uprotocol::datamodel::validator::message::isValidPublish( - transportMock_->message_); + getTransportMock()->getMessage()); EXPECT_EQ(valid, true); } -TEST_F(TestPublisher, PublishFailure) { - std::string testPayloadStr = "test_payload"; - Publisher publisher(transportMock_, std::move(topic_), format_, priority_, - ttl_); +TEST_F(TestPublisher, PublishFailure) { // NOLINT + std::string test_payload_str = "test_payload"; + communication::Publisher publisher(getTransportMock(), getTopic(), + getFormat(), getPriority(), getTTL()); uprotocol::v1::UStatus retval; retval.set_code(uprotocol::v1::UCode::DATA_LOSS); - transportMock_->send_status_ = retval; + getTransportMock()->getSendStatus() = retval; - Payload testPayload(testPayloadStr, format_); - auto status = publisher.publish(std::move(testPayload)); + datamodel::builder::Payload test_payload(test_payload_str, getFormat()); + auto status = publisher.publish(std::move(test_payload)); EXPECT_EQ(status.code(), retval.code()); } -TEST_F(TestPublisher, PublishSuccessWithoutTTL) { - std::string testPayloadStr = "test_payload"; - Publisher publisher(transportMock_, std::move(topic_), format_, priority_); +TEST_F(TestPublisher, PublishSuccessWithoutTTL) { // NOLINT + std::string test_payload_str = "test_payload"; + communication::Publisher publisher(getTransportMock(), getTopic(), + getFormat(), getPriority()); uprotocol::v1::UStatus retval; retval.set_code(uprotocol::v1::UCode::OK); - transportMock_->send_status_ = retval; + getTransportMock()->getSendStatus() = retval; - Payload testPayload(testPayloadStr, format_); - auto status = publisher.publish(std::move(testPayload)); + datamodel::builder::Payload test_payload(test_payload_str, getFormat()); + auto status = publisher.publish(std::move(test_payload)); EXPECT_EQ(status.code(), retval.code()); auto [valid, reason] = uprotocol::datamodel::validator::message::isValidPublish( - transportMock_->message_); + getTransportMock()->getMessage()); EXPECT_EQ(valid, true); - EXPECT_EQ(transportMock_->message_.attributes().ttl(), 0); + EXPECT_EQ(getTransportMock()->getMessage().attributes().ttl(), 0); } -TEST_F(TestPublisher, PublishSuccessWithoutPriority) { - std::string testPayloadStr = "test_payload"; - priority_.reset(); - Publisher publisher(transportMock_, std::move(topic_), format_, priority_, - ttl_); +TEST_F(TestPublisher, PublishSuccessWithoutPriority) { // NOLINT + std::string test_payload_str = "test_payload"; + getPriority().reset(); + communication::Publisher publisher(getTransportMock(), getTopic(), + getFormat(), getPriority(), getTTL()); uprotocol::v1::UStatus retval; retval.set_code(uprotocol::v1::UCode::OK); - transportMock_->send_status_ = retval; + getTransportMock()->getSendStatus() = retval; - Payload testPayload(testPayloadStr, format_); - auto status = publisher.publish(std::move(testPayload)); + datamodel::builder::Payload test_payload(test_payload_str, getFormat()); + auto status = publisher.publish(std::move(test_payload)); EXPECT_EQ(status.code(), retval.code()); auto [valid, reason] = uprotocol::datamodel::validator::message::isValidPublish( - transportMock_->message_); + getTransportMock()->getMessage()); EXPECT_EQ(valid, true); - EXPECT_EQ(transportMock_->message_.attributes().priority(), + EXPECT_EQ(getTransportMock()->getMessage().attributes().priority(), v1::UPriority::UPRIORITY_CS1); } // publisher with null transport -TEST_F(TestPublisher, PublisherWithNullTransport) { +TEST_F(TestPublisher, PublisherWithNullTransport) { // NOLINT auto transport = nullptr; - EXPECT_THROW(Publisher publisher(transport, std::move(topic_), format_, - priority_, ttl_), - uprotocol::transport::NullTransport); + EXPECT_THROW( // NOLINT + communication::Publisher publisher(transport, getTopic(), getFormat(), + getPriority(), getTTL()), + uprotocol::transport::NullTransport); } -} // namespace +} // namespace uprotocol diff --git a/test/coverage/communication/RpcClientTest.cpp b/test/coverage/communication/RpcClientTest.cpp index f45f3596c..4429bc41a 100644 --- a/test/coverage/communication/RpcClientTest.cpp +++ b/test/coverage/communication/RpcClientTest.cpp @@ -23,34 +23,34 @@ #include "UTransportMock.h" -using namespace std::chrono_literals; +constexpr std::chrono::milliseconds ZERO_MILLISECONDS(0); +constexpr std::chrono::milliseconds TEN_MILLISECONDS(10); +constexpr std::chrono::milliseconds ONE_HUNDRED_FIFTY_MILLISECONDS(150); +constexpr uint32_t SHIFT_AMOUNT = 16; -namespace { +namespace uprotocol { -bool operator==(const uprotocol::v1::UUri& lhs, - const uprotocol::v1::UUri& rhs) { - using namespace google::protobuf::util; - return MessageDifferencer::Equals(lhs, rhs); +bool operator==(const v1::UUri& lhs, const v1::UUri& rhs) { + return google::protobuf::util::MessageDifferencer::Equals(lhs, rhs); } -bool operator==(const uprotocol::v1::UMessage& lhs, - const uprotocol::v1::UMessage& rhs) { - using namespace google::protobuf::util; - return MessageDifferencer::Equals(lhs, rhs); +bool operator==(const v1::UMessage& lhs, const v1::UMessage& rhs) { + return google::protobuf::util::MessageDifferencer::Equals(lhs, rhs); } -bool operator==(const uprotocol::v1::UStatus& lhs, - const uprotocol::v1::UCode& rhs) { +bool operator==(const v1::UStatus& lhs, const v1::UCode& rhs) { return lhs.code() == rhs; } class RpcClientTest : public testing::Test { +private: + std::shared_ptr transport_; + protected: // Run once per TEST_F. // Used to set up clean environments per test. void SetUp() override { - transport_ = std::make_shared( - defaultSourceUri()); + transport_ = std::make_shared(defaultSourceUri()); } void TearDown() override {} @@ -58,7 +58,6 @@ class RpcClientTest : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. RpcClientTest() = default; - ~RpcClientTest() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. @@ -70,138 +69,160 @@ class RpcClientTest : public testing::Test { google::protobuf::ShutdownProtobufLibrary(); } - static uprotocol::v1::UUri methodUri(const std::string& auth = "TestAuth", - uint16_t ue_id = 0x8000, - uint16_t ue_instance = 1, - uint16_t ue_version_major = 1, - uint16_t resource_id = 1) { - uprotocol::v1::UUri uri; + static v1::UUri methodUri(const std::string& auth = "TestAuth", + uint16_t ue_id = 0x8000, + uint16_t ue_instance = 1, // NOLINT + uint16_t ue_version_major = 1, + uint16_t resource_id = 1) { + v1::UUri uri; uri.set_authority_name(auth); - uri.set_ue_id(static_cast(ue_instance) << 16 | + uri.set_ue_id(static_cast(ue_instance) << SHIFT_AMOUNT | static_cast(ue_id)); uri.set_ue_version_major(ue_version_major); uri.set_resource_id(resource_id); return uri; } - static uprotocol::v1::UUri defaultSourceUri() { + static v1::UUri defaultSourceUri() { auto uri = methodUri(); uri.set_resource_id(0); return uri; } void validateLastRequest(size_t expected_send_count) { - EXPECT_TRUE(transport_->listener_); - EXPECT_TRUE(transport_->source_filter_ == methodUri()); - EXPECT_TRUE(transport_->sink_filter_); - if (transport_->sink_filter_) { - EXPECT_TRUE(*(transport_->sink_filter_) == defaultSourceUri()); + validateTransportProperties(); + validateFilters(); + validateSendCount(expected_send_count); + validateMessage(); + } + + void validateTransportProperties() const { + EXPECT_TRUE(transport_->getListener()); + } + + void validateFilters() const { + EXPECT_TRUE(transport_->getSourceFilter() == methodUri()); + EXPECT_TRUE(transport_->getSinkFilter()); + if (transport_->getSinkFilter()) { + EXPECT_TRUE(*(transport_->getSinkFilter()) == defaultSourceUri()); } - EXPECT_EQ(transport_->send_count_, expected_send_count); - using namespace uprotocol::datamodel::validator; + } + + void validateSendCount(size_t expected_send_count) const { + EXPECT_EQ(transport_->getSendCount(), expected_send_count); + } + + void validateMessage() const { auto [valid_request, _] = - message::isValidRpcRequest(transport_->message_); + datamodel::validator::message::isValidRpcRequest( + transport_->getMessage()); EXPECT_TRUE(valid_request); } - std::shared_ptr transport_; + [[nodiscard]] std::shared_ptr getTransport() const { + return transport_; + } + +public: + ~RpcClientTest() override = default; }; template void checkErrorResponse( - const uprotocol::communication::RpcClient::MessageOrStatus& maybe_response, + const communication::RpcClient::MessageOrStatus& maybe_response, ExpectedT expected_status) { EXPECT_FALSE(maybe_response); if (!maybe_response) { - auto& status = maybe_response.error(); + const auto& status = maybe_response.error(); EXPECT_TRUE(status == expected_status); } } -uprotocol::datamodel::builder::Payload fakePayload() { - using namespace uprotocol::datamodel; - - auto uuid = builder::UuidBuilder::getBuilder(); - auto uuid_str = serializer::uuid::AsString::serialize(uuid.build()); +datamodel::builder::Payload fakePayload() { + auto uuid = datamodel::builder::UuidBuilder::getBuilder(); + auto uuid_str = + datamodel::serializer::uuid::AsString::serialize(uuid.build()); - return builder::Payload( - std::move(uuid_str), - uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT); + return {std::move(uuid_str), v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT}; } /////////////////////////////////////////////////////////////////////////////// // Construction -TEST_F(RpcClientTest, CanConstructWithoutExceptions) { +TEST_F(RpcClientTest, CanConstructWithoutExceptions) { // NOLINT // Base parameters - EXPECT_NO_THROW(auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), - uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms);); + EXPECT_NO_THROW(auto client = communication::RpcClient( // NOLINT + getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, TEN_MILLISECONDS);); // Optional format - EXPECT_NO_THROW(auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), - uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms, - uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_JSON);); + EXPECT_NO_THROW(auto client = communication::RpcClient( // NOLINT + getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, TEN_MILLISECONDS, + v1::UPayloadFormat::UPAYLOAD_FORMAT_JSON);); // Optional permission level - EXPECT_NO_THROW(auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), - uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms, {}, 9);); + EXPECT_NO_THROW(auto client = communication::RpcClient( // NOLINT + getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, TEN_MILLISECONDS, {}, + 9);); // Optional permission level - EXPECT_NO_THROW(auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), - uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms, {}, {}, + EXPECT_NO_THROW(auto client = communication::RpcClient( // NOLINT + getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, TEN_MILLISECONDS, {}, {}, "Some token");); } -TEST_F(RpcClientTest, ExceptionThrownWithInvalidConstructorArguments) { +TEST_F(RpcClientTest, // NOLINT + ExceptionThrownWithInvalidConstructorArguments) { // Bad method URI - EXPECT_THROW(auto uri = methodUri(); uri.set_resource_id(0); - auto client = uprotocol::communication::RpcClient( - transport_, std::move(uri), - uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); - , uprotocol::datamodel::validator::uri::InvalidUUri); + EXPECT_THROW(auto uri = methodUri(); uri.set_resource_id(0); // NOLINT + auto client = communication::RpcClient( + getTransport(), std::move(uri), + v1::UPriority::UPRIORITY_CS4, TEN_MILLISECONDS); + , datamodel::validator::uri::InvalidUUri); // Bad priority - EXPECT_THROW(auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), - uprotocol::v1::UPriority::UPRIORITY_CS3, 10ms); + EXPECT_THROW(auto client = communication::RpcClient( // NOLINT + getTransport(), methodUri(), v1::UPriority::UPRIORITY_CS3, + TEN_MILLISECONDS); , std::out_of_range); // Bad ttl - EXPECT_THROW(auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), - uprotocol::v1::UPriority::UPRIORITY_CS4, 0ms); + EXPECT_THROW(auto client = communication::RpcClient( // NOLINT + getTransport(), methodUri(), v1::UPriority::UPRIORITY_CS4, + ZERO_MILLISECONDS); , std::out_of_range); // Bad payload format - EXPECT_THROW( - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, - 10ms, static_cast(-1)); + EXPECT_THROW( // NOLINT + auto client = communication::RpcClient( + getTransport(), methodUri(), v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS, static_cast(-1)); , std::out_of_range); } /////////////////////////////////////////////////////////////////////////////// // RpcClient::invokeMethod() -TEST_F(RpcClientTest, InvokeFutureWithoutPayload) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); +TEST_F(RpcClientTest, InvokeFutureWithoutPayload) { // NOLINT + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); decltype(client.invokeMethod()) invoke_future; - EXPECT_NO_THROW(invoke_future = client.invokeMethod()); + EXPECT_NO_THROW(invoke_future = client.invokeMethod()); // NOLINT EXPECT_TRUE(invoke_future.valid()); validateLastRequest(1); - EXPECT_TRUE(transport_->message_.payload().empty()); + EXPECT_TRUE(getTransport()->getMessage().payload().empty()); - using UMessageBuilder = uprotocol::datamodel::builder::UMessageBuilder; - auto response_builder = UMessageBuilder::response(transport_->message_); + using UMessageBuilder = datamodel::builder::UMessageBuilder; + auto response_builder = + UMessageBuilder::response(getTransport()->getMessage()); auto response = response_builder.build(); - EXPECT_NO_THROW(transport_->mockMessage(response)); + EXPECT_NO_THROW(getTransport()->mockMessage(response)); // NOLINT - auto is_ready = invoke_future.wait_for(0ms); + auto is_ready = invoke_future.wait_for(ZERO_MILLISECONDS); EXPECT_EQ(is_ready, std::future_status::ready); if (is_ready == std::future_status::ready) { @@ -211,157 +232,160 @@ TEST_F(RpcClientTest, InvokeFutureWithoutPayload) { } } -TEST_F(RpcClientTest, InvokeFutureWithoutPayloadAndFormatSet) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms, - uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_SOMEIP); +TEST_F(RpcClientTest, InvokeFutureWithoutPayloadAndFormatSet) { // NOLINT + auto client = communication::RpcClient( + getTransport(), methodUri(), v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS, v1::UPayloadFormat::UPAYLOAD_FORMAT_SOMEIP); - EXPECT_THROW( + EXPECT_THROW( // NOLINT auto invoke_future = client.invokeMethod(), - uprotocol::datamodel::builder::UMessageBuilder::UnexpectedFormat); + datamodel::builder::UMessageBuilder::UnexpectedFormat); - EXPECT_EQ(transport_->send_count_, 0); - EXPECT_FALSE(transport_->listener_); + EXPECT_EQ(getTransport()->getSendCount(), 0); + EXPECT_FALSE(getTransport()->getListener()); } -TEST_F(RpcClientTest, InvokeFutureWithoutPayloadTimeout) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); +TEST_F(RpcClientTest, InvokeFutureWithoutPayloadTimeout) { // NOLINT + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); decltype(client.invokeMethod()) invoke_future; auto when_requested = std::chrono::steady_clock::now(); - EXPECT_NO_THROW(invoke_future = client.invokeMethod()); + EXPECT_NO_THROW(invoke_future = client.invokeMethod()); // NOLINT EXPECT_TRUE(invoke_future.valid()); - auto is_ready = invoke_future.wait_for(150ms); + auto is_ready = invoke_future.wait_for(ONE_HUNDRED_FIFTY_MILLISECONDS); auto when_expired = std::chrono::steady_clock::now(); - EXPECT_GE((when_expired - when_requested), 10ms); - EXPECT_LE((when_expired - when_requested), 2 * 10ms); + EXPECT_GE((when_expired - when_requested), TEN_MILLISECONDS); + EXPECT_LE((when_expired - when_requested), 2 * TEN_MILLISECONDS); EXPECT_EQ(is_ready, std::future_status::ready); if (is_ready == std::future_status::ready) { auto maybe_response = invoke_future.get(); - checkErrorResponse(maybe_response, - uprotocol::v1::UCode::DEADLINE_EXCEEDED); + checkErrorResponse(maybe_response, v1::UCode::DEADLINE_EXCEEDED); } } -TEST_F(RpcClientTest, InvokeFutureWithoutPayloadListenFail) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); +TEST_F(RpcClientTest, InvokeFutureWithoutPayloadListenFail) { // NOLINT + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); - transport_->registerListener_status_.set_code( - uprotocol::v1::UCode::RESOURCE_EXHAUSTED); + getTransport()->getRegisterListenerStatus().set_code( + v1::UCode::RESOURCE_EXHAUSTED); decltype(client.invokeMethod()) invoke_future; - EXPECT_NO_THROW(invoke_future = client.invokeMethod()); + EXPECT_NO_THROW(invoke_future = client.invokeMethod()); // NOLINT - EXPECT_EQ(transport_->send_count_, 0); + EXPECT_EQ(getTransport()->getSendCount(), 0); EXPECT_TRUE(invoke_future.valid()); - auto is_ready = invoke_future.wait_for(0ms); + auto is_ready = invoke_future.wait_for(ZERO_MILLISECONDS); EXPECT_EQ(is_ready, std::future_status::ready); if (is_ready == std::future_status::ready) { auto maybe_response = invoke_future.get(); - checkErrorResponse(maybe_response, - uprotocol::v1::UCode::RESOURCE_EXHAUSTED); + checkErrorResponse(maybe_response, v1::UCode::RESOURCE_EXHAUSTED); } } -TEST_F(RpcClientTest, InvokeFutureWithoutPayloadSendFail) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); +TEST_F(RpcClientTest, InvokeFutureWithoutPayloadSendFail) { // NOLINT + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); - transport_->send_status_.set_code( - uprotocol::v1::UCode::FAILED_PRECONDITION); + getTransport()->getSendStatus().set_code(v1::UCode::FAILED_PRECONDITION); decltype(client.invokeMethod()) invoke_future; - EXPECT_NO_THROW(invoke_future = client.invokeMethod()); + EXPECT_NO_THROW(invoke_future = client.invokeMethod()); // NOLINT EXPECT_TRUE(invoke_future.valid()); - auto is_ready = invoke_future.wait_for(0ms); + auto is_ready = invoke_future.wait_for(ZERO_MILLISECONDS); EXPECT_EQ(is_ready, std::future_status::ready); if (is_ready == std::future_status::ready) { auto maybe_response = invoke_future.get(); - checkErrorResponse(maybe_response, - uprotocol::v1::UCode::FAILED_PRECONDITION); + checkErrorResponse(maybe_response, v1::UCode::FAILED_PRECONDITION); } } -TEST_F(RpcClientTest, InvokeFutureWithoutPayloadClientDestroyed) { - uprotocol::communication::RpcClient::InvokeFuture invoke_future; +TEST_F(RpcClientTest, InvokeFutureWithoutPayloadClientDestroyed) { // NOLINT + communication::RpcClient::InvokeFuture invoke_future; { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, - 10ms); + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); - EXPECT_NO_THROW(invoke_future = client.invokeMethod()); + EXPECT_NO_THROW(invoke_future = client.invokeMethod()); // NOLINT } EXPECT_TRUE(invoke_future.valid()); - auto is_ready = invoke_future.wait_for(0ms); + auto is_ready = invoke_future.wait_for(ZERO_MILLISECONDS); EXPECT_EQ(is_ready, std::future_status::ready); if (is_ready == std::future_status::ready) { - EXPECT_NO_THROW(auto maybe_response = invoke_future.get(); - checkErrorResponse(maybe_response, - uprotocol::v1::UCode::CANCELLED);); + EXPECT_NO_THROW( // NOLINT + auto maybe_response = invoke_future.get(); + checkErrorResponse(maybe_response, v1::UCode::CANCELLED);); } } -TEST_F(RpcClientTest, InvokeFutureWithoutPayloadCommstatus) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); +TEST_F(RpcClientTest, InvokeFutureWithoutPayloadCommstatus) { // NOLINT + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); decltype(client.invokeMethod()) invoke_future; - EXPECT_NO_THROW(invoke_future = client.invokeMethod()); + EXPECT_NO_THROW(invoke_future = client.invokeMethod()); // NOLINT - using UMessageBuilder = uprotocol::datamodel::builder::UMessageBuilder; - auto response_builder = UMessageBuilder::response(transport_->message_); - response_builder.withCommStatus(uprotocol::v1::UCode::PERMISSION_DENIED); + using UMessageBuilder = datamodel::builder::UMessageBuilder; + auto response_builder = + UMessageBuilder::response(getTransport()->getMessage()); + response_builder.withCommStatus(v1::UCode::PERMISSION_DENIED); auto response = response_builder.build(); - EXPECT_NO_THROW(transport_->mockMessage(response)); + EXPECT_NO_THROW(getTransport()->mockMessage(response)); // NOLINT EXPECT_TRUE(invoke_future.valid()); - auto is_ready = invoke_future.wait_for(0ms); + auto is_ready = invoke_future.wait_for(ZERO_MILLISECONDS); EXPECT_EQ(is_ready, std::future_status::ready); if (is_ready == std::future_status::ready) { auto maybe_response = invoke_future.get(); - checkErrorResponse(maybe_response, - uprotocol::v1::UCode::PERMISSION_DENIED); + checkErrorResponse(maybe_response, v1::UCode::PERMISSION_DENIED); } } /////////////////////////////////////////////////////////////////////////////// // RpcClient::invokeMethod(Payload) -TEST_F(RpcClientTest, InvokeFutureWithPayload) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); +TEST_F(RpcClientTest, InvokeFutureWithPayload) { // NOLINT + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); auto payload = fakePayload(); auto payload_content = payload.buildCopy(); decltype(client.invokeMethod(std::move(payload))) invoke_future; - EXPECT_NO_THROW(invoke_future = client.invokeMethod(std::move(payload))); + EXPECT_NO_THROW(invoke_future = // NOLINT + client.invokeMethod(std::move(payload))); EXPECT_TRUE(invoke_future.valid()); validateLastRequest(1); - using PayloadField = uprotocol::datamodel::builder::Payload::PayloadType; - EXPECT_EQ(transport_->message_.payload(), + using PayloadField = datamodel::builder::Payload::PayloadType; + EXPECT_EQ(getTransport()->getMessage().payload(), std::get(payload_content)); - EXPECT_EQ(transport_->message_.attributes().payload_format(), + EXPECT_EQ(getTransport()->getMessage().attributes().payload_format(), std::get(payload_content)); - using UMessageBuilder = uprotocol::datamodel::builder::UMessageBuilder; - auto response_builder = UMessageBuilder::response(transport_->message_); + using UMessageBuilder = datamodel::builder::UMessageBuilder; + auto response_builder = + UMessageBuilder::response(getTransport()->getMessage()); auto response = response_builder.build(); - EXPECT_NO_THROW(transport_->mockMessage(response)); + EXPECT_NO_THROW(getTransport()->mockMessage(response)); // NOLINT - auto is_ready = invoke_future.wait_for(0ms); + auto is_ready = invoke_future.wait_for(ZERO_MILLISECONDS); EXPECT_EQ(is_ready, std::future_status::ready); if (is_ready == std::future_status::ready) { @@ -371,31 +395,33 @@ TEST_F(RpcClientTest, InvokeFutureWithPayload) { } } -TEST_F(RpcClientTest, InvokeFutureWithPayloadAndFormatSet) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms, - uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT); +TEST_F(RpcClientTest, InvokeFutureWithPayloadAndFormatSet) { // NOLINT + auto client = communication::RpcClient( + getTransport(), methodUri(), v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS, v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT); auto payload = fakePayload(); auto payload_content = payload.buildCopy(); decltype(client.invokeMethod(std::move(payload))) invoke_future; - EXPECT_NO_THROW(invoke_future = client.invokeMethod(std::move(payload))); + EXPECT_NO_THROW(invoke_future = // NOLINT + client.invokeMethod(std::move(payload))); EXPECT_TRUE(invoke_future.valid()); validateLastRequest(1); - using PayloadField = uprotocol::datamodel::builder::Payload::PayloadType; - EXPECT_EQ(transport_->message_.payload(), + using PayloadField = datamodel::builder::Payload::PayloadType; + EXPECT_EQ(getTransport()->getMessage().payload(), std::get(payload_content)); - EXPECT_EQ(transport_->message_.attributes().payload_format(), + EXPECT_EQ(getTransport()->getMessage().attributes().payload_format(), std::get(payload_content)); - using UMessageBuilder = uprotocol::datamodel::builder::UMessageBuilder; - auto response_builder = UMessageBuilder::response(transport_->message_); + using UMessageBuilder = datamodel::builder::UMessageBuilder; + auto response_builder = + UMessageBuilder::response(getTransport()->getMessage()); auto response = response_builder.build(); - EXPECT_NO_THROW(transport_->mockMessage(response)); + EXPECT_NO_THROW(getTransport()->mockMessage(response)); // NOLINT - auto is_ready = invoke_future.wait_for(0ms); + auto is_ready = invoke_future.wait_for(ZERO_MILLISECONDS); EXPECT_EQ(is_ready, std::future_status::ready); if (is_ready == std::future_status::ready) { @@ -405,551 +431,572 @@ TEST_F(RpcClientTest, InvokeFutureWithPayloadAndFormatSet) { } } -TEST_F(RpcClientTest, InvokeFutureWithPayloadAndWrongFormatSet) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms, - uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_JSON); +TEST_F(RpcClientTest, InvokeFutureWithPayloadAndWrongFormatSet) { // NOLINT + auto client = communication::RpcClient( + getTransport(), methodUri(), v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS, v1::UPayloadFormat::UPAYLOAD_FORMAT_JSON); - EXPECT_THROW( + EXPECT_THROW( // NOLINT auto invoke_future = client.invokeMethod(fakePayload()), - uprotocol::datamodel::builder::UMessageBuilder::UnexpectedFormat); + datamodel::builder::UMessageBuilder::UnexpectedFormat); - EXPECT_EQ(transport_->send_count_, 0); - EXPECT_FALSE(transport_->listener_); + EXPECT_EQ(getTransport()->getSendCount(), 0); + EXPECT_FALSE(getTransport()->getListener()); } -TEST_F(RpcClientTest, InvokeFutureWithPayloadTimeout) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); +TEST_F(RpcClientTest, InvokeFutureWithPayloadTimeout) { // NOLINT + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); decltype(client.invokeMethod()) invoke_future; auto when_requested = std::chrono::steady_clock::now(); - EXPECT_NO_THROW(invoke_future = client.invokeMethod(fakePayload())); + EXPECT_NO_THROW(invoke_future = // NOLINT + client.invokeMethod(fakePayload())); EXPECT_TRUE(invoke_future.valid()); - auto is_ready = invoke_future.wait_for(150ms); + auto is_ready = invoke_future.wait_for(ONE_HUNDRED_FIFTY_MILLISECONDS); auto when_expired = std::chrono::steady_clock::now(); - EXPECT_GE((when_expired - when_requested), 10ms); - EXPECT_LE((when_expired - when_requested), 2 * 10ms); + EXPECT_GE((when_expired - when_requested), TEN_MILLISECONDS); + EXPECT_LE((when_expired - when_requested), 2 * TEN_MILLISECONDS); EXPECT_EQ(is_ready, std::future_status::ready); if (is_ready == std::future_status::ready) { auto maybe_response = invoke_future.get(); - checkErrorResponse(maybe_response, - uprotocol::v1::UCode::DEADLINE_EXCEEDED); + checkErrorResponse(maybe_response, v1::UCode::DEADLINE_EXCEEDED); } } -TEST_F(RpcClientTest, InvokeFutureWithPayloadListenFail) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); +TEST_F(RpcClientTest, InvokeFutureWithPayloadListenFail) { // NOLINT + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); - transport_->registerListener_status_.set_code( - uprotocol::v1::UCode::RESOURCE_EXHAUSTED); + getTransport()->getRegisterListenerStatus().set_code( + v1::UCode::RESOURCE_EXHAUSTED); decltype(client.invokeMethod()) invoke_future; - EXPECT_NO_THROW(invoke_future = client.invokeMethod(fakePayload())); + EXPECT_NO_THROW(invoke_future = // NOLINT + client.invokeMethod(fakePayload())); - EXPECT_EQ(transport_->send_count_, 0); + EXPECT_EQ(getTransport()->getSendCount(), 0); EXPECT_TRUE(invoke_future.valid()); - auto is_ready = invoke_future.wait_for(0ms); + auto is_ready = invoke_future.wait_for(ZERO_MILLISECONDS); EXPECT_EQ(is_ready, std::future_status::ready); if (is_ready == std::future_status::ready) { auto maybe_response = invoke_future.get(); - checkErrorResponse(maybe_response, - uprotocol::v1::UCode::RESOURCE_EXHAUSTED); + checkErrorResponse(maybe_response, v1::UCode::RESOURCE_EXHAUSTED); } } -TEST_F(RpcClientTest, InvokeFutureWithPayloadSendFail) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); +TEST_F(RpcClientTest, InvokeFutureWithPayloadSendFail) { // NOLINT + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); - transport_->send_status_.set_code( - uprotocol::v1::UCode::FAILED_PRECONDITION); + getTransport()->getSendStatus().set_code(v1::UCode::FAILED_PRECONDITION); decltype(client.invokeMethod()) invoke_future; - EXPECT_NO_THROW(invoke_future = client.invokeMethod(fakePayload())); + EXPECT_NO_THROW(invoke_future = // NOLINT + client.invokeMethod(fakePayload())); EXPECT_TRUE(invoke_future.valid()); - auto is_ready = invoke_future.wait_for(0ms); + auto is_ready = invoke_future.wait_for(ZERO_MILLISECONDS); EXPECT_EQ(is_ready, std::future_status::ready); if (is_ready == std::future_status::ready) { auto maybe_response = invoke_future.get(); - checkErrorResponse(maybe_response, - uprotocol::v1::UCode::FAILED_PRECONDITION); + checkErrorResponse(maybe_response, v1::UCode::FAILED_PRECONDITION); } } -TEST_F(RpcClientTest, InvokeFutureWithPayloadClientDestroyed) { - uprotocol::communication::RpcClient::InvokeFuture invoke_future; +TEST_F(RpcClientTest, InvokeFutureWithPayloadClientDestroyed) { // NOLINT + communication::RpcClient::InvokeFuture invoke_future; { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, - 10ms); + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); - EXPECT_NO_THROW(invoke_future = client.invokeMethod(fakePayload())); + EXPECT_NO_THROW(invoke_future = // NOLINT + client.invokeMethod(fakePayload())); } EXPECT_TRUE(invoke_future.valid()); - auto is_ready = invoke_future.wait_for(0ms); + auto is_ready = invoke_future.wait_for(ZERO_MILLISECONDS); EXPECT_EQ(is_ready, std::future_status::ready); if (is_ready == std::future_status::ready) { auto maybe_response = invoke_future.get(); - checkErrorResponse(maybe_response, uprotocol::v1::UCode::CANCELLED); + checkErrorResponse(maybe_response, v1::UCode::CANCELLED); } } -TEST_F(RpcClientTest, InvokeFutureWithPayloadCommstatus) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); +TEST_F(RpcClientTest, InvokeFutureWithPayloadCommstatus) { // NOLINT + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); decltype(client.invokeMethod()) invoke_future; - EXPECT_NO_THROW(invoke_future = client.invokeMethod(fakePayload())); + EXPECT_NO_THROW(invoke_future = // NOLINT + client.invokeMethod(fakePayload())); - using UMessageBuilder = uprotocol::datamodel::builder::UMessageBuilder; - auto response_builder = UMessageBuilder::response(transport_->message_); - response_builder.withCommStatus(uprotocol::v1::UCode::PERMISSION_DENIED); + using UMessageBuilder = datamodel::builder::UMessageBuilder; + auto response_builder = + UMessageBuilder::response(getTransport()->getMessage()); + response_builder.withCommStatus(v1::UCode::PERMISSION_DENIED); auto response = response_builder.build(); - EXPECT_NO_THROW(transport_->mockMessage(response)); + EXPECT_NO_THROW(getTransport()->mockMessage(response)); // NOLINT EXPECT_TRUE(invoke_future.valid()); - auto is_ready = invoke_future.wait_for(0ms); + auto is_ready = invoke_future.wait_for(ZERO_MILLISECONDS); EXPECT_EQ(is_ready, std::future_status::ready); if (is_ready == std::future_status::ready) { auto maybe_response = invoke_future.get(); - checkErrorResponse(maybe_response, - uprotocol::v1::UCode::PERMISSION_DENIED); + checkErrorResponse(maybe_response, v1::UCode::PERMISSION_DENIED); } } /////////////////////////////////////////////////////////////////////////////// // RpcClient::invokeMethod(Callback) -TEST_F(RpcClientTest, InvokeCallbackWithoutPayload) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); +TEST_F(RpcClientTest, InvokeCallbackWithoutPayload) { // NOLINT + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); bool callback_called = false; - uprotocol::v1::UMessage received_response; + v1::UMessage received_response; - uprotocol::communication::RpcClient::InvokeHandle handle; - EXPECT_NO_THROW( + communication::RpcClient::InvokeHandle handle; + EXPECT_NO_THROW( // NOLINT handle = client.invokeMethod( - [this, &callback_called, &received_response](auto maybe_response) { + [&callback_called, &received_response](auto maybe_response) { callback_called = true; EXPECT_TRUE(maybe_response); received_response = std::move(maybe_response).value(); })); validateLastRequest(1); - EXPECT_TRUE(transport_->message_.payload().empty()); + EXPECT_TRUE(getTransport()->getMessage().payload().empty()); - using UMessageBuilder = uprotocol::datamodel::builder::UMessageBuilder; - auto response_builder = UMessageBuilder::response(transport_->message_); + using UMessageBuilder = datamodel::builder::UMessageBuilder; + auto response_builder = + UMessageBuilder::response(getTransport()->getMessage()); auto response = response_builder.build(); - EXPECT_NO_THROW(transport_->mockMessage(response)); + EXPECT_NO_THROW(getTransport()->mockMessage(response)); // NOLINT EXPECT_TRUE(callback_called); EXPECT_TRUE(response == received_response); } -TEST_F(RpcClientTest, InvokeCallbackWithoutPayloadAndFormatSet) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms, - uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_SOMEIP); +TEST_F(RpcClientTest, InvokeCallbackWithoutPayloadAndFormatSet) { // NOLINT + auto client = communication::RpcClient( + getTransport(), methodUri(), v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS, v1::UPayloadFormat::UPAYLOAD_FORMAT_SOMEIP); - uprotocol::communication::RpcClient::InvokeHandle handle; - EXPECT_THROW( + communication::RpcClient::InvokeHandle handle; + EXPECT_THROW( // NOLINT handle = client.invokeMethod([](auto) {}), - uprotocol::datamodel::builder::UMessageBuilder::UnexpectedFormat); + datamodel::builder::UMessageBuilder::UnexpectedFormat); - EXPECT_EQ(transport_->send_count_, 0); - EXPECT_FALSE(transport_->listener_); + EXPECT_EQ(getTransport()->getSendCount(), 0); + EXPECT_FALSE(getTransport()->getListener()); } -TEST_F(RpcClientTest, InvokeCallbackWithoutPayloadTimeout) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); +TEST_F(RpcClientTest, InvokeCallbackWithoutPayloadTimeout) { // NOLINT + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); bool callback_called = false; std::condition_variable callback_event; auto when_requested = std::chrono::steady_clock::now(); - uprotocol::communication::RpcClient::InvokeHandle handle; - EXPECT_NO_THROW( - handle = client.invokeMethod( - [this, &callback_called, &callback_event](auto maybe_response) { - callback_called = true; - checkErrorResponse(maybe_response, - uprotocol::v1::UCode::DEADLINE_EXCEEDED); - callback_event.notify_all(); - })); + communication::RpcClient::InvokeHandle handle; + EXPECT_NO_THROW( // NOLINT + handle = client.invokeMethod([&callback_called, &callback_event]( + const auto& maybe_response) { + callback_called = true; + checkErrorResponse(maybe_response, v1::UCode::DEADLINE_EXCEEDED); + callback_event.notify_all(); + })); std::mutex mtx; std::unique_lock lock(mtx); callback_called = callback_event.wait_for( - lock, 150ms, [&callback_called]() { return callback_called; }); + lock, ONE_HUNDRED_FIFTY_MILLISECONDS, + [&callback_called]() { return callback_called; }); auto when_expired = std::chrono::steady_clock::now(); - EXPECT_GE((when_expired - when_requested), 10ms); - EXPECT_LE((when_expired - when_requested), 2 * 10ms); + EXPECT_GE((when_expired - when_requested), TEN_MILLISECONDS); + EXPECT_LE((when_expired - when_requested), 2 * TEN_MILLISECONDS); EXPECT_TRUE(callback_called); } -TEST_F(RpcClientTest, InvokeCallbackWithoutPayloadListenFail) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); +TEST_F(RpcClientTest, InvokeCallbackWithoutPayloadListenFail) { // NOLINT + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); - transport_->registerListener_status_.set_code( - uprotocol::v1::UCode::RESOURCE_EXHAUSTED); + getTransport()->getRegisterListenerStatus().set_code( + v1::UCode::RESOURCE_EXHAUSTED); bool callback_called = false; - uprotocol::communication::RpcClient::InvokeHandle handle; - EXPECT_NO_THROW(handle = client.invokeMethod([this, &callback_called]( - auto maybe_response) { - callback_called = true; - checkErrorResponse(maybe_response, - uprotocol::v1::UCode::RESOURCE_EXHAUSTED); - })); + communication::RpcClient::InvokeHandle handle; + EXPECT_NO_THROW( // NOLINT + handle = + client.invokeMethod([&callback_called](const auto& maybe_response) { + callback_called = true; + checkErrorResponse(maybe_response, + v1::UCode::RESOURCE_EXHAUSTED); + })); - EXPECT_EQ(transport_->send_count_, 0); + EXPECT_EQ(getTransport()->getSendCount(), 0); EXPECT_TRUE(callback_called); } -TEST_F(RpcClientTest, InvokeCallbackWithoutPayloadSendFail) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); +TEST_F(RpcClientTest, InvokeCallbackWithoutPayloadSendFail) { // NOLINT + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); - transport_->send_status_.set_code( - uprotocol::v1::UCode::FAILED_PRECONDITION); + getTransport()->getSendStatus().set_code(v1::UCode::FAILED_PRECONDITION); bool callback_called = false; - uprotocol::communication::RpcClient::InvokeHandle handle; - EXPECT_NO_THROW(handle = client.invokeMethod([this, &callback_called]( - auto maybe_response) { - callback_called = true; - checkErrorResponse(maybe_response, - uprotocol::v1::UCode::FAILED_PRECONDITION); - })); + communication::RpcClient::InvokeHandle handle; + EXPECT_NO_THROW( // NOLINT + handle = + client.invokeMethod([&callback_called](const auto& maybe_response) { + callback_called = true; + checkErrorResponse(maybe_response, + v1::UCode::FAILED_PRECONDITION); + })); EXPECT_TRUE(callback_called); } -TEST_F(RpcClientTest, InvokeCallbackWithoutPayloadClientDestroyed) { - uprotocol::communication::RpcClient::InvokeFuture invoke_future; +TEST_F(RpcClientTest, InvokeCallbackWithoutPayloadClientDestroyed) { // NOLINT + communication::RpcClient::InvokeFuture invoke_future; bool callback_called = false; - uprotocol::communication::RpcClient::InvokeHandle handle; + communication::RpcClient::InvokeHandle handle; { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, - 10ms); - - EXPECT_NO_THROW(handle = client.invokeMethod([this, &callback_called]( - auto maybe_response) { - callback_called = true; - checkErrorResponse(maybe_response, uprotocol::v1::UCode::CANCELLED); - })); + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); + + EXPECT_NO_THROW( // NOLINT + handle = client.invokeMethod( + [&callback_called](const auto& maybe_response) { + callback_called = true; + checkErrorResponse(maybe_response, v1::UCode::CANCELLED); + })); } EXPECT_TRUE(callback_called); } -TEST_F(RpcClientTest, InvokeCallbackWithoutPayloadCommstatus) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); +TEST_F(RpcClientTest, InvokeCallbackWithoutPayloadCommstatus) { // NOLINT + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); bool callback_called = false; - uprotocol::communication::RpcClient::InvokeHandle handle; - EXPECT_NO_THROW(handle = client.invokeMethod([this, &callback_called]( - auto maybe_response) { - callback_called = true; - checkErrorResponse(maybe_response, - uprotocol::v1::UCode::PERMISSION_DENIED); - })); - - using UMessageBuilder = uprotocol::datamodel::builder::UMessageBuilder; - auto response_builder = UMessageBuilder::response(transport_->message_); - response_builder.withCommStatus(uprotocol::v1::UCode::PERMISSION_DENIED); + communication::RpcClient::InvokeHandle handle; + EXPECT_NO_THROW( // NOLINT + handle = + client.invokeMethod([&callback_called](const auto& maybe_response) { + callback_called = true; + checkErrorResponse(maybe_response, + v1::UCode::PERMISSION_DENIED); + })); + + using UMessageBuilder = datamodel::builder::UMessageBuilder; + auto response_builder = + UMessageBuilder::response(getTransport()->getMessage()); + response_builder.withCommStatus(v1::UCode::PERMISSION_DENIED); auto response = response_builder.build(); - EXPECT_NO_THROW(transport_->mockMessage(response)); + EXPECT_NO_THROW(getTransport()->mockMessage(response)); // NOLINT EXPECT_TRUE(callback_called); } /////////////////////////////////////////////////////////////////////////////// // RpcClient::invokeMethod(Payload, Callback) -TEST_F(RpcClientTest, InvokeCallbackWithPayload) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); +TEST_F(RpcClientTest, InvokeCallbackWithPayload) { // NOLINT + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); auto payload = fakePayload(); auto payload_content = payload.buildCopy(); bool callback_called = false; - uprotocol::v1::UMessage received_response; + v1::UMessage received_response; - uprotocol::communication::RpcClient::InvokeHandle handle; - EXPECT_NO_THROW( + communication::RpcClient::InvokeHandle handle; + EXPECT_NO_THROW( // NOLINT handle = client.invokeMethod( std::move(payload), - [this, &callback_called, &received_response](auto maybe_response) { + [&callback_called, &received_response](auto maybe_response) { callback_called = true; EXPECT_TRUE(maybe_response); received_response = std::move(maybe_response).value(); })); validateLastRequest(1); - using PayloadField = uprotocol::datamodel::builder::Payload::PayloadType; - EXPECT_EQ(transport_->message_.payload(), + using PayloadField = datamodel::builder::Payload::PayloadType; + EXPECT_EQ(getTransport()->getMessage().payload(), std::get(payload_content)); - EXPECT_EQ(transport_->message_.attributes().payload_format(), + EXPECT_EQ(getTransport()->getMessage().attributes().payload_format(), std::get(payload_content)); - using UMessageBuilder = uprotocol::datamodel::builder::UMessageBuilder; - auto response_builder = UMessageBuilder::response(transport_->message_); + using UMessageBuilder = datamodel::builder::UMessageBuilder; + auto response_builder = + UMessageBuilder::response(getTransport()->getMessage()); auto response = response_builder.build(); - EXPECT_NO_THROW(transport_->mockMessage(response)); + EXPECT_NO_THROW(getTransport()->mockMessage(response)); // NOLINT EXPECT_TRUE(callback_called); EXPECT_TRUE(response == received_response); } -TEST_F(RpcClientTest, InvokeCallbackWithPayloadAndFormatSet) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms, - uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT); +TEST_F(RpcClientTest, InvokeCallbackWithPayloadAndFormatSet) { // NOLINT + auto client = communication::RpcClient( + getTransport(), methodUri(), v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS, v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT); auto payload = fakePayload(); auto payload_content = payload.buildCopy(); bool callback_called = false; - uprotocol::v1::UMessage received_response; + v1::UMessage received_response; - uprotocol::communication::RpcClient::InvokeHandle handle; - EXPECT_NO_THROW( + communication::RpcClient::InvokeHandle handle; + EXPECT_NO_THROW( // NOLINT handle = client.invokeMethod( std::move(payload), - [this, &callback_called, &received_response](auto maybe_response) { + [&callback_called, &received_response](auto maybe_response) { callback_called = true; EXPECT_TRUE(maybe_response); received_response = std::move(maybe_response).value(); })); validateLastRequest(1); - using PayloadField = uprotocol::datamodel::builder::Payload::PayloadType; - EXPECT_EQ(transport_->message_.payload(), + using PayloadField = datamodel::builder::Payload::PayloadType; + EXPECT_EQ(getTransport()->getMessage().payload(), std::get(payload_content)); - EXPECT_EQ(transport_->message_.attributes().payload_format(), + EXPECT_EQ(getTransport()->getMessage().attributes().payload_format(), std::get(payload_content)); - using UMessageBuilder = uprotocol::datamodel::builder::UMessageBuilder; - auto response_builder = UMessageBuilder::response(transport_->message_); + using UMessageBuilder = datamodel::builder::UMessageBuilder; + auto response_builder = + UMessageBuilder::response(getTransport()->getMessage()); auto response = response_builder.build(); - EXPECT_NO_THROW(transport_->mockMessage(response)); + EXPECT_NO_THROW(getTransport()->mockMessage(response)); // NOLINT EXPECT_TRUE(callback_called); EXPECT_TRUE(response == received_response); } -TEST_F(RpcClientTest, InvokeCallbackWithPayloadAndWrongFormatSet) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms, - uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_JSON); +TEST_F(RpcClientTest, InvokeCallbackWithPayloadAndWrongFormatSet) { // NOLINT + auto client = communication::RpcClient( + getTransport(), methodUri(), v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS, v1::UPayloadFormat::UPAYLOAD_FORMAT_JSON); - uprotocol::communication::RpcClient::InvokeHandle handle; - EXPECT_THROW( + communication::RpcClient::InvokeHandle handle; + EXPECT_THROW( // NOLINT handle = client.invokeMethod(fakePayload(), [](auto) {}), - uprotocol::datamodel::builder::UMessageBuilder::UnexpectedFormat); + datamodel::builder::UMessageBuilder::UnexpectedFormat); - EXPECT_EQ(transport_->send_count_, 0); - EXPECT_FALSE(transport_->listener_); + EXPECT_EQ(getTransport()->getSendCount(), 0); + EXPECT_FALSE(getTransport()->getListener()); } -TEST_F(RpcClientTest, InvokeCallbackWithPayloadTimeout) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); +TEST_F(RpcClientTest, InvokeCallbackWithPayloadTimeout) { // NOLINT + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); bool callback_called = false; std::condition_variable callback_event; - uprotocol::communication::RpcClient::InvokeHandle handle; + communication::RpcClient::InvokeHandle handle; auto when_requested = std::chrono::steady_clock::now(); - EXPECT_NO_THROW( + EXPECT_NO_THROW( // NOLINT handle = client.invokeMethod( fakePayload(), - [this, &callback_called, &callback_event](auto maybe_response) { + [&callback_called, &callback_event](auto maybe_response) { callback_called = true; checkErrorResponse(maybe_response, - uprotocol::v1::UCode::DEADLINE_EXCEEDED); + v1::UCode::DEADLINE_EXCEEDED); callback_event.notify_all(); })); std::mutex mtx; std::unique_lock lock(mtx); callback_called = callback_event.wait_for( - lock, 150ms, [&callback_called]() { return callback_called; }); + lock, ONE_HUNDRED_FIFTY_MILLISECONDS, + [&callback_called]() { return callback_called; }); auto when_expired = std::chrono::steady_clock::now(); - EXPECT_GE((when_expired - when_requested), 10ms); - EXPECT_LE((when_expired - when_requested), 2 * 10ms); + EXPECT_GE((when_expired - when_requested), TEN_MILLISECONDS); + EXPECT_LE((when_expired - when_requested), 2 * TEN_MILLISECONDS); EXPECT_TRUE(callback_called); } -TEST_F(RpcClientTest, InvokeCallbackWithPayloadListenFail) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); +TEST_F(RpcClientTest, InvokeCallbackWithPayloadListenFail) { // NOLINT + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); - transport_->registerListener_status_.set_code( - uprotocol::v1::UCode::RESOURCE_EXHAUSTED); + getTransport()->getRegisterListenerStatus().set_code( + v1::UCode::RESOURCE_EXHAUSTED); bool callback_called = false; - uprotocol::communication::RpcClient::InvokeHandle handle; - EXPECT_NO_THROW( - handle = client.invokeMethod( - fakePayload(), [this, &callback_called](auto maybe_response) { - callback_called = true; - checkErrorResponse(maybe_response, - uprotocol::v1::UCode::RESOURCE_EXHAUSTED); - })); + communication::RpcClient::InvokeHandle handle; + EXPECT_NO_THROW( // NOLINT + handle = client.invokeMethod(fakePayload(), [&callback_called]( + auto maybe_response) { + callback_called = true; + checkErrorResponse(maybe_response, v1::UCode::RESOURCE_EXHAUSTED); + })); - EXPECT_EQ(transport_->send_count_, 0); + EXPECT_EQ(getTransport()->getSendCount(), 0); EXPECT_TRUE(callback_called); } -TEST_F(RpcClientTest, InvokeCallbackWithPayloadSendFail) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); +TEST_F(RpcClientTest, InvokeCallbackWithPayloadSendFail) { // NOLINT + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); - transport_->send_status_.set_code( - uprotocol::v1::UCode::FAILED_PRECONDITION); + getTransport()->getSendStatus().set_code(v1::UCode::FAILED_PRECONDITION); bool callback_called = false; - uprotocol::communication::RpcClient::InvokeHandle handle; - EXPECT_NO_THROW( - handle = client.invokeMethod( - fakePayload(), [this, &callback_called](auto maybe_response) { - callback_called = true; - checkErrorResponse(maybe_response, - uprotocol::v1::UCode::FAILED_PRECONDITION); - })); + communication::RpcClient::InvokeHandle handle; + EXPECT_NO_THROW( // NOLINT + handle = client.invokeMethod(fakePayload(), [&callback_called]( + auto maybe_response) { + callback_called = true; + checkErrorResponse(maybe_response, v1::UCode::FAILED_PRECONDITION); + })); EXPECT_TRUE(callback_called); } -TEST_F(RpcClientTest, InvokeCallbackWithPayloadClientDestroyed) { - uprotocol::communication::RpcClient::InvokeFuture invoke_future; +TEST_F(RpcClientTest, InvokeCallbackWithPayloadClientDestroyed) { // NOLINT + communication::RpcClient::InvokeFuture invoke_future; bool callback_called = false; - uprotocol::communication::RpcClient::InvokeHandle handle; + communication::RpcClient::InvokeHandle handle; { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, - 10ms); + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); - EXPECT_NO_THROW( + EXPECT_NO_THROW( // NOLINT handle = client.invokeMethod( - fakePayload(), [this, &callback_called](auto maybe_response) { + fakePayload(), [&callback_called](auto maybe_response) { callback_called = true; - checkErrorResponse(maybe_response, - uprotocol::v1::UCode::CANCELLED); + checkErrorResponse(maybe_response, v1::UCode::CANCELLED); })); } EXPECT_TRUE(callback_called); } -TEST_F(RpcClientTest, InvokeCallbackWithPayloadCommstatus) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); +TEST_F(RpcClientTest, InvokeCallbackWithPayloadCommstatus) { // NOLINT + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); bool callback_called = false; - uprotocol::communication::RpcClient::InvokeHandle handle; - EXPECT_NO_THROW( - handle = client.invokeMethod( - fakePayload(), [this, &callback_called](auto maybe_response) { - callback_called = true; - checkErrorResponse(maybe_response, - uprotocol::v1::UCode::PERMISSION_DENIED); - })); - - using UMessageBuilder = uprotocol::datamodel::builder::UMessageBuilder; - auto response_builder = UMessageBuilder::response(transport_->message_); - response_builder.withCommStatus(uprotocol::v1::UCode::PERMISSION_DENIED); + communication::RpcClient::InvokeHandle handle; + EXPECT_NO_THROW( // NOLINT + handle = client.invokeMethod(fakePayload(), [&callback_called]( + auto maybe_response) { + callback_called = true; + checkErrorResponse(maybe_response, v1::UCode::PERMISSION_DENIED); + })); + + using UMessageBuilder = datamodel::builder::UMessageBuilder; + auto response_builder = + UMessageBuilder::response(getTransport()->getMessage()); + response_builder.withCommStatus(v1::UCode::PERMISSION_DENIED); auto response = response_builder.build(); - EXPECT_NO_THROW(transport_->mockMessage(response)); + EXPECT_NO_THROW(getTransport()->mockMessage(response)); // NOLINT EXPECT_TRUE(callback_called); } /////////////////////////////////////////////////////////////////////////////// // Usecases -TEST_F(RpcClientTest, MultiplePendingInvocationsOnOneClient) { - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, - 250ms); +TEST_F(RpcClientTest, MultiplePendingInvocationsOnOneClient) { // NOLINT + constexpr std::chrono::milliseconds TWO_HUNDRED_FIFTY_MILLISECONDS(250); + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TWO_HUNDRED_FIFTY_MILLISECONDS); std::list futures; - std::listlistener_.value())>> callables; - std::list requests; + std::listgetListener().value())>> + callables; + std::list requests; futures.push_back(client.invokeMethod()); - callables.push_back(transport_->listener_.value()); - requests.push_back(transport_->message_); + callables.push_back(getTransport()->getListener().value()); + requests.push_back(getTransport()->getMessage()); futures.push_back(client.invokeMethod(fakePayload())); - callables.push_back(transport_->listener_.value()); - requests.push_back(transport_->message_); + callables.push_back(getTransport()->getListener().value()); + requests.push_back(getTransport()->getMessage()); futures.push_back(client.invokeMethod()); - callables.push_back(transport_->listener_.value()); - requests.push_back(transport_->message_); + callables.push_back(getTransport()->getListener().value()); + requests.push_back(getTransport()->getMessage()); futures.push_back(client.invokeMethod(fakePayload())); - callables.push_back(transport_->listener_.value()); - requests.push_back(transport_->message_); + callables.push_back(getTransport()->getListener().value()); + requests.push_back(getTransport()->getMessage()); - std::vector handles; + std::vector handles; int callback_count = 0; - auto callback = [&callback_count](auto) { ++callback_count; }; + auto callback = [&callback_count](const auto&) { ++callback_count; }; handles.push_back(client.invokeMethod(callback)); - callables.push_back(transport_->listener_.value()); - requests.push_back(transport_->message_); + callables.push_back(getTransport()->getListener().value()); + requests.push_back(getTransport()->getMessage()); handles.push_back(client.invokeMethod(fakePayload(), callback)); - callables.push_back(transport_->listener_.value()); - requests.push_back(transport_->message_); + callables.push_back(getTransport()->getListener().value()); + requests.push_back(getTransport()->getMessage()); handles.push_back(client.invokeMethod(callback)); - callables.push_back(transport_->listener_.value()); - requests.push_back(transport_->message_); + callables.push_back(getTransport()->getListener().value()); + requests.push_back(getTransport()->getMessage()); handles.push_back(client.invokeMethod(fakePayload(), callback)); - callables.push_back(transport_->listener_.value()); - requests.push_back(transport_->message_); + callables.push_back(getTransport()->getListener().value()); + requests.push_back(getTransport()->getMessage()); - auto readyFutures = [&futures]() { + auto ready_futures = [&futures]() { size_t ready = 0; for (auto& future : futures) { - auto is_ready = future.wait_for(0ms); + auto is_ready = future.wait_for(ZERO_MILLISECONDS); if (is_ready == std::future_status::ready) { ++ready; } @@ -958,43 +1005,44 @@ TEST_F(RpcClientTest, MultiplePendingInvocationsOnOneClient) { }; EXPECT_EQ(callback_count, 0); - EXPECT_EQ(readyFutures(), 0); + EXPECT_EQ(ready_futures(), 0); - using UMessageBuilder = uprotocol::datamodel::builder::UMessageBuilder; + using UMessageBuilder = datamodel::builder::UMessageBuilder; - auto deliverMessage = [&callables](uprotocol::v1::UMessage&& message) { + auto deliver_message = [&callables](const v1::UMessage& message) { for (auto& callable : callables) { - callable(std::move(message)); + callable(message); } }; - deliverMessage(UMessageBuilder::response(requests.front()).build()); - deliverMessage(UMessageBuilder::response(requests.back()).build()); + deliver_message(UMessageBuilder::response(requests.front()).build()); + deliver_message(UMessageBuilder::response(requests.back()).build()); EXPECT_EQ(callback_count, 1); - EXPECT_EQ(readyFutures(), 1); - EXPECT_EQ(futures.front().wait_for(0ms), std::future_status::ready); + EXPECT_EQ(ready_futures(), 1); + EXPECT_EQ(futures.front().wait_for(ZERO_MILLISECONDS), + std::future_status::ready); requests.pop_front(); requests.pop_back(); - deliverMessage(UMessageBuilder::response(requests.front()).build()); - deliverMessage(UMessageBuilder::response(requests.back()).build()); + deliver_message(UMessageBuilder::response(requests.front()).build()); + deliver_message(UMessageBuilder::response(requests.back()).build()); requests.pop_front(); requests.pop_back(); - deliverMessage(UMessageBuilder::response(requests.front()).build()); - deliverMessage(UMessageBuilder::response(requests.back()).build()); + deliver_message(UMessageBuilder::response(requests.front()).build()); + deliver_message(UMessageBuilder::response(requests.back()).build()); EXPECT_EQ(callback_count, 3); - EXPECT_EQ(readyFutures(), 3); + EXPECT_EQ(ready_futures(), 3); // Intentionally leaving a couple pending requests to discard } -TEST_F(RpcClientTest, PendingRequestsExpireInOrder) { - constexpr size_t num_clients = 10; - std::vector> - clients; +TEST_F(RpcClientTest, PendingRequestsExpireInOrder) { // NOLINT + constexpr std::chrono::milliseconds TWO_HUNDRED_MILLISECONDS(200); + constexpr size_t NUM_CLIENTS = 10; + std::vector> clients; std::mutex expire_mtx; std::vector expire_order; @@ -1002,24 +1050,23 @@ TEST_F(RpcClientTest, PendingRequestsExpireInOrder) { std::vector expected_order; - constexpr auto per_client_ttl_increment = 5ms; - auto client_ttl = 200ms; + constexpr auto PER_CLIENT_TTL_INCREMENT = std::chrono::milliseconds(5); + auto client_ttl = TWO_HUNDRED_MILLISECONDS; - for (size_t client_id = 0; client_id < num_clients; - ++client_id, client_ttl += per_client_ttl_increment) { - auto transport = std::make_shared( - defaultSourceUri()); + for (size_t client_id = 0; client_id < NUM_CLIENTS; + ++client_id, client_ttl += PER_CLIENT_TTL_INCREMENT) { + auto transport = + std::make_shared(defaultSourceUri()); clients.emplace_back(std::make_tuple( - client_id, - uprotocol::communication::RpcClient( - transport, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, - client_ttl))); + client_id, communication::RpcClient(transport, methodUri(), + v1::UPriority::UPRIORITY_CS4, + client_ttl))); expected_order.push_back(client_id); } - std::vector pending; + std::vector pending; for (auto entry = clients.rbegin(); entry != clients.rend(); ++entry) { auto client_id = std::get<0>(*entry); @@ -1027,11 +1074,10 @@ TEST_F(RpcClientTest, PendingRequestsExpireInOrder) { auto handle = client.invokeMethod([client_id, &expire_mtx, &expire_order, - &expire_signal](auto maybe_response) { + &expire_signal](const auto& maybe_response) { if (!maybe_response) { - auto some_status = maybe_response.error(); - if (some_status.code() != - uprotocol::v1::UCode::DEADLINE_EXCEEDED) { + const auto& some_status = maybe_response.error(); + if (some_status.code() != v1::UCode::DEADLINE_EXCEEDED) { return; } std::lock_guard lock(expire_mtx); @@ -1043,10 +1089,10 @@ TEST_F(RpcClientTest, PendingRequestsExpireInOrder) { } std::unique_lock lock(expire_mtx); - expire_signal.wait_for(lock, 2s, [&expire_order]() { - return expire_order.size() == num_clients; + expire_signal.wait_for(lock, std::chrono::seconds(2), [&expire_order]() { + return expire_order.size() == NUM_CLIENTS; }); - EXPECT_EQ(expire_order.size(), num_clients); + EXPECT_EQ(expire_order.size(), NUM_CLIENTS); EXPECT_TRUE(std::is_sorted(expire_order.begin(), expire_order.end())); EXPECT_EQ(expire_order, expected_order); } @@ -1060,39 +1106,45 @@ TEST_F(RpcClientTest, PendingRequestsExpireInOrder) { // the top. This results in the second request not expiring until after the // first request's expiration time (even though the expirations will be called // in order). -TEST_F(RpcClientTest, ExpireWorkerWakesForRightPendingRequest) { - auto slow_client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10s); +TEST_F(RpcClientTest, ExpireWorkerWakesForRightPendingRequest) { // NOLINT + constexpr std::chrono::seconds TEN_SECONDS(10); + constexpr std::chrono::milliseconds TWENTY_FIVE_MILLISECONDS(25); + constexpr std::chrono::milliseconds ONE_HUNDRED_MILLISECONDS(100); + + auto slow_client = communication::RpcClient( + getTransport(), methodUri(), v1::UPriority::UPRIORITY_CS4, TEN_SECONDS); auto slow_future = slow_client.invokeMethod(); // Waits long enough for the worker to wake and go back to sleep with the // 10s TTL for the slow request as the next scheduled wake time. - auto slow_ready = slow_future.wait_for(100ms); + auto slow_ready = slow_future.wait_for(ONE_HUNDRED_MILLISECONDS); EXPECT_EQ(slow_ready, std::future_status::timeout); - auto fast_client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 25ms); + auto fast_client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TWENTY_FIVE_MILLISECONDS); auto fast_future = fast_client.invokeMethod(); // The request from the fast_client should expire within about 25ms, but // the request from the slow_client should still be pending for several // more seconds. - auto fast_ready = fast_future.wait_for(1s); - slow_ready = slow_future.wait_for(100ms); + auto fast_ready = fast_future.wait_for(std::chrono::seconds(1)); + slow_ready = slow_future.wait_for(ONE_HUNDRED_MILLISECONDS); EXPECT_EQ(fast_ready, std::future_status::ready); EXPECT_EQ(slow_ready, std::future_status::timeout); } + // NOTE: for some reason, when the above test fails, the _next_ test also // fails. I do not know how this is possible. -TEST_F(RpcClientTest, MultipleClientInstances) { - constexpr size_t num_clients = 20; +TEST_F(RpcClientTest, MultipleClientInstances) { // NOLINT + constexpr size_t NUM_CLIENTS = 20; - using UTransportMock = uprotocol::test::UTransportMock; - std::array, num_clients> transports; + using UTransportMock = test::UTransportMock; + std::array, NUM_CLIENTS> transports; uint8_t last_authority_octet = 0; for (auto& transport : transports) { @@ -1103,58 +1155,62 @@ TEST_F(RpcClientTest, MultipleClientInstances) { transport = std::make_shared(uri); } - std::array timeouts; - constexpr std::chrono::milliseconds timeout_step = 7ms; - constexpr std::chrono::milliseconds timeout_min = 200ms; - constexpr std::chrono::milliseconds timeout_max = timeout_min + 40ms; - std::chrono::milliseconds next_timeout = timeout_min; + std::array timeouts{}; + constexpr std::chrono::milliseconds TIMEOUT_STEP = + std::chrono::milliseconds(7); + constexpr std::chrono::milliseconds TIMEOUT_MIN = + std::chrono::milliseconds(200); + constexpr std::chrono::milliseconds TIMEOUT_MAX = + TIMEOUT_MIN + std::chrono::milliseconds(40); + std::chrono::milliseconds next_timeout = TIMEOUT_MIN; for (auto& timeout : timeouts) { timeout = next_timeout; - next_timeout = ((next_timeout - timeout_min + timeout_step) % - (timeout_max - timeout_min)) + - timeout_min; + next_timeout = ((next_timeout - TIMEOUT_MIN + TIMEOUT_STEP) % + (TIMEOUT_MAX - TIMEOUT_MIN)) + + TIMEOUT_MIN; } - std::vector clients; + std::vector clients; auto loop_init = - std::make_tuple(num_clients, transports.begin(), timeouts.begin()); + std::make_tuple(NUM_CLIENTS, transports.begin(), timeouts.begin()); for (auto [remaining, transport, timeout] = std::move(loop_init); remaining > 0; --remaining, ++transport, ++timeout) { auto method_uri = (*transport)->getDefaultSource(); method_uri.set_resource_id(methodUri().resource_id()); - uprotocol::communication::RpcClient client( - *transport, std::move(method_uri), - uprotocol::v1::UPriority::UPRIORITY_CS4, *timeout); + communication::RpcClient client(*transport, std::move(method_uri), + v1::UPriority::UPRIORITY_CS4, *timeout); clients.push_back(std::move(client)); } - constexpr size_t requests_per_client = 8; - constexpr size_t num_invocations = num_clients * requests_per_client; + constexpr size_t REQUESTS_PER_CLIENT = 8; + constexpr size_t NUM_INVOCATIONS = NUM_CLIENTS * REQUESTS_PER_CLIENT; using PendingEntry = std::tuple; std::vector pending; - std::array client_invoke_count{0}; - - for (size_t remaining = num_invocations; remaining > 0; --remaining) { - const size_t client_index = remaining % num_clients; - ++client_invoke_count[client_index]; - pending.push_back( - {std::chrono::steady_clock::now() + timeouts[client_index], - clients[client_index].invokeMethod()}); + std::array client_invoke_count{0}; + + for (size_t remaining = NUM_INVOCATIONS; remaining > 0; --remaining) { + const size_t client_index = remaining % NUM_CLIENTS; + ++client_invoke_count.at(client_index); + pending.emplace_back( + std::chrono::steady_clock::now() + timeouts.at(client_index), + clients[client_index].invokeMethod()); } // Reply to some for (auto& transport : transports) { - using namespace uprotocol::datamodel::builder; - auto reply = UMessageBuilder::response(transport->message_).build(); - transport->mockMessage(std::move(reply)); + auto reply = datamodel::builder::UMessageBuilder::response( + transport->getMessage()) + .build(); + transport->mockMessage(reply); } size_t num_ready = 0; for (auto& request : pending) { auto& future = std::get<1>(request); - const bool is_ready = future.wait_for(0ms) == std::future_status::ready; + const bool is_ready = + future.wait_for(ZERO_MILLISECONDS) == std::future_status::ready; if (is_ready) { ++num_ready; auto maybe_response = future.get(); @@ -1166,8 +1222,8 @@ TEST_F(RpcClientTest, MultipleClientInstances) { EXPECT_EQ(num_ready, transports.size()); // Drop some by discarding the client - constexpr size_t num_discard = 2; - for (auto remaining = num_discard; remaining > 0; --remaining) { + constexpr size_t NUM_DISCARD = 2; + for (auto remaining = NUM_DISCARD; remaining > 0; --remaining) { clients.pop_back(); } size_t num_cancelled = 0; @@ -1175,14 +1231,14 @@ TEST_F(RpcClientTest, MultipleClientInstances) { auto& future = std::get<1>(request); // Ignoring the futures we have already used if (future.valid() && - (future.wait_for(0ms) == std::future_status::ready)) { + (future.wait_for(ZERO_MILLISECONDS) == std::future_status::ready)) { auto maybe_response = future.get(); - checkErrorResponse(maybe_response, uprotocol::v1::UCode::CANCELLED); + checkErrorResponse(maybe_response, v1::UCode::CANCELLED); ++num_cancelled; } } // Note: removing two for the two futures already used earlier in the test - EXPECT_EQ(num_cancelled, num_discard * (requests_per_client - 1)); + EXPECT_EQ(num_cancelled, NUM_DISCARD * (REQUESTS_PER_CLIENT - 1)); // Prune all completed requests auto before_clean = pending.size(); @@ -1194,8 +1250,8 @@ TEST_F(RpcClientTest, MultipleClientInstances) { EXPECT_EQ(pending.size(), before_clean - num_cancelled - num_ready); // Wait for some to time out - decltype(pending.begin()) pending_middle = - pending.begin() + (pending.size() / 2); + auto pending_middle = + pending.begin() + static_cast((pending.size() / 2)); std::nth_element( pending.begin(), pending_middle, pending.end(), [](const auto& a, const auto& b) { @@ -1207,7 +1263,7 @@ TEST_F(RpcClientTest, MultipleClientInstances) { auto& median_expire_future = std::get<1>(*pending_middle); median_expire_future.wait_until(std::get<0>(*pending_middle) + - timeout_step); + TIMEOUT_STEP); size_t expected_expired = 0; size_t ready_futures = 0; @@ -1219,16 +1275,15 @@ TEST_F(RpcClientTest, MultipleClientInstances) { (when_expire <= std::chrono::steady_clock::now())) { ++expected_expired; - if (future.wait_for(2 * timeout_step) == + if (future.wait_for(2 * TIMEOUT_STEP) == std::future_status::ready) { ++ready_futures; auto maybe_message = future.get(); - if (!maybe_message && - (maybe_message.error().code() == - uprotocol::v1::UCode::DEADLINE_EXCEEDED)) { + if (!maybe_message && (maybe_message.error().code() == + v1::UCode::DEADLINE_EXCEEDED)) { ++expired_futures; checkErrorResponse(maybe_message, - uprotocol::v1::UCode::DEADLINE_EXCEEDED); + v1::UCode::DEADLINE_EXCEEDED); } } } @@ -1241,68 +1296,72 @@ TEST_F(RpcClientTest, MultipleClientInstances) { // Discard the rest } -TEST_F(RpcClientTest, ParallelAccessSingleClient) { - std::array workers; +TEST_F(RpcClientTest, ParallelAccessSingleClient) { // NOLINT + constexpr size_t NUM_REQUESTS_PER_WORKER = 10; + + constexpr std::chrono::milliseconds TWENTY_MILLISECONDS(20); + + std::array workers; - auto client = uprotocol::communication::RpcClient( - transport_, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, 10ms); + auto client = communication::RpcClient(getTransport(), methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); - constexpr size_t num_requests_per_worker = 10; std::atomic call_count = 0; - std::array, + std::array, workers.size()> handles; - auto worker_handles = handles.begin(); + size_t handle_counter = 0; for (auto& worker : workers) { - worker = std::thread([&call_count, &client, - &handles = *(worker_handles++)]() { - for (auto remaining = num_requests_per_worker; remaining > 0; - --remaining) { - handles.emplace_back( - client.invokeMethod([&call_count](auto) { ++call_count; })); - } - }); + worker = std::thread( + [&call_count, &client, &handles = handles.at(handle_counter++)]() { + for (auto remaining = NUM_REQUESTS_PER_WORKER; remaining > 0; + --remaining) { + handles.emplace_back(client.invokeMethod( + [&call_count](const auto&) { ++call_count; })); + } + }); } for (auto& worker : workers) { worker.join(); } - for (int remaining_attempts = 10; remaining_attempts > 0; - --remaining_attempts) { - std::this_thread::sleep_for(20ms); - if (call_count == num_requests_per_worker * workers.size()) { + for (int remaining_attempts = NUM_REQUESTS_PER_WORKER; + remaining_attempts > 0; --remaining_attempts) { + std::this_thread::sleep_for(TWENTY_MILLISECONDS); + if (call_count == NUM_REQUESTS_PER_WORKER * workers.size()) { break; } } - EXPECT_EQ(call_count, num_requests_per_worker * workers.size()); + EXPECT_EQ(call_count, NUM_REQUESTS_PER_WORKER * workers.size()); } -TEST_F(RpcClientTest, ParallelAccessMultipleClients) { +TEST_F(RpcClientTest, ParallelAccessMultipleClients) { // NOLINT std::vector workers; - constexpr size_t num_requests_per_worker = 1500; + constexpr size_t NUM_REQUESTS_PER_WORKER = 1500; auto get_client = []() { - auto transport = std::make_shared( - defaultSourceUri()); - return uprotocol::communication::RpcClient( - transport, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, - 10ms); + auto transport = + std::make_shared(defaultSourceUri()); + return communication::RpcClient(transport, methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); }; // Repeatedly creates a client, makes a request, then discards the client std::atomic discard_calls = 0; workers.emplace_back([&discard_calls, &get_client]() { - uprotocol::communication::RpcClient::InvokeHandle handle; - for (auto remaining_requests = num_requests_per_worker; + communication::RpcClient::InvokeHandle handle; + for (auto remaining_requests = NUM_REQUESTS_PER_WORKER; remaining_requests > 0; --remaining_requests) { auto client = get_client(); handle = client.invokeMethod( - [&discard_calls](auto) { ++discard_calls; }); + [&discard_calls](const auto&) { ++discard_calls; }); } }); @@ -1313,11 +1372,11 @@ TEST_F(RpcClientTest, ParallelAccessMultipleClients) { workers.emplace_back([&abandon_calls, &get_client]() { auto client = get_client(); - for (auto remaining_requests = num_requests_per_worker; + for (auto remaining_requests = NUM_REQUESTS_PER_WORKER; remaining_requests > 0; --remaining_requests) { auto future = client.invokeMethod(); - if (future.valid() && - (future.wait_for(0ms) == std::future_status::ready)) { + if (future.valid() && (future.wait_for(std::chrono::milliseconds( + 0)) == std::future_status::ready)) { ++abandon_calls; } } @@ -1331,12 +1390,12 @@ TEST_F(RpcClientTest, ParallelAccessMultipleClients) { workers.emplace_back([&expire_calls, &broken_promises, &get_client]() { auto client = get_client(); std::vector futures; - for (auto remaining_requests = num_requests_per_worker; + for (auto remaining_requests = NUM_REQUESTS_PER_WORKER; remaining_requests > 0; --remaining_requests) { futures.emplace_back(client.invokeMethod()); } for (auto& future : futures) { - auto is_ready = future.wait_for(1s); + auto is_ready = future.wait_for(std::chrono::seconds(1)); if (is_ready == std::future_status::ready) { try { auto maybe_response = future.get(); @@ -1358,29 +1417,29 @@ TEST_F(RpcClientTest, ParallelAccessMultipleClients) { // requests std::atomic self_calls = 0; - auto self_responder = [&self_calls, &get_client]() { - auto transport = std::make_shared( - defaultSourceUri()); - auto client = uprotocol::communication::RpcClient( - transport, methodUri(), uprotocol::v1::UPriority::UPRIORITY_CS4, - 10ms); - for (auto remaining_requests = num_requests_per_worker; + auto self_responder = [&self_calls]() { + auto transport = + std::make_shared(defaultSourceUri()); + auto client = communication::RpcClient(transport, methodUri(), + v1::UPriority::UPRIORITY_CS4, + TEN_MILLISECONDS); + for (auto remaining_requests = NUM_REQUESTS_PER_WORKER; remaining_requests > 0; --remaining_requests) { - auto handle = - client.invokeMethod([&self_calls](auto) { ++self_calls; }); + auto handle = client.invokeMethod( + [&self_calls](const auto&) { ++self_calls; }); // Attempting this without a request having ever been sent results // in an InvalidUUri exception thrown from a thread. gtest can't // guard for that, so we avoid generating the exception. - if (transport->send_count_ > 0) { - using namespace uprotocol::datamodel::builder; - auto response = - UMessageBuilder::response(transport->message_).build(); + if (transport->getSendCount() > 0) { + auto response = datamodel::builder::UMessageBuilder::response( + transport->getMessage()) + .build(); transport->mockMessage(response); } } }; - constexpr size_t num_self_responders = 3; - for (auto remaining = num_self_responders; remaining > 0; --remaining) { + constexpr size_t NUM_SELF_RESPONDERS = 3; + for (auto remaining = NUM_SELF_RESPONDERS; remaining > 0; --remaining) { workers.emplace_back(self_responder); } @@ -1389,11 +1448,11 @@ TEST_F(RpcClientTest, ParallelAccessMultipleClients) { worker.join(); } - EXPECT_EQ(discard_calls, num_requests_per_worker); + EXPECT_EQ(discard_calls, NUM_REQUESTS_PER_WORKER); EXPECT_EQ(abandon_calls, 0); EXPECT_EQ(broken_promises, 0); - EXPECT_EQ(expire_calls, num_requests_per_worker); - EXPECT_EQ(self_calls, num_requests_per_worker * num_self_responders); + EXPECT_EQ(expire_calls, NUM_REQUESTS_PER_WORKER); + EXPECT_EQ(self_calls, NUM_REQUESTS_PER_WORKER * NUM_SELF_RESPONDERS); } -} // namespace +} // namespace uprotocol diff --git a/test/coverage/communication/RpcServerTest.cpp b/test/coverage/communication/RpcServerTest.cpp index 5bc68c664..5ed99b726 100644 --- a/test/coverage/communication/RpcServerTest.cpp +++ b/test/coverage/communication/RpcServerTest.cpp @@ -15,81 +15,98 @@ #include #include -#include #include "UTransportMock.h" -namespace { +constexpr size_t MAX_LEN_RANDOM_STRING = 32; + +namespace uprotocol { using MsgDiff = google::protobuf::util::MessageDifferencer; -static std::random_device random_dev; -static std::mt19937 random_gen(random_dev()); -static std::uniform_int_distribution char_dist('A', 'z'); +std::string get_random_string(size_t max_len = MAX_LEN_RANDOM_STRING) { + std::random_device random_dev; + std::mt19937 random_gen(random_dev()); + std::uniform_int_distribution char_dist('A', 'z'); -std::string get_random_string(size_t max_len = 32) { std::uniform_int_distribution len_dist(1, static_cast(max_len)); - size_t len = len_dist(random_gen); + auto len = static_cast(len_dist(random_gen)); std::string retval; retval.reserve(len); - for (size_t i = 0; i < len; i++) + for (size_t i = 0; i < len; i++) { retval += static_cast(char_dist(random_gen)); + } return retval; } -std::optional RpcCallbackNoReturn( - const uprotocol::v1::UMessage& message) { +std::optional RpcCallbackNoReturn( + const v1::UMessage& /*message*/) { return std::nullopt; } -std::optional RpcCallbackWithReturn( - const uprotocol::v1::UMessage& message) { - uprotocol::v1::UPayloadFormat format = - uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT; - std::string responseData = "RPC Response"; +std::optional RpcCallbackWithReturn( + const v1::UMessage& /*message*/) { + v1::UPayloadFormat format = v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT; + std::string response_data = "RPC Response"; - uprotocol::datamodel::builder::Payload payload(responseData, format); + datamodel::builder::Payload payload(response_data, format); return payload; } class TestRpcServer : public testing::Test { +private: + static constexpr uint16_t DEFAULT_TTL_TIME = 1000; + std::shared_ptr mockTransport_; + std::shared_ptr method_uri_; + std::shared_ptr request_uri_; + std::chrono::milliseconds ttl_ = + std::chrono::milliseconds(DEFAULT_TTL_TIME); + v1::UPayloadFormat format = v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT; + protected: // Run once per TEST_F. // Used to set up clean environments per test. - std::shared_ptr mockTransport_; - std::shared_ptr method_uri_; - std::shared_ptr request_uri_; - std::chrono::milliseconds ttl_; - uprotocol::v1::UPayloadFormat format; + + [[nodiscard]] std::shared_ptr getMockTransport() + const { + return mockTransport_; + } + [[nodiscard]] std::shared_ptr getMethodUri() const { + return method_uri_; + } + [[nodiscard]] std::shared_ptr getRequestUri() const { + return request_uri_; + } + [[nodiscard]] std::chrono::milliseconds getTTL() const { return ttl_; } + [[nodiscard]] v1::UPayloadFormat getFormat() const { return format; } void SetUp() override { - // Set up default values for the test - ttl_ = std::chrono::milliseconds(1000); - format = uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT; + constexpr uint32_t DEF_UE_ID = 0x18000; + constexpr uint32_t METHOD_UE_ID = 0x00010002; + constexpr uint32_t REQUEST_UE_ID = 0x00010001; // Set up a transport URI - uprotocol::v1::UUri def_src_uuri; + v1::UUri def_src_uuri; def_src_uuri.set_authority_name(get_random_string()); - def_src_uuri.set_ue_id(0x18000); + def_src_uuri.set_ue_id(DEF_UE_ID); def_src_uuri.set_ue_version_major(1); def_src_uuri.set_resource_id(0); // Set up a transport - mockTransport_ = - std::make_shared(def_src_uuri); + mockTransport_ = std::make_shared(def_src_uuri); // Set up a method URI - method_uri_ = std::make_shared(); + method_uri_ = std::make_shared(); method_uri_->set_authority_name("10.0.0.2"); - method_uri_->set_ue_id(0x00010002); + method_uri_->set_ue_id(METHOD_UE_ID); method_uri_->set_ue_version_major(2); method_uri_->set_resource_id(0x2); // Create a src uri of entity - request_uri_ = std::make_shared(); + request_uri_ = std::make_shared(); request_uri_->set_authority_name("10.0.0.1"); - request_uri_->set_ue_id(0x00010001); + request_uri_->set_ue_id(REQUEST_UE_ID); request_uri_->set_ue_version_major(1); request_uri_->set_resource_id(0x0); } @@ -102,303 +119,313 @@ class TestRpcServer : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. TestRpcServer() = default; - ~TestRpcServer() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} + +public: + ~TestRpcServer() override = default; }; // Test to ensure RpcServer constructor initializes correctly with valid // parameters -TEST_F(TestRpcServer, ConstructorValidParams) { +TEST_F(TestRpcServer, ConstructorValidParams) { // NOLINT // Define a callback function to be used with the RpcServer - uprotocol::communication::RpcServer::RpcCallback callback = - RpcCallbackNoReturn; + communication::RpcServer::RpcCallback callback = RpcCallbackNoReturn; // Attempt to create an RpcServer instance with valid parameters - auto serverOrStatus = uprotocol::communication::RpcServer::create( - mockTransport_, *method_uri_, std::move(callback)); + auto server_or_status = communication::RpcServer::create( + getMockTransport(), *getMethodUri(), std::move(callback)); // Ensure that the server creation was successful - ASSERT_TRUE(serverOrStatus.has_value()); + ASSERT_TRUE(server_or_status.has_value()); // Obtain a pointer to the created RpcServer instance - auto& serverPtr = serverOrStatus.value(); + const auto& server_ptr = server_or_status.value(); // Verify that the server pointer is not null, indicating successful // creation - ASSERT_NE(serverPtr, nullptr); + ASSERT_NE(server_ptr, nullptr); } // Null transport -TEST_F(TestRpcServer, CreateWithNullTransport) { +TEST_F(TestRpcServer, CreateWithNullTransport) { // NOLINT // Define a callback function to be used with the RpcServer - uprotocol::communication::RpcServer::RpcCallback callback = - RpcCallbackNoReturn; + communication::RpcServer::RpcCallback callback = RpcCallbackNoReturn; auto transport = nullptr; // Attempt to create an RpcServer instance with valid parameters - EXPECT_THROW( - auto serverOrStatus = uprotocol::communication::RpcServer::create( - transport, *method_uri_, std::move(callback)), - uprotocol::transport::NullTransport); + EXPECT_THROW( // NOLINT + auto server_or_status = communication::RpcServer::create( + transport, *getMethodUri(), std::move(callback)), + transport::NullTransport); } // Test to verify RpcServer construction with a specific payload format -TEST_F(TestRpcServer, ConstructorWithPayloadFormat) { +TEST_F(TestRpcServer, ConstructorWithPayloadFormat) { // NOLINT // Define a callback that returns a specific value, simulating a response - uprotocol::communication::RpcServer::RpcCallback callback = - RpcCallbackWithReturn; + communication::RpcServer::RpcCallback callback = RpcCallbackWithReturn; // Attempt to create an RpcServer instance with the provided callback and a // specific format - auto serverOrStatus = uprotocol::communication::RpcServer::create( - mockTransport_, *method_uri_, std::move(callback), format); + auto server_or_status = communication::RpcServer::create( + getMockTransport(), *getMethodUri(), std::move(callback), getFormat()); // Ensure the server creation was successful and a valid instance was // returned - ASSERT_TRUE(serverOrStatus.has_value()); + ASSERT_TRUE(server_or_status.has_value()); // Retrieve the server instance from the optional return value - auto& serverPtr = serverOrStatus.value(); + const auto& server_ptr = server_or_status.value(); // Verify that the server instance is not null, indicating successful // creation - ASSERT_NE(serverPtr, nullptr); + ASSERT_NE(server_ptr, nullptr); } // Test to ensure RpcServer can be constructed with both a specific payload // format and TTL -TEST_F(TestRpcServer, ConstructorWithPayloadFormatAndTTL) { +TEST_F(TestRpcServer, ConstructorWithPayloadFormatAndTTL) { // NOLINT // Define a callback that returns a specific value, simulating a server // response - uprotocol::communication::RpcServer::RpcCallback callback = - RpcCallbackWithReturn; + communication::RpcServer::RpcCallback callback = RpcCallbackWithReturn; // Attempt to create an RpcServer instance with additional parameters: // payload format and TTL - auto serverOrStatus = uprotocol::communication::RpcServer::create( - mockTransport_, *method_uri_, std::move(callback), format, ttl_); + auto server_or_status = communication::RpcServer::create( + getMockTransport(), *getMethodUri(), std::move(callback), getFormat(), + getTTL()); // Verify that the server creation was successful and a valid instance was // returned - ASSERT_TRUE(serverOrStatus.has_value()); + ASSERT_TRUE(server_or_status.has_value()); // Retrieve the server instance from the optional return value - auto& serverPtr = serverOrStatus.value(); + const auto& server_ptr = server_or_status.value(); // Ensure that the server instance is not null, indicating successful // creation - ASSERT_NE(serverPtr, nullptr); + ASSERT_NE(server_ptr, nullptr); } // Test to verify RpcServer construction fails with invalid URI -TEST_F(TestRpcServer, ConstructorWithInvalidURI) { +TEST_F(TestRpcServer, ConstructorWithInvalidURI) { // NOLINT // Create an invalid URI object to simulate invalid input parameters - uprotocol::v1::UUri invalid_uri; + v1::UUri invalid_uri; // Expecte error message const std::string error_message = "Invalid rpc URI"; // Define a callback function to be used with the RpcServer, even though // it's expected to fail - uprotocol::communication::RpcServer::RpcCallback callback = - RpcCallbackNoReturn; + communication::RpcServer::RpcCallback callback = RpcCallbackNoReturn; // Attempt to create an RpcServer instance with the invalid URI and verify // creation fails - auto serverOrStatus = uprotocol::communication::RpcServer::create( - mockTransport_, invalid_uri, std::move(callback)); + auto server_or_status = communication::RpcServer::create( + getMockTransport(), invalid_uri, std::move(callback)); // Define the expected error code for this operation - uprotocol::v1::UCode expectedCode = uprotocol::v1::UCode::INVALID_ARGUMENT; + v1::UCode expected_code = v1::UCode::INVALID_ARGUMENT; // Verify that the error code matches the expected error code for invalid // arguments - EXPECT_EQ(serverOrStatus.error().code(), expectedCode); - EXPECT_EQ(serverOrStatus.error().message(), error_message); + EXPECT_EQ(server_or_status.error().code(), expected_code); + EXPECT_EQ(server_or_status.error().message(), error_message); } // Test to verify RpcServer construction fails with invalid PaylodFormat -TEST_F(TestRpcServer, ConstructorWithInvalidPaylodFormat) { +TEST_F(TestRpcServer, ConstructorWithInvalidPaylodFormat) { // NOLINT + constexpr uint16_t INVALID_PAYLOADFORMAT = 9999; + // Create an invalid PaylodFormat to simulate invalid input parameters - auto invalid_format = static_cast(9999); + auto invalid_format = + static_cast(INVALID_PAYLOADFORMAT); // Expecte error message const std::string error_message = "Invalid payload format"; // Define a callback function to be used with the RpcServer, even though // it's expected to fail - uprotocol::communication::RpcServer::RpcCallback callback = - RpcCallbackNoReturn; + communication::RpcServer::RpcCallback callback = RpcCallbackNoReturn; // Attempt to create an RpcServer instance with the invalid PaylodFormat and // verify creation fails - auto serverOrStatus = uprotocol::communication::RpcServer::create( - mockTransport_, *method_uri_, std::move(callback), invalid_format); + auto server_or_status = + communication::RpcServer::create(getMockTransport(), *getMethodUri(), + std::move(callback), invalid_format); // Define the expected error code for this operation - uprotocol::v1::UCode expectedCode = uprotocol::v1::UCode::OUT_OF_RANGE; + v1::UCode expected_code = v1::UCode::OUT_OF_RANGE; // Verify that the error code matches the expected error code for invalid // arguments - EXPECT_EQ(serverOrStatus.error().code(), expectedCode); - EXPECT_EQ(serverOrStatus.error().message(), error_message); + EXPECT_EQ(server_or_status.error().code(), expected_code); + EXPECT_EQ(server_or_status.error().message(), error_message); } // Test case to verify successful connection with a valid handle -TEST_F(TestRpcServer, ConnectwithValidHandle) { +TEST_F(TestRpcServer, ConnectwithValidHandle) { // NOLINT // Define a callback function that simulates a server response - uprotocol::communication::RpcServer::RpcCallback callback = - RpcCallbackWithReturn; + communication::RpcServer::RpcCallback callback = RpcCallbackWithReturn; // Attempt to create an RpcServer instance with mockTransport_ - auto serverOrStatus = uprotocol::communication::RpcServer::create( - mockTransport_, *method_uri_, std::move(callback), format); + auto server_or_status = communication::RpcServer::create( + getMockTransport(), *getMethodUri(), std::move(callback), getFormat()); // Check if the RpcServer was successfully created and a valid handle was // returned - EXPECT_TRUE(serverOrStatus.has_value()); + EXPECT_TRUE(server_or_status.has_value()); - // Retrieve the handle from the serverOrStatus object - auto& handle = serverOrStatus.value(); + // Retrieve the handle from the server_or_status object + const auto& handle = server_or_status.value(); // Ensure that the handle is not null, indicating successful server creation EXPECT_NE(handle, nullptr); // Verify that the register listener uri mataches with input method uri - EXPECT_TRUE(MsgDiff::Equals(*method_uri_, *mockTransport_->sink_filter_)); + EXPECT_TRUE( + MsgDiff::Equals(*getMethodUri(), *getMockTransport()->getSinkFilter())); } // Test case to verify RPC request handling with return payload and TTL -TEST_F(TestRpcServer, RPCRequestWithReturnPayloadAndTTL) { +TEST_F(TestRpcServer, RPCRequestWithReturnPayloadAndTTL) { // NOLINT // Expected response by RPC method std::string expected_response_payload = "RPC Response"; // Create a callback to be called when request is received - uprotocol::communication::RpcServer::RpcCallback callback = - RpcCallbackWithReturn; + communication::RpcServer::RpcCallback callback = RpcCallbackWithReturn; // Create a server to offer the RPC method - auto serverOrStatus = uprotocol::communication::RpcServer::create( - mockTransport_, *method_uri_, std::move(callback), format, ttl_); + auto server_or_status = communication::RpcServer::create( + getMockTransport(), *getMethodUri(), std::move(callback), getFormat(), + getTTL()); // Check if the server was created successfully - auto& handle = serverOrStatus.value(); + const auto& handle = server_or_status.value(); EXPECT_NE(handle, nullptr); - EXPECT_TRUE(MsgDiff::Equals(*method_uri_, *mockTransport_->sink_filter_)); + EXPECT_TRUE( + MsgDiff::Equals(*getMethodUri(), *getMockTransport()->getSinkFilter())); // Create request umessage - auto builder = uprotocol::datamodel::builder::UMessageBuilder::request( - std::move(*method_uri_), std::move(*request_uri_), - uprotocol::v1::UPriority::UPRIORITY_CS5, ttl_); + auto builder = datamodel::builder::UMessageBuilder::request( + std::move(*getMethodUri()), std::move(*getRequestUri()), + v1::UPriority::UPRIORITY_CS5, getTTL()); auto msg = builder.build(); // Ignore the return value - auto _ = mockTransport_->send(msg); - EXPECT_TRUE(mockTransport_->send_count_ == 1); - EXPECT_TRUE(mockTransport_->listener_); - mockTransport_->mockMessage(msg); - EXPECT_TRUE(mockTransport_->send_count_ == 2); + auto _ = getMockTransport()->send(msg); + EXPECT_TRUE(getMockTransport()->getSendCount() == 1); + EXPECT_TRUE(getMockTransport()->getListener()); + getMockTransport()->mockMessage(msg); + EXPECT_TRUE(getMockTransport()->getSendCount() == 2); // Compare expected reposen message with actual response message auto expected_response_msg = - uprotocol::datamodel::builder::UMessageBuilder::response(msg) - .withTtl(ttl_) - .withPayloadFormat(format) - .build({expected_response_payload, format}); - + datamodel::builder::UMessageBuilder::response(msg) + .withTtl(getTTL()) + .withPayloadFormat(getFormat()) + .build({expected_response_payload, getFormat()}); + + EXPECT_TRUE(MsgDiff::Equals( + expected_response_msg.attributes().source(), + getMockTransport()->getMessage().attributes().source())); EXPECT_TRUE( - MsgDiff::Equals(expected_response_msg.attributes().source(), - mockTransport_->message_.attributes().source())); - EXPECT_TRUE(MsgDiff::Equals(expected_response_msg.attributes().sink(), - mockTransport_->message_.attributes().sink())); - EXPECT_TRUE(MsgDiff::Equals(expected_response_msg.attributes().reqid(), - mockTransport_->message_.attributes().reqid())); + MsgDiff::Equals(expected_response_msg.attributes().sink(), + getMockTransport()->getMessage().attributes().sink())); + EXPECT_TRUE( + MsgDiff::Equals(expected_response_msg.attributes().reqid(), + getMockTransport()->getMessage().attributes().reqid())); EXPECT_EQ(static_cast(expected_response_msg.attributes().type()), - static_cast(mockTransport_->message_.attributes().type())); - EXPECT_EQ(static_cast(expected_response_msg.attributes().ttl()), - static_cast(mockTransport_->message_.attributes().ttl())); + static_cast( + getMockTransport()->getMessage().attributes().type())); EXPECT_EQ( - static_cast(expected_response_msg.attributes().priority()), - static_cast(mockTransport_->message_.attributes().priority())); - EXPECT_EQ(mockTransport_->message_.payload().data(), + static_cast(expected_response_msg.attributes().ttl()), + static_cast(getMockTransport()->getMessage().attributes().ttl())); + EXPECT_EQ(static_cast(expected_response_msg.attributes().priority()), + static_cast( + getMockTransport()->getMessage().attributes().priority())); + EXPECT_EQ(getMockTransport()->getMessage().payload().data(), expected_response_payload); } // Test case to verify RPC request handling without return payload -TEST_F(TestRpcServer, RPCRequestWithoutReturnPayload) { +TEST_F(TestRpcServer, RPCRequestWithoutReturnPayload) { // NOLINT // Create a callback to be called when request is received - uprotocol::communication::RpcServer::RpcCallback callback = - RpcCallbackNoReturn; + communication::RpcServer::RpcCallback callback = RpcCallbackNoReturn; // Create a server to offer the RPC method - auto serverOrStatus = uprotocol::communication::RpcServer::create( - mockTransport_, *method_uri_, std::move(callback)); + auto server_or_status = communication::RpcServer::create( + getMockTransport(), *getMethodUri(), std::move(callback)); // Check if the server was created successfully - auto& handle = serverOrStatus.value(); + const auto& handle = server_or_status.value(); EXPECT_NE(handle, nullptr); - EXPECT_TRUE(MsgDiff::Equals(*method_uri_, *mockTransport_->sink_filter_)); + EXPECT_TRUE( + MsgDiff::Equals(*getMethodUri(), *getMockTransport()->getSinkFilter())); // Create request umessage - auto builder = uprotocol::datamodel::builder::UMessageBuilder::request( - std::move(*method_uri_), std::move(*request_uri_), - uprotocol::v1::UPriority::UPRIORITY_CS5, ttl_); + auto builder = datamodel::builder::UMessageBuilder::request( + std::move(*getMethodUri()), std::move(*getRequestUri()), + v1::UPriority::UPRIORITY_CS5, getTTL()); auto msg = builder.build(); // Ignore the return value - auto _ = mockTransport_->send(msg); - EXPECT_TRUE(mockTransport_->send_count_ == 1); - EXPECT_TRUE(mockTransport_->listener_); - mockTransport_->mockMessage(msg); - EXPECT_TRUE(mockTransport_->send_count_ == 2); + auto _ = getMockTransport()->send(msg); + EXPECT_TRUE(getMockTransport()->getSendCount() == 1); + EXPECT_TRUE(getMockTransport()->getListener()); + getMockTransport()->mockMessage(msg); + EXPECT_TRUE(getMockTransport()->getSendCount() == 2); // Compare expected reposen message with actual response message auto expected_response_msg = - uprotocol::datamodel::builder::UMessageBuilder::response(msg).build(); + datamodel::builder::UMessageBuilder::response(msg).build(); + EXPECT_TRUE(MsgDiff::Equals( + expected_response_msg.attributes().source(), + getMockTransport()->getMessage().attributes().source())); EXPECT_TRUE( - MsgDiff::Equals(expected_response_msg.attributes().source(), - mockTransport_->message_.attributes().source())); - EXPECT_TRUE(MsgDiff::Equals(expected_response_msg.attributes().sink(), - mockTransport_->message_.attributes().sink())); - EXPECT_TRUE(MsgDiff::Equals(expected_response_msg.attributes().reqid(), - mockTransport_->message_.attributes().reqid())); + MsgDiff::Equals(expected_response_msg.attributes().sink(), + getMockTransport()->getMessage().attributes().sink())); + EXPECT_TRUE( + MsgDiff::Equals(expected_response_msg.attributes().reqid(), + getMockTransport()->getMessage().attributes().reqid())); EXPECT_EQ(static_cast(expected_response_msg.attributes().type()), - static_cast(mockTransport_->message_.attributes().type())); - EXPECT_EQ( - static_cast(expected_response_msg.attributes().priority()), - static_cast(mockTransport_->message_.attributes().priority())); - EXPECT_FALSE(mockTransport_->message_.has_payload()); + static_cast( + getMockTransport()->getMessage().attributes().type())); + EXPECT_EQ(static_cast(expected_response_msg.attributes().priority()), + static_cast( + getMockTransport()->getMessage().attributes().priority())); + EXPECT_FALSE(getMockTransport()->getMessage().has_payload()); } // Test case to verify RPC request handling with invalid request -TEST_F(TestRpcServer, RPCRequestWithInValidRequest) { +TEST_F(TestRpcServer, RPCRequestWithInValidRequest) { // NOLINT + constexpr std::chrono::milliseconds THREEHOUNDRED_MILLISECONDS(300); // Create a callback to be called when request is received - uprotocol::communication::RpcServer::RpcCallback callback = - RpcCallbackWithReturn; + communication::RpcServer::RpcCallback callback = RpcCallbackWithReturn; // Create a server to offer the RPC method - auto serverOrStatus = uprotocol::communication::RpcServer::create( - mockTransport_, *method_uri_, std::move(callback), format, ttl_); + auto server_or_status = communication::RpcServer::create( + getMockTransport(), *getMethodUri(), std::move(callback), getFormat(), + getTTL()); // Check if the server was created successfully - auto& handle = serverOrStatus.value(); + const auto& handle = server_or_status.value(); EXPECT_NE(handle, nullptr); // Create request umessage using namespace std::chrono_literals; - auto builder = uprotocol::datamodel::builder::UMessageBuilder::request( - std::move(*method_uri_), std::move(*request_uri_), - uprotocol::v1::UPriority::UPRIORITY_CS5, 300ms); + auto builder = datamodel::builder::UMessageBuilder::request( + std::move(*getMethodUri()), std::move(*getRequestUri()), + v1::UPriority::UPRIORITY_CS5, THREEHOUNDRED_MILLISECONDS); auto msg = builder.build(); @@ -406,40 +433,40 @@ TEST_F(TestRpcServer, RPCRequestWithInValidRequest) { msg.mutable_attributes()->mutable_sink()->set_resource_id(0); // Check results when invalid request is received - EXPECT_TRUE(mockTransport_->listener_); - mockTransport_->mockMessage(msg); - EXPECT_TRUE(mockTransport_->send_count_ == 0); + EXPECT_TRUE(getMockTransport()->getListener()); + getMockTransport()->mockMessage(msg); + EXPECT_TRUE(getMockTransport()->getSendCount() == 0); } // Test case to verify RPC sever resets the listener when the server is // destroyed -TEST_F(TestRpcServer, RestRPCServerHandle) { - uprotocol::communication::RpcServer::RpcCallback callback = - RpcCallbackWithReturn; +TEST_F(TestRpcServer, RestRPCServerHandle) { // NOLINT + communication::RpcServer::RpcCallback callback = RpcCallbackWithReturn; { - auto serverOrStatus = uprotocol::communication::RpcServer::create( - mockTransport_, *method_uri_, std::move(callback), format); + auto server_or_status = communication::RpcServer::create( + getMockTransport(), *getMethodUri(), std::move(callback), + getFormat()); - EXPECT_TRUE(serverOrStatus.has_value()); + EXPECT_TRUE(server_or_status.has_value()); - auto& handle = serverOrStatus.value(); + const auto& handle = server_or_status.value(); EXPECT_NE(handle, nullptr); } // Create request umessage - auto builder = uprotocol::datamodel::builder::UMessageBuilder::request( - std::move(*method_uri_), std::move(*request_uri_), - uprotocol::v1::UPriority::UPRIORITY_CS5, ttl_); + auto builder = datamodel::builder::UMessageBuilder::request( + std::move(*getMethodUri()), std::move(*getRequestUri()), + v1::UPriority::UPRIORITY_CS5, getTTL()); auto msg = builder.build(); // Ignore the return value - auto _ = mockTransport_->send(msg); - EXPECT_TRUE(mockTransport_->send_count_ == 1); - mockTransport_->mockMessage(msg); + auto _ = getMockTransport()->send(msg); + EXPECT_TRUE(getMockTransport()->getSendCount() == 1); + getMockTransport()->mockMessage(msg); // Check if the listener is reset - EXPECT_FALSE(mockTransport_->send_count_ == 2); + EXPECT_FALSE(getMockTransport()->getSendCount() == 2); } -} // namespace +} // namespace uprotocol diff --git a/test/coverage/communication/SubscriberTest.cpp b/test/coverage/communication/SubscriberTest.cpp index c5f8414cc..e58921e22 100644 --- a/test/coverage/communication/SubscriberTest.cpp +++ b/test/coverage/communication/SubscriberTest.cpp @@ -19,13 +19,17 @@ #include "UTransportMock.h" #include "up-cpp/datamodel/validator/UUri.h" -namespace { +namespace uprotocol { using MsgDiff = google::protobuf::util::MessageDifferencer; -using namespace uprotocol::communication; -using namespace uprotocol::test; -namespace UriValidator = uprotocol::datamodel::validator::uri; class SubscriberTest : public testing::Test { +private: + uprotocol::v1::UUri testTopicUUri_; + uprotocol::v1::UUri testInvalidTopicUUri_; + uprotocol::v1::UUri testDefaultSourceUUri_; + size_t capture_count_ = 0; + uprotocol::v1::UMessage capture_msg_; + protected: // Run once per TEST_F. // Used to set up clean environments per test. @@ -35,7 +39,6 @@ class SubscriberTest : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. SubscriberTest() = default; - ~SubscriberTest() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. @@ -46,14 +49,19 @@ class SubscriberTest : public testing::Test { void buildInValidSubscribeURI(); void buildDefaultSourceURI(); - uprotocol::v1::UUri testTopicUUri_; - uprotocol::v1::UUri testInvalidTopicUUri_; - uprotocol::v1::UUri testDefaultSourceUUri_; - size_t capture_count_ = 0; - uprotocol::v1::UMessage capture_msg_; + uprotocol::v1::UUri getTestTopicUUri() const { return testTopicUUri_; } + uprotocol::v1::UUri getTestInvalidTopicUUri() const { + return testInvalidTopicUUri_; + } + uprotocol::v1::UUri getTestDefaultSourceUUri() const { + return testDefaultSourceUUri_; + } + size_t getCaptureCount() const { return capture_count_; } + uprotocol::v1::UMessage getCaptureMsg() const { return capture_msg_; } public: void handleCallbackMessage(const uprotocol::v1::UMessage& message); + ~SubscriberTest() override = default; }; void SubscriberTest::SetUp() { @@ -63,34 +71,46 @@ void SubscriberTest::SetUp() { } void SubscriberTest::buildValidSubscribeURI() { + constexpr uint32_t VALID_UE_ID = 0x00011101; + constexpr uint32_t DEFAULT_RESOURCE_ID = 0x8001; + testTopicUUri_.set_authority_name("192.168.1.10"); - testTopicUUri_.set_ue_id(0x00011101); + testTopicUUri_.set_ue_id(VALID_UE_ID); testTopicUUri_.set_ue_version_major(0x1); - testTopicUUri_.set_resource_id(0x8001); + testTopicUUri_.set_resource_id(DEFAULT_RESOURCE_ID); } void SubscriberTest::buildInValidSubscribeURI() { + constexpr uint32_t VALID_UE_ID = 0x00011101; + // Resource ID should be in the range of 0x8000 to 0xFFFF + constexpr uint32_t INVALID_RESOURCE_ID = 0x1200; + testInvalidTopicUUri_.set_authority_name("192.168.1.10"); - testInvalidTopicUUri_.set_ue_id(0x00011101); + testInvalidTopicUUri_.set_ue_id(VALID_UE_ID); testInvalidTopicUUri_.set_ue_version_major(0x1); - // Resource ID should be in the range of 0x8000 to 0xFFFF - testInvalidTopicUUri_.set_resource_id(0x1200); + testInvalidTopicUUri_.set_resource_id(INVALID_RESOURCE_ID); } void SubscriberTest::buildDefaultSourceURI() { + constexpr uint32_t DEFAULT_UE_ID = 0x00011102; + testDefaultSourceUUri_.set_authority_name("192.168.1.10"); - testDefaultSourceUUri_.set_ue_id(0x00011102); + testDefaultSourceUUri_.set_ue_id(DEFAULT_UE_ID); testDefaultSourceUUri_.set_ue_version_major(0x1); testDefaultSourceUUri_.set_resource_id(0x0); } std::string get_random_string(size_t length) { auto randchar = []() -> char { - const char charset[] = - "0123456789" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz"; - const size_t max_index = (sizeof(charset) - 1); - return charset[rand() % max_index]; + constexpr std::array CHARSET = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', + 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', + 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', + 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; + std::random_device rd; + std::mt19937 gen(rd()); + std::uniform_int_distribution<> distr(0, CHARSET.size() - 1); + return CHARSET.at(static_cast(distr(gen))); }; std::string str(length, 0); std::generate_n(str.begin(), length, randchar); @@ -104,103 +124,107 @@ void SubscriberTest::handleCallbackMessage( } // Positive test case to subscribe to a valid topic -TEST_F(SubscriberTest, SubscribeSuccess) { +TEST_F(SubscriberTest, SubscribeSuccess) { // NOLINT + constexpr uint16_t RANDOM_STRING_LENGTH = 1400; + auto transport = std::make_shared( - testDefaultSourceUUri_); + getTestDefaultSourceUUri()); - auto callback = [this](auto arg1) { + auto callback = [this](const auto& arg1) { return this->handleCallbackMessage(arg1); }; - auto result = - Subscriber::subscribe(transport, testTopicUUri_, std::move(callback)); + auto result = communication::Subscriber::subscribe( + transport, getTestTopicUUri(), std::move(callback)); - EXPECT_TRUE(transport->listener_); + EXPECT_TRUE(transport->getListener()); EXPECT_TRUE(result.has_value()); auto handle = std::move(result).value(); EXPECT_TRUE(handle); - EXPECT_TRUE(MsgDiff::Equals(testTopicUUri_, transport->source_filter_)); - EXPECT_FALSE(transport->sink_filter_); + EXPECT_TRUE( + MsgDiff::Equals(getTestTopicUUri(), transport->getSourceFilter())); + EXPECT_FALSE(transport->getSinkFilter()); const size_t max_count = 100; for (size_t i = 0; i < max_count; i++) { uprotocol::v1::UMessage msg; auto attr = std::make_shared(); *msg.mutable_attributes() = *attr; - msg.set_payload(get_random_string(1400)); + msg.set_payload(get_random_string(RANDOM_STRING_LENGTH)); transport->mockMessage(msg); - EXPECT_EQ(i + 1, capture_count_); - EXPECT_TRUE(MsgDiff::Equals(msg, capture_msg_)); + EXPECT_EQ(i + 1, getCaptureCount()); + EXPECT_TRUE(MsgDiff::Equals(msg, getCaptureMsg())); } } // Negative test case to subscribe to a invalid topic -TEST_F(SubscriberTest, SubscribeFailWithInvalidTopic) { +TEST_F(SubscriberTest, SubscribeFailWithInvalidTopic) { // NOLINT auto transport = std::make_shared( - testDefaultSourceUUri_); + getTestDefaultSourceUUri()); - auto callback = [this](auto arg1) { + auto callback = [this](const auto& arg1) { return this->handleCallbackMessage(arg1); }; // Subscribe to invalid UUri topic with resource ID not in correct range - EXPECT_THROW(auto result = Subscriber::subscribe( - transport, testInvalidTopicUUri_, std::move(callback)), - UriValidator::InvalidUUri); + EXPECT_THROW(auto result = communication::Subscriber::subscribe( // NOLINT + transport, getTestInvalidTopicUUri(), std::move(callback)), + datamodel::validator::uri::InvalidUUri); } // Negative test case to subscribe to a topic with registerListener failure -TEST_F(SubscriberTest, SubscribeFailWithErrorCode) { +TEST_F(SubscriberTest, SubscribeFailWithErrorCode) { // NOLINT auto transport = std::make_shared( - testDefaultSourceUUri_); + getTestDefaultSourceUUri()); - auto callback = [this](auto arg1) { + auto callback = [this](const auto& arg1) { return this->handleCallbackMessage(arg1); }; - uprotocol::v1::UStatus expectedStatus; - expectedStatus.set_code(uprotocol::v1::UCode::ABORTED); - transport->registerListener_status_ = expectedStatus; + uprotocol::v1::UStatus expected_status; + expected_status.set_code(uprotocol::v1::UCode::ABORTED); + transport->getRegisterListenerStatus() = expected_status; - auto result = - Subscriber::subscribe(transport, testTopicUUri_, std::move(callback)); + auto result = communication::Subscriber::subscribe( + transport, getTestTopicUUri(), std::move(callback)); - auto actualStatus = std::move(result).error(); - EXPECT_EQ(actualStatus.code(), expectedStatus.code()); + auto actual_status = std::move(result).error(); + EXPECT_EQ(actual_status.code(), expected_status.code()); } // subscribe to a topic with null transport -TEST_F(SubscriberTest, SubscribeNullTransport) { +TEST_F(SubscriberTest, SubscribeNullTransport) { // NOLINT // set transport to null auto transport = nullptr; - auto callback = [this](auto arg1) { + auto callback = [this](const auto& arg1) { return this->handleCallbackMessage(arg1); }; - EXPECT_THROW(auto result = Subscriber::subscribe(transport, testTopicUUri_, - std::move(callback)), + EXPECT_THROW(auto result = communication::Subscriber::subscribe( // NOLINT + transport, getTestTopicUUri(), std::move(callback)), std::invalid_argument); } // subscribe to a topic with null callback -TEST_F(SubscriberTest, SubscribeNullCallback) { +TEST_F(SubscriberTest, SubscribeNullCallback) { // NOLINT auto transport = std::make_shared( - testDefaultSourceUUri_); + getTestDefaultSourceUUri()); // bind to null callback auto test_subscribe_nullptr = [transport, this]() { - std::ignore = Subscriber::subscribe(transport, testTopicUUri_, - std::move(nullptr)); + std::ignore = communication::Subscriber::subscribe( + transport, getTestTopicUUri(), nullptr); }; - using namespace uprotocol::utils; - - EXPECT_THROW(test_subscribe_nullptr(), callbacks::EmptyFunctionObject); + EXPECT_THROW(test_subscribe_nullptr(), // NOLINT + utils::callbacks::EmptyFunctionObject); // Default construct a function object auto test_subscribe_empty = [transport, this]() { - std::ignore = Subscriber::subscribe(transport, testTopicUUri_, {}); + std::ignore = communication::Subscriber::subscribe( + transport, getTestTopicUUri(), {}); }; - EXPECT_THROW(test_subscribe_empty(), callbacks::EmptyFunctionObject); + EXPECT_THROW(test_subscribe_empty(), // NOLINT + utils::callbacks::EmptyFunctionObject); } -} // namespace +} // namespace uprotocol diff --git a/test/coverage/datamodel/PayloadBuilderTest.cpp b/test/coverage/datamodel/PayloadBuilderTest.cpp index ac8d46da6..26e837df0 100644 --- a/test/coverage/datamodel/PayloadBuilderTest.cpp +++ b/test/coverage/datamodel/PayloadBuilderTest.cpp @@ -14,8 +14,7 @@ #include -namespace { -using namespace uprotocol::datamodel::builder; +namespace uprotocol::datamodel::builder { struct TimeAsPayloadSerializer { static Payload::Serialized serialize(std::chrono::milliseconds t) { @@ -33,6 +32,14 @@ struct TimeAsPayloadSerializer { }; class PayloadTest : public testing::Test { +private: + // Note : Need to make the std::string version longer to avoid SSO (small + // string optimization) as it will interfere with the move tests + const std::string testStringPayload_ = + "Testttttttttttttttttttttttttttttttttttttttttttttttttttttttttt"; + const std::vector testBytesPayload_{'T', 'e', 's', 't', + '0', '1', '2', '3'}; + protected: // Run once per TEST_F. // Used to set up clean environments per test. @@ -42,107 +49,111 @@ class PayloadTest : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. PayloadTest() = default; - ~PayloadTest() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} - // Note : Need to make the std::string version longer to avoid SSO (small - // string optimization) as it will interfere with the move tests - const std::string testStringPayload_ = - "Testttttttttttttttttttttttttttttttttttttttttttttttttttttttttt"; - const std::vector testBytesPayload_{'T', 'e', 's', 't', - '0', '1', '2', '3'}; + [[nodiscard]] std::string getTestStringPayload() const { + return testStringPayload_; + } + [[nodiscard]] std::vector getTestBytesPayload() const { + return testBytesPayload_; + } + +public: + ~PayloadTest() override = default; }; /////////////////Serialized Protobuf Tests///////////////////////// // Create serialized protobuf payload and verify build payload -TEST_F(PayloadTest, CreateSerializedProtobufPayloadAndBuildTest) { +TEST_F(PayloadTest, CreateSerializedProtobufPayloadAndBuildTest) { // NOLINT // Arrange - uprotocol::v1::UUri uriObject; - uriObject.set_authority_name(testStringPayload_); - auto expectedPayloadData = uriObject.SerializeAsString(); + uprotocol::v1::UUri uri_object; + uri_object.set_authority_name(getTestStringPayload()); + auto expected_payload_data = uri_object.SerializeAsString(); // Act - Payload payload(uriObject); + Payload payload(uri_object); // Assert auto [payloadData, payloadFormat] = payload.buildCopy(); EXPECT_EQ(payloadFormat, uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_PROTOBUF); - EXPECT_EQ(payloadData, expectedPayloadData); + EXPECT_EQ(payloadData, expected_payload_data); } // Create serialized protobuf payload with empty message -TEST_F(PayloadTest, CreateEmptySerializedProtobufPayloadTest) { +TEST_F(PayloadTest, CreateEmptySerializedProtobufPayloadTest) { // NOLINT // Arrange - uprotocol::v1::UUri uriObject; - uriObject.set_authority_name(""); + uprotocol::v1::UUri uri_object; + uri_object.set_authority_name(""); // Act - Payload payload(uriObject); + Payload payload(uri_object); // Assert auto [payloadData, payloadFormat] = payload.buildCopy(); EXPECT_EQ(payloadFormat, uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_PROTOBUF); - EXPECT_EQ(payloadData, uriObject.SerializeAsString()); + EXPECT_EQ(payloadData, uri_object.SerializeAsString()); } // Create serialized protobuf payload and verify moved payload -TEST_F(PayloadTest, CreateSerializedProtobufPayloadAndMoveTest) { +TEST_F(PayloadTest, CreateSerializedProtobufPayloadAndMoveTest) { // NOLINT // Arrange - uprotocol::v1::UUri uriObject; - uriObject.set_authority_name(testStringPayload_); - auto expectedPayloadData = uriObject.SerializeAsString(); + uprotocol::v1::UUri uri_object; + uri_object.set_authority_name(getTestStringPayload()); + auto expected_payload_data = uri_object.SerializeAsString(); // Act - Payload payload(uriObject); - auto& [payload_reference, payload_format] = payload.buildCopy(); + Payload payload(uri_object); + const auto& [payload_reference, payload_format] = payload.buildCopy(); const void* original_address = payload_reference.data(); // Assert auto [payloadData, payloadFormat] = std::move(payload).buildMove(); EXPECT_EQ(payloadFormat, uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_PROTOBUF); - EXPECT_EQ(payloadData, expectedPayloadData); + EXPECT_EQ(payloadData, expected_payload_data); - EXPECT_THROW(auto result = payload.buildCopy(), Payload::PayloadMoved); + EXPECT_THROW(static_cast(payload.buildCopy()), // NOLINT + Payload::PayloadMoved); EXPECT_EQ(original_address, payloadData.data()); } // Create serialized protobuf payload. Verify exception for move paylod twice -TEST_F(PayloadTest, CreateSerializedProtobufPayloadAndMoveTwiceExceptionTest) { +TEST_F(PayloadTest, // NOLINT + CreateSerializedProtobufPayloadAndMoveTwiceExceptionTest) { // Arrange - uprotocol::v1::UUri uriObject; - uriObject.set_authority_name(testStringPayload_); + uprotocol::v1::UUri uri_object; + uri_object.set_authority_name(getTestStringPayload()); // Act - Payload payload(uriObject); + Payload payload(uri_object); // Assert auto [payloadData, payloadFormat] = std::move(payload).buildMove(); EXPECT_EQ(payloadFormat, uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_PROTOBUF); - EXPECT_EQ(payloadData, uriObject.SerializeAsString()); + EXPECT_EQ(payloadData, uri_object.SerializeAsString()); - EXPECT_THROW({ auto _ = std::move(payload).buildMove(); }, + EXPECT_THROW({ auto _ = std::move(payload).buildMove(); }, // NOLINT Payload::PayloadMoved); } // Create serialized protobuf payload. Call build after move. -TEST_F(PayloadTest, +TEST_F(PayloadTest, // NOLINT CreateSerializedProtobufPayloadAndCallBuildAfterMoveExceptionTest) { // Arrange - uprotocol::v1::UUri uriObject; - uriObject.set_authority_name(testStringPayload_); + uprotocol::v1::UUri uri_object; + uri_object.set_authority_name(getTestStringPayload()); // Act - Payload payload(uriObject); + Payload payload(uri_object); // Call move on payload first auto [payloadData, payloadFormat] = std::move(payload).buildMove(); @@ -150,106 +161,124 @@ TEST_F(PayloadTest, EXPECT_EQ(payloadFormat, uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_PROTOBUF); - EXPECT_EQ(payloadData, uriObject.SerializeAsString()); + EXPECT_EQ(payloadData, uri_object.SerializeAsString()); // Call build on payload after move - EXPECT_THROW(auto _ = payload.buildCopy(), Payload::PayloadMoved); + EXPECT_THROW(auto _ = payload.buildCopy(), // NOLINT + Payload::PayloadMoved); } /////////////Serializer Payload Protobuf Tests///////////////// // Create a serializer payload and verify build payload -TEST_F(PayloadTest, CreateSerializerPayloadAndBuildTest) { +TEST_F(PayloadTest, CreateSerializerPayloadAndBuildTest) { // NOLINT + constexpr uint16_t RANDOM_TIME = 1234; // Arrange - std::chrono::milliseconds t(1234); - TimeAsPayloadSerializer timeSerializer; - timeSerializer.setFormat( + std::chrono::milliseconds t(RANDOM_TIME); + TimeAsPayloadSerializer time_serializer; + uprotocol::datamodel::builder::TimeAsPayloadSerializer::setFormat( uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_RAW); - auto expectedSerializedObject = timeSerializer.serialize( - std::chrono::duration_cast(t)); + auto expected_serialized_object = + uprotocol::datamodel::builder::TimeAsPayloadSerializer::serialize( + std::chrono::duration_cast(t)); // Act - Payload payload(timeSerializer, t); + Payload payload(time_serializer, t); // Assert auto [payloadData, payloadFormat] = payload.buildCopy(); EXPECT_EQ(payloadData, - std::get(expectedSerializedObject)); - EXPECT_EQ(payloadFormat, - std::get(expectedSerializedObject)); + std::get(expected_serialized_object)); + EXPECT_EQ(payloadFormat, std::get( + expected_serialized_object)); } // Create a serializer payload with invalid format -TEST_F(PayloadTest, CreateSerializerPayloadWithInvalidFormat) { +TEST_F(PayloadTest, CreateSerializerPayloadWithInvalidFormat) { // NOLINT + constexpr uint16_t RANDOM_TIME = 1234; + constexpr uint16_t INVALID_PAYLOAD_FORMAT = 9999; + // Arrange - std::chrono::milliseconds t(1234); - TimeAsPayloadSerializer timeSerializer; - auto invalidFormat = static_cast(9999); + std::chrono::milliseconds t(RANDOM_TIME); + TimeAsPayloadSerializer time_serializer; + auto invalid_format = + static_cast(INVALID_PAYLOAD_FORMAT); // Ovreide the format with invalid value - timeSerializer.setFormat(invalidFormat); + uprotocol::datamodel::builder::TimeAsPayloadSerializer::setFormat( + invalid_format); - auto expectedSerializedObject = timeSerializer.serialize( - std::chrono::duration_cast(t)); + auto expected_serialized_object = + uprotocol::datamodel::builder::TimeAsPayloadSerializer::serialize( + std::chrono::duration_cast(t)); // Act - EXPECT_THROW(Payload payload(timeSerializer, t), std::out_of_range); + EXPECT_THROW(Payload payload(time_serializer, t), // NOLINT + std::out_of_range); } // Create a serializer payload and verify moved payload -TEST_F(PayloadTest, CreateSerializerPayloadAndMoveTest) { +TEST_F(PayloadTest, CreateSerializerPayloadAndMoveTest) { // NOLINT + constexpr uint16_t RANDOM_TIME = 12345; + // Arrange - std::chrono::milliseconds t(12345); - TimeAsPayloadSerializer timeSerializer; - timeSerializer.setFormat( + std::chrono::milliseconds t(RANDOM_TIME); + TimeAsPayloadSerializer time_serializer; + uprotocol::datamodel::builder::TimeAsPayloadSerializer::setFormat( uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_RAW); - auto expectedSerializedObject = timeSerializer.serialize( - std::chrono::duration_cast(t)); + auto expected_serialized_object = + uprotocol::datamodel::builder::TimeAsPayloadSerializer::serialize( + std::chrono::duration_cast(t)); // Act - Payload payload(timeSerializer, t); + Payload payload(time_serializer, t); // Assert auto [payloadData, payloadFormat] = std::move(payload).buildMove(); EXPECT_EQ(payloadData, - std::get(expectedSerializedObject)); - EXPECT_EQ(payloadFormat, - std::get(expectedSerializedObject)); + std::get(expected_serialized_object)); + EXPECT_EQ(payloadFormat, std::get( + expected_serialized_object)); - EXPECT_THROW(auto _ = payload.buildCopy(), Payload::PayloadMoved); + EXPECT_THROW(auto _ = payload.buildCopy(), // NOLINT + Payload::PayloadMoved); } ////////////////////////Byte Array Payload Tests//////////////////////// // Create payload of Byte array and check if the payload is created correctly -TEST_F(PayloadTest, ByteArrayPayloadTest) { +TEST_F(PayloadTest, ByteArrayPayloadTest) { // NOLINT // Arrange uprotocol::v1::UPayloadFormat format = uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_RAW; // Act - Payload payload(testBytesPayload_, format); + Payload payload(getTestBytesPayload(), format); // Assert - auto [serializedData, payloadFormat] = payload.buildCopy(); + auto [serialized_data, payloadFormat] = payload.buildCopy(); - EXPECT_EQ(serializedData, "Test0123"); + EXPECT_EQ(serialized_data, "Test0123"); EXPECT_EQ(payloadFormat, format); } // Create payload of Byte array with invalid format and check if it throws // exception -TEST_F(PayloadTest, ConstructorInvalidFormatForByteArrayPayloadTest) { +TEST_F(PayloadTest, // NOLINT + ConstructorInvalidFormatForByteArrayPayloadTest) { + constexpr uint16_t INVALID_PAYLOAD_FORMAT = 9999; + // Arrange - uprotocol::v1::UPayloadFormat invalid_format = - static_cast(9999); + auto invalid_format = + static_cast(INVALID_PAYLOAD_FORMAT); // Act and Assert - EXPECT_THROW(Payload payload(testBytesPayload_, invalid_format), - std::out_of_range); + EXPECT_THROW( // NOLINT + Payload payload(getTestBytesPayload(), invalid_format), + std::out_of_range); } // Create empty byte array payload -TEST_F(PayloadTest, EmptyByteArrayPayloadTest) { +TEST_F(PayloadTest, EmptyByteArrayPayloadTest) { // NOLINT // Arrange std::vector value_bytes = {}; uprotocol::v1::UPayloadFormat format = @@ -259,60 +288,64 @@ TEST_F(PayloadTest, EmptyByteArrayPayloadTest) { Payload payload(value_bytes, format); // Assert - auto [serializedData, payloadFormat] = payload.buildCopy(); + auto [serialized_data, payloadFormat] = payload.buildCopy(); - EXPECT_TRUE(serializedData.empty()); + EXPECT_TRUE(serialized_data.empty()); EXPECT_EQ(payloadFormat, format); } // Create byte array payload and call buildMove() -TEST_F(PayloadTest, MoveByteArrayPayloadTest) { +TEST_F(PayloadTest, MoveByteArrayPayloadTest) { // NOLINT // Arrange uprotocol::v1::UPayloadFormat format = uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_RAW; // Act - Payload payload(testBytesPayload_, format); - auto [serializedData, payloadFormat] = std::move(payload).buildMove(); + Payload payload(getTestBytesPayload(), format); + auto [serialized_data, payloadFormat] = std::move(payload).buildMove(); // Assert - EXPECT_EQ(serializedData, "Test0123"); + EXPECT_EQ(serialized_data, "Test0123"); EXPECT_EQ(payloadFormat, format); - EXPECT_THROW(auto _ = payload.buildCopy(), Payload::PayloadMoved); + EXPECT_THROW(auto _ = payload.buildCopy(), // NOLINT + Payload::PayloadMoved); } //////////////String Payload Tests////////////// // Create payload of std::string and check if the payload is created -TEST_F(PayloadTest, StringPayloadTest) { +TEST_F(PayloadTest, StringPayloadTest) { // NOLINT // Arrange uprotocol::v1::UPayloadFormat format = uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT; // Act - Payload payload(testStringPayload_, format); + Payload payload(getTestStringPayload(), format); // Assert - auto [serializedData, payloadFormat] = payload.buildCopy(); - EXPECT_EQ(serializedData, testStringPayload_); + auto [serialized_data, payloadFormat] = payload.buildCopy(); + EXPECT_EQ(serialized_data, getTestStringPayload()); EXPECT_EQ(payloadFormat, format); } // Create payload of std::string with invalid format -TEST_F(PayloadTest, ConstructorInvalidFormatForStringPayloadTest) { +TEST_F(PayloadTest, ConstructorInvalidFormatForStringPayloadTest) { // NOLINT + constexpr uint16_t INVALID_PAYLOAD_FORMAT = 9999; + // Arrange - uprotocol::v1::UPayloadFormat invalid_format = - static_cast(9999); + auto invalid_format = + static_cast(INVALID_PAYLOAD_FORMAT); // Act and Assert - EXPECT_THROW(Payload payload(testStringPayload_, invalid_format), - std::out_of_range); + EXPECT_THROW( // NOLINT + Payload payload(getTestStringPayload(), invalid_format), + std::out_of_range); } // Create empty string payload -TEST_F(PayloadTest, EmptyStringPayloadTest) { +TEST_F(PayloadTest, EmptyStringPayloadTest) { // NOLINT // Arrange - std::string value_string = ""; + std::string value_string; uprotocol::v1::UPayloadFormat format = uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT; @@ -320,32 +353,33 @@ TEST_F(PayloadTest, EmptyStringPayloadTest) { Payload payload(value_string, format); // Assert - auto [serializedData, payloadFormat] = payload.buildCopy(); - EXPECT_TRUE(serializedData.empty()); + auto [serialized_data, payloadFormat] = payload.buildCopy(); + EXPECT_TRUE(serialized_data.empty()); EXPECT_EQ(payloadFormat, format); } // Create std::string payload and call move on payload object test -TEST_F(PayloadTest, StringMovePayloadTest) { +TEST_F(PayloadTest, StringMovePayloadTest) { // NOLINT // Arrange uprotocol::v1::UPayloadFormat format = uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT; // Act - Payload payload(testStringPayload_, format); - auto [serializedData, payloadFormat] = std::move(payload).buildMove(); + Payload payload(getTestStringPayload(), format); + auto [serialized_data, payloadFormat] = std::move(payload).buildMove(); // Assert - EXPECT_EQ(serializedData, testStringPayload_); + EXPECT_EQ(serialized_data, getTestStringPayload()); EXPECT_EQ(payloadFormat, format); - EXPECT_THROW(auto _ = payload.buildCopy(), Payload::PayloadMoved); + EXPECT_THROW(auto _ = payload.buildCopy(), // NOLINT + Payload::PayloadMoved); } // Create Any and move payload object test TEST_F(PayloadTest, AnyMovePayloadTest) { // NOLINT // Arrange uprotocol::v1::UUri uri_object; // NOLINT - uri_object.set_authority_name(testStringPayload_); + uri_object.set_authority_name(getTestStringPayload()); google::protobuf::Any any; any.PackFrom(uri_object, "hello_world"); @@ -363,15 +397,15 @@ TEST_F(PayloadTest, AnyMovePayloadTest) { // NOLINT uprotocol::v1::UUri parsed_uri_object; EXPECT_TRUE(parsed_uri_object.ParseFromString(parsed_any.value())); - EXPECT_EQ(parsed_uri_object.authority_name(), testStringPayload_); + EXPECT_EQ(parsed_uri_object.authority_name(), getTestStringPayload()); } /////////////////////RValue String Payload Tests///////////////////// // Create RValue String Payload -TEST_F(PayloadTest, RValueStringPayloadTest) { +TEST_F(PayloadTest, RValueStringPayloadTest) { // NOLINT // Arrange - std::string value_string = testStringPayload_; + std::string value_string = getTestStringPayload(); uprotocol::v1::UPayloadFormat format = uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT; const void* original_address = value_string.data(); @@ -380,28 +414,32 @@ TEST_F(PayloadTest, RValueStringPayloadTest) { Payload payload(std::move(value_string), format); // Assert - auto [serializedData, payloadFormat] = std::move(payload).buildMove(); - EXPECT_EQ(serializedData, testStringPayload_); + auto [serialized_data, payloadFormat] = std::move(payload).buildMove(); + EXPECT_EQ(serialized_data, getTestStringPayload()); EXPECT_EQ(payloadFormat, format); - EXPECT_EQ(serializedData.data(), original_address); + EXPECT_EQ(serialized_data.data(), original_address); } // Create payload of RValue String with invalid format -TEST_F(PayloadTest, ConstructorInvalidFormatForRValueStringPayloadTest) { +TEST_F(PayloadTest, // NOLINT + ConstructorInvalidFormatForRValueStringPayloadTest) { + constexpr uint16_t INVALID_PAYLOAD_FORMAT = 9999; + // Arrange - std::string value_string = testStringPayload_; - uprotocol::v1::UPayloadFormat invalid_format = - static_cast(9999); + std::string value_string = getTestStringPayload(); + auto invalid_format = + static_cast(INVALID_PAYLOAD_FORMAT); // Act and Assert - EXPECT_THROW(Payload payload(std::move(value_string), invalid_format), - std::out_of_range); + EXPECT_THROW( // NOLINT + Payload payload(std::move(value_string), invalid_format), + std::out_of_range); } // Create empty RValue String payload -TEST_F(PayloadTest, EmptyRValueStringPayloadTest) { +TEST_F(PayloadTest, EmptyRValueStringPayloadTest) { // NOLINT // Arrange - std::string value_string = ""; + std::string value_string; uprotocol::v1::UPayloadFormat format = uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT; @@ -409,42 +447,43 @@ TEST_F(PayloadTest, EmptyRValueStringPayloadTest) { Payload payload(std::move(value_string), format); // Assert - auto [serializedData, payloadFormat] = payload.buildCopy(); - EXPECT_TRUE(serializedData.empty()); + auto [serialized_data, payloadFormat] = payload.buildCopy(); + EXPECT_TRUE(serialized_data.empty()); EXPECT_EQ(payloadFormat, format); } // Create RValue String and move payload object test -TEST_F(PayloadTest, RValueStringMovePayloadTest) { +TEST_F(PayloadTest, RValueStringMovePayloadTest) { // NOLINT // Arrange - std::string value_string = testStringPayload_; - const void* originalAddress = value_string.data(); + std::string value_string = getTestStringPayload(); + const void* original_address = value_string.data(); uprotocol::v1::UPayloadFormat format = uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT; // Act Payload payload(std::move(value_string), format); - auto [serializedData, payloadFormat] = std::move(payload).buildMove(); - const void* movedAddress = serializedData.data(); + auto [serialized_data, payloadFormat] = std::move(payload).buildMove(); + const void* moved_address = serialized_data.data(); // Assert - EXPECT_EQ(serializedData, testStringPayload_); + EXPECT_EQ(serialized_data, getTestStringPayload()); EXPECT_EQ(payloadFormat, format); - EXPECT_EQ(originalAddress, movedAddress); - EXPECT_THROW(auto _ = payload.buildCopy(), Payload::PayloadMoved); + EXPECT_EQ(original_address, moved_address); + EXPECT_THROW(auto _ = payload.buildCopy(), // NOLINT + Payload::PayloadMoved); } ///////////////////////RValue Serialized Payload Tests////////////////////// // Create RValue Serialized payload -TEST_F(PayloadTest, RvalueSerializedConstructorTest) { +TEST_F(PayloadTest, RvalueSerializedConstructorTest) { // NOLINT // Arrange uprotocol::v1::UPayloadFormat format = uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_RAW; Payload::Serialized serialized = - std::make_tuple(testStringPayload_, format); - const void* originalAddress = + std::make_tuple(getTestStringPayload(), format); + const void* original_address = std::get(serialized).data(); // Act @@ -452,30 +491,34 @@ TEST_F(PayloadTest, RvalueSerializedConstructorTest) { // Assert auto [payloadData, payloadFormat] = std::move(payload).buildMove(); - EXPECT_EQ(payloadData, testStringPayload_); + EXPECT_EQ(payloadData, getTestStringPayload()); EXPECT_EQ(payloadFormat, format); - EXPECT_EQ(payloadData.data(), originalAddress); + EXPECT_EQ(payloadData.data(), original_address); } // Create payload of RValue Serialized with invalid format -TEST_F(PayloadTest, ConstructorInvalidFormatForRValueSerializedPayloadTest) { +TEST_F(PayloadTest, // NOLINT + ConstructorInvalidFormatForRValueSerializedPayloadTest) { + constexpr uint16_t INVALID_PAYLOAD_FORMAT = 9999; + // Arrange - uprotocol::v1::UPayloadFormat format = - static_cast(9999); + auto format = + static_cast(INVALID_PAYLOAD_FORMAT); Payload::Serialized serialized = - std::make_tuple(testStringPayload_, format); + std::make_tuple(getTestStringPayload(), format); // Act - EXPECT_THROW(Payload payload(std::move(serialized));, std::out_of_range); + EXPECT_THROW(Payload payload(std::move(serialized)); // NOLINT + , std::out_of_range); } // Create empty RValue Serialized payload and build. -TEST_F(PayloadTest, EmptyRValueSerializedPayloadTest) { +TEST_F(PayloadTest, EmptyRValueSerializedPayloadTest) { // NOLINT // Arrange - std::string serializedData = ""; + std::string serialized_data; uprotocol::v1::UPayloadFormat format = uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_RAW; - Payload::Serialized serialized = std::make_tuple(serializedData, format); + Payload::Serialized serialized = std::make_tuple(serialized_data, format); // Act Payload payload(std::move(serialized)); @@ -487,103 +530,105 @@ TEST_F(PayloadTest, EmptyRValueSerializedPayloadTest) { } // Create RValue Serialized and move payload object test -TEST_F(PayloadTest, RValueSerializedMovePayloadTest) { +TEST_F(PayloadTest, RValueSerializedMovePayloadTest) { // NOLINT // Arrange uprotocol::v1::UPayloadFormat format = uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_RAW; Payload::Serialized serialized = - std::make_tuple(testStringPayload_, format); + std::make_tuple(getTestStringPayload(), format); - const void* originalAddress = + const void* original_address = std::get(serialized).data(); // Act Payload payload(std::move(serialized)); auto [payloadData, payloadFormat] = std::move(payload).buildMove(); - const void* movedAddress = payloadData.data(); + const void* moved_address = payloadData.data(); // Assert - EXPECT_EQ(payloadData, testStringPayload_); + EXPECT_EQ(payloadData, getTestStringPayload()); EXPECT_EQ(payloadFormat, format); - EXPECT_EQ(originalAddress, movedAddress); - EXPECT_THROW(auto _ = payload.buildCopy(), Payload::PayloadMoved); + EXPECT_EQ(original_address, moved_address); + EXPECT_THROW(auto _ = payload.buildCopy(), // NOLINT + Payload::PayloadMoved); } //////////////////////Other Constructor Tests/////////////////////// // Move Constructor Test -TEST_F(PayloadTest, MoveConstructorTest) { +TEST_F(PayloadTest, MoveConstructorTest) { // NOLINT // Arrange uprotocol::v1::UPayloadFormat format = uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT; - Payload originalPayload(testStringPayload_, format); + Payload original_payload(getTestStringPayload(), format); // Act - Payload movedPayload(std::move(originalPayload).buildMove()); + Payload moved_payload(std::move(original_payload).buildMove()); // Assert - auto [movedData, movedFormat] = movedPayload.buildCopy(); - EXPECT_EQ(movedData, testStringPayload_); + auto [movedData, movedFormat] = moved_payload.buildCopy(); + EXPECT_EQ(movedData, getTestStringPayload()); EXPECT_EQ(movedFormat, format); - EXPECT_THROW(auto _ = originalPayload.buildCopy(), Payload::PayloadMoved); + EXPECT_THROW(auto _ = original_payload.buildCopy(), // NOLINT + Payload::PayloadMoved); } // Cppy Constructor Test -TEST_F(PayloadTest, CopyConstructorTest) { +TEST_F(PayloadTest, CopyConstructorTest) { // NOLINT // Arrange uprotocol::v1::UPayloadFormat format = uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT; - Payload originalPayload(testStringPayload_, format); + Payload original_payload(getTestStringPayload(), format); // Act - Payload copiedPayload(originalPayload); + const Payload& copied_payload(original_payload); // Assert - auto [originalData, originalFormat] = originalPayload.buildCopy(); - auto [copiedData, copiedFormat] = copiedPayload.buildCopy(); + auto [originalData, originalFormat] = original_payload.buildCopy(); + auto [copiedData, copiedFormat] = copied_payload.buildCopy(); EXPECT_EQ(copiedData, originalData); EXPECT_EQ(copiedFormat, originalFormat); } // Move Assignment Operator Test -TEST_F(PayloadTest, MoveAssignmentOperatorTest) { +TEST_F(PayloadTest, MoveAssignmentOperatorTest) { // NOLINT // Arrange - uprotocol::v1::UUri uriObject1; - uriObject1.set_authority_name("test1"); - Payload payload1(uriObject1); + uprotocol::v1::UUri uri_object1; + uri_object1.set_authority_name("test1"); + Payload payload1(uri_object1); - uprotocol::v1::UUri uriObject2; - uriObject2.set_authority_name("test2"); - Payload payload2(uriObject2); + uprotocol::v1::UUri uri_object2; + uri_object2.set_authority_name("test2"); + Payload payload2(uri_object2); // Act payload1 = std::move(payload2); // Assert auto [payloadData, payloadFormat] = payload1.buildCopy(); - EXPECT_EQ(payloadData, uriObject2.SerializeAsString()); + EXPECT_EQ(payloadData, uri_object2.SerializeAsString()); EXPECT_EQ(payloadFormat, uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_PROTOBUF); } // Copy Assignment Operator Test -TEST_F(PayloadTest, CopyAssignmentOperatorTest) { +TEST_F(PayloadTest, CopyAssignmentOperatorTest) { // NOLINT // Arrange uprotocol::v1::UPayloadFormat format = uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT; - Payload originalPayload(testStringPayload_, format); - Payload copiedPayload(testStringPayload_, format); + Payload original_payload(getTestStringPayload(), format); + Payload copied_payload(getTestStringPayload(), format); // Act - copiedPayload = originalPayload; + copied_payload = original_payload; // Assert - auto [originalData, originalFormat] = originalPayload.buildCopy(); - auto [copiedData, copiedFormat] = copiedPayload.buildCopy(); + auto [originalData, originalFormat] = original_payload.buildCopy(); + auto [copiedData, copiedFormat] = copied_payload.buildCopy(); EXPECT_EQ(copiedData, originalData); EXPECT_EQ(copiedFormat, originalFormat); } -} // namespace +} // namespace uprotocol::datamodel::builder diff --git a/test/coverage/datamodel/UMessageBuilderTest.cpp b/test/coverage/datamodel/UMessageBuilderTest.cpp index 87d76bb54..53b007f6e 100644 --- a/test/coverage/datamodel/UMessageBuilderTest.cpp +++ b/test/coverage/datamodel/UMessageBuilderTest.cpp @@ -16,42 +16,70 @@ #include #include -namespace { -using namespace uprotocol::v1; -using namespace uprotocol::datamodel::serializer::uri; -using namespace uprotocol::datamodel::validator::uri; -using namespace uprotocol::datamodel::builder; -using namespace uprotocol::datamodel::validator::uuid; +constexpr uint16_t TTL_TIME = 5000; +constexpr uint32_t UI_ID_INVALID_TEST = 0xFFFF0000; + +namespace uprotocol { class TestUMessageBuilder : public testing::Test { protected: // Run once per TEST_F. // Used to set up clean environments per test. - void SetUp() override {} + void SetUp() override { + constexpr uint32_t SOURCE_UE_ID = 0x00011101; + constexpr uint32_t SINK_UE_ID = 0x00011102; + constexpr uint32_t METHOD_UE_ID = 0x00011103; + + constexpr uint32_t SOURCE_UE_VERSION_MAJOR = 0xF8; + constexpr uint32_t SINK_UE_VERSION_MAJOR = 0xF9; + constexpr uint32_t METHOD_UE_VERSION_MAJOR = 0xFA; + + constexpr uint32_t SOURCE_RESOURCE_ID = 0x8101; + constexpr uint32_t SINK_RESOURCE_ID = 0; + constexpr uint32_t METHOD_RESOURCE_ID = 0x0101; + + // Create a UUri object for testing + source_.set_authority_name("10.0.0.1"); + source_.set_ue_id(SOURCE_UE_ID); + source_.set_ue_version_major(SOURCE_UE_VERSION_MAJOR); + source_.set_resource_id(SOURCE_RESOURCE_ID); + + sink_.set_authority_name("10.0.0.2"); + sink_.set_ue_id(SINK_UE_ID); + sink_.set_ue_version_major(SINK_UE_VERSION_MAJOR); + sink_.set_resource_id(SINK_RESOURCE_ID); + + method_.set_authority_name("10.0.0.3"); + method_.set_ue_id(METHOD_UE_ID); + method_.set_ue_version_major(METHOD_UE_VERSION_MAJOR); + method_.set_resource_id(METHOD_RESOURCE_ID); + + req_id_ = datamodel::builder::UuidBuilder::getBuilder().build(); + } void TearDown() override {} - UMessageBuilder createFakeRequest() { - UPriority priority = UPriority::UPRIORITY_CS4; - std::chrono::milliseconds ttl(5000); - UUri method = method_; - UUri source = sink_; + datamodel::builder::UMessageBuilder createFakeRequest() { + v1::UPriority priority = v1::UPriority::UPRIORITY_CS4; + std::chrono::milliseconds ttl(TTL_TIME); + v1::UUri method = method_; + v1::UUri source = sink_; - return UMessageBuilder::request(std::move(method), std::move(source), - priority, ttl); + return datamodel::builder::UMessageBuilder::request( + std::move(method), std::move(source), priority, ttl); } - UMessageBuilder createFakeResponse() { - UUri sink = sink_; - UUri method = method_; - UUID request_id = reqId_; + datamodel::builder::UMessageBuilder createFakeResponse() { + v1::UUri sink = sink_; + v1::UUri method = method_; + v1::UUID request_id = req_id_; - UPriority priority = UPriority::UPRIORITY_CS4; - return UMessageBuilder::response(std::move(sink), std::move(request_id), - priority, std::move(method)); + v1::UPriority priority = v1::UPriority::UPRIORITY_CS4; + return datamodel::builder::UMessageBuilder::response( + std::move(sink), std::move(request_id), priority, + std::move(method)); } - bool urisAreEqual(const uprotocol::v1::UUri& uri1, - const uprotocol::v1::UUri& uri2) { + static bool urisAreEqual(const v1::UUri& uri1, const v1::UUri& uri2) { return uri1.authority_name() == uri2.authority_name() && uri1.ue_id() == uri2.ue_id() && uri1.ue_version_major() == uri2.ue_version_major() && @@ -60,280 +88,294 @@ class TestUMessageBuilder : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. TestUMessageBuilder() = default; - ~TestUMessageBuilder() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. - static void SetUpTestSuite() { - // Create a UUri object for testing - source_.set_authority_name("10.0.0.1"); - source_.set_ue_id(0x00011101); - source_.set_ue_version_major(0xF8); - source_.set_resource_id(0x8101); + static void SetUpTestSuite() {} + static void TearDownTestSuite() {} - sink_.set_authority_name("10.0.0.2"); - sink_.set_ue_id(0x00011102); - sink_.set_ue_version_major(0xF9); - sink_.set_resource_id(0); + const v1::UUri& getSource() const { return source_; } + const v1::UUri& getSink() const { return sink_; } + const v1::UUri& getMethod() const { return method_; } + const v1::UUID& getReqId() const { return req_id_; } - method_.set_authority_name("10.0.0.3"); - method_.set_ue_id(0x00011103); - method_.set_ue_version_major(0xFA); - method_.set_resource_id(0x0101); - - reqId_ = UuidBuilder::getBuilder().build(); - } - static void TearDownTestSuite() {} +private: + v1::UUri source_; + v1::UUri sink_; + v1::UUri method_; + v1::UUID req_id_; - static UUri source_; - static UUri sink_; - static UUri method_; - static UUID reqId_; +public: + ~TestUMessageBuilder() override = default; }; -UUri TestUMessageBuilder::source_; -UUri TestUMessageBuilder::sink_; -UUri TestUMessageBuilder::method_; -UUID TestUMessageBuilder::reqId_; - /// @brief Test the publish function of the UMessageBuilder -TEST_F(TestUMessageBuilder, PublishValidTopicUriSuccess) { - UUri topic = source_; - EXPECT_NO_THROW({ - auto builder = UMessageBuilder::publish(std::move(topic)); - UAttributes attr = builder.attributes(); - EXPECT_EQ(attr.type(), UMessageType::UMESSAGE_TYPE_PUBLISH); - EXPECT_EQ(AsString::serialize(attr.source()), - AsString::serialize(source_)); +TEST_F(TestUMessageBuilder, PublishValidTopicUriSuccess) { // NOLINT + v1::UUri topic = getSource(); + EXPECT_NO_THROW({ // NOLINT + auto builder = + datamodel::builder::UMessageBuilder::publish(std::move(topic)); + const v1::UAttributes& attr = builder.attributes(); + EXPECT_EQ(attr.type(), v1::UMessageType::UMESSAGE_TYPE_PUBLISH); + EXPECT_EQ( + datamodel::serializer::uri::AsString::serialize(attr.source()), + datamodel::serializer::uri::AsString::serialize(getSource())); }); } -TEST_F(TestUMessageBuilder, PublishInvalidTopicUriThrows) { - UUri topic; - EXPECT_THROW({ UMessageBuilder::publish(std::move(topic)); }, InvalidUUri); +TEST_F(TestUMessageBuilder, PublishInvalidTopicUriThrows) { // NOLINT + v1::UUri topic; + EXPECT_THROW( // NOLINT + { datamodel::builder::UMessageBuilder::publish(std::move(topic)); }, + datamodel::validator::uri::InvalidUUri); } /// @brief Test the notification function of the UMessageBuilder -TEST_F(TestUMessageBuilder, NotificationTest) { +TEST_F(TestUMessageBuilder, NotificationTest) { // NOLINT // Call the notification function - UUri source = source_; - UUri sink = sink_; + v1::UUri source = getSource(); + v1::UUri sink = getSink(); - EXPECT_NO_THROW({ - auto builder = - UMessageBuilder::notification(std::move(source), std::move(sink)); + EXPECT_NO_THROW({ // NOLINT + auto builder = datamodel::builder::UMessageBuilder::notification( + std::move(source), std::move(sink)); // Verify the result - UAttributes attr = builder.attributes(); - EXPECT_EQ(attr.type(), UMessageType::UMESSAGE_TYPE_NOTIFICATION); - EXPECT_EQ(AsString::serialize(attr.source()), - AsString::serialize(source_)); - EXPECT_EQ(AsString::serialize(attr.sink()), AsString::serialize(sink_)); + const v1::UAttributes& attr = builder.attributes(); + EXPECT_EQ(attr.type(), v1::UMessageType::UMESSAGE_TYPE_NOTIFICATION); + EXPECT_EQ( + datamodel::serializer::uri::AsString::serialize(attr.source()), + datamodel::serializer::uri::AsString::serialize(getSource())); + EXPECT_EQ(datamodel::serializer::uri::AsString::serialize(attr.sink()), + datamodel::serializer::uri::AsString::serialize(getSink())); }); } -TEST_F(TestUMessageBuilder, NotificationInvalidSourceUriThrows) { - UUri source; +TEST_F(TestUMessageBuilder, NotificationInvalidSourceUriThrows) { // NOLINT + v1::UUri source; // Set the source Service Instance ID a wildcard (any) - source.set_ue_id(0xFFFF0000); - UUri sink = sink_; - EXPECT_THROW( - { UMessageBuilder::notification(std::move(source), std::move(sink)); }, - InvalidUUri); + source.set_ue_id(UI_ID_INVALID_TEST); + v1::UUri sink = getSink(); + EXPECT_THROW( // NOLINT + { + datamodel::builder::UMessageBuilder::notification(std::move(source), + std::move(sink)); + }, + datamodel::validator::uri::InvalidUUri); } -TEST_F(TestUMessageBuilder, NotificationInvalidSinkUriThrows) { - UUri source = source_; - UUri sink; +TEST_F(TestUMessageBuilder, NotificationInvalidSinkUriThrows) { // NOLINT + v1::UUri source = getSource(); + v1::UUri sink; // Set the source Service Instance ID a wildcard (any) - sink.set_ue_id(0xFFFF0000); - EXPECT_THROW( - { UMessageBuilder::notification(std::move(source), std::move(sink)); }, - InvalidUUri); + sink.set_ue_id(UI_ID_INVALID_TEST); + EXPECT_THROW( // NOLINT + { + datamodel::builder::UMessageBuilder::notification(std::move(source), + std::move(sink)); + }, + datamodel::validator::uri::InvalidUUri); } /// @brief Test the request function of the UMessageBuilder -TEST_F(TestUMessageBuilder, RequestValidParametersSuccess) { - UPriority priority = UPriority::UPRIORITY_CS4; - std::chrono::milliseconds ttl(5000); - UUri method = method_; - UUri source = sink_; - - EXPECT_NO_THROW({ - auto builder = UMessageBuilder::request( +TEST_F(TestUMessageBuilder, RequestValidParametersSuccess) { // NOLINT + v1::UPriority priority = v1::UPriority::UPRIORITY_CS4; + std::chrono::milliseconds ttl(TTL_TIME); + v1::UUri method = getMethod(); + v1::UUri source = getSink(); + + EXPECT_NO_THROW({ // NOLINT + auto builder = datamodel::builder::UMessageBuilder::request( std::move(method), std::move(source), priority, ttl); auto attr = builder.build().attributes(); - EXPECT_EQ(attr.type(), UMessageType::UMESSAGE_TYPE_REQUEST); - EXPECT_EQ(AsString::serialize(attr.sink()), - AsString::serialize(method_)); - EXPECT_EQ(AsString::serialize(attr.source()), - AsString::serialize(sink_)); + EXPECT_EQ(attr.type(), v1::UMessageType::UMESSAGE_TYPE_REQUEST); + EXPECT_EQ(datamodel::serializer::uri::AsString::serialize(attr.sink()), + datamodel::serializer::uri::AsString::serialize(getMethod())); + EXPECT_EQ( + datamodel::serializer::uri::AsString::serialize(attr.source()), + datamodel::serializer::uri::AsString::serialize(getSink())); EXPECT_EQ(attr.priority(), priority); - EXPECT_EQ(attr.ttl(), 5000); + EXPECT_EQ(attr.ttl(), TTL_TIME); }); } -TEST_F(TestUMessageBuilder, RequestInvalidMethodUriThrows) { - UUri method; - UUri source = source_; - UPriority priority = UPriority::UPRIORITY_CS4; - std::chrono::milliseconds ttl(5000); - EXPECT_THROW( +TEST_F(TestUMessageBuilder, RequestInvalidMethodUriThrows) { // NOLINT + v1::UUri method; + v1::UUri source = getSource(); + v1::UPriority priority = v1::UPriority::UPRIORITY_CS4; + std::chrono::milliseconds ttl(TTL_TIME); + EXPECT_THROW( // NOLINT { - UMessageBuilder::request(std::move(method), std::move(source), - priority, ttl); + datamodel::builder::UMessageBuilder::request( + std::move(method), std::move(source), priority, ttl); }, - InvalidUUri); + datamodel::validator::uri::InvalidUUri); } -TEST_F(TestUMessageBuilder, RequestInvalidSourceUriThrows) { - UUri source; +TEST_F(TestUMessageBuilder, RequestInvalidSourceUriThrows) { // NOLINT + v1::UUri source; // Set the source Service Instance ID a wildcard (any) - source.set_ue_id(0xFFFF0000); - UUri method = method_; - UPriority priority = UPriority::UPRIORITY_CS4; - std::chrono::milliseconds ttl(5000); - EXPECT_THROW( + source.set_ue_id(UI_ID_INVALID_TEST); + v1::UUri method = getMethod(); + v1::UPriority priority = v1::UPriority::UPRIORITY_CS4; + std::chrono::milliseconds ttl(TTL_TIME); + EXPECT_THROW( // NOLINT { - UMessageBuilder::request(std::move(method), std::move(source), - priority, ttl); + datamodel::builder::UMessageBuilder::request( + std::move(method), std::move(source), priority, ttl); }, - InvalidUUri); + datamodel::validator::uri::InvalidUUri); } -TEST_F(TestUMessageBuilder, RequestInvalidTtlThrows) { - UUri method = method_; - UUri source = sink_; - UPriority priority = UPriority::UPRIORITY_CS4; +TEST_F(TestUMessageBuilder, RequestInvalidTtlThrows) { // NOLINT + v1::UUri method = getMethod(); + v1::UUri source = getSink(); + v1::UPriority priority = v1::UPriority::UPRIORITY_CS4; std::chrono::milliseconds ttl(-1); // Invalid TTL - EXPECT_THROW( + EXPECT_THROW( // NOLINT { - UMessageBuilder::request(std::move(method), std::move(source), - priority, ttl); + datamodel::builder::UMessageBuilder::request( + std::move(method), std::move(source), priority, ttl); }, std::out_of_range); } /// @brief Test the response function of the UMessageBuilder -TEST_F(TestUMessageBuilder, ResponseValidParametersSuccess) { - UUri sink = sink_; - UUri method = method_; - UUID request_id = reqId_; - - UPriority priority = UPriority::UPRIORITY_CS4; - EXPECT_NO_THROW({ - auto builder = - UMessageBuilder::response(std::move(sink), std::move(request_id), - priority, std::move(method)); - UAttributes attr = builder.attributes(); - EXPECT_EQ(attr.type(), UMessageType::UMESSAGE_TYPE_RESPONSE); - EXPECT_EQ(AsString::serialize(attr.sink()), AsString::serialize(sink_)); - EXPECT_EQ(AsString::serialize(attr.source()), - AsString::serialize(method_)); - // EXPECT_EQ(attr.reqid(), reqId_); +TEST_F(TestUMessageBuilder, ResponseValidParametersSuccess) { // NOLINT + v1::UUri sink = getSink(); + v1::UUri method = getMethod(); + v1::UUID request_id = getReqId(); + + v1::UPriority priority = v1::UPriority::UPRIORITY_CS4; + EXPECT_NO_THROW({ // NOLINT + auto builder = datamodel::builder::UMessageBuilder::response( + std::move(sink), std::move(request_id), priority, + std::move(method)); + const v1::UAttributes& attr = builder.attributes(); + EXPECT_EQ(attr.type(), v1::UMessageType::UMESSAGE_TYPE_RESPONSE); + EXPECT_EQ(datamodel::serializer::uri::AsString::serialize(attr.sink()), + datamodel::serializer::uri::AsString::serialize(getSink())); + EXPECT_EQ( + datamodel::serializer::uri::AsString::serialize(attr.source()), + datamodel::serializer::uri::AsString::serialize(getMethod())); + // EXPECT_EQ(attr.reqid(), req_id_); EXPECT_EQ(attr.priority(), priority); }); } -TEST_F(TestUMessageBuilder, ResponseInvalidMethodUriThrows) { - UUri sink = sink_; - UUri method; - UUID request_id = reqId_; - UPriority priority = UPriority::UPRIORITY_CS4; - EXPECT_THROW( +TEST_F(TestUMessageBuilder, ResponseInvalidMethodUriThrows) { // NOLINT + v1::UUri sink = getSink(); + v1::UUri method; + v1::UUID request_id = getReqId(); + v1::UPriority priority = v1::UPriority::UPRIORITY_CS4; + EXPECT_THROW( // NOLINT { - UMessageBuilder::response(std::move(sink), std::move(request_id), - priority, std::move(method)); + datamodel::builder::UMessageBuilder::response( + std::move(sink), std::move(request_id), priority, + std::move(method)); }, - InvalidUUri); + datamodel::validator::uri::InvalidUUri); } -TEST_F(TestUMessageBuilder, ResponseInvalidSinkUriThrows) { - UUri sink; +TEST_F(TestUMessageBuilder, ResponseInvalidSinkUriThrows) { // NOLINT + v1::UUri sink; // Set the source Service Instance ID a wildcard (any) - sink.set_ue_id(0xFFFF0000); - UUri method = method_; - UUID request_id = reqId_; - UPriority priority = UPriority::UPRIORITY_CS4; - EXPECT_THROW( + sink.set_ue_id(UI_ID_INVALID_TEST); + v1::UUri method = getMethod(); + v1::UUID request_id = getReqId(); + v1::UPriority priority = v1::UPriority::UPRIORITY_CS4; + EXPECT_THROW( // NOLINT { - UMessageBuilder::response(std::move(sink), std::move(request_id), - priority, std::move(method)); + datamodel::builder::UMessageBuilder::response( + std::move(sink), std::move(request_id), priority, + std::move(method)); }, - InvalidUUri); + datamodel::validator::uri::InvalidUUri); } -TEST_F(TestUMessageBuilder, ResponseInvalidRequestIdThrows) { - UUri sink = sink_; - UUri method = method_; - UUID request_id; - UPriority priority = UPriority::UPRIORITY_CS4; - EXPECT_THROW( +TEST_F(TestUMessageBuilder, ResponseInvalidRequestIdThrows) { // NOLINT + v1::UUri sink = getSink(); + v1::UUri method = getMethod(); + v1::UUID request_id; + v1::UPriority priority = v1::UPriority::UPRIORITY_CS4; + EXPECT_THROW( // NOLINT { - UMessageBuilder::response(std::move(sink), std::move(request_id), - priority, std::move(method)); + datamodel::builder::UMessageBuilder::response( + std::move(sink), std::move(request_id), priority, + std::move(method)); }, - InvalidUuid); + datamodel::validator::uuid::InvalidUuid); } /// @brief withPriority test -TEST_F(TestUMessageBuilder, WithPriorityValidForRequestOrResponseSuccess) { +TEST_F(TestUMessageBuilder, // NOLINT + WithPriorityValidForRequestOrResponseSuccess) { auto builder = createFakeRequest(); - EXPECT_NO_THROW({ builder.withPriority(UPriority::UPRIORITY_CS4); }); + EXPECT_NO_THROW( // NOLINT + { builder.withPriority(v1::UPriority::UPRIORITY_CS4); }); auto builder2 = createFakeResponse(); - EXPECT_NO_THROW({ builder2.withPriority(UPriority::UPRIORITY_CS4); }); + EXPECT_NO_THROW( // NOLINT + { builder2.withPriority(v1::UPriority::UPRIORITY_CS4); }); } -TEST_F(TestUMessageBuilder, WithPriorityOutOfRangeThrows) { +TEST_F(TestUMessageBuilder, WithPriorityOutOfRangeThrows) { // NOLINT auto builder = createFakeRequest(); - EXPECT_THROW( - { builder.withPriority(static_cast(UPriority_MIN - 1)); }, + EXPECT_THROW( // NOLINT + { + builder.withPriority( + static_cast(v1::UPriority_MIN - 1)); + }, std::out_of_range); - EXPECT_THROW( - { builder.withPriority(static_cast(UPriority_MAX + 1)); }, + EXPECT_THROW( // NOLINT + { + builder.withPriority( + static_cast(v1::UPriority_MAX + 1)); + }, std::out_of_range); } -TEST_F(TestUMessageBuilder, WithPriorityLessThanCS4ForRequestOrResponseThrows) { +TEST_F(TestUMessageBuilder, // NOLINT + WithPriorityLessThanCS4ForRequestOrResponseThrows) { auto builder = createFakeRequest(); - EXPECT_THROW( + EXPECT_THROW( // NOLINT { builder.withPriority( - static_cast(UPriority::UPRIORITY_CS4 - 1)); + static_cast(v1::UPriority::UPRIORITY_CS4 - 1)); }, std::out_of_range); auto builder2 = createFakeResponse(); - EXPECT_THROW( + EXPECT_THROW( // NOLINT { builder2.withPriority( - static_cast(UPriority::UPRIORITY_CS4 - 1)); + static_cast(v1::UPriority::UPRIORITY_CS4 - 1)); }, std::out_of_range); } ///@brief withTtl() tests -TEST_F(TestUMessageBuilder, WithTtlValidSuccess) { +TEST_F(TestUMessageBuilder, WithTtlValidSuccess) { // NOLINT auto builder = createFakeRequest(); - EXPECT_NO_THROW({ builder.withTtl(std::chrono::milliseconds(1)); }); - EXPECT_NO_THROW({ + EXPECT_NO_THROW( // NOLINT + { builder.withTtl(std::chrono::milliseconds(1)); }); + EXPECT_NO_THROW({ // NOLINT builder.withTtl( std::chrono::milliseconds(std::numeric_limits::max())); }); } -TEST_F(TestUMessageBuilder, WithTtlOutOfRangeThrows) { +TEST_F(TestUMessageBuilder, WithTtlOutOfRangeThrows) { // NOLINT auto builder = createFakeRequest(); - EXPECT_THROW({ builder.withTtl(std::chrono::milliseconds(-1)); }, + EXPECT_THROW({ builder.withTtl(std::chrono::milliseconds(-1)); }, // NOLINT std::out_of_range); - EXPECT_THROW( + EXPECT_THROW( // NOLINT { builder.withTtl(std::chrono::milliseconds( static_cast(std::numeric_limits::max()) + @@ -342,110 +384,119 @@ TEST_F(TestUMessageBuilder, WithTtlOutOfRangeThrows) { std::out_of_range); } -TEST_F(TestUMessageBuilder, WithTtlZeroThrows) { +TEST_F(TestUMessageBuilder, WithTtlZeroThrows) { // NOLINT auto builder = createFakeRequest(); - EXPECT_THROW({ builder.withTtl(std::chrono::milliseconds(0)); }, + EXPECT_THROW({ builder.withTtl(std::chrono::milliseconds(0)); }, // NOLINT std::out_of_range); } /// @brief withToken tests -TEST_F(TestUMessageBuilder, WithTokenEmptyStringSuccess) { +TEST_F(TestUMessageBuilder, WithTokenEmptyStringSuccess) { // NOLINT auto builder = createFakeRequest(); - EXPECT_NO_THROW({ builder.withToken(""); }); + EXPECT_NO_THROW({ builder.withToken(""); }); // NOLINT } -TEST_F(TestUMessageBuilder, WithTokenOnNonRequestThrows) { +TEST_F(TestUMessageBuilder, WithTokenOnNonRequestThrows) { // NOLINT auto builder = createFakeResponse(); - EXPECT_THROW({ builder.withToken("token"); }, std::domain_error); + EXPECT_THROW({ builder.withToken("token"); }, std::domain_error); // NOLINT } -TEST_F(TestUMessageBuilder, WithTokenOnRequestSuccess) { +TEST_F(TestUMessageBuilder, WithTokenOnRequestSuccess) { // NOLINT auto builder = createFakeRequest(); - EXPECT_NO_THROW({ builder.withToken("token"); }); + EXPECT_NO_THROW({ builder.withToken("token"); }); // NOLINT } /// @brief withPermissionLevel tests -TEST_F(TestUMessageBuilder, WithPermissionLevelOnRequestSuccess) { +TEST_F(TestUMessageBuilder, WithPermissionLevelOnRequestSuccess) { // NOLINT auto builder = createFakeRequest(); - EXPECT_NO_THROW({ builder.withPermissionLevel(1); }); + EXPECT_NO_THROW({ builder.withPermissionLevel(1); }); // NOLINT } -TEST_F(TestUMessageBuilder, WithPermissionLevelOnNonRequestThrows) { +TEST_F(TestUMessageBuilder, WithPermissionLevelOnNonRequestThrows) { // NOLINT auto builder = createFakeResponse(); - EXPECT_THROW({ builder.withPermissionLevel(1); }, std::domain_error); + EXPECT_THROW({ builder.withPermissionLevel(1); }, // NOLINT + std::domain_error); } -TEST_F(TestUMessageBuilder, WithPermissionLevelZeroSuccess) { +TEST_F(TestUMessageBuilder, WithPermissionLevelZeroSuccess) { // NOLINT auto builder = createFakeRequest(); - EXPECT_NO_THROW({ builder.withPermissionLevel(0); }); + EXPECT_NO_THROW({ builder.withPermissionLevel(0); }); // NOLINT } /// @brief withCommStatus tests -TEST_F(TestUMessageBuilder, WithCommStatusOnResponseSuccess) { +TEST_F(TestUMessageBuilder, WithCommStatusOnResponseSuccess) { // NOLINT auto builder = createFakeResponse(); - EXPECT_NO_THROW({ builder.withCommStatus(UCode::OK); }); + EXPECT_NO_THROW({ builder.withCommStatus(v1::UCode::OK); }); // NOLINT } -TEST_F(TestUMessageBuilder, WithCommStatusValidValueSuccess) { +TEST_F(TestUMessageBuilder, WithCommStatusValidValueSuccess) { // NOLINT auto builder = createFakeResponse(); - EXPECT_NO_THROW({ builder.withCommStatus(UCode::OK); }); + EXPECT_NO_THROW({ builder.withCommStatus(v1::UCode::OK); }); // NOLINT } -TEST_F(TestUMessageBuilder, WithCommStatusOnNonResponseThrows) { +TEST_F(TestUMessageBuilder, WithCommStatusOnNonResponseThrows) { // NOLINT auto builder = createFakeRequest(); - EXPECT_THROW({ builder.withCommStatus(UCode::OK); }, std::domain_error); + EXPECT_THROW({ builder.withCommStatus(v1::UCode::OK); }, // NOLINT + std::domain_error); } -TEST_F(TestUMessageBuilder, WithCommStatusInvalidValueThrows) { +TEST_F(TestUMessageBuilder, WithCommStatusInvalidValueThrows) { // NOLINT auto builder = createFakeResponse(); - EXPECT_THROW({ builder.withCommStatus(static_cast(-1)); }, - std::out_of_range); + EXPECT_THROW( // NOLINT + { builder.withCommStatus(static_cast(-1)); }, + std::out_of_range); } /// @brief withPayloadFormat tests -TEST_F(TestUMessageBuilder, WithPayloadFormatOnRequestSuccess) { +TEST_F(TestUMessageBuilder, WithPayloadFormatOnRequestSuccess) { // NOLINT auto builder = createFakeRequest(); - EXPECT_NO_THROW( - { builder.withPayloadFormat(UPayloadFormat::UPAYLOAD_FORMAT_JSON); }); + EXPECT_NO_THROW( // NOLINT + { + builder.withPayloadFormat(v1::UPayloadFormat::UPAYLOAD_FORMAT_JSON); + }); } -TEST_F(TestUMessageBuilder, WithPayloadFormatOnResponseSuccess) { +TEST_F(TestUMessageBuilder, WithPayloadFormatOnResponseSuccess) { // NOLINT auto builder = createFakeResponse(); - EXPECT_NO_THROW( - { builder.withPayloadFormat(UPayloadFormat::UPAYLOAD_FORMAT_JSON); }); + EXPECT_NO_THROW( // NOLINT + { + builder.withPayloadFormat(v1::UPayloadFormat::UPAYLOAD_FORMAT_JSON); + }); } -TEST_F(TestUMessageBuilder, WithPayloadFormatInvalidValueLessThanMinThrows) { +TEST_F(TestUMessageBuilder, // NOLINT + WithPayloadFormatInvalidValueLessThanMinThrows) { auto builder = createFakeRequest(); - EXPECT_THROW( + EXPECT_THROW( // NOLINT { builder.withPayloadFormat( - static_cast(UPayloadFormat_MIN - 1)); + static_cast(v1::UPayloadFormat_MIN - 1)); }, std::out_of_range); } -TEST_F(TestUMessageBuilder, WithPayloadFormatInvalidValueMoreThanMaxThrows) { +TEST_F(TestUMessageBuilder, // NOLINT + WithPayloadFormatInvalidValueMoreThanMaxThrows) { auto builder = createFakeRequest(); - EXPECT_THROW( + EXPECT_THROW( // NOLINT { builder.withPayloadFormat( - static_cast(UPayloadFormat_MAX + 1)); + static_cast(v1::UPayloadFormat_MAX + 1)); }, std::out_of_range); } /// @brief build() tests -TEST_F(TestUMessageBuilder, BuildWithPayloadFormatSuccess) { +TEST_F(TestUMessageBuilder, BuildWithPayloadFormatSuccess) { // NOLINT auto builder = createFakeRequest(); - EXPECT_NO_THROW({ auto message = builder.build(); }); + EXPECT_NO_THROW({ auto message = builder.build(); }); // NOLINT } -TEST_F(TestUMessageBuilder, BuildReturnsUMessage) { +TEST_F(TestUMessageBuilder, BuildReturnsUMessage) { // NOLINT auto builder = createFakeRequest(); auto message = builder.build(); - EXPECT_TRUE(typeid(message) == typeid(UMessage)); + EXPECT_TRUE(typeid(message) == typeid(v1::UMessage)); EXPECT_TRUE(builder.attributes().priority() == message.attributes().priority()); EXPECT_TRUE(builder.attributes().ttl() == message.attributes().ttl()); @@ -455,39 +506,46 @@ TEST_F(TestUMessageBuilder, BuildReturnsUMessage) { urisAreEqual(builder.attributes().sink(), message.attributes().sink())); } -TEST_F(TestUMessageBuilder, BuildWithoutPayloadFormatThrows) { +TEST_F(TestUMessageBuilder, BuildWithoutPayloadFormatThrows) { // NOLINT auto builder = createFakeRequest(); - builder.withPayloadFormat(UPayloadFormat::UPAYLOAD_FORMAT_JSON); - EXPECT_THROW( + builder.withPayloadFormat(v1::UPayloadFormat::UPAYLOAD_FORMAT_JSON); + EXPECT_THROW( // NOLINT { auto message = builder.build(); }, - uprotocol::datamodel::builder::UMessageBuilder::UnexpectedFormat); + datamodel::builder::UMessageBuilder::UnexpectedFormat); } -TEST_F(TestUMessageBuilder, BuildWithPayloadWithPayloadFormatSuccess) { +TEST_F(TestUMessageBuilder, // NOLINT + BuildWithPayloadWithPayloadFormatSuccess) { auto builder = createFakeRequest(); - builder.withPayloadFormat(UPayloadFormat::UPAYLOAD_FORMAT_TEXT); + builder.withPayloadFormat(v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT); std::string data = "test-data"; - Payload payload(data, UPayloadFormat::UPAYLOAD_FORMAT_TEXT); + datamodel::builder::Payload payload( + data, v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT); - EXPECT_NO_THROW({ auto message = builder.build(std::move(payload)); }); + EXPECT_NO_THROW( // NOLINT + { auto message = builder.build(std::move(payload)); }); } -TEST_F(TestUMessageBuilder, BuildWithPayloadWithoutPayloadFormatSuccess) { +TEST_F(TestUMessageBuilder, // NOLINT + BuildWithPayloadWithoutPayloadFormatSuccess) { auto builder = createFakeRequest(); std::string data = "test-data"; - Payload payload(data, UPayloadFormat::UPAYLOAD_FORMAT_TEXT); + datamodel::builder::Payload payload( + data, v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT); - EXPECT_NO_THROW({ auto message = builder.build(std::move(payload)); }); + EXPECT_NO_THROW( // NOLINT + { auto message = builder.build(std::move(payload)); }); } -TEST_F(TestUMessageBuilder, BuildWithPayloadReturnsUMessage) { +TEST_F(TestUMessageBuilder, BuildWithPayloadReturnsUMessage) { // NOLINT auto builder = createFakeRequest(); - builder.withPayloadFormat(UPayloadFormat::UPAYLOAD_FORMAT_TEXT); + builder.withPayloadFormat(v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT); std::string data = "test-data"; - Payload payload(data, UPayloadFormat::UPAYLOAD_FORMAT_TEXT); + datamodel::builder::Payload payload( + data, v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT); auto message = builder.build(std::move(payload)); - EXPECT_TRUE(typeid(message) == typeid(UMessage)); + EXPECT_TRUE(typeid(message) == typeid(v1::UMessage)); EXPECT_TRUE(builder.attributes().priority() == message.attributes().priority()); EXPECT_TRUE(builder.attributes().ttl() == message.attributes().ttl()); @@ -496,18 +554,20 @@ TEST_F(TestUMessageBuilder, BuildWithPayloadReturnsUMessage) { EXPECT_TRUE( urisAreEqual(builder.attributes().sink(), message.attributes().sink())); - EXPECT_TRUE(message.payload().data() == data); + EXPECT_TRUE(message.payload() == data); } -TEST_F(TestUMessageBuilder, BuildWithPayloadMismatchedPayloadFormatThrows) { +TEST_F(TestUMessageBuilder, // NOLINT + BuildWithPayloadMismatchedPayloadFormatThrows) { auto builder = createFakeRequest(); - builder.withPayloadFormat(UPayloadFormat::UPAYLOAD_FORMAT_JSON); + builder.withPayloadFormat(v1::UPayloadFormat::UPAYLOAD_FORMAT_JSON); std::string data = "test-data"; - Payload payload(data, UPayloadFormat::UPAYLOAD_FORMAT_TEXT); + datamodel::builder::Payload payload( + data, v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT); - EXPECT_THROW( + EXPECT_THROW( // NOLINT { auto message = builder.build(std::move(payload)); }, - uprotocol::datamodel::builder::UMessageBuilder::UnexpectedFormat); + datamodel::builder::UMessageBuilder::UnexpectedFormat); } -} // namespace +} // namespace uprotocol diff --git a/test/coverage/datamodel/UMessageValidatorTest.cpp b/test/coverage/datamodel/UMessageValidatorTest.cpp index 7624e584a..185143292 100644 --- a/test/coverage/datamodel/UMessageValidatorTest.cpp +++ b/test/coverage/datamodel/UMessageValidatorTest.cpp @@ -13,29 +13,38 @@ #include #include #include +#include -namespace { - -using namespace uprotocol::v1; -using namespace uprotocol::datamodel::validator::message; +namespace uprotocol::v1 { class TestUMessageValidator : public testing::Test { +private: + UUri source_; + UUri sink_; + // Note: this is used when intentionally setting an unexpected request ID + UUID reqId_; + protected: // Run once per TEST_F. // Used to set up clean environments per test. void SetUp() override { + constexpr uint32_t SOURCE_UE_ID = 0x00010001; + constexpr uint32_t SINK_UE_ID = 0x00010002; + constexpr uint32_t REQID_MSB = 0x1234; + constexpr uint32_t REQID_LSB = 0x5678; + source_.set_authority_name("10.0.0.1"); - source_.set_ue_id(0x00010001); + source_.set_ue_id(SOURCE_UE_ID); source_.set_ue_version_major(1); source_.set_resource_id(1); sink_.set_authority_name("10.0.0.2"); - sink_.set_ue_id(0x00010002); + sink_.set_ue_id(SINK_UE_ID); sink_.set_ue_version_major(2); sink_.set_resource_id(2); - reqId_.set_msb(0x1234); - reqId_.set_lsb(0x5678); + reqId_.set_msb(REQID_MSB); + reqId_.set_lsb(REQID_LSB); } void TearDown() override {} @@ -43,20 +52,23 @@ class TestUMessageValidator : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. TestUMessageValidator() = default; - ~TestUMessageValidator() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} - UUri source_; - UUri sink_; - // Note: this is used when intentionally setting an unexpected request ID - UUID reqId_; + UUri& getSource() { return source_; } + UUri& getSink() { return sink_; } + const UUID& getReqId() const { return reqId_; } + +public: + ~TestUMessageValidator() override = default; }; UAttributes fakeRequest(const UUri& source, const UUri& sink) { + constexpr uint16_t DEFAULT_TTL = 1000; + UAttributes attributes; static auto uuid_builder = @@ -68,7 +80,7 @@ UAttributes fakeRequest(const UUri& source, const UUri& sink) { *attributes.mutable_sink() = sink; attributes.set_priority(UPRIORITY_CS4); attributes.set_payload_format(UPAYLOAD_FORMAT_PROTOBUF); - attributes.set_ttl(1000); + attributes.set_ttl(DEFAULT_TTL); return attributes; } @@ -91,6 +103,8 @@ UAttributes fakeResponse(const UUri& sink, const UUri& source) { } UAttributes fakePublish(const UUri& source) { + constexpr uint16_t DEFAULT_TTL = 1000; + UAttributes attributes; static auto uuid_builder = @@ -100,7 +114,7 @@ UAttributes fakePublish(const UUri& source) { *attributes.mutable_id() = uuid_builder.build(); *attributes.mutable_source() = source; attributes.set_payload_format(UPAYLOAD_FORMAT_PROTOBUF); - attributes.set_ttl(1000); + attributes.set_ttl(DEFAULT_TTL); return attributes; } @@ -126,215 +140,281 @@ UMessage build(UAttributes& attributes) { return umessage; } -void testCommonAttributes(UAttributes& attributesIn) { - { - // valid w/ttl - auto attributes = UAttributes(attributesIn); - auto umessage = build(attributes); - auto [valid, reason] = areCommonAttributesValid(umessage); - EXPECT_TRUE(valid); - EXPECT_FALSE(reason.has_value()); - } +void testValidWithTTL(UAttributes& attributes_in) { + auto attributes = UAttributes(attributes_in); + auto umessage = build(attributes); + auto [valid, reason] = + uprotocol::datamodel::validator::message::areCommonAttributesValid( + umessage); + EXPECT_TRUE(valid); + EXPECT_FALSE(reason.has_value()); +} - { - // valid w/o ttl - auto attributes = UAttributes(attributesIn); - attributes.clear_ttl(); - auto umessage = build(attributes); - auto [valid, reason] = areCommonAttributesValid(umessage); - EXPECT_TRUE(valid); - EXPECT_FALSE(reason.has_value()); - } +void testValidWithoutTTL(UAttributes& attributes_in) { + auto attributes = UAttributes(attributes_in); + attributes.clear_ttl(); + auto umessage = build(attributes); + auto [valid, reason] = + uprotocol::datamodel::validator::message::areCommonAttributesValid( + umessage); + EXPECT_TRUE(valid); + EXPECT_FALSE(reason.has_value()); +} - { - // missing id - auto attributes = UAttributes(attributesIn); - attributes.clear_id(); - auto umessage = build(attributes); - auto [valid, reason] = areCommonAttributesValid(umessage); - EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::BAD_ID); - } +void testMissingId(UAttributes& attributes_in) { + auto attributes = UAttributes(attributes_in); + attributes.clear_id(); + auto umessage = build(attributes); + auto [valid, reason] = + uprotocol::datamodel::validator::message::areCommonAttributesValid( + umessage); + EXPECT_FALSE(valid); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason::BAD_ID); +} - { - // invalid id - auto attributes = UAttributes(attributesIn); - UUID local_id(attributes.id()); - local_id.set_lsb(0); - *attributes.mutable_id() = local_id; - auto umessage = build(attributes); - auto [valid, reason] = areCommonAttributesValid(umessage); - EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::BAD_ID); - } +void testInvalidId(UAttributes& attributes_in) { + auto attributes = UAttributes(attributes_in); + UUID local_id(attributes.id()); + local_id.set_lsb(0); + *attributes.mutable_id() = local_id; + auto umessage = build(attributes); + auto [valid, reason] = + uprotocol::datamodel::validator::message::areCommonAttributesValid( + umessage); + EXPECT_FALSE(valid); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason::BAD_ID); +} - { - // expired ttl - auto attributes = UAttributes(attributesIn); - attributes.set_ttl(10); - usleep(20000); // sleep (id should be expired by now) - auto umessage = build(attributes); - auto [valid, reason] = areCommonAttributesValid(umessage); - EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::ID_EXPIRED); - } +void testExpiredTTL(UAttributes& attributes_in) { + constexpr uint16_t SLEEP_TIME = 20000; + constexpr uint16_t DEFAULT_TTL = 10; + + auto attributes = UAttributes(attributes_in); + attributes.set_ttl(DEFAULT_TTL); + usleep(SLEEP_TIME); // sleep (id should be expired by now) + auto umessage = build(attributes); + auto [valid, reason] = + uprotocol::datamodel::validator::message::areCommonAttributesValid( + umessage); + EXPECT_FALSE(valid); + EXPECT_EQ(reason, + uprotocol::datamodel::validator::message::Reason::ID_EXPIRED); +} - { - // out of range priority - auto attributes = UAttributes(attributesIn); - attributes.set_priority(UPriority(UPriority_MAX + 10)); - auto umessage = build(attributes); - auto [valid, reason] = areCommonAttributesValid(umessage); - EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::PRIORITY_OUT_OF_RANGE); - } +void testOutOfRangePriority(UAttributes& attributes_in) { + constexpr uint16_t DEFAULT_TTL = 10; + + auto attributes = UAttributes(attributes_in); + attributes.set_priority(UPriority(UPriority_MAX + DEFAULT_TTL)); + auto umessage = build(attributes); + auto [valid, reason] = + uprotocol::datamodel::validator::message::areCommonAttributesValid( + umessage); + EXPECT_FALSE(valid); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + PRIORITY_OUT_OF_RANGE); +} - { - // out of range payload format - auto attributes = UAttributes(attributesIn); - attributes.set_payload_format(UPayloadFormat(UPayloadFormat_MAX + 10)); - auto umessage = build(attributes); - auto [valid, reason] = areCommonAttributesValid(umessage); - EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::PAYLOAD_FORMAT_OUT_OF_RANGE); - } +void testOutOfRangePayloadFormat(UAttributes& attributes_in) { + constexpr uint16_t DEFAULT_TTL = 10; + + auto attributes = UAttributes(attributes_in); + attributes.set_payload_format( + UPayloadFormat(UPayloadFormat_MAX + DEFAULT_TTL)); + auto umessage = build(attributes); + auto [valid, reason] = + uprotocol::datamodel::validator::message::areCommonAttributesValid( + umessage); + EXPECT_FALSE(valid); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + PAYLOAD_FORMAT_OUT_OF_RANGE); +} + +void testCommonAttributes(UAttributes& attributes_in) { + testValidWithTTL(attributes_in); + testValidWithoutTTL(attributes_in); + testMissingId(attributes_in); + testInvalidId(attributes_in); + testExpiredTTL(attributes_in); + testOutOfRangePriority(attributes_in); + testOutOfRangePayloadFormat(attributes_in); } -TEST_F(TestUMessageValidator, ValidRpcRequest) { - source_.set_resource_id(0); // must be 0 for valid requests +TEST_F(TestUMessageValidator, ValidRpcRequest) { // NOLINT + getSource().set_resource_id(0); // must be 0 for valid requests { // test common attributes for any message - auto attributes = fakeRequest(source_, sink_); + auto attributes = fakeRequest(getSource(), getSink()); testCommonAttributes(attributes); } { // valid - auto attributes = fakeRequest(source_, sink_); + auto attributes = fakeRequest(getSource(), getSink()); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcRequest(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcRequest( + umessage); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); } { // set wrong type - auto attributes = fakeRequest(source_, sink_); + auto attributes = fakeRequest(getSource(), getSink()); attributes.set_type(UMESSAGE_TYPE_RESPONSE); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcRequest(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcRequest( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::WRONG_MESSAGE_TYPE); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + WRONG_MESSAGE_TYPE); } { // missing source - auto attributes = fakeRequest(source_, sink_); + auto attributes = fakeRequest(getSource(), getSink()); attributes.clear_source(); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcRequest(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcRequest( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::BAD_SOURCE_URI); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::BAD_SOURCE_URI); } { // missing sink - auto attributes = fakeRequest(source_, sink_); + auto attributes = fakeRequest(getSource(), getSink()); attributes.clear_sink(); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcRequest(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcRequest( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::BAD_SINK_URI); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::BAD_SINK_URI); } { // invalid source - UUri source = source_; + UUri source = getSource(); source.set_resource_id(1); // should be zero - auto attributes = fakeRequest(source, sink_); + auto attributes = fakeRequest(source, getSink()); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcRequest(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcRequest( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::BAD_SOURCE_URI); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::BAD_SOURCE_URI); } { // invalid sink - UUri sink = sink_; + UUri sink = getSink(); sink.set_resource_id(0); // should NOT be zero - auto attributes = fakeRequest(source_, sink); + auto attributes = fakeRequest(getSource(), sink); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcRequest(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcRequest( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::BAD_SINK_URI); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::BAD_SINK_URI); } { // wrong priority - auto attributes = fakeRequest(source_, sink_); + auto attributes = fakeRequest(getSource(), getSink()); attributes.set_priority(UPRIORITY_CS3); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcRequest(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcRequest( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::PRIORITY_OUT_OF_RANGE); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + PRIORITY_OUT_OF_RANGE); } { // Missing TTL - auto attributes = fakeRequest(source_, sink_); + auto attributes = fakeRequest(getSource(), getSink()); attributes.clear_ttl(); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcRequest(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcRequest( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::INVALID_TTL); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::INVALID_TTL); } { // Invalid TTL (zero) - auto attributes = fakeRequest(source_, sink_); + auto attributes = fakeRequest(getSource(), getSink()); attributes.set_ttl(0); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcRequest(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcRequest( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::INVALID_TTL); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::INVALID_TTL); } { // incorrectly set commstatus - auto attributes = fakeRequest(source_, sink_); + auto attributes = fakeRequest(getSource(), getSink()); attributes.set_commstatus(OK); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcRequest(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcRequest( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::DISALLOWED_FIELD_SET); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + DISALLOWED_FIELD_SET); } { // incorrectly set reqid - auto attributes = fakeRequest(source_, sink_); - *attributes.mutable_reqid() = reqId_; + auto attributes = fakeRequest(getSource(), getSink()); + *attributes.mutable_reqid() = getReqId(); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcRequest(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcRequest( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::DISALLOWED_FIELD_SET); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + DISALLOWED_FIELD_SET); } } -TEST_F(TestUMessageValidator, ValidRpcResponse) { - source_.set_resource_id(0); +TEST_F(TestUMessageValidator, ValidRpcResponse) { // NOLINT + getSource().set_resource_id(0); { // test common attributes for any message - auto attributes = fakeResponse(source_, sink_); + auto attributes = fakeResponse(getSource(), getSink()); testCommonAttributes(attributes); } { // valid - auto attributes = fakeResponse(source_, sink_); + auto attributes = fakeResponse(getSource(), getSink()); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcResponse(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcResponse( + umessage); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); // Only for debugging a test - should only happen if test is already @@ -346,65 +426,88 @@ TEST_F(TestUMessageValidator, ValidRpcResponse) { { // set wrong type - auto attributes = fakeResponse(source_, sink_); + auto attributes = fakeResponse(getSource(), getSink()); attributes.set_type(UMESSAGE_TYPE_REQUEST); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcResponse(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcResponse( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::WRONG_MESSAGE_TYPE); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + WRONG_MESSAGE_TYPE); } { // missing source - auto attributes = fakeResponse(source_, sink_); + auto attributes = fakeResponse(getSource(), getSink()); attributes.clear_source(); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcResponse(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcResponse( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::BAD_SOURCE_URI); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::BAD_SOURCE_URI); } { // missing sink - auto attributes = fakeResponse(source_, sink_); + auto attributes = fakeResponse(getSource(), getSink()); attributes.clear_sink(); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcResponse(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcResponse( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::BAD_SINK_URI); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::BAD_SINK_URI); } { // invalid source - UUri source = source_; + UUri source = getSource(); source.set_resource_id(1); // should be zero - auto attributes = fakeResponse(source, sink_); + auto attributes = fakeResponse(source, getSink()); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcResponse(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcResponse( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::BAD_SINK_URI); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::BAD_SINK_URI); } { // invalid sink - UUri sink = sink_; + UUri sink = getSink(); sink.set_resource_id(0); // should NOT be zero - auto attributes = fakeResponse(source_, sink); + auto attributes = fakeResponse(getSource(), sink); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcResponse(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcResponse( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::BAD_SOURCE_URI); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::BAD_SOURCE_URI); } { // missing reqid - UUri sink = sink_; - auto attributes = fakeResponse(source_, sink_); + UUri sink = getSink(); + auto attributes = fakeResponse(getSource(), getSink()); attributes.clear_reqid(); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcResponse(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcResponse( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::REQID_MISMATCH); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::REQID_MISMATCH); } { @@ -412,77 +515,99 @@ TEST_F(TestUMessageValidator, ValidRpcResponse) { UUID local_id; local_id.set_lsb(0); local_id.set_msb(0); - auto attributes = fakeResponse(source_, sink_); + auto attributes = fakeResponse(getSource(), getSink()); *attributes.mutable_reqid() = local_id; auto umessage = build(attributes); - auto [valid, reason] = isValidRpcResponse(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcResponse( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::REQID_MISMATCH); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::REQID_MISMATCH); } { // no ttl set - auto attributes = fakeResponse(source_, sink_); + auto attributes = fakeResponse(getSource(), getSink()); attributes.clear_ttl(); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcResponse(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcResponse( + umessage); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); } { // expired ttl - auto attributes = fakeResponse(source_, sink_); + constexpr uint16_t SLEEP_TIME = 20000; + auto attributes = fakeResponse(getSource(), getSink()); attributes.set_ttl(1); - usleep(20000); // sleep (id should be expired by now) + usleep(SLEEP_TIME); // sleep (id should be expired by now) auto umessage = build(attributes); - auto [valid, reason] = isValidRpcResponse(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcResponse( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::ID_EXPIRED); + EXPECT_EQ(reason, + uprotocol::datamodel::validator::message::Reason::ID_EXPIRED); } { // invalid priority - auto attributes = fakeResponse(source_, sink_); + auto attributes = fakeResponse(getSource(), getSink()); attributes.set_priority(UPRIORITY_CS3); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcResponse(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcResponse( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::PRIORITY_OUT_OF_RANGE); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + PRIORITY_OUT_OF_RANGE); } { // set permission level (shouldn't be set) - auto attributes = fakeResponse(source_, sink_); - attributes.set_permission_level(7); + constexpr uint16_t ATTRIBUTES_PERMISSION_LEVEL = 7; + auto attributes = fakeResponse(getSource(), getSink()); + attributes.set_permission_level(ATTRIBUTES_PERMISSION_LEVEL); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcResponse(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcResponse( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::DISALLOWED_FIELD_SET); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + DISALLOWED_FIELD_SET); } { // set token (shouldn't be set) - auto attributes = fakeResponse(source_, sink_); + auto attributes = fakeResponse(getSource(), getSink()); attributes.set_token("token"); auto umessage = build(attributes); - auto [valid, reason] = isValidRpcResponse(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcResponse( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::DISALLOWED_FIELD_SET); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + DISALLOWED_FIELD_SET); } } -TEST_F(TestUMessageValidator, ValidRpcResponseFor) { - source_.set_resource_id(0); +TEST_F(TestUMessageValidator, ValidRpcResponseFor) { // NOLINT + getSource().set_resource_id(0); { // valid - auto req_attr = fakeRequest(source_, sink_); - auto res_attr = fakeResponse(source_, sink_); + auto req_attr = fakeRequest(getSource(), getSink()); + auto res_attr = fakeResponse(getSource(), getSink()); *res_attr.mutable_reqid() = req_attr.id(); auto request = build(req_attr); auto response = build(res_attr); - auto [valid, reason] = isValidRpcResponseFor(request, response); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcResponseFor( + request, response); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); // Only for debugging test - shows reason when test is already failing @@ -493,293 +618,377 @@ TEST_F(TestUMessageValidator, ValidRpcResponseFor) { { // missing reqId - auto req_attr = fakeRequest(source_, sink_); - auto res_attr = fakeResponse(source_, sink_); + auto req_attr = fakeRequest(getSource(), getSink()); + auto res_attr = fakeResponse(getSource(), getSink()); res_attr.clear_reqid(); auto request = build(req_attr); auto response = build(res_attr); - auto [valid, reason] = isValidRpcResponseFor(request, response); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcResponseFor( + request, response); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::REQID_MISMATCH); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::REQID_MISMATCH); } { // invalid reqId (does NOT match the request's id) - auto req_attr = fakeRequest(source_, sink_); - auto res_attr = fakeResponse(source_, sink_); + auto req_attr = fakeRequest(getSource(), getSink()); + auto res_attr = fakeResponse(getSource(), getSink()); *res_attr.mutable_reqid() = res_attr.id(); auto request = build(req_attr); auto response = build(res_attr); - auto [valid, reason] = isValidRpcResponseFor(request, response); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcResponseFor( + request, response); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::REQID_MISMATCH); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::REQID_MISMATCH); } { // URI Mismatch - the response's sink doesn't match the request source - auto req_attr = fakeRequest(source_, sink_); - auto res_attr = fakeResponse(source_, sink_); + auto req_attr = fakeRequest(getSource(), getSink()); + auto res_attr = fakeResponse(getSource(), getSink()); res_attr.mutable_sink()->set_ue_version_major( res_attr.sink().ue_version_major() + 1); auto request = build(req_attr); auto response = build(res_attr); - auto [valid, reason] = isValidRpcResponseFor(request, response); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcResponseFor( + request, response); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::URI_MISMATCH); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::URI_MISMATCH); } { // URI Mismatch - the response's source doesn't match the request sink - auto req_attr = fakeRequest(source_, sink_); - auto res_attr = fakeResponse(source_, sink_); + auto req_attr = fakeRequest(getSource(), getSink()); + auto res_attr = fakeResponse(getSource(), getSink()); res_attr.mutable_source()->set_ue_version_major( res_attr.source().ue_version_major() + 1); auto request = build(req_attr); auto response = build(res_attr); - auto [valid, reason] = isValidRpcResponseFor(request, response); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcResponseFor( + request, response); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::URI_MISMATCH); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::URI_MISMATCH); } { // mismatch the priority - auto req_attr = fakeRequest(source_, sink_); - auto res_attr = fakeResponse(source_, sink_); + auto req_attr = fakeRequest(getSource(), getSink()); + auto res_attr = fakeResponse(getSource(), getSink()); res_attr.set_priority(UPRIORITY_CS6); *res_attr.mutable_reqid() = req_attr.id(); auto request = build(req_attr); auto response = build(res_attr); - auto [valid, reason] = isValidRpcResponseFor(request, response); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidRpcResponseFor( + request, response); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::PRIORITY_MISMATCH); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + PRIORITY_MISMATCH); // Test debugging - EXPECT_EQ(message(*reason), message(Reason::PRIORITY_MISMATCH)); + EXPECT_EQ(message(*reason), + message(uprotocol::datamodel::validator::message::Reason:: + PRIORITY_MISMATCH)); } } -TEST_F(TestUMessageValidator, ValidPublish) { - source_.set_resource_id(0x8000); +TEST_F(TestUMessageValidator, ValidPublish) { // NOLINT + constexpr uint32_t SOURCE_RESOURCE_ID = 0x8000; + getSource().set_resource_id(SOURCE_RESOURCE_ID); { // test common attributes for any message - auto attributes = fakePublish(source_); + auto attributes = fakePublish(getSource()); testCommonAttributes(attributes); } { // valid - auto attributes = fakePublish(source_); + auto attributes = fakePublish(getSource()); auto umessage = build(attributes); - auto [valid, reason] = isValidPublish(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidPublish(umessage); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); } { // wrong type - auto attributes = fakePublish(source_); + auto attributes = fakePublish(getSource()); attributes.set_type(UMESSAGE_TYPE_REQUEST); auto umessage = build(attributes); - auto [valid, reason] = isValidPublish(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidPublish(umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::WRONG_MESSAGE_TYPE); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + WRONG_MESSAGE_TYPE); } { // missing source - auto attributes = fakePublish(source_); + auto attributes = fakePublish(getSource()); attributes.clear_source(); auto umessage = build(attributes); - auto [valid, reason] = isValidPublish(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidPublish(umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::BAD_SOURCE_URI); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::BAD_SOURCE_URI); } { // invalid source - UUri source = source_; - source.set_resource_id(0x7FFF); // should greater than 0x8000 + constexpr uint32_t SOURCE_RESOURCE_ID_INVALID = 0x7FFF; + UUri source = getSource(); + source.set_resource_id( + SOURCE_RESOURCE_ID_INVALID); // should greater than 0x8000 auto attributes = fakePublish(source); auto umessage = build(attributes); - auto [valid, reason] = isValidPublish(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidPublish(umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::BAD_SOURCE_URI); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::BAD_SOURCE_URI); } { // set a sink (unexpected) - auto attributes = fakePublish(source_); - *attributes.mutable_sink() = sink_; + auto attributes = fakePublish(getSource()); + *attributes.mutable_sink() = getSink(); auto umessage = build(attributes); - auto [valid, reason] = isValidPublish(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidPublish(umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::DISALLOWED_FIELD_SET); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + DISALLOWED_FIELD_SET); } { // set commstat (unexpected) - auto attributes = fakePublish(source_); + auto attributes = fakePublish(getSource()); attributes.set_commstatus(OK); auto umessage = build(attributes); - auto [valid, reason] = isValidPublish(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidPublish(umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::DISALLOWED_FIELD_SET); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + DISALLOWED_FIELD_SET); } { // set reqid (unexpected) - auto attributes = fakePublish(source_); - *attributes.mutable_reqid() = reqId_; + auto attributes = fakePublish(getSource()); + *attributes.mutable_reqid() = getReqId(); auto umessage = build(attributes); - auto [valid, reason] = isValidPublish(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidPublish(umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::DISALLOWED_FIELD_SET); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + DISALLOWED_FIELD_SET); } { // set permission level (unexpected) - auto attributes = fakePublish(source_); - attributes.set_permission_level(7); + constexpr uint16_t ATTRIBUTES_PERMISSION_LEVEL = 7; + auto attributes = fakePublish(getSource()); + attributes.set_permission_level(ATTRIBUTES_PERMISSION_LEVEL); auto umessage = build(attributes); - auto [valid, reason] = isValidPublish(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidPublish(umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::DISALLOWED_FIELD_SET); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + DISALLOWED_FIELD_SET); } { // set token (unexpected) - auto attributes = fakePublish(source_); + auto attributes = fakePublish(getSource()); attributes.set_token("token"); auto umessage = build(attributes); - auto [valid, reason] = isValidPublish(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidPublish(umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::DISALLOWED_FIELD_SET); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + DISALLOWED_FIELD_SET); } } -TEST_F(TestUMessageValidator, ValidNotification) { - source_.set_resource_id(0x8001); - sink_.set_resource_id(0); +TEST_F(TestUMessageValidator, ValidNotification) { // NOLINT + constexpr uint32_t SOURCE_RESOURCE_ID = 0x8001; + getSource().set_resource_id(SOURCE_RESOURCE_ID); + getSink().set_resource_id(0); { // test common attributes for any message - auto attributes = fakeNotification(source_, sink_); + auto attributes = fakeNotification(getSource(), getSink()); testCommonAttributes(attributes); } { // valid - auto attributes = fakeNotification(source_, sink_); + auto attributes = fakeNotification(getSource(), getSink()); auto umessage = build(attributes); - auto [valid, reason] = isValidNotification(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidNotification( + umessage); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); } { // incorrect type - auto attributes = fakeNotification(source_, sink_); + auto attributes = fakeNotification(getSource(), getSink()); attributes.set_type(UMESSAGE_TYPE_REQUEST); auto umessage = build(attributes); - auto [valid, reason] = isValidNotification(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidNotification( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::WRONG_MESSAGE_TYPE); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + WRONG_MESSAGE_TYPE); } { // missing source - auto attributes = fakeNotification(source_, sink_); + auto attributes = fakeNotification(getSource(), getSink()); attributes.clear_source(); auto umessage = build(attributes); - auto [valid, reason] = isValidNotification(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidNotification( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::BAD_SOURCE_URI); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::BAD_SOURCE_URI); } { // missing sink - auto attributes = fakeNotification(source_, sink_); + auto attributes = fakeNotification(getSource(), getSink()); attributes.clear_sink(); auto umessage = build(attributes); - auto [valid, reason] = isValidNotification(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidNotification( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::BAD_SINK_URI); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::BAD_SINK_URI); } { // invalid source - UUri local_source = source_; - local_source.set_resource_id(0x7FFF); // should be greater than 0x8000 - auto attributes = fakeNotification(local_source, sink_); + constexpr uint32_t LOCAL_SOURCE_RESOURCE_ID = 0x7FFF; + UUri local_source = getSource(); + local_source.set_resource_id( + LOCAL_SOURCE_RESOURCE_ID); // should be greater than 0x8000 + auto attributes = fakeNotification(local_source, getSink()); auto umessage = build(attributes); - auto [valid, reason] = isValidNotification(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidNotification( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::BAD_SOURCE_URI); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::BAD_SOURCE_URI); } { // invalid sink - UUri local_sink = sink_; - local_sink.set_resource_id(0x7FFF); // should be greater than 0x8000 - auto attributes = fakeNotification(source_, local_sink); + constexpr uint32_t LOCAL_SOURCE_RESOURCE_ID = 0x7FFF; + UUri local_sink = getSink(); + local_sink.set_resource_id( + LOCAL_SOURCE_RESOURCE_ID); // should be greater than 0x8000 + auto attributes = fakeNotification(getSource(), local_sink); auto umessage = build(attributes); - auto [valid, reason] = isValidNotification(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidNotification( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::BAD_SINK_URI); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::BAD_SINK_URI); } { // set commstatus (unexpected) - auto attributes = fakeNotification(source_, sink_); + auto attributes = fakeNotification(getSource(), getSink()); attributes.set_commstatus(OK); auto umessage = build(attributes); - auto [valid, reason] = isValidNotification(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidNotification( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::DISALLOWED_FIELD_SET); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + DISALLOWED_FIELD_SET); } { // set reqid (unexpected) - auto attributes = fakeNotification(source_, sink_); - *attributes.mutable_reqid() = reqId_; + auto attributes = fakeNotification(getSource(), getSink()); + *attributes.mutable_reqid() = getReqId(); auto umessage = build(attributes); - auto [valid, reason] = isValidNotification(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidNotification( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::DISALLOWED_FIELD_SET); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + DISALLOWED_FIELD_SET); } { // set permission level (unexpected) - auto attributes = fakeNotification(source_, sink_); - attributes.set_permission_level(7); + constexpr uint16_t ATTRIBUTES_PERMISSION_LEVEL = 7; + auto attributes = fakeNotification(getSource(), getSink()); + attributes.set_permission_level(ATTRIBUTES_PERMISSION_LEVEL); auto umessage = build(attributes); - auto [valid, reason] = isValidNotification(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidNotification( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::DISALLOWED_FIELD_SET); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + DISALLOWED_FIELD_SET); } { // set token (unexpected) - auto attributes = fakeNotification(source_, sink_); + auto attributes = fakeNotification(getSource(), getSink()); attributes.set_token("token"); auto umessage = build(attributes); - auto [valid, reason] = isValidNotification(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValidNotification( + umessage); EXPECT_FALSE(valid); - EXPECT_EQ(reason, Reason::DISALLOWED_FIELD_SET); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + DISALLOWED_FIELD_SET); } } -TEST_F(TestUMessageValidator, IsValid) { +TEST_F(TestUMessageValidator, IsValid) { // NOLINT { // valid request - auto source = source_; - auto sink = sink_; + auto source = getSource(); + auto sink = getSink(); source.set_resource_id(0); auto attributes = fakeRequest(source, sink); auto umessage = build(attributes); { - auto [valid, reason] = isValid(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValid(umessage); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); } @@ -790,10 +999,12 @@ TEST_F(TestUMessageValidator, IsValid) { uprotocol::v1::UMessageType::UMESSAGE_TYPE_UNSPECIFIED); umessage = build(attributes); { - auto [valid, reason] = isValid(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValid(umessage); EXPECT_FALSE(valid); EXPECT_TRUE(reason.has_value()); - EXPECT_EQ(reason, Reason::UNSPECIFIED_MESSAGE_TYPE); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + UNSPECIFIED_MESSAGE_TYPE); } // Check with an invalid type @@ -802,10 +1013,12 @@ TEST_F(TestUMessageValidator, IsValid) { static_cast(max_type + 1)); umessage = build(attributes); { - auto [valid, reason] = isValid(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValid(umessage); EXPECT_FALSE(valid); EXPECT_TRUE(reason.has_value()); - EXPECT_EQ(reason, Reason::INVALID_MESSAGE_TYPE); + EXPECT_EQ(reason, uprotocol::datamodel::validator::message::Reason:: + INVALID_MESSAGE_TYPE); } // Restore the message type to finish out the test @@ -815,22 +1028,26 @@ TEST_F(TestUMessageValidator, IsValid) { attributes.set_ttl(0); umessage = build(attributes); { - auto [valid, reason] = isValid(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValid(umessage); EXPECT_FALSE(valid); EXPECT_TRUE(reason.has_value()); - EXPECT_EQ(reason, Reason::INVALID_TTL); + EXPECT_EQ( + reason, + uprotocol::datamodel::validator::message::Reason::INVALID_TTL); } } { // valid response - auto source = source_; - auto sink = sink_; + auto source = getSource(); + auto sink = getSink(); source.set_resource_id(0); auto attributes = fakeResponse(source, sink); auto umessage = build(attributes); - auto [valid, reason] = isValid(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValid(umessage); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); @@ -838,43 +1055,54 @@ TEST_F(TestUMessageValidator, IsValid) { attributes = fakeResponse(sink, source); umessage = build(attributes); - auto [valid2, reason2] = isValid(umessage); + auto [valid2, reason2] = + uprotocol::datamodel::validator::message::isValid(umessage); EXPECT_FALSE(valid2); EXPECT_TRUE(reason2.has_value()); - EXPECT_EQ(reason2, Reason::BAD_SOURCE_URI); + EXPECT_EQ( + reason2, + uprotocol::datamodel::validator::message::Reason::BAD_SOURCE_URI); } { + constexpr uint32_t ATTRIBUTES_INVALID_PRIORITY = 0xFFFF; // valid publish - auto source = source_; - source.set_resource_id(0x8000); + constexpr uint32_t PUBLISH_SOURCE_RESOURCE_ID = 0x8000; + auto source = getSource(); + source.set_resource_id(PUBLISH_SOURCE_RESOURCE_ID); auto attributes = fakePublish(source); auto umessage = build(attributes); - auto [valid, reason] = isValid(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValid(umessage); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); // Make the request invalid by making one change - attributes.set_priority(static_cast(0xFFFF)); + attributes.set_priority( + static_cast(ATTRIBUTES_INVALID_PRIORITY)); umessage = build(attributes); - auto [valid2, reason2] = isValid(umessage); + auto [valid2, reason2] = + uprotocol::datamodel::validator::message::isValid(umessage); EXPECT_FALSE(valid2); EXPECT_TRUE(reason2.has_value()); - EXPECT_EQ(reason2, Reason::PRIORITY_OUT_OF_RANGE); + EXPECT_EQ(reason2, uprotocol::datamodel::validator::message::Reason:: + PRIORITY_OUT_OF_RANGE); } { // valid notification - auto source = source_; - auto sink = sink_; - source.set_resource_id(0x8001); + constexpr uint32_t NOTIFICATION_SOURCE_RESOURCE_ID = 0x8001; + auto source = getSource(); + auto sink = getSink(); + source.set_resource_id(NOTIFICATION_SOURCE_RESOURCE_ID); sink.set_resource_id(0); auto attributes = fakeNotification(source, sink); auto umessage = build(attributes); - auto [valid, reason] = isValid(umessage); + auto [valid, reason] = + uprotocol::datamodel::validator::message::isValid(umessage); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); @@ -882,11 +1110,13 @@ TEST_F(TestUMessageValidator, IsValid) { *(attributes.mutable_reqid()) = attributes.id(); umessage = build(attributes); - auto [valid2, reason2] = isValid(umessage); + auto [valid2, reason2] = + uprotocol::datamodel::validator::message::isValid(umessage); EXPECT_FALSE(valid2); EXPECT_TRUE(reason2.has_value()); - EXPECT_EQ(reason2, Reason::DISALLOWED_FIELD_SET); + EXPECT_EQ(reason2, uprotocol::datamodel::validator::message::Reason:: + DISALLOWED_FIELD_SET); } } -} // namespace +} // namespace uprotocol::v1 diff --git a/test/coverage/datamodel/UUriSerializerTest.cpp b/test/coverage/datamodel/UUriSerializerTest.cpp index ccf154e41..43544931b 100644 --- a/test/coverage/datamodel/UUriSerializerTest.cpp +++ b/test/coverage/datamodel/UUriSerializerTest.cpp @@ -13,10 +13,11 @@ #include #include -namespace { -using namespace uprotocol::datamodel::serializer::uri; -using namespace uprotocol::datamodel::validator; -using namespace uprotocol; +constexpr uint32_t DEFAULT_RESOURCE_ID = 0x7500; +constexpr uint32_t DEFAULT_UE_ID = 0x10010001; +constexpr uint32_t DEFAULT_VERSION_MAJOR = 0xFE; + +namespace uprotocol::datamodel::serializer::uri { class TestUUriSerializer : public testing::Test { protected: @@ -28,267 +29,332 @@ class TestUUriSerializer : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. TestUUriSerializer() = default; - ~TestUUriSerializer() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} + +public: + ~TestUUriSerializer() override = default; }; -v1::UUri buildValidTestURI(const std::string& authority = "192.168.1.10") { - v1::UUri uri; +uprotocol::v1::UUri buildValidTestURI( + const std::string& authority = "192.168.1.10") { + uprotocol::v1::UUri uri; uri.set_authority_name(authority); - uri.set_ue_id(0x10010001); - uri.set_ue_version_major(0xFE); - uri.set_resource_id(0x7500); + uri.set_ue_id(DEFAULT_UE_ID); + uri.set_ue_version_major(DEFAULT_VERSION_MAJOR); + uri.set_resource_id(DEFAULT_RESOURCE_ID); return uri; } // Positive test case - test serialization of UUri to string -TEST_F(TestUUriSerializer, SerializeUUriToString) { - auto testUUri = buildValidTestURI(); - const std::string expectedUUri = "//192.168.1.10/10010001/FE/7500"; - const std::string actualUUri = AsString::serialize(testUUri); - ASSERT_EQ(expectedUUri, actualUUri); +TEST_F(TestUUriSerializer, SerializeUUriToString) { // NOLINT + auto test_u_uri = buildValidTestURI(); + const std::string expected_u_uri = "//192.168.1.10/10010001/FE/7500"; + const std::string actual_u_uri = AsString::serialize(test_u_uri); + ASSERT_EQ(expected_u_uri, actual_u_uri); } // Positive test case - test serialization of UUri with no authority to string -TEST_F(TestUUriSerializer, SerializeUUriWithNoAuthorityToString) { - auto testUUri = buildValidTestURI(""); - const std::string expectedUUri = "/10010001/FE/7500"; - const std::string actualUUri = AsString::serialize(testUUri); - ASSERT_EQ(expectedUUri, actualUUri); +TEST_F(TestUUriSerializer, SerializeUUriWithNoAuthorityToString) { // NOLINT + auto test_u_uri = buildValidTestURI(""); + const std::string expected_u_uri = "/10010001/FE/7500"; + const std::string actual_u_uri = AsString::serialize(test_u_uri); + ASSERT_EQ(expected_u_uri, actual_u_uri); } // Test authority name '*' to see if it serializes without an exception for // using wildcard -TEST_F(TestUUriSerializer, SerializeUUriToStringWithAuthorityWildCard) { - v1::UUri testUUri; - testUUri.set_authority_name("*"); // Wildcard - testUUri.set_ue_id(0x1FFFE); - testUUri.set_ue_version_major(0xFE); - testUUri.set_resource_id(0x7500); +TEST_F(TestUUriSerializer, // NOLINT + SerializeUUriToStringWithAuthorityWildCard) { + constexpr uint32_t WILDCARD = 0x1FFFE; + uprotocol::v1::UUri test_u_uri; + test_u_uri.set_authority_name("*"); // Wildcard + test_u_uri.set_ue_id(WILDCARD); + test_u_uri.set_ue_version_major(DEFAULT_VERSION_MAJOR); + test_u_uri.set_resource_id(DEFAULT_RESOURCE_ID); std::string serialized; - ASSERT_NO_THROW(serialized = AsString::serialize(testUUri)); + ASSERT_NO_THROW(serialized = AsString::serialize(test_u_uri)); // NOLINT ASSERT_EQ(serialized, "//*/1FFFE/FE/7500"); } // Test Service ID in uEID field as a 0xFFFF to see if it serializes without // an exception for using wildcard -TEST_F(TestUUriSerializer, SerializeUUriToStringWithServiceIDWildCard) { - v1::UUri testUUri; - testUUri.set_authority_name("testAuthority"); - testUUri.set_ue_id(0x1FFFF); // Wildcard - testUUri.set_ue_version_major(0xFE); - testUUri.set_resource_id(0x7500); +TEST_F(TestUUriSerializer, // NOLINT + SerializeUUriToStringWithServiceIDWildCard) { + constexpr uint32_t WILDCARD = 0x1FFFF; + uprotocol::v1::UUri test_u_uri; + test_u_uri.set_authority_name("testAuthority"); + test_u_uri.set_ue_id(WILDCARD); // Wildcard + test_u_uri.set_ue_version_major(DEFAULT_VERSION_MAJOR); + test_u_uri.set_resource_id(DEFAULT_RESOURCE_ID); std::string serialized; - ASSERT_NO_THROW(serialized = AsString::serialize(testUUri)); + ASSERT_NO_THROW(serialized = AsString::serialize(test_u_uri)); // NOLINT ASSERT_EQ(serialized, "//testAuthority/1FFFF/FE/7500"); } // Test Instance ID in uEID field as a 0x0 to see if it serializes without an // exception for using wildcard -TEST_F(TestUUriSerializer, SerializeUUriToStringWithInstanceIDWildCard) { - v1::UUri testUUri; - testUUri.set_authority_name("testAuthority"); - testUUri.set_ue_id(0x00001234); // Wildcard - testUUri.set_ue_version_major(0xFE); - testUUri.set_resource_id(0x7500); +TEST_F(TestUUriSerializer, // NOLINT + SerializeUUriToStringWithInstanceIDWildCard) { + constexpr uint32_t WILDCARD = 0x00001234; + uprotocol::v1::UUri test_u_uri; + test_u_uri.set_authority_name("testAuthority"); + test_u_uri.set_ue_id(WILDCARD); // Wildcard + test_u_uri.set_ue_version_major(DEFAULT_VERSION_MAJOR); + test_u_uri.set_resource_id(DEFAULT_RESOURCE_ID); std::string serialized; - ASSERT_NO_THROW(serialized = AsString::serialize(testUUri)); + ASSERT_NO_THROW(serialized = AsString::serialize(test_u_uri)); // NOLINT ASSERT_EQ(serialized, "//testAuthority/1234/FE/7500"); } // Test major version as 0xFF to see if it serializes without an exception for // using wildcard -TEST_F(TestUUriSerializer, SerializeUUriToStringWithMajorVersionWildCard) { - v1::UUri testUUri; - testUUri.set_authority_name("testAuthority"); - testUUri.set_ue_id(0x12340000); - testUUri.set_ue_version_major(0xFF); // Wildcard - testUUri.set_resource_id(0x7500); +TEST_F(TestUUriSerializer, // NOLINT + SerializeUUriToStringWithMajorVersionWildCard) { + constexpr uint32_t TEST_UE_ID = 0x12340000; + constexpr uint32_t WILDCARD = 0xFF; + uprotocol::v1::UUri test_u_uri; + test_u_uri.set_authority_name("testAuthority"); + test_u_uri.set_ue_id(TEST_UE_ID); + test_u_uri.set_ue_version_major(WILDCARD); // Wildcard + test_u_uri.set_resource_id(DEFAULT_RESOURCE_ID); std::string serialized; - ASSERT_NO_THROW(serialized = AsString::serialize(testUUri)); + ASSERT_NO_THROW(serialized = AsString::serialize(test_u_uri)); // NOLINT ASSERT_EQ(serialized, "//testAuthority/12340000/FF/7500"); } // Test resource id as 0xFFFF to see if it thorws an exception for using // wildcard -TEST_F(TestUUriSerializer, SerializeUUriToStringWithResourceIDWildCard) { - v1::UUri testUUri; - testUUri.set_authority_name("testAuthority"); - testUUri.set_ue_id(0x12340000); - testUUri.set_ue_version_major(0xFE); - testUUri.set_resource_id(0xFFFF); // Wildcard +TEST_F(TestUUriSerializer, // NOLINT + SerializeUUriToStringWithResourceIDWildCard) { + constexpr uint32_t TEST_UE_ID = 0x12340000; + constexpr uint32_t WILDCARD = 0xFFFF; + uprotocol::v1::UUri test_u_uri; + test_u_uri.set_authority_name("testAuthority"); + test_u_uri.set_ue_id(TEST_UE_ID); + test_u_uri.set_ue_version_major(DEFAULT_VERSION_MAJOR); + test_u_uri.set_resource_id(WILDCARD); // Wildcard std::string serialized; - ASSERT_NO_THROW(serialized = AsString::serialize(testUUri)); + ASSERT_NO_THROW(serialized = AsString::serialize(test_u_uri)); // NOLINT ASSERT_EQ(serialized, "//testAuthority/12340000/FE/FFFF"); } // Attempt to serialize invalid UUris and verify exceptions are thrown -TEST_F(TestUUriSerializer, SerializeUUriToStringWithInvalidUUri) { - const v1::UUri baseUUri = []() { - v1::UUri uuri; +TEST_F(TestUUriSerializer, SerializeUUriToStringWithInvalidUUri) { // NOLINT + constexpr uint32_t AUTHORITY_NAME_NUMBER = 129; + constexpr uint32_t TEST_UE_ID = 0x12340000; + constexpr uint32_t WILDCARD = 0xFFFE; + constexpr uint32_t INVALID_VERSION_MAJOR = 0x100; + constexpr uint32_t INVALID_RESOURCE_ID = 0x10000; + const uprotocol::v1::UUri base_u_uri = []() { + uprotocol::v1::UUri uuri; uuri.set_authority_name("testAuthority"); - uuri.set_ue_id(0x12340000); - uuri.set_ue_version_major(0xFE); - uuri.set_resource_id(0xFFFE); + uuri.set_ue_id(TEST_UE_ID); + uuri.set_ue_version_major(DEFAULT_VERSION_MAJOR); + uuri.set_resource_id(WILDCARD); return uuri; }(); std::string serialized; // Empty UUri - v1::UUri testUUri; - ASSERT_THROW(serialized = AsString::serialize(testUUri), uri::InvalidUUri); + uprotocol::v1::UUri test_u_uri; + ASSERT_THROW(serialized = AsString::serialize(test_u_uri), // NOLINT + uprotocol::datamodel::validator::uri::InvalidUUri); // Authority name too long - testUUri = baseUUri; - testUUri.set_authority_name(std::string(129, 'b')); - ASSERT_THROW(serialized = AsString::serialize(testUUri), uri::InvalidUUri); + test_u_uri = base_u_uri; + test_u_uri.set_authority_name(std::string(AUTHORITY_NAME_NUMBER, 'b')); + ASSERT_THROW(serialized = AsString::serialize(test_u_uri), // NOLINT + uprotocol::datamodel::validator::uri::InvalidUUri); // Version out of uint8 range - testUUri = baseUUri; - testUUri.set_ue_version_major(0x100); - ASSERT_THROW(serialized = AsString::serialize(testUUri), uri::InvalidUUri); + test_u_uri = base_u_uri; + test_u_uri.set_ue_version_major(INVALID_VERSION_MAJOR); + ASSERT_THROW(serialized = AsString::serialize(test_u_uri), // NOLINT + uprotocol::datamodel::validator::uri::InvalidUUri); // Version reserved - testUUri = baseUUri; - testUUri.set_ue_version_major(0); - ASSERT_THROW(serialized = AsString::serialize(testUUri), uri::InvalidUUri); + test_u_uri = base_u_uri; + test_u_uri.set_ue_version_major(0); + ASSERT_THROW(serialized = AsString::serialize(test_u_uri), // NOLINT + uprotocol::datamodel::validator::uri::InvalidUUri); // Resource ID out of uint16 range - testUUri = baseUUri; - testUUri.set_ue_version_major(0x10000); - ASSERT_THROW(serialized = AsString::serialize(testUUri), uri::InvalidUUri); + test_u_uri = base_u_uri; + test_u_uri.set_resource_id(INVALID_RESOURCE_ID); + ASSERT_THROW(serialized = AsString::serialize(test_u_uri), // NOLINT + uprotocol::datamodel::validator::uri::InvalidUUri); } // Test deserialize by providing scheme "up:" which is allowed to have as per // spec -TEST_F(TestUUriSerializer, DeSerializeUUriStringWithScheme) { - const std::string uuriAsString = "up://192.168.1.10/10010001/FE/7500"; - const std::string expectedAuthority = "192.168.1.10"; - const uint32_t expectedUEID = 0x10010001; - const uint32_t expectedMajorVersion = 0xFE; - const uint32_t expectedResourceID = 0x7500; - - auto uri = AsString::deserialize(uuriAsString); - ASSERT_EQ(expectedAuthority, uri.authority_name()); - ASSERT_EQ(expectedUEID, uri.ue_id()); - ASSERT_EQ(expectedMajorVersion, uri.ue_version_major()); - ASSERT_EQ(expectedResourceID, uri.resource_id()); +TEST_F(TestUUriSerializer, DeSerializeUUriStringWithScheme) { // NOLINT + const std::string uuri_as_string = "up://192.168.1.10/10010001/FE/7500"; + const std::string expected_authority = "192.168.1.10"; + const uint32_t expected_ue_id = DEFAULT_UE_ID; + const uint32_t expected_major_version = DEFAULT_VERSION_MAJOR; + const uint32_t expected_resource_id = DEFAULT_RESOURCE_ID; + + auto uri = AsString::deserialize(uuri_as_string); + ASSERT_EQ(expected_authority, uri.authority_name()); + ASSERT_EQ(expected_ue_id, uri.ue_id()); + ASSERT_EQ(expected_major_version, uri.ue_version_major()); + ASSERT_EQ(expected_resource_id, uri.resource_id()); } // Test deserialize by providing incorrect scheme "uprotocol:" -TEST_F(TestUUriSerializer, DeSerializeUUriStringWithIncorrectScheme) { - const std::string uuriAsString = +TEST_F(TestUUriSerializer, // NOLINT + DeSerializeUUriStringWithIncorrectScheme) { + const std::string uuri_as_string = "uprotocol://192.168.1.10/10010001/FE/7500"; - ASSERT_THROW(AsString::deserialize(uuriAsString), std::invalid_argument); + ASSERT_THROW( // NOLINT + static_cast(AsString::deserialize(uuri_as_string)), + std::invalid_argument); } // Test deserialize without providing scheme "up:" -TEST_F(TestUUriSerializer, DeSerializeUUriStringWithoutScheme) { - const std::string uuriAsString = "//192.168.1.10/10010001/FE/7500"; - const std::string expectedAuthority = "192.168.1.10"; - const uint32_t expectedUEID = 0x10010001; - const uint32_t expectedMajorVersion = 0xFE; - const uint32_t expectedResourceID = 0x7500; - - auto uri = AsString::deserialize(uuriAsString); - ASSERT_EQ(expectedAuthority, uri.authority_name()); - ASSERT_EQ(expectedUEID, uri.ue_id()); - ASSERT_EQ(expectedMajorVersion, uri.ue_version_major()); - ASSERT_EQ(expectedResourceID, uri.resource_id()); +TEST_F(TestUUriSerializer, DeSerializeUUriStringWithoutScheme) { // NOLINT + const std::string uuri_as_string = "//192.168.1.10/10010001/FE/7500"; + const std::string expected_authority = "192.168.1.10"; + const uint32_t expected_ue_id = DEFAULT_UE_ID; + const uint32_t expected_major_version = DEFAULT_VERSION_MAJOR; + const uint32_t expected_resource_id = DEFAULT_RESOURCE_ID; + + auto uri = AsString::deserialize(uuri_as_string); + ASSERT_EQ(expected_authority, uri.authority_name()); + ASSERT_EQ(expected_ue_id, uri.ue_id()); + ASSERT_EQ(expected_major_version, uri.ue_version_major()); + ASSERT_EQ(expected_resource_id, uri.resource_id()); } // Test deserializing empty string to check if it thorws an exception -TEST_F(TestUUriSerializer, DeSerializeEmptyUUriString) { - const std::string uuriAsString = ""; - ASSERT_THROW(AsString::deserialize(uuriAsString), std::invalid_argument); +TEST_F(TestUUriSerializer, DeSerializeEmptyUUriString) { // NOLINT + const std::string uuri_as_string; + ASSERT_THROW( // NOLINT + static_cast(AsString::deserialize(uuri_as_string)), + std::invalid_argument); } // Test deserializing string with no authority -TEST_F(TestUUriSerializer, DeSerializeUUriStringWithNoAuthority) { - const std::string uuriAsString = "/10010001/FE/7500"; - const std::string expectedAuthority = ""; - const uint32_t expectedUEID = 0x10010001; - const uint32_t expectedMajorVersion = 0xFE; - const uint32_t expectedResourceID = 0x7500; - - auto uri = AsString::deserialize(uuriAsString); - ASSERT_EQ(expectedAuthority, uri.authority_name()); - ASSERT_EQ(expectedUEID, uri.ue_id()); - ASSERT_EQ(expectedMajorVersion, uri.ue_version_major()); - ASSERT_EQ(expectedResourceID, uri.resource_id()); +TEST_F(TestUUriSerializer, DeSerializeUUriStringWithNoAuthority) { // NOLINT + const std::string uuri_as_string = "/10010001/FE/7500"; + const std::string expected_authority; + const uint32_t expected_ue_id = DEFAULT_UE_ID; + const uint32_t expected_major_version = DEFAULT_VERSION_MAJOR; + const uint32_t expected_resource_id = DEFAULT_RESOURCE_ID; + + auto uri = AsString::deserialize(uuri_as_string); + ASSERT_EQ(expected_authority, uri.authority_name()); + ASSERT_EQ(expected_ue_id, uri.ue_id()); + ASSERT_EQ(expected_major_version, uri.ue_version_major()); + ASSERT_EQ(expected_resource_id, uri.resource_id()); } // Test deserializing string with invalid number of arguments -TEST_F(TestUUriSerializer, DeSerializeUUriStringWithInvalidNumberOfArgument) { +TEST_F(TestUUriSerializer, // NOLINT + DeSerializeUUriStringWithInvalidNumberOfArgument) { // Provided 5 arguments instead of 4 when authority exist - std::string uuriAsString = "//192.168.1.10/10010001/FE/FE/7500"; + std::string uuri_as_string = "//192.168.1.10/10010001/FE/FE/7500"; - ASSERT_THROW(AsString::deserialize(uuriAsString), std::invalid_argument); + ASSERT_THROW( // NOLINT + static_cast(AsString::deserialize(uuri_as_string)), + std::invalid_argument); // UE ID is missing. Provided 3 arguments instead of 4 when authority exist. - uuriAsString = "//192.168.1.10/FE/7500"; - ASSERT_THROW(AsString::deserialize(uuriAsString), std::invalid_argument); + uuri_as_string = "//192.168.1.10/FE/7500"; + ASSERT_THROW( // NOLINT + static_cast(AsString::deserialize(uuri_as_string)), + std::invalid_argument); // Provided 4 arguments instead of 3 when authority does not exist. - uuriAsString = "/1102/FE/FE/7500"; - ASSERT_THROW(AsString::deserialize(uuriAsString), std::invalid_argument); + uuri_as_string = "/1102/FE/FE/7500"; + ASSERT_THROW( // NOLINT + static_cast(AsString::deserialize(uuri_as_string)), + std::invalid_argument); // UE ID is missing. Provided 2 arguments instead of 3 when authority does // not exist. - uuriAsString = "/FE/7500"; - ASSERT_THROW(AsString::deserialize(uuriAsString), std::invalid_argument); + uuri_as_string = "/FE/7500"; + ASSERT_THROW( // NOLINT + static_cast(AsString::deserialize(uuri_as_string)), + std::invalid_argument); // Valid Uri but no leading / - uuriAsString = "192.168.1.10/1102/FE/7500"; - ASSERT_THROW(AsString::deserialize(uuriAsString), std::invalid_argument); + uuri_as_string = "192.168.1.10/1102/FE/7500"; + ASSERT_THROW( // NOLINT + static_cast(AsString::deserialize(uuri_as_string)), + std::invalid_argument); // Valid Uri but no leading / - uuriAsString = "1102/FE/7500"; - ASSERT_THROW(AsString::deserialize(uuriAsString), std::invalid_argument); + uuri_as_string = "1102/FE/7500"; + ASSERT_THROW( // NOLINT + static_cast(AsString::deserialize(uuri_as_string)), + std::invalid_argument); // Valid Uri but leading /// . - uuriAsString = "///192.168.1.10/1102/FE/7500"; - ASSERT_THROW(AsString::deserialize(uuriAsString), std::invalid_argument); + uuri_as_string = "///192.168.1.10/1102/FE/7500"; + ASSERT_THROW( // NOLINT + static_cast(AsString::deserialize(uuri_as_string)), + std::invalid_argument); // Valid Uri but additional trailing / - uuriAsString = "//192.168.1.10/1102/FE/7500/"; - ASSERT_THROW(AsString::deserialize(uuriAsString), std::invalid_argument); + uuri_as_string = "//192.168.1.10/1102/FE/7500/"; + ASSERT_THROW( // NOLINT + static_cast(AsString::deserialize(uuri_as_string)), + std::invalid_argument); } // Test deserializing string with invalid arguments -TEST_F(TestUUriSerializer, DeSerializeUUriStringWithInvalidArgument) { +TEST_F(TestUUriSerializer, // NOLINT + DeSerializeUUriStringWithInvalidArgument) { // UE ID provided is invalid. It should be hex numeric - std::string uuriAsString = "//192.168.1.10/testUE/FE/7500"; - ASSERT_THROW(AsString::deserialize(uuriAsString), std::invalid_argument); + std::string uuri_as_string = "//192.168.1.10/testUE/FE/7500"; + ASSERT_THROW( // NOLINT + static_cast(AsString::deserialize(uuri_as_string)), + std::invalid_argument); // Major Version provided is invalid. It should be hex numeric - uuriAsString = "//192.168.1.10/10010001/^%/7500"; - ASSERT_THROW(AsString::deserialize(uuriAsString), std::invalid_argument); + uuri_as_string = "//192.168.1.10/10010001/^%/7500"; + ASSERT_THROW( // NOLINT + static_cast(AsString::deserialize(uuri_as_string)), + std::invalid_argument); // Resource ID provided is invalid. It should be hex numeric - uuriAsString = "//192.168.1.10/10010001/FE/xyz"; - ASSERT_THROW(AsString::deserialize(uuriAsString), std::invalid_argument); + uuri_as_string = "//192.168.1.10/10010001/FE/xyz"; + ASSERT_THROW( // NOLINT + static_cast(AsString::deserialize(uuri_as_string)), + std::invalid_argument); // UE ID is outside the 32-bit int range - uuriAsString = "//192.168.1.10/110010001/FE/7500"; - ASSERT_THROW(AsString::deserialize(uuriAsString), std::invalid_argument); + uuri_as_string = "//192.168.1.10/110010001/FE/7500"; + ASSERT_THROW( // NOLINT + static_cast(AsString::deserialize(uuri_as_string)), + std::invalid_argument); // Major Version is outside the 8-bit int range - uuriAsString = "//192.168.1.10/10010001/100/7500"; - ASSERT_THROW(AsString::deserialize(uuriAsString), std::invalid_argument); + uuri_as_string = "//192.168.1.10/10010001/100/7500"; + ASSERT_THROW( // NOLINT + static_cast(AsString::deserialize(uuri_as_string)), + std::invalid_argument); // Resiource ID is outside the 16-bit int range - uuriAsString = "//192.168.1.10/10010001/FE/10000"; - ASSERT_THROW(AsString::deserialize(uuriAsString), std::invalid_argument); + uuri_as_string = "//192.168.1.10/10010001/FE/10000"; + ASSERT_THROW( // NOLINT + static_cast(AsString::deserialize(uuri_as_string)), + std::invalid_argument); } // Test deserializing string with wildcard arguments to see if throws exception -TEST_F(TestUUriSerializer, DeSerializeUUriStringWithWildcardArgument) { +TEST_F(TestUUriSerializer, // NOLINT + DeSerializeUUriStringWithWildcardArgument) { + constexpr uint32_t UE_SERVICE_ID_WILDCARD = 0x1FFFF; + constexpr uint32_t UE_INSTANCE_ID_WILDCARD = 0x1234; + constexpr uint32_t VERSION_MAJOR_WILDCARD = 0xFF; + constexpr uint32_t RESOURCE_ID_WILDCARD = 0xFFFF; uprotocol::v1::UUri uuri; auto check_uri = [&uuri](auto auth, uint32_t ueid, uint32_t mv, @@ -300,76 +366,87 @@ TEST_F(TestUUriSerializer, DeSerializeUUriStringWithWildcardArgument) { }; // Authority name provided in ueID is wildcard as "*" - std::string uuriAsString = "//*/1FFFF/FE/7500"; - ASSERT_NO_THROW(uuri = AsString::deserialize(uuriAsString)); + std::string uuri_as_string = "//*/1FFFF/FE/7500"; + ASSERT_NO_THROW(uuri = AsString::deserialize(uuri_as_string)); // NOLINT { SCOPED_TRACE("uE Authority Name Wildcard"); - check_uri("*", 0x1FFFF, 0xFE, 0x7500); + check_uri("*", UE_SERVICE_ID_WILDCARD, DEFAULT_VERSION_MAJOR, + DEFAULT_RESOURCE_ID); } // Service ID provided in ueID is wildcard as 0xFFFF - uuriAsString = "//192.168.1.10/1FFFF/FE/7500"; - ASSERT_NO_THROW(uuri = AsString::deserialize(uuriAsString)); + uuri_as_string = "//192.168.1.10/1FFFF/FE/7500"; + ASSERT_NO_THROW(uuri = AsString::deserialize(uuri_as_string)); // NOLINT { SCOPED_TRACE("uE Service ID Wildcard"); - check_uri("192.168.1.10", 0x1FFFF, 0xFE, 0x7500); + check_uri("192.168.1.10", UE_SERVICE_ID_WILDCARD, DEFAULT_VERSION_MAJOR, + DEFAULT_RESOURCE_ID); } // Instance ID provided in ueID is wildcard as 0x0 - uuriAsString = "//192.168.1.10/00001234/FE/7500"; - ASSERT_NO_THROW(uuri = AsString::deserialize(uuriAsString)); + uuri_as_string = "//192.168.1.10/00001234/FE/7500"; + ASSERT_NO_THROW(uuri = AsString::deserialize(uuri_as_string)); // NOLINT { SCOPED_TRACE("uE Instance ID Wildcard"); - check_uri("192.168.1.10", 0x1234, 0xFE, 0x7500); + check_uri("192.168.1.10", UE_INSTANCE_ID_WILDCARD, + DEFAULT_VERSION_MAJOR, DEFAULT_RESOURCE_ID); } // Major Version provided is wildcard as 0xFF - uuriAsString = "//192.168.1.10/10010001/FF/7500"; - ASSERT_NO_THROW(uuri = AsString::deserialize(uuriAsString)); + uuri_as_string = "//192.168.1.10/10010001/FF/7500"; + ASSERT_NO_THROW(uuri = AsString::deserialize(uuri_as_string)); // NOLINT { SCOPED_TRACE("uE Major Version Wildcard"); - check_uri("192.168.1.10", 0x10010001, 0xFF, 0x7500); + check_uri("192.168.1.10", DEFAULT_UE_ID, VERSION_MAJOR_WILDCARD, + DEFAULT_RESOURCE_ID); } // Resource ID provided is wildcard as 0xFFFF - uuriAsString = "//192.168.1.10/10010001/FE/FFFF"; - ASSERT_NO_THROW(uuri = AsString::deserialize(uuriAsString)); + uuri_as_string = "//192.168.1.10/10010001/FE/FFFF"; + ASSERT_NO_THROW(uuri = AsString::deserialize(uuri_as_string)); // NOLINT { SCOPED_TRACE("uE Resource ID Wildcard"); - check_uri("192.168.1.10", 0x10010001, 0xFE, 0xFFFF); + check_uri("192.168.1.10", DEFAULT_UE_ID, DEFAULT_VERSION_MAJOR, + RESOURCE_ID_WILDCARD); } } // Test deserializing string with invalid field values to verify exceptions are // thrown -TEST_F(TestUUriSerializer, DeSerializeUUriStringWithInvalidUUri) { +TEST_F(TestUUriSerializer, DeSerializeUUriStringWithInvalidUUri) { // NOLINT + constexpr uint32_t UURI_NUMBER = 129; uprotocol::v1::UUri uuri; // Major Version reserved - std::string uuriAsString = "//192.168.1.10/1FFFE/0/7500"; - ASSERT_THROW(uuri = AsString::deserialize(uuriAsString), uri::InvalidUUri); + std::string uuri_as_string = "//192.168.1.10/1FFFE/0/7500"; + ASSERT_THROW(uuri = AsString::deserialize(uuri_as_string), // NOLINT + uprotocol::datamodel::validator::uri::InvalidUUri); // Empty UUri - uuriAsString = "// /0/0/0"; - ASSERT_THROW(uuri = AsString::deserialize(uuriAsString), uri::InvalidUUri); + uuri_as_string = "// /0/0/0"; + ASSERT_THROW(uuri = AsString::deserialize(uuri_as_string), // NOLINT + uprotocol::datamodel::validator::uri::InvalidUUri); // Major Version reserved - uuriAsString = "//"; - uuriAsString += std::string(129, 'a'); - uuriAsString += "/1FFFE/1/7500"; - ASSERT_THROW(uuri = AsString::deserialize(uuriAsString), uri::InvalidUUri); + uuri_as_string = "//"; + uuri_as_string += std::string(UURI_NUMBER, 'a'); + uuri_as_string += "/1FFFE/1/7500"; + ASSERT_THROW(uuri = AsString::deserialize(uuri_as_string), // NOLINT + uprotocol::datamodel::validator::uri::InvalidUUri); // NOTE These are also checked earlier against the std::invalid_argument // exception. They can be caught either way. These can be checked against // InvalidUUri since they are valid uint32 values, but *not* valid for UUri // Major Version outside the uint8 range - uuriAsString = "//192.168.1.10/1FFFE/FFFE/7500"; - ASSERT_THROW(uuri = AsString::deserialize(uuriAsString), uri::InvalidUUri); + uuri_as_string = "//192.168.1.10/1FFFE/FFFE/7500"; + ASSERT_THROW(uuri = AsString::deserialize(uuri_as_string), // NOLINT + uprotocol::datamodel::validator::uri::InvalidUUri); // Resource ID outside the uint8 range - uuriAsString = "//192.168.1.10/1FFFE/FE/C0FFEEEE"; - ASSERT_THROW(uuri = AsString::deserialize(uuriAsString), uri::InvalidUUri); + uuri_as_string = "//192.168.1.10/1FFFE/FE/C0FFEEEE"; + ASSERT_THROW(uuri = AsString::deserialize(uuri_as_string), // NOLINT + uprotocol::datamodel::validator::uri::InvalidUUri); } -} // namespace +} // namespace uprotocol::datamodel::serializer::uri diff --git a/test/coverage/datamodel/UUriValidatorTest.cpp b/test/coverage/datamodel/UUriValidatorTest.cpp index b8acca4e8..a1ffbb89f 100644 --- a/test/coverage/datamodel/UUriValidatorTest.cpp +++ b/test/coverage/datamodel/UUriValidatorTest.cpp @@ -12,9 +12,10 @@ #include #include -namespace { +constexpr uint32_t DEFAULT_UE_ID = 0x00010001; +constexpr uint32_t WILDCARD = 0xFFFF; -using namespace uprotocol::datamodel::validator::uri; +namespace uprotocol::datamodel::validator::uri { constexpr const char* AUTHORITY_NAME = "test"; @@ -28,26 +29,28 @@ class TestUUriValidator : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. TestUUriValidator() = default; - ~TestUUriValidator() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} + +public: + ~TestUUriValidator() override = default; }; -TEST_F(TestUUriValidator, Valid) { - auto getUuri = []() { +TEST_F(TestUUriValidator, Valid) { // NOLINT + auto get_u_uri = []() { uprotocol::v1::UUri uuri; uuri.set_authority_name(AUTHORITY_NAME); - uuri.set_ue_id(0x00010001); + uuri.set_ue_id(DEFAULT_UE_ID); uuri.set_ue_version_major(1); uuri.set_resource_id(1); return uuri; }; { - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_authority_name(""); auto [valid, reason] = isValid(uuri); EXPECT_TRUE(valid); @@ -55,7 +58,7 @@ TEST_F(TestUUriValidator, Valid) { } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_resource_id(0); auto [valid, reason] = isValid(uuri); EXPECT_TRUE(valid); @@ -63,7 +66,7 @@ TEST_F(TestUUriValidator, Valid) { } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_resource_id(1); auto [valid, reason] = isValid(uuri); EXPECT_TRUE(valid); @@ -71,32 +74,35 @@ TEST_F(TestUUriValidator, Valid) { } { - auto uuri = getUuri(); - uuri.set_resource_id(0x7FFF); + constexpr uint32_t VALID_RESOURCE_ID = 0x7FFF; + auto uuri = get_u_uri(); + uuri.set_resource_id(VALID_RESOURCE_ID); auto [valid, reason] = isValid(uuri); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); } { - auto uuri = getUuri(); - uuri.set_resource_id(0x8000); + constexpr uint32_t VALID_RESOURCE_ID = 0x8000; + auto uuri = get_u_uri(); + uuri.set_resource_id(VALID_RESOURCE_ID); auto [valid, reason] = isValid(uuri); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); } { - auto uuri = getUuri(); - uuri.set_resource_id(0xFFFE); + constexpr uint32_t VALID_RESOURCE_ID = 0xFFFE; + auto uuri = get_u_uri(); + uuri.set_resource_id(VALID_RESOURCE_ID); auto [valid, reason] = isValid(uuri); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); } { - auto uuri = getUuri(); - uuri.set_resource_id(0xFFFF); + auto uuri = get_u_uri(); + uuri.set_resource_id(WILDCARD); EXPECT_TRUE(uses_wildcards(uuri)); auto [valid, reason] = isValid(uuri); @@ -105,72 +111,75 @@ TEST_F(TestUUriValidator, Valid) { } } -TEST_F(TestUUriValidator, Wildcards) { - auto getUuri = []() { +TEST_F(TestUUriValidator, Wildcards) { // NOLINT + auto get_u_uri = []() { uprotocol::v1::UUri uuri; uuri.set_authority_name(AUTHORITY_NAME); - uuri.set_ue_id(0x00010001); + uuri.set_ue_id(DEFAULT_UE_ID); uuri.set_ue_version_major(1); uuri.set_resource_id(1); return uuri; }; { // Check for no wildcards - auto uuri = getUuri(); + auto uuri = get_u_uri(); EXPECT_FALSE(uses_wildcards(uuri)); } { // Change Authority name to "hello*" (Any) - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_authority_name("hello*"); EXPECT_TRUE(uses_wildcards(uuri)); } { // Set Service ID to FFFF (Any) and Instance ID to 1 - auto uuri = getUuri(); - uuri.set_ue_id(0x0001FFFF); + constexpr uint32_t WILDCARD_SERVICE_UE_ID = 0x0001FFFF; + auto uuri = get_u_uri(); + uuri.set_ue_id(WILDCARD_SERVICE_UE_ID); EXPECT_TRUE(uses_wildcards(uuri)); } { // Set Service ID to 1 and Instance ID to FFFF (Any) + constexpr uint32_t WILDCARD_INSTANCE_UE_ID = 0xFFFF0001; // This changed in 581291f in up-spec - auto uuri = getUuri(); - uuri.set_ue_id(0xFFFF0001); + auto uuri = get_u_uri(); + uuri.set_ue_id(WILDCARD_INSTANCE_UE_ID); EXPECT_TRUE(uses_wildcards(uuri)); } { // Set major version to FF (Any) - auto uuri = getUuri(); - uuri.set_ue_version_major(0xFF); + constexpr uint32_t WILDCARD_VERSION_MAJOR = 0xFF; + auto uuri = get_u_uri(); + uuri.set_ue_version_major(WILDCARD_VERSION_MAJOR); EXPECT_TRUE(uses_wildcards(uuri)); } { // Set Resource ID to FFFF (any) - auto uuri = getUuri(); - uuri.set_resource_id(0xFFFF); + auto uuri = get_u_uri(); + uuri.set_resource_id(WILDCARD); EXPECT_TRUE(uses_wildcards(uuri)); } } -TEST_F(TestUUriValidator, ValidRpcMethod) { - auto getUuri = []() { +TEST_F(TestUUriValidator, ValidRpcMethod) { // NOLINT + auto get_u_uri = []() { uprotocol::v1::UUri uuri; uuri.set_authority_name(AUTHORITY_NAME); - uuri.set_ue_id(0x00010001); + uuri.set_ue_id(DEFAULT_UE_ID); uuri.set_ue_version_major(1); uuri.set_resource_id(1); return uuri; }; { - auto uuri = getUuri(); + auto uuri = get_u_uri(); auto [valid, reason] = isValid(uuri); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); auto [valid, reason] = isValidRpcMethod(uuri); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); @@ -178,7 +187,7 @@ TEST_F(TestUUriValidator, ValidRpcMethod) { } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_authority_name(""); auto [valid, reason] = isValidRpcMethod(uuri); EXPECT_TRUE(valid); @@ -186,41 +195,42 @@ TEST_F(TestUUriValidator, ValidRpcMethod) { } { - auto uuri = getUuri(); - uuri.set_resource_id(0xFFFF); + auto uuri = get_u_uri(); + uuri.set_resource_id(WILDCARD); auto [valid, reason] = isValidRpcMethod(uuri); EXPECT_FALSE(valid); EXPECT_TRUE(reason == Reason::DISALLOWED_WILDCARD); } { - auto uuri = getUuri(); - uuri.set_resource_id(0x8000); + constexpr uint32_t VALID_RESOURCE_ID = 0x8000; + auto uuri = get_u_uri(); + uuri.set_resource_id(VALID_RESOURCE_ID); auto [valid, reason] = isValidRpcMethod(uuri); EXPECT_FALSE(valid); EXPECT_TRUE(reason == Reason::BAD_RESOURCE_ID); } } -TEST_F(TestUUriValidator, ValidRpcResponse) { - auto getUuri = []() { +TEST_F(TestUUriValidator, ValidRpcResponse) { // NOLINT + auto get_u_uri = []() { uprotocol::v1::UUri uuri; uuri.set_authority_name(AUTHORITY_NAME); - uuri.set_ue_id(0x00010001); + uuri.set_ue_id(DEFAULT_UE_ID); uuri.set_ue_version_major(1); uuri.set_resource_id(0); return uuri; }; { - auto uuri = getUuri(); + auto uuri = get_u_uri(); auto [valid, reason] = isValid(uuri); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); auto [valid, reason] = isValidRpcResponse(uuri); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); @@ -228,7 +238,7 @@ TEST_F(TestUUriValidator, ValidRpcResponse) { } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_authority_name(""); auto [valid, reason] = isValidRpcResponse(uuri); EXPECT_TRUE(valid); @@ -236,15 +246,15 @@ TEST_F(TestUUriValidator, ValidRpcResponse) { } { - auto uuri = getUuri(); - uuri.set_resource_id(0xFFFF); + auto uuri = get_u_uri(); + uuri.set_resource_id(WILDCARD); auto [valid, reason] = isValidRpcResponse(uuri); EXPECT_FALSE(valid); EXPECT_TRUE(reason == Reason::DISALLOWED_WILDCARD); } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_resource_id(1); auto [valid, reason] = isValidRpcResponse(uuri); EXPECT_FALSE(valid); @@ -252,25 +262,26 @@ TEST_F(TestUUriValidator, ValidRpcResponse) { } } -TEST_F(TestUUriValidator, ValidPublishTopic) { - auto getUuri = []() { +TEST_F(TestUUriValidator, ValidPublishTopic) { // NOLINT + constexpr uint32_t VALID_RESOURCE_ID = 0x8000; + auto get_u_uri = []() { uprotocol::v1::UUri uuri; uuri.set_authority_name(AUTHORITY_NAME); - uuri.set_ue_id(0x00010001); + uuri.set_ue_id(DEFAULT_UE_ID); uuri.set_ue_version_major(1); - uuri.set_resource_id(0x8000); + uuri.set_resource_id(VALID_RESOURCE_ID); return uuri; }; { - auto uuri = getUuri(); + auto uuri = get_u_uri(); auto [valid, reason] = isValid(uuri); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); auto [valid, reason] = isValidPublishTopic(uuri); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); @@ -278,7 +289,7 @@ TEST_F(TestUUriValidator, ValidPublishTopic) { } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_authority_name(""); auto [valid, reason] = isValidPublishTopic(uuri); EXPECT_TRUE(valid); @@ -286,15 +297,15 @@ TEST_F(TestUUriValidator, ValidPublishTopic) { } { - auto uuri = getUuri(); - uuri.set_resource_id(0xFFFF); + auto uuri = get_u_uri(); + uuri.set_resource_id(WILDCARD); auto [valid, reason] = isValidPublishTopic(uuri); EXPECT_FALSE(valid); EXPECT_TRUE(reason == Reason::DISALLOWED_WILDCARD); } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_resource_id(1); auto [valid, reason] = isValidPublishTopic(uuri); EXPECT_FALSE(valid); @@ -302,33 +313,35 @@ TEST_F(TestUUriValidator, ValidPublishTopic) { } { - auto uuri = getUuri(); - uuri.set_resource_id(0x10000); + constexpr uint32_t VALID_RESOURCE_ID = 0x10000; + auto uuri = get_u_uri(); + uuri.set_resource_id(VALID_RESOURCE_ID); auto [valid, reason] = isValidPublishTopic(uuri); EXPECT_FALSE(valid); EXPECT_TRUE(reason == Reason::BAD_RESOURCE_ID); } } -TEST_F(TestUUriValidator, ValidNotificationSource) { - auto getUuri = []() { +TEST_F(TestUUriValidator, ValidNotificationSource) { // NOLINT + constexpr uint32_t VALID_RESOURCE_ID = 0x8000; + auto get_u_uri = []() { uprotocol::v1::UUri uuri; uuri.set_authority_name(AUTHORITY_NAME); - uuri.set_ue_id(0x00010001); + uuri.set_ue_id(DEFAULT_UE_ID); uuri.set_ue_version_major(1); - uuri.set_resource_id(0x8000); + uuri.set_resource_id(VALID_RESOURCE_ID); return uuri; }; { - auto uuri = getUuri(); + auto uuri = get_u_uri(); auto [valid, reason] = isValid(uuri); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); auto [valid, reason] = isValidNotificationSource(uuri); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); @@ -336,7 +349,7 @@ TEST_F(TestUUriValidator, ValidNotificationSource) { } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_authority_name(""); auto [valid, reason] = isValidNotificationSource(uuri); EXPECT_TRUE(valid); @@ -344,15 +357,15 @@ TEST_F(TestUUriValidator, ValidNotificationSource) { } { - auto uuri = getUuri(); - uuri.set_resource_id(0xFFFF); + auto uuri = get_u_uri(); + uuri.set_resource_id(WILDCARD); auto [valid, reason] = isValidNotificationSource(uuri); EXPECT_FALSE(valid); EXPECT_TRUE(reason == Reason::DISALLOWED_WILDCARD); } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_resource_id(1); auto [valid, reason] = isValidNotificationSource(uuri); EXPECT_FALSE(valid); @@ -360,33 +373,34 @@ TEST_F(TestUUriValidator, ValidNotificationSource) { } { - auto uuri = getUuri(); - uuri.set_resource_id(0x10000); + constexpr uint32_t VALID_RESOURCE_ID = 0x10000; + auto uuri = get_u_uri(); + uuri.set_resource_id(VALID_RESOURCE_ID); auto [valid, reason] = isValidNotificationSource(uuri); EXPECT_FALSE(valid); EXPECT_TRUE(reason == Reason::BAD_RESOURCE_ID); } } -TEST_F(TestUUriValidator, ValidNotificationSink) { - auto getUuri = []() { +TEST_F(TestUUriValidator, ValidNotificationSink) { // NOLINT + auto get_u_uri = []() { uprotocol::v1::UUri uuri; uuri.set_authority_name(AUTHORITY_NAME); - uuri.set_ue_id(0x00010001); + uuri.set_ue_id(DEFAULT_UE_ID); uuri.set_ue_version_major(1); uuri.set_resource_id(0); return uuri; }; { - auto uuri = getUuri(); + auto uuri = get_u_uri(); auto [valid, reason] = isValid(uuri); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); auto [valid, reason] = isValidNotificationSink(uuri); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); @@ -394,7 +408,7 @@ TEST_F(TestUUriValidator, ValidNotificationSink) { } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_authority_name(""); auto [valid, reason] = isValidNotificationSink(uuri); EXPECT_TRUE(valid); @@ -402,15 +416,15 @@ TEST_F(TestUUriValidator, ValidNotificationSink) { } { - auto uuri = getUuri(); - uuri.set_resource_id(0xFFFF); + auto uuri = get_u_uri(); + uuri.set_resource_id(WILDCARD); auto [valid, reason] = isValidNotificationSink(uuri); EXPECT_FALSE(valid); EXPECT_TRUE(reason == Reason::DISALLOWED_WILDCARD); } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_resource_id(1); auto [valid, reason] = isValidNotificationSink(uuri); EXPECT_FALSE(valid); @@ -418,18 +432,19 @@ TEST_F(TestUUriValidator, ValidNotificationSink) { } } -TEST_F(TestUUriValidator, ValidSubscription) { - auto getUuri = []() { +TEST_F(TestUUriValidator, ValidSubscription) { // NOLINT + constexpr uint32_t VALID_RESOURCE_ID = 0x8000; + auto get_u_uri = []() { uprotocol::v1::UUri uuri; uuri.set_authority_name(AUTHORITY_NAME); - uuri.set_ue_id(0x00010001); + uuri.set_ue_id(DEFAULT_UE_ID); uuri.set_ue_version_major(1); - uuri.set_resource_id(0x8000); + uuri.set_resource_id(VALID_RESOURCE_ID); return uuri; }; { - auto uuri = getUuri(); + auto uuri = get_u_uri(); auto [valid, reason] = isValidSubscription(uuri); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); @@ -437,7 +452,7 @@ TEST_F(TestUUriValidator, ValidSubscription) { } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_authority_name(""); auto [valid, reason] = isValidSubscription(uuri); EXPECT_TRUE(valid); @@ -445,7 +460,7 @@ TEST_F(TestUUriValidator, ValidSubscription) { } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_resource_id(1); auto [valid, reason] = isValidSubscription(uuri); EXPECT_FALSE(valid); @@ -453,34 +468,36 @@ TEST_F(TestUUriValidator, ValidSubscription) { } { - auto uuri = getUuri(); - uuri.set_resource_id(0x10000); + constexpr uint32_t VALID_RESOURCE_ID = 0x10000; + auto uuri = get_u_uri(); + uuri.set_resource_id(VALID_RESOURCE_ID); auto [valid, reason] = isValidSubscription(uuri); EXPECT_FALSE(valid); EXPECT_TRUE(reason == Reason::BAD_RESOURCE_ID); } { - auto uuri = getUuri(); - uuri.set_resource_id(0xFFFF); + auto uuri = get_u_uri(); + uuri.set_resource_id(WILDCARD); auto [valid, reason] = isValidSubscription(uuri); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); } } -TEST_F(TestUUriValidator, ValidDefaultSource) { - auto getUuri = []() { +TEST_F(TestUUriValidator, ValidDefaultSource) { // NOLINT + constexpr uint32_t VALID_RESOURCE_ID = 0x8000; + auto get_u_uri = []() { uprotocol::v1::UUri uuri; uuri.set_authority_name(AUTHORITY_NAME); - uuri.set_ue_id(0x00010001); + uuri.set_ue_id(DEFAULT_UE_ID); uuri.set_ue_version_major(1); - uuri.set_resource_id(0x8000); + uuri.set_resource_id(VALID_RESOURCE_ID); return uuri; }; { - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_authority_name(""); auto [valid, reason] = isValidDefaultSource(uuri); EXPECT_FALSE(valid); @@ -488,8 +505,8 @@ TEST_F(TestUUriValidator, ValidDefaultSource) { } } -TEST_F(TestUUriValidator, Empty) { - auto getUuri = []() { +TEST_F(TestUUriValidator, Empty) { // NOLINT + auto get_u_uri = []() { uprotocol::v1::UUri uuri; uuri.set_authority_name(""); uuri.set_ue_id(0); @@ -499,14 +516,14 @@ TEST_F(TestUUriValidator, Empty) { }; { - auto uuri = getUuri(); + auto uuri = get_u_uri(); auto [valid, reason] = isEmpty(uuri); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_authority_name(" bad "); auto [valid, reason] = isEmpty(uuri); EXPECT_FALSE(valid); @@ -514,7 +531,7 @@ TEST_F(TestUUriValidator, Empty) { } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_authority_name(AUTHORITY_NAME); auto [valid, reason] = isEmpty(uuri); EXPECT_FALSE(valid); @@ -522,7 +539,7 @@ TEST_F(TestUUriValidator, Empty) { } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_ue_id(1); auto [valid, reason] = isEmpty(uuri); EXPECT_FALSE(valid); @@ -530,7 +547,7 @@ TEST_F(TestUUriValidator, Empty) { } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_ue_version_major(1); auto [valid, reason] = isEmpty(uuri); EXPECT_FALSE(valid); @@ -538,7 +555,7 @@ TEST_F(TestUUriValidator, Empty) { } { - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_resource_id(1); auto [valid, reason] = isEmpty(uuri); EXPECT_FALSE(valid); @@ -546,11 +563,12 @@ TEST_F(TestUUriValidator, Empty) { } } -TEST_F(TestUUriValidator, ValidFilter) { - auto getUuri = []() { +TEST_F(TestUUriValidator, ValidFilter) { // NOLINT + constexpr uint32_t VALID_UE_ID_FILTER = 10001; + auto get_u_uri = []() { uprotocol::v1::UUri uuri; uuri.set_authority_name("ValidFilterTest"); - uuri.set_ue_id(10001); + uuri.set_ue_id(VALID_UE_ID_FILTER); uuri.set_ue_version_major(1); uuri.set_resource_id(1); return uuri; @@ -559,7 +577,7 @@ TEST_F(TestUUriValidator, ValidFilter) { ////// GOOD ////// { // Plain URI - auto uuri = getUuri(); + auto uuri = get_u_uri(); auto [valid, reason] = isValidFilter(uuri); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); @@ -567,11 +585,12 @@ TEST_F(TestUUriValidator, ValidFilter) { { // Wildcard URI + constexpr uint32_t WILDCARD_VERSION_MAJOR = 0xFF; uprotocol::v1::UUri uuri; uuri.set_authority_name("*"); - uuri.set_ue_id(0xFFFF); - uuri.set_ue_version_major(0xFF); - uuri.set_resource_id(0xFFFF); + uuri.set_ue_id(WILDCARD); + uuri.set_ue_version_major(WILDCARD_VERSION_MAJOR); + uuri.set_resource_id(WILDCARD); auto [valid, reason] = isValidFilter(uuri); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); @@ -588,7 +607,7 @@ TEST_F(TestUUriValidator, ValidFilter) { { // Reserved Version - auto uuri = getUuri(); + auto uuri = get_u_uri(); uuri.set_ue_version_major(0); auto [valid, reason] = isValidFilter(uuri); EXPECT_FALSE(valid); @@ -598,8 +617,9 @@ TEST_F(TestUUriValidator, ValidFilter) { { // Overflow Version - auto uuri = getUuri(); - uuri.set_ue_version_major(0x100); + constexpr uint32_t OVERFLOW_VERSION_MAJOR = 0x100; + auto uuri = get_u_uri(); + uuri.set_ue_version_major(OVERFLOW_VERSION_MAJOR); auto [valid, reason] = isValidFilter(uuri); EXPECT_FALSE(valid); EXPECT_EQ(reason.value_or(static_cast(-1)), @@ -608,8 +628,9 @@ TEST_F(TestUUriValidator, ValidFilter) { { // Overflow Resource - auto uuri = getUuri(); - uuri.set_resource_id(0x10000); + constexpr uint32_t OVERFLOW_RESOURCE_ID = 0x10000; + auto uuri = get_u_uri(); + uuri.set_resource_id(OVERFLOW_RESOURCE_ID); auto [valid, reason] = isValidFilter(uuri); EXPECT_FALSE(valid); EXPECT_EQ(reason.value_or(static_cast(-1)), @@ -618,8 +639,9 @@ TEST_F(TestUUriValidator, ValidFilter) { { // Long Authority - auto uuri = getUuri(); - uuri.set_authority_name(std::string(129, 'i')); + constexpr uint32_t AUTHORITY_NAME_NUMBER = 129; + auto uuri = get_u_uri(); + uuri.set_authority_name(std::string(AUTHORITY_NAME_NUMBER, 'i')); auto [valid, reason] = isValidFilter(uuri); EXPECT_FALSE(valid); EXPECT_EQ(reason.value_or(static_cast(-1)), @@ -627,7 +649,7 @@ TEST_F(TestUUriValidator, ValidFilter) { } } -TEST_F(TestUUriValidator, ReasonMessages) { +TEST_F(TestUUriValidator, ReasonMessages) { // NOLINT std::array all_reasons{Reason::EMPTY, Reason::RESERVED_VERSION, Reason::RESERVED_RESOURCE, @@ -687,4 +709,4 @@ TEST_F(TestUUriValidator, ReasonMessages) { } } -} // namespace +} // namespace uprotocol::datamodel::validator::uri diff --git a/test/coverage/datamodel/UuidBuilderTest.cpp b/test/coverage/datamodel/UuidBuilderTest.cpp index f6f7d1cea..07bc80592 100644 --- a/test/coverage/datamodel/UuidBuilderTest.cpp +++ b/test/coverage/datamodel/UuidBuilderTest.cpp @@ -14,10 +14,7 @@ #include "up-cpp/datamodel/builder/Uuid.h" #include "up-cpp/datamodel/constants/UuidConstants.h" -namespace { - -using namespace uprotocol::datamodel::builder; -using namespace uprotocol::datamodel; +namespace uprotocol::datamodel { class TestUuidBuilder : public testing::Test { protected: @@ -25,15 +22,17 @@ class TestUuidBuilder : public testing::Test { void TearDown() override {} TestUuidBuilder() = default; - ~TestUuidBuilder() = default; static void SetUpTestSuite() {} static void TearDownTestSuite() {} + +public: + ~TestUuidBuilder() override = default; }; // Test getBuilder -TEST(UuidBuilderTest, GetBuilder) { - auto builder = UuidBuilder::getBuilder(); +TEST(UuidBuilderTest, GetBuilder) { // NOLINT + auto builder = builder::UuidBuilder::getBuilder(); auto uuid = builder.build(); EXPECT_TRUE(uuid.msb()); @@ -41,8 +40,8 @@ TEST(UuidBuilderTest, GetBuilder) { } // Test GetTestBuilder -TEST(UuidBuilderTest, GetTestBuilder) { - auto builder = UuidBuilder::getTestBuilder(); +TEST(UuidBuilderTest, GetTestBuilder) { // NOLINT + auto builder = builder::UuidBuilder::getTestBuilder(); auto uuid = builder.build(); EXPECT_TRUE(uuid.msb()); @@ -50,11 +49,12 @@ TEST(UuidBuilderTest, GetTestBuilder) { } // Test TestBuilder with time source -TEST(UuidBuilderTest, WithTimeSource) { - auto fixed_time = std::chrono::system_clock::from_time_t(1234567890); +TEST(UuidBuilderTest, WithTimeSource) { // NOLINT + constexpr std::time_t FIXED_TIME_T = 1234567890; + auto fixed_time = std::chrono::system_clock::from_time_t(FIXED_TIME_T); auto fixed_time_ms = std::chrono::time_point_cast(fixed_time); - auto builder = UuidBuilder::getTestBuilder().withTimeSource( + auto builder = builder::UuidBuilder::getTestBuilder().withTimeSource( [fixed_time]() { return fixed_time; }); auto uuid = builder.build(); @@ -63,9 +63,10 @@ TEST(UuidBuilderTest, WithTimeSource) { } // Test RandomSource -TEST(UuidBuilderTest, WithRandomSource) { - auto fixed_random = 0x1234567890ABCDEF; - auto builder = UuidBuilder::getTestBuilder().withRandomSource( +TEST(UuidBuilderTest, WithRandomSource) { // NOLINT + constexpr uint64_t FIXED_RANDOM_UINT = 0x1234567890ABCDEF; + uint64_t fixed_random = FIXED_RANDOM_UINT; + auto builder = builder::UuidBuilder::getTestBuilder().withRandomSource( [fixed_random]() { return fixed_random; }); auto uuid = builder.build(); @@ -76,9 +77,9 @@ TEST(UuidBuilderTest, WithRandomSource) { } // Test independent state -TEST(UuidBuilderTest, Unguessability) { - auto builder1 = UuidBuilder::getBuilder(); - auto builder2 = UuidBuilder::getBuilder(); +TEST(UuidBuilderTest, Unguessability) { // NOLINT + auto builder1 = builder::UuidBuilder::getBuilder(); + auto builder2 = builder::UuidBuilder::getBuilder(); { // Check that rand fields generated by different builders are different @@ -104,19 +105,20 @@ TEST(UuidBuilderTest, Unguessability) { } // Test exception thrown -TEST(UuidBuilderTest, TestModeOnly) { - auto builder = UuidBuilder::getBuilder(); +TEST(UuidBuilderTest, TestModeOnly) { // NOLINT + auto builder = builder::UuidBuilder::getBuilder(); - EXPECT_THROW(builder.withTimeSource( + EXPECT_THROW(builder.withTimeSource( // NOLINT []() { return std::chrono::system_clock::now(); }), std::domain_error); - EXPECT_THROW(builder.withRandomSource([]() { return 0x1234567890ABCDEF; }), + EXPECT_THROW(builder.withRandomSource( // NOLINT + []() { return 0x1234567890ABCDEF; }), std::domain_error); } // Test version and variant -TEST_F(TestUuidBuilder, CheckVersionAndVariant) { - auto builder = UuidBuilder::getBuilder(); +TEST_F(TestUuidBuilder, CheckVersionAndVariant) { // NOLINT + auto builder = builder::UuidBuilder::getBuilder(); auto uuid = builder.build(); EXPECT_EQ((uuid.msb() >> UUID_VERSION_SHIFT) & UUID_VERSION_MASK, @@ -126,17 +128,19 @@ TEST_F(TestUuidBuilder, CheckVersionAndVariant) { } // Test custom time and random source with builder -TEST(UuidBuilderTest, CustomTimeAndRandomSource) { +TEST(UuidBuilderTest, CustomTimeAndRandomSource) { // NOLINT + constexpr std::time_t FIXED_TIME_T = 1623456789; + constexpr uint64_t FIXED_RANDOM_UINT = 0x1234567890ABCDEF; // Create a custom time source that returns a fixed timestamp - auto fixed_time = std::chrono::system_clock::from_time_t(1623456789); + auto fixed_time = std::chrono::system_clock::from_time_t(FIXED_TIME_T); auto time_source = [fixed_time]() { return fixed_time; }; // Create a custom random source that returns a fixed random value - uint64_t fixed_random = 0x1234567890ABCDEF; + uint64_t fixed_random = FIXED_RANDOM_UINT; auto random_source = [fixed_random]() { return fixed_random; }; // Create a UuidBuilder with the custom time and random sources - auto builder = UuidBuilder::getTestBuilder() + auto builder = builder::UuidBuilder::getTestBuilder() .withTimeSource(time_source) .withRandomSource(random_source); @@ -157,4 +161,4 @@ TEST(UuidBuilderTest, CustomTimeAndRandomSource) { EXPECT_EQ(random_value, fixed_random); } -} // namespace +} // namespace uprotocol::datamodel diff --git a/test/coverage/datamodel/UuidSerializerTest.cpp b/test/coverage/datamodel/UuidSerializerTest.cpp index 152f29fe5..ccf68af4a 100644 --- a/test/coverage/datamodel/UuidSerializerTest.cpp +++ b/test/coverage/datamodel/UuidSerializerTest.cpp @@ -13,10 +13,9 @@ #include #include -#include #include -namespace { +namespace uprotocol::datamodel::serializer::uuid { class TestUuidSerializer : public testing::Test { protected: @@ -28,94 +27,100 @@ class TestUuidSerializer : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. TestUuidSerializer() = default; - ~TestUuidSerializer() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} + +public: + ~TestUuidSerializer() override = default; }; // Test string serialization -TEST_F(TestUuidSerializer, SerializeToString) { +TEST_F(TestUuidSerializer, SerializeToString) { // NOLINT + constexpr uint64_t UUID_MSB = 0x1234567890ABCDEF; + constexpr uint64_t UUID_LSB = 0xFEDCBA0987654321; uprotocol::v1::UUID uuid; - uuid.set_msb(0x1234567890ABCDEF); - uuid.set_lsb(0xFEDCBA0987654321); + uuid.set_msb(UUID_MSB); + uuid.set_lsb(UUID_LSB); - std::string serialized_uuid = - uprotocol::datamodel::serializer::uuid::AsString::serialize(uuid); + std::string serialized_uuid = AsString::serialize(uuid); // Assert the serialized UUID matches the expected value EXPECT_EQ(serialized_uuid, "12345678-90ab-cdef-fedc-ba0987654321"); } // Test serialization with leading zeros in each segment -TEST_F(TestUuidSerializer, SerializeWithLeadingZeros) { +TEST_F(TestUuidSerializer, SerializeWithLeadingZeros) { // NOLINT + constexpr uint64_t UUID_MSB = 0x00001234007800AB; + constexpr uint64_t UUID_LSB = 0x00FE00BA09876543; uprotocol::v1::UUID uuid; - uuid.set_msb(0x00001234007800AB); - uuid.set_lsb(0x00FE00BA09876543); + uuid.set_msb(UUID_MSB); + uuid.set_lsb(UUID_LSB); - std::string serialized_uuid = - uprotocol::datamodel::serializer::uuid::AsString::serialize(uuid); + std::string serialized_uuid = AsString::serialize(uuid); // Assert the serialized UUID matches the expected value EXPECT_EQ(serialized_uuid, "00001234-0078-00ab-00fe-00ba09876543"); } // Test serialization with mixed case letters -TEST_F(TestUuidSerializer, SerializeWithMixedCaseLetters) { +TEST_F(TestUuidSerializer, SerializeWithMixedCaseLetters) { // NOLINT + constexpr uint64_t UUID_MSB = 0x1234567890ABcDEF; + constexpr uint64_t UUID_LSB = 0x00dcbA0987654321; uprotocol::v1::UUID uuid; - uuid.set_msb(0x1234567890ABcDEF); - uuid.set_lsb(0x00dcbA0987654321); + uuid.set_msb(UUID_MSB); + uuid.set_lsb(UUID_LSB); - std::string serialized_uuid = - uprotocol::datamodel::serializer::uuid::AsString::serialize(uuid); + std::string serialized_uuid = AsString::serialize(uuid); // Assert the serialized UUID matches the expected value in lowercase EXPECT_EQ(serialized_uuid, "12345678-90ab-cdef-00dc-ba0987654321"); } // Test serialization with leading zeros and mixed case letters -TEST_F(TestUuidSerializer, SerializeWithLeadingZerosAndMixedCaseLetters) { +TEST_F(TestUuidSerializer, // NOLINT + SerializeWithLeadingZerosAndMixedCaseLetters) { + constexpr uint64_t UUID_MSB = 0x00001234567890AB; + constexpr uint64_t UUID_LSB = 0xFedcba0987654982; uprotocol::v1::UUID uuid; - uuid.set_msb(0x00001234567890AB); - uuid.set_lsb(0xFedcba0987654982); + uuid.set_msb(UUID_MSB); + uuid.set_lsb(UUID_LSB); - std::string serialized_uuid = - uprotocol::datamodel::serializer::uuid::AsString::serialize(uuid); + std::string serialized_uuid = AsString::serialize(uuid); // Assert the serialized UUID matches the expected value EXPECT_EQ(serialized_uuid, "00001234-5678-90ab-fedc-ba0987654982"); } // Test serialization with leading/trailing zeros and mixed case letters -TEST_F(TestUuidSerializer, +TEST_F(TestUuidSerializer, // NOLINT SerializeWithLeadingZerosAndTrailingZerosAndMixedCaseLetters) { + constexpr uint64_t UUID_MSB = 0x00001234567890AB; + constexpr uint64_t UUID_LSB = 0xFedcba0987600000; uprotocol::v1::UUID uuid; - uuid.set_msb(0x00001234567890AB); - uuid.set_lsb(0xFedcba0987600000); + uuid.set_msb(UUID_MSB); + uuid.set_lsb(UUID_LSB); - std::string serialized_uuid = - uprotocol::datamodel::serializer::uuid::AsString::serialize(uuid); + std::string serialized_uuid = AsString::serialize(uuid); // Assert the serialized UUID matches the expected value EXPECT_EQ(serialized_uuid, "00001234-5678-90ab-fedc-ba0987600000"); } // Test string deserialization -TEST(DeserializerTest, DeserializeUUID) { +TEST(DeserializerTest, DeserializeUUID) { // NOLINT // Define a UUID string in the traditional format std::string uuid_str = "12345678-9abc-def0-fedc-ba9876543210"; // Deserialize the UUID string - uprotocol::v1::UUID deserialized_uuid = - uprotocol::datamodel::serializer::uuid::AsString::deserialize(uuid_str); + uprotocol::v1::UUID deserialized_uuid = AsString::deserialize(uuid_str); // Assert the deserialized UUID matches the expected values EXPECT_EQ(deserialized_uuid.msb(), 0x123456789ABCDEF0); EXPECT_EQ(deserialized_uuid.lsb(), 0xFEDCBA9876543210); } // Test deserialization with leading/trailing zeros and mixed case letters -TEST_F(TestUuidSerializer, +TEST_F(TestUuidSerializer, // NOLINT DeserializeWithLeadingZerosAndTrailingZerosAndMixedCaseLetters) { std::string uuid_str = "00001234-5678-90ab-feDc-ba0987600000"; - uprotocol::v1::UUID deserialized_uuid = - uprotocol::datamodel::serializer::uuid::AsString::deserialize(uuid_str); + uprotocol::v1::UUID deserialized_uuid = AsString::deserialize(uuid_str); // Assert the deserialized UUID matches the expected values EXPECT_EQ(deserialized_uuid.msb(), 0x00001234567890aB); @@ -123,167 +128,168 @@ TEST_F(TestUuidSerializer, } // Test invalid string deserialization -TEST(DeserializerTest, InvalidUUIDFormat) { +TEST(DeserializerTest, InvalidUUIDFormat) { // NOLINT // Define an invalid UUID string (missing dashes) std::string invalid_uuid_str = "123456789abcdef0123456789abcdef0"; // Assert that deserialization throws an invalid argument exception - EXPECT_THROW(uprotocol::datamodel::serializer::uuid::AsString::deserialize( - invalid_uuid_str), + EXPECT_THROW(static_cast(AsString::deserialize( // NOLINT + invalid_uuid_str)), std::invalid_argument); } // Test deserialization with correct length but incorrect placement of dashes -TEST(DeserializerTest, DeserializeWithMissingOneCharacter) { +TEST(DeserializerTest, DeserializeWithMissingOneCharacter) { // NOLINT std::string invalid_uuid = "12345678-1234-5678-1234-56781234567"; // Missing one character - EXPECT_THROW(uprotocol::datamodel::serializer::uuid::AsString::deserialize( - invalid_uuid), + EXPECT_THROW(static_cast(AsString::deserialize( // NOLINT + invalid_uuid)), std::invalid_argument); } // Test deserialization with UUIDs that have an extra character -TEST(DeserializerTest, DeserializeWithExtraCharacter) { +TEST(DeserializerTest, DeserializeWithExtraCharacter) { // NOLINT std::string invalid_uuid1 = "12345678-1234-5678-1234-1234567890123"; // Extra character at the end - EXPECT_THROW(uprotocol::datamodel::serializer::uuid::AsString::deserialize( - invalid_uuid1), + EXPECT_THROW(static_cast(AsString::deserialize( // NOLINT + invalid_uuid1)), std::invalid_argument); } -TEST(DeserializerTest, DeserializeWithIncorrectDashPlacement) { +TEST(DeserializerTest, DeserializeWithIncorrectDashPlacement) { // NOLINT std::string invalid_uuid1 = "123456781-2345-6781-2345-67812345678"; // First Dash placement - EXPECT_THROW(uprotocol::datamodel::serializer::uuid::AsString::deserialize( - invalid_uuid1), + EXPECT_THROW(static_cast(AsString::deserialize( // NOLINT + invalid_uuid1)), std::invalid_argument); std::string invalid_uuid2 = "12345678-12345-6781-2345-67812345678"; // Second Dash placement - EXPECT_THROW(uprotocol::datamodel::serializer::uuid::AsString::deserialize( - invalid_uuid2), + EXPECT_THROW(static_cast(AsString::deserialize( // NOLINT + invalid_uuid2)), std::invalid_argument); std::string invalid_uuid3 = "12345678-1234-56781-2345-67812345678"; // Third Dash placement - EXPECT_THROW(uprotocol::datamodel::serializer::uuid::AsString::deserialize( - invalid_uuid3), + EXPECT_THROW(static_cast(AsString::deserialize( // NOLINT + invalid_uuid3)), std::invalid_argument); std::string invalid_uuid4 = "12345678-1234-5678-12345-67812345678"; // Fourth Dash placement - EXPECT_THROW(uprotocol::datamodel::serializer::uuid::AsString::deserialize( - invalid_uuid4), + EXPECT_THROW(static_cast(AsString::deserialize( // NOLINT + invalid_uuid4)), std::invalid_argument); } // Test deserialization with a zero-length string -TEST(DeserializerTest, DeserializeEmptyString) { +TEST(DeserializerTest, DeserializeEmptyString) { // NOLINT // Define an empty UUID string - std::string empty_uuid_str = ""; + std::string empty_uuid_str; // Deserialize the empty UUID string - EXPECT_THROW(uprotocol::datamodel::serializer::uuid::AsString::deserialize( - empty_uuid_str), + EXPECT_THROW(static_cast(AsString::deserialize( // NOLINT + empty_uuid_str)), std::invalid_argument); } // Test deserialization with an invalid character in the UUID string -TEST(DeserializerTest, DeserializeInvalidCharacter) { +TEST(DeserializerTest, DeserializeInvalidCharacter) { // NOLINT // Define a UUID string with an invalid character ('x' instead of valid hex) std::string invalid_uuid_str = "1234567890ab-cdef-1234-5678-90abcdefxabc"; - EXPECT_THROW(uprotocol::datamodel::serializer::uuid::AsString::deserialize( - invalid_uuid_str), + EXPECT_THROW(static_cast(AsString::deserialize( // NOLINT + invalid_uuid_str)), std::invalid_argument); } // Test byte serialization -TEST_F(TestUuidSerializer, SerializeToBytes) { +TEST_F(TestUuidSerializer, SerializeToBytes) { // NOLINT uprotocol::v1::UUID uuid; - uuid.set_msb(0x1234567890ABCDEF); - uuid.set_lsb(0xFEDCBA0987654321); - - std::vector uuid_bytes = - uprotocol::datamodel::serializer::uuid::AsBytes::serialize(uuid); - std::vector expected_bytes = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, - 0xCD, 0xEF, 0xFE, 0xDC, 0xBA, 0x09, - 0x87, 0x65, 0x43, 0x21}; + constexpr uint64_t UUID_MSB = 0x1234567890ABCDEF; + constexpr uint64_t UUID_LSB = 0xFEDCBA0987654321; + constexpr std::array EXPECTED_BYTES_ARRAY = { + 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, + 0xFE, 0xDC, 0xBA, 0x09, 0x87, 0x65, 0x43, 0x21}; + uuid.set_msb(UUID_MSB); + uuid.set_lsb(UUID_LSB); + + std::vector uuid_bytes = AsBytes::serialize(uuid); + std::vector expected_bytes(EXPECTED_BYTES_ARRAY.begin(), + EXPECTED_BYTES_ARRAY.end()); EXPECT_EQ(uuid_bytes, expected_bytes); } // Test byte deserialization -TEST_F(TestUuidSerializer, DeserializeFromBytes) { - std::vector uuid_bytes = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, - 0xCD, 0xEF, 0xFE, 0xDC, 0xBA, 0x09, - 0x87, 0x65, 0x43, 0x21}; - uprotocol::v1::UUID uuid = - uprotocol::datamodel::serializer::uuid::AsBytes::deserialize( - uuid_bytes); +TEST_F(TestUuidSerializer, DeserializeFromBytes) { // NOLINT + constexpr std::array UUID_BYTES_ARRAY = { + 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, + 0xFE, 0xDC, 0xBA, 0x09, 0x87, 0x65, 0x43, 0x21}; + std::vector uuid_bytes(UUID_BYTES_ARRAY.begin(), + UUID_BYTES_ARRAY.end()); + uprotocol::v1::UUID uuid = AsBytes::deserialize(uuid_bytes); EXPECT_EQ(uuid.msb(), 0x1234567890ABCDEF); EXPECT_EQ(uuid.lsb(), 0xFEDCBA0987654321); } // Test invalid byte deserialization -TEST_F(TestUuidSerializer, DeserializeInvalidBytes) { - std::vector invalid_bytes = {0x12, 0x34, 0x56}; - EXPECT_THROW(uprotocol::datamodel::serializer::uuid::AsBytes::deserialize( - invalid_bytes), +TEST_F(TestUuidSerializer, DeserializeInvalidBytes) { // NOLINT + constexpr std::array INVALID_BYTES_ARRAY = {0x12, 0x34, 0x56}; + std::vector invalid_bytes(INVALID_BYTES_ARRAY.begin(), + INVALID_BYTES_ARRAY.end()); + EXPECT_THROW(static_cast(AsBytes::deserialize( // NOLINT + invalid_bytes)), std::invalid_argument); } // Test edge case: minimum values for msb and lsb -TEST_F(TestUuidSerializer, SerializeDeserializeMinValues) { +TEST_F(TestUuidSerializer, SerializeDeserializeMinValues) { // NOLINT + constexpr uint16_t NUM_BYTES = 16; uprotocol::v1::UUID uuid; uuid.set_msb(0x0000000000000000); uuid.set_lsb(0x0000000000000000); - std::string uuid_str = - uprotocol::datamodel::serializer::uuid::AsString::serialize(uuid); + std::string uuid_str = AsString::serialize(uuid); EXPECT_EQ(uuid_str, "00000000-0000-0000-0000-000000000000"); - uprotocol::v1::UUID deserialized_uuid = - uprotocol::datamodel::serializer::uuid::AsString::deserialize(uuid_str); + uprotocol::v1::UUID deserialized_uuid = AsString::deserialize(uuid_str); EXPECT_EQ(deserialized_uuid.msb(), 0x0000000000000000); EXPECT_EQ(deserialized_uuid.lsb(), 0x0000000000000000); - std::vector uuid_bytes = - uprotocol::datamodel::serializer::uuid::AsBytes::serialize(uuid); - std::vector expected_bytes(16, 0x00); + std::vector uuid_bytes = AsBytes::serialize(uuid); + + std::vector expected_bytes(NUM_BYTES, 0x00); EXPECT_EQ(uuid_bytes, expected_bytes); - deserialized_uuid = - uprotocol::datamodel::serializer::uuid::AsBytes::deserialize( - uuid_bytes); + deserialized_uuid = AsBytes::deserialize(uuid_bytes); EXPECT_EQ(deserialized_uuid.msb(), 0x0000000000000000); EXPECT_EQ(deserialized_uuid.lsb(), 0x0000000000000000); } // Test edge case: maximum values for msb and lsb -TEST_F(TestUuidSerializer, SerializeDeserializeMaxValues) { +TEST_F(TestUuidSerializer, SerializeDeserializeMaxValues) { // NOLINT + constexpr uint16_t NUM_BYTES = 16; + constexpr uint16_t VAL_BYTES = 0xFF; uprotocol::v1::UUID uuid; - uuid.set_msb(0xFFFFFFFFFFFFFFFF); - uuid.set_lsb(0xFFFFFFFFFFFFFFFF); + constexpr uint64_t UUID_MSB = 0xFFFFFFFFFFFFFFFF; + constexpr uint64_t UUID_LSB = 0xFFFFFFFFFFFFFFFF; + uuid.set_msb(UUID_MSB); + uuid.set_lsb(UUID_LSB); - std::string uuid_str = - uprotocol::datamodel::serializer::uuid::AsString::serialize(uuid); + std::string uuid_str = AsString::serialize(uuid); EXPECT_EQ(uuid_str, "ffffffff-ffff-ffff-ffff-ffffffffffff"); - uprotocol::v1::UUID deserialized_uuid = - uprotocol::datamodel::serializer::uuid::AsString::deserialize(uuid_str); + uprotocol::v1::UUID deserialized_uuid = AsString::deserialize(uuid_str); EXPECT_EQ(deserialized_uuid.msb(), 0xFFFFFFFFFFFFFFFF); EXPECT_EQ(deserialized_uuid.lsb(), 0xFFFFFFFFFFFFFFFF); - std::vector uuid_bytes = - uprotocol::datamodel::serializer::uuid::AsBytes::serialize(uuid); - std::vector expected_bytes(16, 0xFF); + std::vector uuid_bytes = AsBytes::serialize(uuid); + std::vector expected_bytes(NUM_BYTES, VAL_BYTES); EXPECT_EQ(uuid_bytes, expected_bytes); - deserialized_uuid = - uprotocol::datamodel::serializer::uuid::AsBytes::deserialize( - uuid_bytes); + deserialized_uuid = AsBytes::deserialize(uuid_bytes); EXPECT_EQ(deserialized_uuid.msb(), 0xFFFFFFFFFFFFFFFF); EXPECT_EQ(deserialized_uuid.lsb(), 0xFFFFFFFFFFFFFFFF); } -} // namespace +} // namespace uprotocol::datamodel::serializer::uuid diff --git a/test/coverage/datamodel/UuidValidatorTest.cpp b/test/coverage/datamodel/UuidValidatorTest.cpp index aae1d32df..e4e2f2a79 100644 --- a/test/coverage/datamodel/UuidValidatorTest.cpp +++ b/test/coverage/datamodel/UuidValidatorTest.cpp @@ -15,13 +15,11 @@ #include #include "up-cpp/datamodel/constants/UuidConstants.h" +constexpr std::chrono::seconds HUNDRED_SECONDS(100); +constexpr std::chrono::seconds SIXTY_SECONDS(60); +constexpr std::chrono::seconds THIRTY_SECONDS(30); -namespace { - -using namespace uprotocol::datamodel; -using namespace std::chrono_literals; -using namespace uprotocol::v1; -using namespace uprotocol::datamodel::validator::uuid; +namespace uprotocol::datamodel { class TestUuidValidator : public testing::Test { protected: @@ -33,16 +31,20 @@ class TestUuidValidator : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. TestUuidValidator() = default; - ~TestUuidValidator() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} + +public: + ~TestUuidValidator() override = default; }; // Helper fn for a fake UUID -UUID createFakeUuid(uint64_t timestamp = 0) { +uprotocol::v1::UUID createFakeUuid(uint64_t timestamp = 0) { + constexpr uint64_t UUID_MSB = 0x123ULL; + constexpr uint64_t UUID_LSB = 0xFFFFFFFFFFFFULL; uprotocol::v1::UUID uuid; // Create UUID with: // timestamp = 0 @@ -51,126 +53,134 @@ UUID createFakeUuid(uint64_t timestamp = 0) { // variant 0b10 (0x2) // random value = 0xFFFFFFFFFFFF uuid.set_msb((timestamp << UUID_TIMESTAMP_SHIFT) | - (UUID_VERSION_7 << UUID_VERSION_SHIFT) | (0x123ULL)); - uuid.set_lsb((UUID_VARIANT_RFC4122 << UUID_VARIANT_SHIFT) | - (0xFFFFFFFFFFFFULL)); + (UUID_VERSION_7 << UUID_VERSION_SHIFT) | (UUID_MSB)); + uuid.set_lsb((UUID_VARIANT_RFC4122 << UUID_VARIANT_SHIFT) | (UUID_LSB)); return uuid; } // Test valid UUID v7 -TEST_F(TestUuidValidator, ValidUuid) { +TEST_F(TestUuidValidator, ValidUuid) { // NOLINT // Create a valid UUID with version 7 and correct variant (10) auto uuid = createFakeUuid(); - auto [valid, reason] = isUuid(uuid); + auto [valid, reason] = validator::uuid::isUuid(uuid); EXPECT_TRUE(valid); EXPECT_FALSE(reason.has_value()); } // Test UUID with wrong version -TEST_F(TestUuidValidator, WrongVersion) { +TEST_F(TestUuidValidator, WrongVersion) { // NOLINT // Creating a UUID with wrong version (!7) + constexpr uint64_t UUID_MSB_VERSION8 = 8ULL; + constexpr uint64_t UUID_MSB = 0x123ULL; auto uuid = createFakeUuid(); - uuid.set_msb((8ULL << UUID_VERSION_SHIFT) | (0x123ULL)); // version 8 + uuid.set_msb((UUID_MSB_VERSION8 << UUID_VERSION_SHIFT) | + (UUID_MSB)); // version 8 - auto [valid, reason] = isUuid(uuid); + auto [valid, reason] = validator::uuid::isUuid(uuid); EXPECT_FALSE(valid); - EXPECT_EQ(reason.value(), Reason::WRONG_VERSION); - EXPECT_THROW(getVersion(uuid), InvalidUuid); + EXPECT_EQ(reason.value(), validator::uuid::Reason::WRONG_VERSION); + EXPECT_THROW(validator::uuid::getVersion(uuid), // NOLINT + validator::uuid::InvalidUuid); } // Test UUID with unsupported variant -TEST_F(TestUuidValidator, UnsupportedVariant) { +TEST_F(TestUuidValidator, UnsupportedVariant) { // NOLINT // Creating UUID with unsupported variant.(!10) auto uuid = createFakeUuid(); uuid.set_lsb(uuid.lsb() | (3ULL << UUID_VARIANT_SHIFT)); // variant 11 - auto [valid, reason] = isUuid(uuid); + auto [valid, reason] = validator::uuid::isUuid(uuid); EXPECT_FALSE(valid); - EXPECT_EQ(reason.value(), Reason::UNSUPPORTED_VARIANT); - EXPECT_THROW(getVariant(uuid), InvalidUuid); + EXPECT_EQ(reason.value(), validator::uuid::Reason::UNSUPPORTED_VARIANT); + EXPECT_THROW(validator::uuid::getVariant(uuid), // NOLINT + validator::uuid::InvalidUuid); } // Test UUID from the future // Exception on getRemainingTime() -TEST_F(TestUuidValidator, FromTheFuture) { +TEST_F(TestUuidValidator, FromTheFuture) { // NOLINT // Creating UUID with a timestamp in the future - auto future_time = std::chrono::system_clock::now() + 100s; - uint64_t future_timestamp = + auto future_time = std::chrono::system_clock::now() + HUNDRED_SECONDS; + auto future_timestamp = std::chrono::duration_cast( future_time.time_since_epoch()) .count(); - auto uuid = createFakeUuid(future_timestamp); - auto [valid, reason] = isUuid(uuid); + auto uuid = createFakeUuid(static_cast(future_timestamp)); + auto [valid, reason] = validator::uuid::isUuid(uuid); EXPECT_FALSE(valid); - EXPECT_EQ(reason.value(), Reason::FROM_THE_FUTURE); - EXPECT_THROW(getRemainingTime(uuid, 60s), InvalidUuid); + EXPECT_EQ(reason.value(), validator::uuid::Reason::FROM_THE_FUTURE); + EXPECT_THROW( // NOLINT + validator::uuid::getRemainingTime(uuid, SIXTY_SECONDS), + validator::uuid::InvalidUuid); } // Test expired UUID -TEST_F(TestUuidValidator, ExpiredUuid) { +TEST_F(TestUuidValidator, ExpiredUuid) { // NOLINT // Creating a UUID with a past timestamp - auto past_time = std::chrono::system_clock::now() - 100s; - uint64_t past_timestamp = - std::chrono::duration_cast( - past_time.time_since_epoch()) - .count(); - - auto uuid = createFakeUuid(past_timestamp); - auto [valid, reason] = isExpired(uuid, 60s); // 60 seconds TTL + auto past_time = std::chrono::system_clock::now() - HUNDRED_SECONDS; + auto past_timestamp = std::chrono::duration_cast( + past_time.time_since_epoch()) + .count(); + + auto uuid = createFakeUuid(static_cast(past_timestamp)); + auto [valid, reason] = + validator::uuid::isExpired(uuid, SIXTY_SECONDS); // 60 seconds TTL EXPECT_TRUE(valid); - EXPECT_EQ(reason.value(), Reason::EXPIRED); + EXPECT_EQ(reason.value(), validator::uuid::Reason::EXPIRED); } // Test non-expired UUID -TEST_F(TestUuidValidator, NonExpiredUuid) { +TEST_F(TestUuidValidator, NonExpiredUuid) { // NOLINT // Creating a UUID with a recent timestamp - auto recent_time = std::chrono::system_clock::now() - 30s; - uint64_t recent_timestamp = + auto recent_time = std::chrono::system_clock::now() - THIRTY_SECONDS; + auto recent_timestamp = std::chrono::duration_cast( recent_time.time_since_epoch()) .count(); - auto uuid = createFakeUuid(recent_timestamp); - auto [valid, reason] = isExpired(uuid, 60s); // 60 seconds TTL + auto uuid = createFakeUuid(static_cast(recent_timestamp)); + auto [valid, reason] = + validator::uuid::isExpired(uuid, SIXTY_SECONDS); // 60 seconds TTL EXPECT_FALSE(valid); EXPECT_FALSE(reason.has_value()); } // Test retrieving version -TEST_F(TestUuidValidator, RetrieveVersion) { +TEST_F(TestUuidValidator, RetrieveVersion) { // NOLINT auto uuid = createFakeUuid(); - EXPECT_EQ(getVersion(uuid), UUID_VERSION_7); + EXPECT_EQ(validator::uuid::getVersion(uuid), UUID_VERSION_7); } // Test retrieving variant -TEST_F(TestUuidValidator, RetrieveVariant) { +TEST_F(TestUuidValidator, RetrieveVariant) { // NOLINT auto uuid = createFakeUuid(); - EXPECT_EQ(getVariant(uuid), UUID_VARIANT_RFC4122); + EXPECT_EQ(validator::uuid::getVariant(uuid), UUID_VARIANT_RFC4122); } -TEST_F(TestUuidValidator, RetrieveTimestamp) { +TEST_F(TestUuidValidator, RetrieveTimestamp) { // NOLINT auto time_now = std::chrono::system_clock::now(); auto time_now_ms = std::chrono::time_point_cast(time_now); - uint64_t timestamp = time_now_ms.time_since_epoch().count(); + uint64_t timestamp = + static_cast(time_now_ms.time_since_epoch().count()); auto uuid = createFakeUuid(timestamp); - auto uuid_time = getTime(uuid); + auto uuid_time = validator::uuid::getTime(uuid); auto uuid_ms = std::chrono::time_point_cast(uuid_time); EXPECT_EQ(uuid_ms, time_now_ms); } // Test retrieving elapsed time -TEST_F(TestUuidValidator, RetrieveElapsedTime) { - auto past_time = std::chrono::system_clock::now() - 30s; - uint64_t timestamp = std::chrono::duration_cast( - past_time.time_since_epoch()) - .count(); - - auto uuid = createFakeUuid(timestamp); - auto elapsed_time = getElapsedTime(uuid); +TEST_F(TestUuidValidator, RetrieveElapsedTime) { // NOLINT + auto past_time = std::chrono::system_clock::now() - THIRTY_SECONDS; + auto timestamp = std::chrono::duration_cast( + past_time.time_since_epoch()) + .count(); + + auto uuid = createFakeUuid(static_cast(timestamp)); + auto elapsed_time = validator::uuid::getElapsedTime(uuid); auto expected_elapsed_time = std::chrono::duration_cast( std::chrono::system_clock::now() - past_time); @@ -185,15 +195,15 @@ TEST_F(TestUuidValidator, RetrieveElapsedTime) { } // Test retrieving remaining time -TEST_F(TestUuidValidator, RetrieveRemainingTime) { - auto past_time = std::chrono::system_clock::now() - 30s; - uint64_t timestamp = std::chrono::duration_cast( - past_time.time_since_epoch()) - .count(); - - auto uuid = createFakeUuid(timestamp); - auto ttl = 60s; - auto remaining_time = getRemainingTime(uuid, ttl); +TEST_F(TestUuidValidator, RetrieveRemainingTime) { // NOLINT + auto past_time = std::chrono::system_clock::now() - THIRTY_SECONDS; + auto timestamp = std::chrono::duration_cast( + past_time.time_since_epoch()) + .count(); + + auto uuid = createFakeUuid(static_cast(timestamp)); + auto ttl = SIXTY_SECONDS; + auto remaining_time = validator::uuid::getRemainingTime(uuid, ttl); auto expected_remaining_time = ttl - std::chrono::duration_cast( std::chrono::system_clock::now() - past_time); @@ -208,28 +218,30 @@ TEST_F(TestUuidValidator, RetrieveRemainingTime) { } // Test remaining time of 0ms -TEST_F(TestUuidValidator, ExpiredUuidRemainingTime) { - auto past_time = std::chrono::system_clock::now() - 100s; - uint64_t past_timestamp = - std::chrono::duration_cast( - past_time.time_since_epoch()) - .count(); - - auto uuid = createFakeUuid(past_timestamp); - auto remaining_time = getRemainingTime(uuid, 60s); - EXPECT_EQ(remaining_time, 0ms); +TEST_F(TestUuidValidator, ExpiredUuidRemainingTime) { // NOLINT + constexpr std::chrono::milliseconds ZERO_MILLISECONDS(0); + auto past_time = std::chrono::system_clock::now() - HUNDRED_SECONDS; + auto past_timestamp = std::chrono::duration_cast( + past_time.time_since_epoch()) + .count(); + + auto uuid = createFakeUuid(static_cast(past_timestamp)); + auto remaining_time = + validator::uuid::getRemainingTime(uuid, SIXTY_SECONDS); + EXPECT_EQ(remaining_time, ZERO_MILLISECONDS); } // Future timestamp to test exception thrown on getElapsedTime() -TEST_F(TestUuidValidator, InvalidUuidElapsedTime) { - auto future_time = std::chrono::system_clock::now() + 100s; - uint64_t future_timestamp = +TEST_F(TestUuidValidator, InvalidUuidElapsedTime) { // NOLINT + auto future_time = std::chrono::system_clock::now() + HUNDRED_SECONDS; + auto future_timestamp = std::chrono::duration_cast( future_time.time_since_epoch()) .count(); - auto uuid = createFakeUuid(future_timestamp); - EXPECT_THROW(getElapsedTime(uuid), InvalidUuid); + auto uuid = createFakeUuid(static_cast(future_timestamp)); + EXPECT_THROW(validator::uuid::getElapsedTime(uuid), // NOLINT + validator::uuid::InvalidUuid); } -} // namespace +} // namespace uprotocol::datamodel diff --git a/test/coverage/transport/UTransportTest.cpp b/test/coverage/transport/UTransportTest.cpp index 0757c1fe4..70498a53a 100644 --- a/test/coverage/transport/UTransportTest.cpp +++ b/test/coverage/transport/UTransportTest.cpp @@ -18,26 +18,18 @@ #include "UTransportMock.h" -namespace { +constexpr uint32_t WILDCARD = 0xFFFF; +constexpr uint32_t RESOURCE_ID_F00D = 0xF00D; -bool operator==(const uprotocol::v1::UUri& lhs, - const uprotocol::v1::UUri& rhs) { - using namespace google::protobuf::util; - return MessageDifferencer::Equals(lhs, rhs); -} +namespace uprotocol { -bool operator==(const uprotocol::v1::UMessage& lhs, - const uprotocol::v1::UMessage& rhs) { - using namespace google::protobuf::util; - return MessageDifferencer::Equals(lhs, rhs); +bool operator==(const v1::UUri& lhs, const v1::UUri& rhs) { + return google::protobuf::util::MessageDifferencer::Equals(lhs, rhs); } -#if 0 -bool operator==(const uprotocol::v1::UStatus& lhs, - const uprotocol::v1::UCode& rhs) { - return lhs.code() == rhs; +bool operator==(const v1::UMessage& lhs, const v1::UMessage& rhs) { + return google::protobuf::util::MessageDifferencer::Equals(lhs, rhs); } -#endif class TestUTransport : public testing::Test { protected: @@ -50,117 +42,123 @@ class TestUTransport : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. TestUTransport() = default; - ~TestUTransport() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} - static std::shared_ptr makeMockTransport( - const uprotocol::v1::UUri& uri) { - return std::make_shared(uri); + static std::shared_ptr makeMockTransport( + const v1::UUri& uri) { + return std::make_shared(uri); } - static std::shared_ptr makeTransport( - const uprotocol::v1::UUri& uri) { + static std::shared_ptr makeTransport( + const v1::UUri& uri) { return makeMockTransport(uri); } - static std::shared_ptr makeTransport( - std::shared_ptr mock) { + static std::shared_ptr makeTransport( + std::shared_ptr mock) { return mock; } - static uprotocol::v1::UUri getValidUri() { - uprotocol::v1::UUri uri; + static v1::UUri getValidUri() { + constexpr uint32_t RANDOM_UE_ID = 0xdeadbeef; + constexpr uint32_t RANDOM_VERSION_MAJOR = 16; + v1::UUri uri; uri.set_authority_name("UTransportTest"); - uri.set_ue_id(0xdeadbeef); - uri.set_ue_version_major(16); + uri.set_ue_id(RANDOM_UE_ID); + uri.set_ue_version_major(RANDOM_VERSION_MAJOR); uri.set_resource_id(0); return uri; } - static uprotocol::v1::UUri getWildcardUri() { - uprotocol::v1::UUri uri; + static v1::UUri getWildcardUri() { + constexpr uint32_t WILDCARD_VERSION_MAJOR = 0xFF; + v1::UUri uri; uri.set_authority_name("*"); - uri.set_ue_id(0xFFFF); - uri.set_ue_version_major(0xFF); - uri.set_resource_id(0xFFFF); + uri.set_ue_id(WILDCARD); + uri.set_ue_version_major(WILDCARD_VERSION_MAJOR); + uri.set_resource_id(WILDCARD); return uri; } + +public: + ~TestUTransport() override = default; }; -TEST_F(TestUTransport, CreateTransport) { - EXPECT_NO_THROW(auto transport = makeTransport(getValidUri())); +TEST_F(TestUTransport, CreateTransport) { // NOLINT + EXPECT_NO_THROW(auto transport = makeTransport(getValidUri())); // NOLINT } -using InvalidUUri = uprotocol::datamodel::validator::uri::InvalidUUri; +using InvalidUUri = datamodel::validator::uri::InvalidUUri; -TEST_F(TestUTransport, CreateTransportInvalidUUri) { +TEST_F(TestUTransport, CreateTransportInvalidUUri) { // NOLINT auto uri = getValidUri(); uri.set_authority_name("*"); - EXPECT_THROW({ auto transport = makeTransport(uri); }, InvalidUUri); + EXPECT_THROW({ auto transport = makeTransport(uri); }, // NOLINT + InvalidUUri); } -using UMessageBuilder = uprotocol::datamodel::builder::UMessageBuilder; -using PayloadBuilder = uprotocol::datamodel::builder::Payload; +using UMessageBuilder = datamodel::builder::UMessageBuilder; +using PayloadBuilder = datamodel::builder::Payload; -TEST_F(TestUTransport, SendOk) { +TEST_F(TestUTransport, SendOk) { // NOLINT + constexpr uint32_t RANDOM_RESOURCE_ID = 0xABBA; auto transport_mock = makeMockTransport(getValidUri()); auto transport = makeTransport(transport_mock); auto topic = getValidUri(); - topic.set_resource_id(0xABBA); - PayloadBuilder payload(std::string("[\"Arrival\", \"Waterloo\"]"), - uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_JSON); + topic.set_resource_id(RANDOM_RESOURCE_ID); + PayloadBuilder payload(std::string(R"(["Arrival", "Waterloo"])"), + v1::UPayloadFormat::UPAYLOAD_FORMAT_JSON); auto message = UMessageBuilder::publish(std::move(topic)).build(std::move(payload)); decltype(transport->send(message)) result; - EXPECT_NO_THROW(result = transport->send(message)); + EXPECT_NO_THROW(result = transport->send(message)); // NOLINT - EXPECT_EQ(result.code(), uprotocol::v1::UCode::OK); - EXPECT_EQ(transport_mock->send_count_, 1); - EXPECT_TRUE(transport_mock->message_ == message); + EXPECT_EQ(result.code(), v1::UCode::OK); + EXPECT_EQ(transport_mock->getSendCount(), 1); + EXPECT_TRUE(transport_mock->getMessage() == message); } -using InvalidUMessge = - uprotocol::datamodel::validator::message::InvalidUMessage; +using InvalidUMessge = datamodel::validator::message::InvalidUMessage; -TEST_F(TestUTransport, SendInvalidMessage) { +TEST_F(TestUTransport, SendInvalidMessage) { // NOLINT auto transport_mock = makeMockTransport(getValidUri()); auto transport = makeTransport(transport_mock); auto topic = getValidUri(); - topic.set_resource_id(0xF00D); + topic.set_resource_id(RESOURCE_ID_F00D); auto message = UMessageBuilder::publish(std::move(topic)).build(); message.mutable_attributes()->set_type( - uprotocol::v1::UMessageType::UMESSAGE_TYPE_REQUEST); + v1::UMessageType::UMESSAGE_TYPE_REQUEST); decltype(transport->send(message)) result; - EXPECT_THROW({ result = transport->send(message); }, InvalidUMessge); - EXPECT_EQ(transport_mock->send_count_, 0); + EXPECT_THROW({ result = transport->send(message); }, // NOLINT + InvalidUMessge); + EXPECT_EQ(transport_mock->getSendCount(), 0); } -TEST_F(TestUTransport, SendImplStatus) { +TEST_F(TestUTransport, SendImplStatus) { // NOLINT auto transport_mock = makeMockTransport(getValidUri()); auto transport = makeTransport(transport_mock); - transport_mock->send_status_.set_code( - uprotocol::v1::UCode::PERMISSION_DENIED); + transport_mock->getSendStatus().set_code(v1::UCode::PERMISSION_DENIED); auto topic = getValidUri(); - topic.set_resource_id(0xF00D); + topic.set_resource_id(RESOURCE_ID_F00D); auto message = UMessageBuilder::publish(std::move(topic)).build(); decltype(transport->send(message)) result; - EXPECT_NO_THROW(result = transport->send(message)); + EXPECT_NO_THROW(result = transport->send(message)); // NOLINT - EXPECT_EQ(result.code(), uprotocol::v1::UCode::PERMISSION_DENIED); + EXPECT_EQ(result.code(), v1::UCode::PERMISSION_DENIED); } -TEST_F(TestUTransport, RegisterListenerOk) { +TEST_F(TestUTransport, RegisterListenerOk) { // NOLINT auto transport_mock = makeMockTransport(getValidUri()); auto transport = makeTransport(transport_mock); @@ -168,8 +166,8 @@ TEST_F(TestUTransport, RegisterListenerOk) { auto callback = [&called](const auto&) { called = true; }; auto source_filter = getWildcardUri(); - uprotocol::transport::UTransport::ListenHandle handle; - EXPECT_NO_THROW({ + transport::UTransport::ListenHandle handle; + EXPECT_NO_THROW({ // NOLINT auto maybe_handle = transport->registerListener(callback, source_filter); @@ -181,21 +179,21 @@ TEST_F(TestUTransport, RegisterListenerOk) { EXPECT_TRUE(handle); - EXPECT_FALSE(transport_mock->sink_filter_); - EXPECT_TRUE(source_filter == transport_mock->source_filter_); - EXPECT_TRUE(transport_mock->listener_); - if (transport_mock->listener_) { - auto callable = transport_mock->listener_.value(); + EXPECT_FALSE(transport_mock->getSinkFilter()); + EXPECT_TRUE(source_filter == transport_mock->getSourceFilter()); + EXPECT_TRUE(transport_mock->getListener()); + if (transport_mock->getListener()) { + auto callable = transport_mock->getListener().value(); EXPECT_FALSE(called); auto topic = getValidUri(); - topic.set_resource_id(0xF00D); + topic.set_resource_id(RESOURCE_ID_F00D); auto message = UMessageBuilder::publish(std::move(topic)).build(); callable(message); EXPECT_TRUE(called); } } -TEST_F(TestUTransport, RegisterListenerInvalidSource) { +TEST_F(TestUTransport, RegisterListenerInvalidSource) { // NOLINT auto transport_mock = makeMockTransport(getValidUri()); auto transport = makeTransport(transport_mock); @@ -204,7 +202,7 @@ TEST_F(TestUTransport, RegisterListenerInvalidSource) { auto source_filter = getWildcardUri(); source_filter.set_resource_id(1); - EXPECT_THROW( + EXPECT_THROW( // NOLINT { auto maybe_handle = transport->registerListener(callback, source_filter); @@ -212,24 +210,23 @@ TEST_F(TestUTransport, RegisterListenerInvalidSource) { InvalidUUri); // Did not attempt to register a callback - EXPECT_FALSE(transport_mock->sink_filter_); - EXPECT_FALSE(transport_mock->listener_); + EXPECT_FALSE(transport_mock->getSinkFilter()); + EXPECT_FALSE(transport_mock->getListener()); EXPECT_FALSE(called); } -TEST_F(TestUTransport, RegisterListenerImplStatus) { +TEST_F(TestUTransport, RegisterListenerImplStatus) { // NOLINT auto transport_mock = makeMockTransport(getValidUri()); auto transport = makeTransport(transport_mock); - transport_mock->registerListener_status_.set_code( - uprotocol::v1::UCode::INTERNAL); + transport_mock->getRegisterListenerStatus().set_code(v1::UCode::INTERNAL); bool called = false; auto callback = [&called](const auto&) { called = true; }; auto source_filter = getWildcardUri(); - uprotocol::v1::UStatus status; - EXPECT_NO_THROW({ + v1::UStatus status; + EXPECT_NO_THROW({ // NOLINT auto maybe_handle = transport->registerListener(callback, source_filter); @@ -240,19 +237,19 @@ TEST_F(TestUTransport, RegisterListenerImplStatus) { }); // The listener that was sent to the impl is not connected - EXPECT_TRUE(transport_mock->listener_); - if (transport_mock->listener_) { - auto callable = transport_mock->listener_.value(); + EXPECT_TRUE(transport_mock->getListener()); + if (transport_mock->getListener()) { + auto callable = transport_mock->getListener().value(); EXPECT_FALSE(callable); auto topic = getValidUri(); - topic.set_resource_id(0xF00D); + topic.set_resource_id(RESOURCE_ID_F00D); auto message = UMessageBuilder::publish(std::move(topic)).build(); callable(message); EXPECT_FALSE(called); } } -TEST_F(TestUTransport, RegisterListenerWithSinkFilterOk) { +TEST_F(TestUTransport, RegisterListenerWithSinkFilterOk) { // NOLINT auto transport_mock = makeMockTransport(getValidUri()); auto transport = makeTransport(transport_mock); @@ -260,10 +257,10 @@ TEST_F(TestUTransport, RegisterListenerWithSinkFilterOk) { auto callback = [&called](const auto&) { called = true; }; auto source_filter = getWildcardUri(); auto sink_filter = getValidUri(); - sink_filter.set_resource_id(0xFFFF); + sink_filter.set_resource_id(WILDCARD); - uprotocol::transport::UTransport::ListenHandle handle; - EXPECT_NO_THROW({ + transport::UTransport::ListenHandle handle; + EXPECT_NO_THROW({ // NOLINT auto maybe_handle = transport->registerListener(callback, source_filter, sink_filter); @@ -275,25 +272,25 @@ TEST_F(TestUTransport, RegisterListenerWithSinkFilterOk) { EXPECT_TRUE(handle); - EXPECT_TRUE(transport_mock->sink_filter_); - if (transport_mock->sink_filter_) { - EXPECT_TRUE(sink_filter == transport_mock->sink_filter_.value()); + EXPECT_TRUE(transport_mock->getSinkFilter()); + if (transport_mock->getSinkFilter()) { + EXPECT_TRUE(sink_filter == transport_mock->getSinkFilter().value()); } - EXPECT_TRUE(source_filter == transport_mock->source_filter_); - EXPECT_TRUE(transport_mock->listener_); - if (transport_mock->listener_) { - auto callable = transport_mock->listener_.value(); + EXPECT_TRUE(source_filter == transport_mock->getSourceFilter()); + EXPECT_TRUE(transport_mock->getListener()); + if (transport_mock->getListener()) { + auto callable = transport_mock->getListener().value(); EXPECT_FALSE(called); auto topic = getValidUri(); - topic.set_resource_id(0xF00D); + topic.set_resource_id(RESOURCE_ID_F00D); auto message = UMessageBuilder::publish(std::move(topic)).build(); callable(message); EXPECT_TRUE(called); } } -TEST_F(TestUTransport, RegisterListenerWithSinkFilterInvalidSource) { +TEST_F(TestUTransport, RegisterListenerWithSinkFilterInvalidSource) { // NOLINT auto transport_mock = makeMockTransport(getValidUri()); auto transport = makeTransport(transport_mock); @@ -301,12 +298,12 @@ TEST_F(TestUTransport, RegisterListenerWithSinkFilterInvalidSource) { auto callback = [&called](const auto&) { called = true; }; auto source_filter = getWildcardUri(); auto sink_filter = getValidUri(); - sink_filter.set_resource_id(0xFFFF); + sink_filter.set_resource_id(WILDCARD); // Make source invalid - source_filter.set_ue_version_major(0xFFFF); + source_filter.set_ue_version_major(WILDCARD); - EXPECT_THROW( + EXPECT_THROW( // NOLINT { auto maybe_handle = transport->registerListener( callback, source_filter, sink_filter); @@ -314,12 +311,12 @@ TEST_F(TestUTransport, RegisterListenerWithSinkFilterInvalidSource) { InvalidUUri); // Did not attempt to register a callback - EXPECT_FALSE(transport_mock->sink_filter_); - EXPECT_FALSE(transport_mock->listener_); + EXPECT_FALSE(transport_mock->getSinkFilter()); + EXPECT_FALSE(transport_mock->getListener()); EXPECT_FALSE(called); } -TEST_F(TestUTransport, RegisterListenerWithSinkFilterInvalidSink) { +TEST_F(TestUTransport, RegisterListenerWithSinkFilterInvalidSink) { // NOLINT auto transport_mock = makeMockTransport(getValidUri()); auto transport = makeTransport(transport_mock); @@ -327,12 +324,12 @@ TEST_F(TestUTransport, RegisterListenerWithSinkFilterInvalidSink) { auto callback = [&called](const auto&) { called = true; }; auto source_filter = getWildcardUri(); auto sink_filter = getValidUri(); - sink_filter.set_resource_id(0xFFFF); + sink_filter.set_resource_id(WILDCARD); // Make sink invalid - sink_filter.set_ue_version_major(0xFFFF); + sink_filter.set_ue_version_major(WILDCARD); - EXPECT_THROW( + EXPECT_THROW( // NOLINT { auto maybe_handle = transport->registerListener( callback, source_filter, sink_filter); @@ -340,26 +337,25 @@ TEST_F(TestUTransport, RegisterListenerWithSinkFilterInvalidSink) { InvalidUUri); // Did not attempt to register a callback - EXPECT_FALSE(transport_mock->sink_filter_); - EXPECT_FALSE(transport_mock->listener_); + EXPECT_FALSE(transport_mock->getSinkFilter()); + EXPECT_FALSE(transport_mock->getListener()); EXPECT_FALSE(called); } -TEST_F(TestUTransport, RegisterListenerWithSinkFilterImplStatus) { +TEST_F(TestUTransport, RegisterListenerWithSinkFilterImplStatus) { // NOLINT auto transport_mock = makeMockTransport(getValidUri()); auto transport = makeTransport(transport_mock); - transport_mock->registerListener_status_.set_code( - uprotocol::v1::UCode::NOT_FOUND); + transport_mock->getRegisterListenerStatus().set_code(v1::UCode::NOT_FOUND); bool called = false; auto callback = [&called](const auto&) { called = true; }; auto source_filter = getWildcardUri(); auto sink_filter = getValidUri(); - sink_filter.set_resource_id(0xFFFF); + sink_filter.set_resource_id(WILDCARD); - uprotocol::v1::UStatus status; - EXPECT_NO_THROW({ + v1::UStatus status; + EXPECT_NO_THROW({ // NOLINT auto maybe_handle = transport->registerListener(callback, source_filter, sink_filter); @@ -370,19 +366,19 @@ TEST_F(TestUTransport, RegisterListenerWithSinkFilterImplStatus) { }); // The listener that was sent to the impl is not connected - EXPECT_TRUE(transport_mock->listener_); - if (transport_mock->listener_) { - auto callable = transport_mock->listener_.value(); + EXPECT_TRUE(transport_mock->getListener()); + if (transport_mock->getListener()) { + auto callable = transport_mock->getListener().value(); EXPECT_FALSE(callable); auto topic = getValidUri(); - topic.set_resource_id(0xF00D); + topic.set_resource_id(RESOURCE_ID_F00D); auto message = UMessageBuilder::publish(std::move(topic)).build(); callable(message); EXPECT_FALSE(called); } } -TEST_F(TestUTransport, RegisterListenerWithSinkResourceOk) { +TEST_F(TestUTransport, RegisterListenerWithSinkResourceOk) { // NOLINT auto transport_mock = makeMockTransport(getValidUri()); auto transport = makeTransport(transport_mock); @@ -390,10 +386,10 @@ TEST_F(TestUTransport, RegisterListenerWithSinkResourceOk) { auto callback = [&called](const auto&) { called = true; }; auto source_filter = getWildcardUri(); - uprotocol::transport::UTransport::ListenHandle handle; - EXPECT_NO_THROW({ - auto maybe_handle = - transport->registerListener(callback, source_filter, 0xF00D); + transport::UTransport::ListenHandle handle; + EXPECT_NO_THROW({ // NOLINT + auto maybe_handle = transport->registerListener(callback, source_filter, + RESOURCE_ID_F00D); EXPECT_TRUE(maybe_handle); if (maybe_handle) { @@ -403,27 +399,28 @@ TEST_F(TestUTransport, RegisterListenerWithSinkResourceOk) { EXPECT_TRUE(handle); - EXPECT_TRUE(transport_mock->sink_filter_); - if (transport_mock->sink_filter_) { + EXPECT_TRUE(transport_mock->getSinkFilter()); + if (transport_mock->getSinkFilter()) { auto sink_filter = getValidUri(); - sink_filter.set_resource_id(0xF00D); - EXPECT_TRUE(sink_filter == transport_mock->sink_filter_.value()); + sink_filter.set_resource_id(RESOURCE_ID_F00D); + EXPECT_TRUE(sink_filter == transport_mock->getSinkFilter().value()); } - EXPECT_TRUE(source_filter == transport_mock->source_filter_); - EXPECT_TRUE(transport_mock->listener_); - if (transport_mock->listener_) { - auto callable = transport_mock->listener_.value(); + EXPECT_TRUE(source_filter == transport_mock->getSourceFilter()); + EXPECT_TRUE(transport_mock->getListener()); + if (transport_mock->getListener()) { + auto callable = transport_mock->getListener().value(); EXPECT_FALSE(called); auto topic = getValidUri(); - topic.set_resource_id(0xF00D); + topic.set_resource_id(RESOURCE_ID_F00D); auto message = UMessageBuilder::publish(std::move(topic)).build(); callable(message); EXPECT_TRUE(called); } } -TEST_F(TestUTransport, RegisterListenerWithSinkResourceInvalidSource) { +TEST_F(TestUTransport, // NOLINT + RegisterListenerWithSinkResourceInvalidSource) { auto transport_mock = makeMockTransport(getValidUri()); auto transport = makeTransport(transport_mock); @@ -432,9 +429,9 @@ TEST_F(TestUTransport, RegisterListenerWithSinkResourceInvalidSource) { auto source_filter = getWildcardUri(); // Make source invalid - source_filter.set_ue_version_major(0xFFFF); + source_filter.set_ue_version_major(WILDCARD); - EXPECT_THROW( + EXPECT_THROW( // NOLINT { auto maybe_handle = transport->registerListener(callback, source_filter, 0xABBA); @@ -442,29 +439,28 @@ TEST_F(TestUTransport, RegisterListenerWithSinkResourceInvalidSource) { InvalidUUri); // Did not attempt to register a callback - EXPECT_FALSE(transport_mock->sink_filter_); - EXPECT_FALSE(transport_mock->listener_); + EXPECT_FALSE(transport_mock->getSinkFilter()); + EXPECT_FALSE(transport_mock->getListener()); EXPECT_FALSE(called); } // NOTE: it is not possible to produce an invalid sink filter with this method // since it constrains the sink resource parameter to uint16_t -TEST_F(TestUTransport, RegisterListenerWithSinkResourceImplStatus) { +TEST_F(TestUTransport, RegisterListenerWithSinkResourceImplStatus) { // NOLINT auto transport_mock = makeMockTransport(getValidUri()); auto transport = makeTransport(transport_mock); - transport_mock->registerListener_status_.set_code( - uprotocol::v1::UCode::NOT_FOUND); + transport_mock->getRegisterListenerStatus().set_code(v1::UCode::NOT_FOUND); bool called = false; auto callback = [&called](const auto&) { called = true; }; auto source_filter = getWildcardUri(); - uprotocol::v1::UStatus status; - EXPECT_NO_THROW({ + v1::UStatus status; + EXPECT_NO_THROW({ // NOLINT auto maybe_handle = - transport->registerListener(callback, source_filter, 0xFFFF); + transport->registerListener(callback, source_filter, WILDCARD); EXPECT_FALSE(maybe_handle); if (!maybe_handle) { @@ -473,21 +469,21 @@ TEST_F(TestUTransport, RegisterListenerWithSinkResourceImplStatus) { }); // The listener that was sent to the impl is not connected - EXPECT_TRUE(transport_mock->listener_); - if (transport_mock->listener_) { - auto callable = transport_mock->listener_.value(); + EXPECT_TRUE(transport_mock->getListener()); + if (transport_mock->getListener()) { + auto callable = transport_mock->getListener().value(); // The callback isn't connected... EXPECT_FALSE(callable); // ...but we're still going to try to call it anyway auto topic = getValidUri(); - topic.set_resource_id(0xF00D); + topic.set_resource_id(RESOURCE_ID_F00D); auto message = UMessageBuilder::publish(std::move(topic)).build(); callable(message); EXPECT_FALSE(called); } } -TEST_F(TestUTransport, DeprecatedRegisterListenerOk) { +TEST_F(TestUTransport, DeprecatedRegisterListenerOk) { // NOLINT auto transport_mock = makeMockTransport(getValidUri()); auto transport = makeTransport(transport_mock); @@ -495,8 +491,8 @@ TEST_F(TestUTransport, DeprecatedRegisterListenerOk) { auto callback = [&called](const auto&) { called = true; }; auto topic_source_filter = getWildcardUri(); - uprotocol::transport::UTransport::ListenHandle handle; - EXPECT_NO_THROW({ + transport::UTransport::ListenHandle handle; + EXPECT_NO_THROW({ // NOLINT // When source_filter is omitted, sink_filter is treated as a publish // topic. auto maybe_handle = @@ -510,21 +506,22 @@ TEST_F(TestUTransport, DeprecatedRegisterListenerOk) { EXPECT_TRUE(handle); - EXPECT_FALSE(transport_mock->sink_filter_); - EXPECT_TRUE(topic_source_filter == transport_mock->source_filter_); - EXPECT_TRUE(transport_mock->listener_); - if (transport_mock->listener_) { - auto callable = transport_mock->listener_.value(); + EXPECT_FALSE(transport_mock->getSinkFilter()); + EXPECT_TRUE(topic_source_filter == transport_mock->getSourceFilter()); + EXPECT_TRUE(transport_mock->getListener()); + if (transport_mock->getListener()) { + auto callable = transport_mock->getListener().value(); EXPECT_FALSE(called); auto topic = getValidUri(); - topic.set_resource_id(0xF00D); + topic.set_resource_id(RESOURCE_ID_F00D); auto message = UMessageBuilder::publish(std::move(topic)).build(); callable(message); EXPECT_TRUE(called); } } -TEST_F(TestUTransport, DeprecatedRegisterListenerWithSourceFilterOk) { +TEST_F(TestUTransport, // NOLINT + DeprecatedRegisterListenerWithSourceFilterOk) { auto transport_mock = makeMockTransport(getValidUri()); auto transport = makeTransport(transport_mock); @@ -532,10 +529,10 @@ TEST_F(TestUTransport, DeprecatedRegisterListenerWithSourceFilterOk) { auto callback = [&called](const auto&) { called = true; }; auto source_filter = getWildcardUri(); auto sink_filter = getValidUri(); - sink_filter.set_resource_id(0xFFFF); + sink_filter.set_resource_id(WILDCARD); - uprotocol::transport::UTransport::ListenHandle handle; - EXPECT_NO_THROW({ + transport::UTransport::ListenHandle handle; + EXPECT_NO_THROW({ // NOLINT auto maybe_handle = transport->registerListener(sink_filter, callback, source_filter); @@ -547,22 +544,22 @@ TEST_F(TestUTransport, DeprecatedRegisterListenerWithSourceFilterOk) { EXPECT_TRUE(handle); - EXPECT_TRUE(transport_mock->sink_filter_); - if (transport_mock->sink_filter_) { - EXPECT_TRUE(sink_filter == transport_mock->sink_filter_.value()); + EXPECT_TRUE(transport_mock->getSinkFilter()); + if (transport_mock->getSinkFilter()) { + EXPECT_TRUE(sink_filter == transport_mock->getSinkFilter().value()); } - EXPECT_TRUE(source_filter == transport_mock->source_filter_); - EXPECT_TRUE(transport_mock->listener_); - if (transport_mock->listener_) { - auto callable = transport_mock->listener_.value(); + EXPECT_TRUE(source_filter == transport_mock->getSourceFilter()); + EXPECT_TRUE(transport_mock->getListener()); + if (transport_mock->getListener()) { + auto callable = transport_mock->getListener().value(); EXPECT_FALSE(called); auto topic = getValidUri(); - topic.set_resource_id(0xF00D); + topic.set_resource_id(RESOURCE_ID_F00D); auto message = UMessageBuilder::publish(std::move(topic)).build(); callable(message); EXPECT_TRUE(called); } } -} // namespace +} // namespace uprotocol diff --git a/test/coverage/utils/CallbackConnectionTest.cpp b/test/coverage/utils/CallbackConnectionTest.cpp index fd265b4ac..74a284bf4 100644 --- a/test/coverage/utils/CallbackConnectionTest.cpp +++ b/test/coverage/utils/CallbackConnectionTest.cpp @@ -17,7 +17,7 @@ #include #include -namespace { +namespace uprotocol::utils { class CallbackTest : public testing::Test { protected: @@ -29,27 +29,26 @@ class CallbackTest : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. CallbackTest() = default; - ~CallbackTest() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} + +public: + ~CallbackTest() override = default; }; /// It should be possible to establish a connection without an exception /// being thrown. Exceptions that can be thrown at this stage would be a result /// of a system-level failure, such as running out of memory. -TEST_F(CallbackTest, EstablishDoesNotThrow) { - using namespace uprotocol::utils; - - EXPECT_NO_THROW(callbacks::Connection::establish([]() {})); +TEST_F(CallbackTest, EstablishDoesNotThrow) { // NOLINT + EXPECT_NO_THROW(callbacks::Connection::establish([]() {})); // NOLINT } /// It should be possible to establish a connection and call the callback /// function via the CallerHandle (aka the callable). -TEST_F(CallbackTest, EstablishLinkedPair) { - using namespace uprotocol::utils; +TEST_F(CallbackTest, EstablishLinkedPair) { // NOLINT int call_count{0}; @@ -62,7 +61,7 @@ TEST_F(CallbackTest, EstablishLinkedPair) { // It's the first time we're calling the callback - check that it doesn't // throw to stop the test here if something is wrong. - EXPECT_NO_THROW(callable()); + EXPECT_NO_THROW(callable()); // NOLINT EXPECT_TRUE(handle); EXPECT_TRUE(callable); @@ -78,13 +77,11 @@ TEST_F(CallbackTest, EstablishLinkedPair) { // When dropping a CalleeHandle or the last CallerHandle, the connection should // be broken. -TEST_F(CallbackTest, DroppedHandlesBreakConnection) { +TEST_F(CallbackTest, DroppedHandlesBreakConnection) { // NOLINT int call_count{0}; // Utility to produce connected pairs that have been validated as connected - auto getPair = ([&call_count]() { - using namespace uprotocol::utils; - + auto get_pair = ([&call_count]() { auto connected_pair = callbacks::Connection::establish( [&call_count]() { ++call_count; }); @@ -98,7 +95,7 @@ TEST_F(CallbackTest, DroppedHandlesBreakConnection) { // Drop the handle end via reset() { - auto [handle, callable] = getPair(); + auto [handle, callable] = get_pair(); handle.reset(); EXPECT_FALSE(handle); EXPECT_FALSE(callable); @@ -108,7 +105,7 @@ TEST_F(CallbackTest, DroppedHandlesBreakConnection) { // Drop the callable end via reset() { - auto [handle, callable] = getPair(); + auto [handle, callable] = get_pair(); callable.reset(); EXPECT_FALSE(handle); EXPECT_FALSE(callable); @@ -116,34 +113,32 @@ TEST_F(CallbackTest, DroppedHandlesBreakConnection) { // Drop the handle end by letting it go out of scope { - using namespace uprotocol::utils; callbacks::Connection::Callable callable_outside; static_assert(std::is_move_assignable_v); EXPECT_FALSE(callable_outside); { - auto [handle, callable] = getPair(); + auto [handle, callable] = get_pair(); callable_outside = std::move(callable); - EXPECT_FALSE(callable); + EXPECT_FALSE(callable); // NOLINT EXPECT_TRUE(callable_outside); // Handle dropped here } EXPECT_FALSE(callable_outside); // Calling the callback after disconnect from the callee end should not // result in an exception. - EXPECT_NO_THROW(callable_outside()); + EXPECT_NO_THROW(callable_outside()); // NOLINT EXPECT_EQ(call_count, 0); } // Drop the callable end by letting it go out of scope { - using namespace uprotocol::utils; callbacks::Connection::Handle handle_outside; static_assert(std::is_move_assignable_v); EXPECT_FALSE(handle_outside); { - auto [handle, callable] = getPair(); + auto [handle, callable] = get_pair(); handle_outside = std::move(handle); - EXPECT_FALSE(handle); + EXPECT_FALSE(handle); // NOLINT EXPECT_TRUE(handle_outside); // Callable dropped here } @@ -153,7 +148,7 @@ TEST_F(CallbackTest, DroppedHandlesBreakConnection) { // If multiple copies of the callable end are held, dropping one doesn't // break the connection. { - auto [handle, callable] = getPair(); + auto [handle, callable] = get_pair(); auto other_callable = callable; EXPECT_TRUE(other_callable); callable(); @@ -168,13 +163,12 @@ TEST_F(CallbackTest, DroppedHandlesBreakConnection) { // CallerHandles cannot be used when default constructed or after reset is // called. Doing so will result in an exception being thrown. -TEST_F(CallbackTest, CallerHandleThrowsBadCall) { - using namespace uprotocol::utils; +TEST_F(CallbackTest, CallerHandleThrowsBadCall) { // NOLINT // Default constructed CallerHandle cannot be called { callbacks::CallerHandle callable; - EXPECT_THROW(callable(), callbacks::BadCallerAccess); + EXPECT_THROW(callable(), callbacks::BadCallerAccess); // NOLINT } // Freshly reset CallerHandle cannot be called @@ -182,15 +176,14 @@ TEST_F(CallbackTest, CallerHandleThrowsBadCall) { auto [handle, callable] = callbacks::Connection::establish([]() {}); callable.reset(); - EXPECT_THROW(callable(), callbacks::BadCallerAccess); + EXPECT_THROW(callable(), callbacks::BadCallerAccess); // NOLINT } } // This connection system will be used for multiple connected callbacks // simultaneously. As such, it should be possible to have multiple handle pairs // in use and not have any unexpected interactions between them. -TEST_F(CallbackTest, MultipleConnectionsCanCoexist) { - using namespace uprotocol::utils; +TEST_F(CallbackTest, MultipleConnectionsCanCoexist) { // NOLINT std::array call_count{0}; @@ -247,13 +240,12 @@ TEST_F(CallbackTest, MultipleConnectionsCanCoexist) { // Cleanup functions should be called when the connection is broken from the // callee end of the connection. -TEST_F(CallbackTest, CleanupCalledWhenCalleeHandleDropped) { - using namespace uprotocol::utils; +TEST_F(CallbackTest, CleanupCalledWhenCalleeHandleDropped) { // NOLINT int cleanup_count{0}; auto [handle, callable] = callbacks::Connection::establish( - []() {}, [&cleanup_count](auto c) { ++cleanup_count; }); + []() {}, [&cleanup_count](const auto& /*c*/) { ++cleanup_count; }); EXPECT_EQ(cleanup_count, 0); handle.reset(); @@ -262,14 +254,13 @@ TEST_F(CallbackTest, CleanupCalledWhenCalleeHandleDropped) { // Cleanup functions should not be called when the connection is broken from // the caller end of the connection. -TEST_F(CallbackTest, CleanupNotCalledWhenCallerHandleDropped) { - using namespace uprotocol::utils; +TEST_F(CallbackTest, CleanupNotCalledWhenCallerHandleDropped) { // NOLINT { int cleanup_count{0}; auto [handle, callable] = callbacks::Connection::establish( - []() {}, [&cleanup_count](auto c) { ++cleanup_count; }); + []() {}, [&cleanup_count](const auto& /*c*/) { ++cleanup_count; }); EXPECT_EQ(cleanup_count, 0); callable.reset(); @@ -280,7 +271,7 @@ TEST_F(CallbackTest, CleanupNotCalledWhenCallerHandleDropped) { int cleanup_count{0}; auto [handle, callable] = callbacks::Connection::establish( - []() {}, [&cleanup_count](auto c) { ++cleanup_count; }); + []() {}, [&cleanup_count](const auto& /*c*/) { ++cleanup_count; }); auto callable_copy = callable; @@ -295,17 +286,16 @@ TEST_F(CallbackTest, CleanupNotCalledWhenCallerHandleDropped) { // It is very likely that connections will be held in some sort of map. In // order to effectively make use of the cleanup function, it should be possible // to use the CallerHandle as a reverse-lookup key. -TEST_F(CallbackTest, CleanupParameterCanLookUpCallable) { - using namespace uprotocol::utils; +TEST_F(CallbackTest, CleanupParameterCanLookUpCallable) { // NOLINT std::map::Callable, int> cleanup_count; auto [handle_a, callable_a] = callbacks::Connection::establish( - []() {}, [&cleanup_count](auto c) { ++cleanup_count[c]; }); + []() {}, [&cleanup_count](const auto& c) { ++cleanup_count[c]; }); auto [handle_b, callable_b] = callbacks::Connection::establish( - []() {}, [&cleanup_count](auto c) { ++cleanup_count[c]; }); + []() {}, [&cleanup_count](const auto& c) { ++cleanup_count[c]; }); auto [handle_c, callable_c] = callbacks::Connection::establish( - []() {}, [&cleanup_count](auto c) { ++cleanup_count[c]; }); + []() {}, [&cleanup_count](const auto& c) { ++cleanup_count[c]; }); EXPECT_EQ(cleanup_count[callable_a], 0); EXPECT_EQ(cleanup_count[callable_b], 0); @@ -331,8 +321,11 @@ TEST_F(CallbackTest, CleanupParameterCanLookUpCallable) { // functions. However, this should be supported by the connection system. We // can verify the parameters are passed through by checking for the result of // known operations. -TEST_F(CallbackTest, CallablesCanTakeArguments) { - using namespace uprotocol::utils; +TEST_F(CallbackTest, CallablesCanTakeArguments) { // NOLINT + constexpr uint16_t RANDOM_NUMBER_1 = 5; + constexpr uint16_t RANDOM_NUMBER_2 = 9; + constexpr int16_t RANDOM_NUMBER_3 = -80; + constexpr uint16_t RANDOM_NUMBER_4 = 79; // Add a couple of numbers together, check the result { @@ -342,9 +335,9 @@ TEST_F(CallbackTest, CallablesCanTakeArguments) { callbacks::Connection::establish( [&sum](int x, int y) { sum = x + y; }); - callable(5, 9); + callable(RANDOM_NUMBER_1, RANDOM_NUMBER_2); EXPECT_EQ(sum, 14); - callable(-80, 79); + callable(RANDOM_NUMBER_3, RANDOM_NUMBER_4); EXPECT_EQ(sum, -1); } @@ -366,8 +359,7 @@ TEST_F(CallbackTest, CallablesCanTakeArguments) { // Until this point, the callback has not returned a value. This should be // supported by the connection system. Building on passing parameters, we can // return the result of an operation performed by the callback function. -TEST_F(CallbackTest, CallablesCanReturnValues) { - using namespace uprotocol::utils; +TEST_F(CallbackTest, CallablesCanReturnValues) { // NOLINT // Multiply two numbers together, check the result { @@ -404,9 +396,7 @@ TEST_F(CallbackTest, CallablesCanReturnValues) { // inadvertently introduce a copy. We can detect this by a) using a non- // copyable type as the return and b) checking container objects for changes // in their data pointers. -TEST_F(CallbackTest, ReturnValuesAreMoved) { - using namespace uprotocol::utils; - +TEST_F(CallbackTest, ReturnValuesAreMoved) { // NOLINT // Checking with a non-copyable object (in this case, std::unique_ptr) { void* original_location{nullptr}; @@ -414,7 +404,8 @@ TEST_F(CallbackTest, ReturnValuesAreMoved) { auto [handle, callable] = callbacks::Connection>::establish( [&original_location]() { - auto p = std::make_unique(71); + constexpr int RANDOM_NUMBER = 71; + auto p = std::make_unique(RANDOM_NUMBER); original_location = p.get(); return p; }); @@ -427,7 +418,7 @@ TEST_F(CallbackTest, ReturnValuesAreMoved) { // Checking with a container object (in this case, std::string) { void* original_string_location{nullptr}; - constexpr size_t expected_capacity = 9000; + constexpr size_t EXPECTED_CAPACITY = 9000; std::string a_copy; auto [handle, callable] = @@ -437,7 +428,7 @@ TEST_F(CallbackTest, ReturnValuesAreMoved) { // to see if a copy or a move has occurred. Copies will // generally only reserve what is needed to hold the // current content of the original string. - s.reserve(expected_capacity); + s.reserve(EXPECTED_CAPACITY); original_string_location = s.data(); a_copy = s; return s; @@ -446,12 +437,12 @@ TEST_F(CallbackTest, ReturnValuesAreMoved) { auto result = callable(); EXPECT_TRUE(result); EXPECT_EQ(original_string_location, (*result).data()); - EXPECT_EQ(expected_capacity, (*result).capacity()); + EXPECT_EQ(EXPECTED_CAPACITY, (*result).capacity()); // Just to be safe, check our assumptions about copies vs moves. The // a_copy variable should hold a copy of the original string, this time // with a different pointer and capacity. EXPECT_NE(original_string_location, a_copy.data()); - EXPECT_NE(expected_capacity, a_copy.capacity()); + EXPECT_NE(EXPECTED_CAPACITY, a_copy.capacity()); } } @@ -459,12 +450,11 @@ TEST_F(CallbackTest, ReturnValuesAreMoved) { // still exist. It is safe to call - nothing will happen. However, when the // callback is a returning callback, an empty optional will be returned to // indicate that the connection is not active. -TEST_F(CallbackTest, DisconnectedCallablesReturnNothing) { - using namespace uprotocol::utils; +TEST_F(CallbackTest, DisconnectedCallablesReturnNothing) { // NOLINT { auto [handle, callable] = - callbacks::Connection::establish([]() { return 1.0f; }); + callbacks::Connection::establish([]() { return 1.0F; }); static_assert( std::is_same_v, decltype(callable())>); @@ -496,19 +486,18 @@ TEST_F(CallbackTest, DisconnectedCallablesReturnNothing) { // The typical use case for these callbacks is to pass asynchronous events. // It should work with the caller executing from a separate context. -TEST_F(CallbackTest, CanCallFromAnotherThread) { - using namespace uprotocol::utils; +TEST_F(CallbackTest, CanCallFromAnotherThread) { // NOLINT std::atomic call_count{0}; auto [handle, callable] = callbacks::Connection::establish( [&call_count]() { ++call_count; }); - constexpr int expected = 21; + constexpr int EXPECTED = 21; // Note: C++20 could use jthread instead of std::thread std::thread other([c = std::move(callable)]() mutable { - for (int i = 0; i < expected; ++i) { + for (int i = 0; i < EXPECTED; ++i) { c(); } }); @@ -517,7 +506,7 @@ TEST_F(CallbackTest, CanCallFromAnotherThread) { EXPECT_FALSE(callable); other.join(); EXPECT_FALSE(handle); - EXPECT_EQ(call_count, expected); + EXPECT_EQ(call_count, EXPECTED); } //////////////////////////////////////////////////////////////////////////// @@ -538,15 +527,14 @@ struct SemaphoreLike { if (ctr_ > 0) { --ctr_; return true; - } else { - return cv_.wait_for(l, t, [this]() { - if (ctr_ > 0) { - --ctr_; - return true; - } - return false; - }); } + return cv_.wait_for(l, t, [this]() { + if (ctr_ > 0) { + --ctr_; + return true; + } + return false; + }); } private: @@ -562,8 +550,8 @@ struct SemaphoreLike { // threads all blocking to acquire resources (via semaphore-like object). These // blocks are released one-by-one to check that the connection states remain // valid and the callee remains blocked throughout the process. -TEST_F(CallbackTest, HandleResetBlocksWhileCallbacksRunning) { - using namespace uprotocol::utils; +TEST_F(CallbackTest, HandleResetBlocksWhileCallbacksRunning) { // NOLINT + using namespace std::chrono_literals; std::atomic disconnect_done{false}; @@ -583,9 +571,15 @@ TEST_F(CallbackTest, HandleResetBlocksWhileCallbacksRunning) { // for startup synchronization. SemaphoreLike callee_sync; - auto [handle, callable] = callbacks::Connection::establish( + auto connected_pair = callbacks::Connection::establish( [&fake_blocking_op]() { return fake_blocking_op.try_acquire_for(1s); }); + auto handle = std::move(std::get<0>(connected_pair)); + auto callable = std::get<1>(connected_pair); + // auto [handle, callable] = callbacks::Connection::establish( + // [&fake_blocking_op]() { return fake_blocking_op.try_acquire_for(1s); + // }); + auto caller_fn = ([callable, &callbacks_pending, &callbacks_released, &main_task_sync]() mutable { ++callbacks_pending; @@ -676,10 +670,9 @@ TEST_F(CallbackTest, HandleResetBlocksWhileCallbacksRunning) { // construct a CallerHandle then initialize it later. Check this works, that // the default-constructed object reports as disconnected, and that no // exception is thrown. -TEST_F(CallbackTest, CallerHandleCanDefaultConstruct) { - using namespace uprotocol::utils; +TEST_F(CallbackTest, CallerHandleCanDefaultConstruct) { // NOLINT - EXPECT_NO_THROW({ + EXPECT_NO_THROW({ // NOLINT callbacks::CallerHandle x; EXPECT_FALSE(x); }); @@ -689,10 +682,9 @@ TEST_F(CallbackTest, CallerHandleCanDefaultConstruct) { // construct a CalleeHandle then initialize it later. Check this works, that // the default-constructed object reports as disconnected, and that no // exception is thrown. -TEST_F(CallbackTest, CalleeHandleCanDefaultConstruct) { - using namespace uprotocol::utils; +TEST_F(CallbackTest, CalleeHandleCanDefaultConstruct) { // NOLINT - EXPECT_NO_THROW({ + EXPECT_NO_THROW({ // NOLINT callbacks::CalleeHandle x; EXPECT_FALSE(x); }); @@ -705,12 +697,11 @@ TEST_F(CallbackTest, CalleeHandleCanDefaultConstruct) { // function objects they receive // Tests invalid callback function objects -TEST_F(CallbackTest, EstablishWithNonCallableCallback) { - using namespace uprotocol::utils; +TEST_F(CallbackTest, EstablishWithNonCallableCallback) { // NOLINT callbacks::Connection::ConnectedPair conn; - EXPECT_THROW(conn = callbacks::Connection::establish({}), + EXPECT_THROW(conn = callbacks::Connection::establish({}), // NOLINT callbacks::EmptyFunctionObject); auto& [handle, callable] = conn; @@ -720,20 +711,20 @@ TEST_F(CallbackTest, EstablishWithNonCallableCallback) { // is broken. When that happens, the destructor will try to reset again. // By resetting the callable second, there is no need to try the cleanup // funciton again, so the destructor won't throw. - EXPECT_NO_THROW(handle.reset()); - EXPECT_NO_THROW(callable.reset()); + EXPECT_NO_THROW(handle.reset()); // NOLINT + EXPECT_NO_THROW(callable.reset()); // NOLINT } // Tests invalid cleanup function objects -TEST_F(CallbackTest, EstablishWithNonCallableCleanup) { - using namespace uprotocol::utils; +TEST_F(CallbackTest, EstablishWithNonCallableCleanup) { // NOLINT auto cb = []() -> bool { return true; }; callbacks::Connection::Cleanup empty; callbacks::Connection::ConnectedPair conn; - EXPECT_THROW(conn = callbacks::Connection::establish(cb, empty), - callbacks::EmptyFunctionObject); + EXPECT_THROW( // NOLINT + conn = callbacks::Connection::establish(cb, empty), + callbacks::EmptyFunctionObject); auto& [handle, callable] = conn; @@ -742,19 +733,19 @@ TEST_F(CallbackTest, EstablishWithNonCallableCleanup) { // is broken. When that happens, the destructor will try to reset again. // By resetting the callable second, there is no need to try the cleanup // funciton again, so the destructor won't throw. - EXPECT_NO_THROW(handle.reset()); - EXPECT_NO_THROW(callable.reset()); + EXPECT_NO_THROW(handle.reset()); // NOLINT + EXPECT_NO_THROW(callable.reset()); // NOLINT } // Tests both invalid cleanup and invalid callback function objects -TEST_F(CallbackTest, EstablishWithNonCallableCallbackAndCleanup) { - using namespace uprotocol::utils; +TEST_F(CallbackTest, EstablishWithNonCallableCallbackAndCleanup) { // NOLINT callbacks::Connection::Cleanup empty; callbacks::Connection::ConnectedPair conn; - EXPECT_THROW(conn = callbacks::Connection::establish({}, empty), - callbacks::EmptyFunctionObject); + EXPECT_THROW( // NOLINT + conn = callbacks::Connection::establish({}, empty), + callbacks::EmptyFunctionObject); auto& [handle, callable] = conn; @@ -763,8 +754,8 @@ TEST_F(CallbackTest, EstablishWithNonCallableCallbackAndCleanup) { // is broken. When that happens, the destructor will try to reset again. // By resetting the callable second, there is no need to try the cleanup // funciton again, so the destructor won't throw. - EXPECT_NO_THROW(handle.reset()); - EXPECT_NO_THROW(callable.reset()); + EXPECT_NO_THROW(handle.reset()); // NOLINT + EXPECT_NO_THROW(callable.reset()); // NOLINT } -} // namespace +} // namespace uprotocol::utils diff --git a/test/coverage/utils/CyclicQueueTest.cpp b/test/coverage/utils/CyclicQueueTest.cpp index 8160e8b33..2aa6d018b 100644 --- a/test/coverage/utils/CyclicQueueTest.cpp +++ b/test/coverage/utils/CyclicQueueTest.cpp @@ -24,15 +24,17 @@ class TestFixture : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. TestFixture() = default; - ~TestFixture() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} + +public: + ~TestFixture() override = default; }; -// TODO replace -TEST_F(TestFixture, SomeTestName) {} +// TODO(unknown) +TEST_F(TestFixture, SomeTestName) {} // NOLINT } // namespace diff --git a/test/coverage/utils/ExpectedTest.cpp b/test/coverage/utils/ExpectedTest.cpp index 76f712854..9680df219 100644 --- a/test/coverage/utils/ExpectedTest.cpp +++ b/test/coverage/utils/ExpectedTest.cpp @@ -30,22 +30,26 @@ class ExpectedTest : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. ExpectedTest() = default; - ~ExpectedTest() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} + +public: + ~ExpectedTest() override = default; }; +constexpr int MAX_BIT_SHIFT = 30; + int get_rand() { static std::random_device rd; static std::mt19937 mt(rd()); - static std::uniform_int_distribution dist(0, 1 << 30); + static std::uniform_int_distribution dist(0, 1 << MAX_BIT_SHIFT); return dist(mt); } -TEST_F(ExpectedTest, ExpectScalarScalar) { +TEST_F(ExpectedTest, ExpectScalarScalar) { // NOLINT auto sample = get_rand(); auto expected = Expected(sample); EXPECT_TRUE(bool(expected)); @@ -54,7 +58,7 @@ TEST_F(ExpectedTest, ExpectScalarScalar) { EXPECT_EQ(sample, *expected); } -TEST_F(ExpectedTest, UnexpectScalarScalar) { +TEST_F(ExpectedTest, UnexpectScalarScalar) { // NOLINT int sample = get_rand(); auto expected = Expected(Unexpected(sample)); EXPECT_FALSE(bool(expected)); @@ -62,7 +66,7 @@ TEST_F(ExpectedTest, UnexpectScalarScalar) { EXPECT_EQ(sample, expected.error()); } -TEST_F(ExpectedTest, ExpectScalar) { +TEST_F(ExpectedTest, ExpectScalar) { // NOLINT auto sample = get_rand(); auto expected = Expected(sample); EXPECT_TRUE(bool(expected)); @@ -71,7 +75,7 @@ TEST_F(ExpectedTest, ExpectScalar) { EXPECT_EQ(sample, *expected); } -TEST_F(ExpectedTest, UnexpectScalar) { +TEST_F(ExpectedTest, UnexpectScalar) { // NOLINT int sample = get_rand(); auto expected = Expected(Unexpected(sample)); EXPECT_FALSE(bool(expected)); @@ -79,7 +83,7 @@ TEST_F(ExpectedTest, UnexpectScalar) { EXPECT_EQ(sample, expected.error()); } -TEST_F(ExpectedTest, UnexpectValueOr) { +TEST_F(ExpectedTest, UnexpectValueOr) { // NOLINT int sample = get_rand(); auto expected = Expected(Unexpected(std::string("hello"))); @@ -89,13 +93,17 @@ TEST_F(ExpectedTest, UnexpectValueOr) { } struct Pair { +private: int x; int y; - Pair(int x, int y) : x(x), y(y) {} +public: + Pair(int x_value, int y_value) : x(x_value), y(y_value) {} + [[nodiscard]] int getX() const { return x; } + [[nodiscard]] int getY() const { return y; } }; -TEST_F(ExpectedTest, ExpectUnique) { +TEST_F(ExpectedTest, ExpectUnique) { // NOLINT auto x = get_rand(); auto y = get_rand(); auto expected = Expected, std::string>( @@ -103,11 +111,11 @@ TEST_F(ExpectedTest, ExpectUnique) { EXPECT_TRUE(bool(expected)); EXPECT_TRUE(expected.has_value()); auto p = std::move(expected).value(); - EXPECT_EQ(x, p->x); - EXPECT_EQ(y, p->y); + EXPECT_EQ(x, p->getX()); + EXPECT_EQ(y, p->getY()); } -TEST_F(ExpectedTest, UnexpectUnique) { +TEST_F(ExpectedTest, UnexpectUnique) { // NOLINT auto x = get_rand(); auto y = get_rand(); auto expected = Expected>( @@ -115,107 +123,114 @@ TEST_F(ExpectedTest, UnexpectUnique) { EXPECT_FALSE(bool(expected)); EXPECT_FALSE(expected.has_value()); auto p = std::move(expected).error(); - EXPECT_EQ(x, p->x); - EXPECT_EQ(y, p->y); + EXPECT_EQ(x, p->getX()); + EXPECT_EQ(y, p->getY()); } -TEST_F(ExpectedTest, ExpectShared) { +TEST_F(ExpectedTest, ExpectShared) { // NOLINT auto x = get_rand(); auto y = get_rand(); auto expected = Expected, std::string>( std::make_shared(x, y)); EXPECT_TRUE(bool(expected)); EXPECT_TRUE(expected.has_value()); - EXPECT_EQ(x, expected.value()->x); - EXPECT_EQ(y, expected.value()->y); - EXPECT_EQ(x, (*expected)->x); - EXPECT_EQ(y, (*expected)->y); + EXPECT_EQ(x, expected.value()->getX()); + EXPECT_EQ(y, expected.value()->getY()); + EXPECT_EQ(x, (*expected)->getX()); + EXPECT_EQ(y, (*expected)->getY()); } -TEST_F(ExpectedTest, UnexpectShared) { +TEST_F(ExpectedTest, UnexpectShared) { // NOLINT auto x = get_rand(); auto y = get_rand(); auto expected = Expected>( Unexpected(std::make_shared(x, y))); EXPECT_FALSE(bool(expected)); EXPECT_FALSE(expected.has_value()); - EXPECT_EQ(x, expected.error()->x); - EXPECT_EQ(y, expected.error()->y); + EXPECT_EQ(x, expected.error()->getX()); + EXPECT_EQ(y, expected.error()->getY()); } -TEST_F(ExpectedTest, ExpectStruct) { +TEST_F(ExpectedTest, ExpectStruct) { // NOLINT auto x = get_rand(); auto y = get_rand(); auto expected = Expected(Pair(x, y)); EXPECT_TRUE(bool(expected)); EXPECT_TRUE(expected.has_value()); - EXPECT_EQ(x, expected.value().x); - EXPECT_EQ(y, expected.value().y); - EXPECT_EQ(x, expected->x); - EXPECT_EQ(y, expected->y); + EXPECT_EQ(x, expected.value().getX()); + EXPECT_EQ(y, expected.value().getY()); + EXPECT_EQ(x, expected->getX()); + EXPECT_EQ(y, expected->getY()); } -TEST_F(ExpectedTest, UnexpectStruct) { +TEST_F(ExpectedTest, UnexpectStruct) { // NOLINT auto x = get_rand(); auto y = get_rand(); auto expected = Expected(Unexpected(Pair(x, y))); EXPECT_FALSE(bool(expected)); EXPECT_FALSE(expected.has_value()); - EXPECT_EQ(x, expected.error().x); - EXPECT_EQ(y, expected.error().y); + EXPECT_EQ(x, expected.error().getX()); + EXPECT_EQ(y, expected.error().getY()); } struct PairDestruct { +private: int x; int y; - static int cd_count; - - PairDestruct(int x, int y) : x(x), y(y) { cd_count++; } - PairDestruct(const PairDestruct& arg) : x(arg.x), y(arg.y) { cd_count++; } +public: + static int cd_count_; + PairDestruct(int x_value, int y_value) : x(x_value), y(y_value) { + cd_count_++; + } + PairDestruct(const PairDestruct& arg) : x(arg.getX()), y(arg.getY()) { + cd_count_++; + } + ~PairDestruct() { cd_count_--; } - ~PairDestruct() { cd_count--; } + [[nodiscard]] int getX() const { return x; } + [[nodiscard]] int getY() const { return y; } }; -int PairDestruct::cd_count = 0; +int PairDestruct::cd_count_ = 0; -TEST_F(ExpectedTest, ExpectStructDestruct) { - PairDestruct::cd_count = 0; +TEST_F(ExpectedTest, ExpectStructDestruct) { // NOLINT + PairDestruct::cd_count_ = 0; { auto x = get_rand(); auto y = get_rand(); auto expected = Expected(PairDestruct(x, y)); - EXPECT_EQ(1, PairDestruct::cd_count); + EXPECT_EQ(1, PairDestruct::cd_count_); EXPECT_TRUE(bool(expected)); EXPECT_TRUE(expected.has_value()); - EXPECT_EQ(x, expected.value().x); - EXPECT_EQ(y, expected.value().y); - EXPECT_EQ(x, expected->x); - EXPECT_EQ(y, expected->y); + EXPECT_EQ(x, expected.value().getX()); + EXPECT_EQ(y, expected.value().getY()); + EXPECT_EQ(x, expected->getX()); + EXPECT_EQ(y, expected->getY()); } - EXPECT_EQ(0, PairDestruct::cd_count); + EXPECT_EQ(0, PairDestruct::cd_count_); } -TEST_F(ExpectedTest, UnexpectStructDestruct) { - PairDestruct::cd_count = 0; +TEST_F(ExpectedTest, UnexpectStructDestruct) { // NOLINT + PairDestruct::cd_count_ = 0; { auto x = get_rand(); auto y = get_rand(); auto expected = Expected(Unexpected(PairDestruct(x, y))); - EXPECT_EQ(1, PairDestruct::cd_count); + EXPECT_EQ(1, PairDestruct::cd_count_); EXPECT_FALSE(bool(expected)); EXPECT_FALSE(expected.has_value()); - EXPECT_EQ(x, expected.error().x); - EXPECT_EQ(y, expected.error().y); + EXPECT_EQ(x, expected.error().getX()); + EXPECT_EQ(y, expected.error().getY()); } - EXPECT_EQ(0, PairDestruct::cd_count); + EXPECT_EQ(0, PairDestruct::cd_count_); } -TEST_F(ExpectedTest, ExceptionValueCheckedWhenIsError) { +TEST_F(ExpectedTest, ExceptionValueCheckedWhenIsError) { // NOLINT auto expected = Expected(Unexpected(std::string("hello"))); - EXPECT_THROW( + EXPECT_THROW( // NOLINT { try { EXPECT_FALSE(bool(expected)); @@ -230,9 +245,10 @@ TEST_F(ExpectedTest, ExceptionValueCheckedWhenIsError) { BadExpectedAccess); } -TEST_F(ExpectedTest, ExceptionErrorCheckedWhenNotError) { - auto expected = Expected(5); - EXPECT_THROW( +TEST_F(ExpectedTest, ExceptionErrorCheckedWhenNotError) { // NOLINT + constexpr int DEFAULT_EXPECTED_VALUE = 5; + auto expected = Expected(DEFAULT_EXPECTED_VALUE); + EXPECT_THROW( // NOLINT { try { EXPECT_TRUE(bool(expected)); @@ -247,10 +263,10 @@ TEST_F(ExpectedTest, ExceptionErrorCheckedWhenNotError) { BadExpectedAccess); } -TEST_F(ExpectedTest, ExceptionDerefValueWhenUnexpected) { +TEST_F(ExpectedTest, ExceptionDerefValueWhenUnexpected) { // NOLINT auto expected = Expected(Unexpected(std::string("hello"))); - EXPECT_THROW( + EXPECT_THROW( // NOLINT { try { EXPECT_FALSE(bool(expected)); @@ -266,15 +282,15 @@ TEST_F(ExpectedTest, ExceptionDerefValueWhenUnexpected) { BadExpectedAccess); } -TEST_F(ExpectedTest, ExceptionDerefPtrWhenUnexpected) { +TEST_F(ExpectedTest, ExceptionDerefPtrWhenUnexpected) { // NOLINT auto expected = Expected(Unexpected(std::string("hello"))); - EXPECT_THROW( + EXPECT_THROW( // NOLINT { try { EXPECT_FALSE(bool(expected)); EXPECT_FALSE(expected.has_value()); - static_cast(expected->x); + static_cast(expected->getX()); } catch (const BadExpectedAccess& ex) { EXPECT_STREQ( "Attempt to dereference expected pointer when unexpected.", @@ -294,4 +310,4 @@ int main(int argc, char* argv[]) { return RUN_ALL_TESTS(); } -#endif \ No newline at end of file +#endif diff --git a/test/coverage/utils/IpAddressTest.cpp b/test/coverage/utils/IpAddressTest.cpp index b243bd071..12ca42a84 100644 --- a/test/coverage/utils/IpAddressTest.cpp +++ b/test/coverage/utils/IpAddressTest.cpp @@ -24,15 +24,17 @@ class TestFixture : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. TestFixture() = default; - ~TestFixture() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} + +public: + ~TestFixture() override = default; }; -// TODO replace -TEST_F(TestFixture, SomeTestName) {} +// TODO(unknown) +TEST_F(TestFixture, SomeTestName) {} // NOLINT } // namespace diff --git a/test/coverage/utils/ThreadPoolTest.cpp b/test/coverage/utils/ThreadPoolTest.cpp index 22b1dfd6f..042c46371 100644 --- a/test/coverage/utils/ThreadPoolTest.cpp +++ b/test/coverage/utils/ThreadPoolTest.cpp @@ -24,15 +24,17 @@ class TestFixture : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. TestFixture() = default; - ~TestFixture() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} + +public: + ~TestFixture() override = default; }; -// TODO replace -TEST_F(TestFixture, SomeTestName) {} +// TODO(unknown) +TEST_F(TestFixture, SomeTestName) {} // NOLINT } // namespace diff --git a/test/coverage/utils/base64Test.cpp b/test/coverage/utils/base64Test.cpp index 34fec4db0..181eedaf6 100644 --- a/test/coverage/utils/base64Test.cpp +++ b/test/coverage/utils/base64Test.cpp @@ -24,15 +24,17 @@ class TestFixture : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. TestFixture() = default; - ~TestFixture() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} + +public: + ~TestFixture() override = default; }; -// TODO replace -TEST_F(TestFixture, SomeTestName) {} +// TODO(unknown) +TEST_F(TestFixture, SomeTestName) {} // NOLINT } // namespace diff --git a/test/extra/NotificationTest.cpp b/test/extra/NotificationTest.cpp index db4268160..5134b8ea2 100644 --- a/test/extra/NotificationTest.cpp +++ b/test/extra/NotificationTest.cpp @@ -17,10 +17,13 @@ #include "UTransportMock.h" #include "up-cpp/datamodel/serializer/UUri.h" -namespace { -using namespace uprotocol::communication; -using namespace uprotocol::datamodel::serializer::uri; -using MsgDiff = google::protobuf::util::MessageDifferencer; +constexpr uint32_t DEFAULT_UE_ID = 0x00011101; +constexpr uint32_t DEFAULT_RESOURCE_ID = 0x8101; +constexpr uint32_t DEFAULT_SOURCE_UE_ID = 0x18000; +constexpr uint16_t DEFAULT_VERSION_MAJOR = 0xF8; +constexpr std::chrono::milliseconds THOUSAND_MILLISECONDS(1000); + +namespace uprotocol::datamodel::serializer::uri { class NotificationTest : public testing::Test { protected: @@ -32,94 +35,100 @@ class NotificationTest : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. NotificationTest() = default; - ~NotificationTest() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} - [[nodiscard]] uprotocol::v1::UUri buildValidTestTopic() const; - [[nodiscard]] uprotocol::v1::UUri buildValidDefaultSourceURI() const; + [[nodiscard]] static uprotocol::v1::UUri buildValidTestTopic(); + [[nodiscard]] static uprotocol::v1::UUri buildValidDefaultSourceURI(); + +public: + ~NotificationTest() override = default; }; -[[nodiscard]] uprotocol::v1::UUri NotificationTest::buildValidDefaultSourceURI() - const { - uprotocol::v1::UUri testDefaultSourceURI_; - testDefaultSourceURI_.set_authority_name("10.0.0.1"); - testDefaultSourceURI_.set_ue_id(0x18000); - testDefaultSourceURI_.set_ue_version_major(0x1); - testDefaultSourceURI_.set_resource_id(0x0); - return testDefaultSourceURI_; +[[nodiscard]] uprotocol::v1::UUri +NotificationTest::buildValidDefaultSourceURI() { + uprotocol::v1::UUri test_default_source_uri; + test_default_source_uri.set_authority_name("10.0.0.1"); + test_default_source_uri.set_ue_id(DEFAULT_SOURCE_UE_ID); + test_default_source_uri.set_ue_version_major(0x1); + test_default_source_uri.set_resource_id(0x0); + return test_default_source_uri; } -[[nodiscard]] uprotocol::v1::UUri NotificationTest::buildValidTestTopic() - const { - uprotocol::v1::UUri testTopic_; - testTopic_.set_authority_name("10.0.0.2"); - testTopic_.set_ue_id(0x00011101); - testTopic_.set_ue_version_major(0xF8); - testTopic_.set_resource_id(0x8101); - return testTopic_; +[[nodiscard]] uprotocol::v1::UUri NotificationTest::buildValidTestTopic() { + uprotocol::v1::UUri test_topic; + test_topic.set_authority_name("10.0.0.2"); + test_topic.set_ue_id(DEFAULT_UE_ID); + test_topic.set_ue_version_major(DEFAULT_VERSION_MAJOR); + test_topic.set_resource_id(DEFAULT_RESOURCE_ID); + return test_topic; } -TEST_F(NotificationTest, NotificationSuccess) { +TEST_F(NotificationTest, NotificationSuccess) { // NOLINT // Initialize uprotocol::v1::UPayloadFormat format = uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT; std::optional priority = uprotocol::v1::UPriority::UPRIORITY_CS1; - std::optional ttl = - std::chrono::milliseconds(1000); - uprotocol::v1::UUri testDefaultSourceURI = buildValidDefaultSourceURI(); - uprotocol::v1::UUri testTopic = buildValidTestTopic(); + std::optional ttl = THOUSAND_MILLISECONDS; + uprotocol::v1::UUri test_default_source_uri = buildValidDefaultSourceURI(); + uprotocol::v1::UUri test_topic = buildValidTestTopic(); // Notify Sink - auto transportMockNotificationSink = - std::make_shared(testDefaultSourceURI); + auto transport_mock_notification_sink = + std::make_shared( + test_default_source_uri); uprotocol::v1::UMessage capture_msg; auto callback = [&capture_msg](const auto& message) { capture_msg = message; }; - auto result = NotificationSink::create(transportMockNotificationSink, - std::move(callback), testTopic); + auto result = uprotocol::communication::NotificationSink::create( + transport_mock_notification_sink, std::move(callback), test_topic); // Notify Source - std::string testPayloadStr = "test_payload"; - auto transportMockNotificationSource_ = - std::make_shared(testDefaultSourceURI); + std::string test_payload_str = "test_payload"; + auto transport_mock_notification_source = + std::make_shared( + test_default_source_uri); - auto movableTopic = testTopic; + auto movable_topic = test_topic; - NotificationSource notificationSource( - transportMockNotificationSource_, std::move(movableTopic), - std::move(testDefaultSourceURI), format, priority, ttl); + uprotocol::communication::NotificationSource notification_source( + transport_mock_notification_source, std::move(movable_topic), + std::move(test_default_source_uri), format, priority, ttl); - uprotocol::datamodel::builder::Payload testPayload(testPayloadStr, format); - auto status = notificationSource.notify(std::move(testPayload)); + uprotocol::datamodel::builder::Payload test_payload(test_payload_str, + format); + auto status = notification_source.notify(std::move(test_payload)); EXPECT_EQ( + AsString::serialize(transport_mock_notification_source->getMessage() + .attributes() + .source()), AsString::serialize( - transportMockNotificationSource_->message_.attributes().source()), - AsString::serialize(transportMockNotificationSink->source_filter_)); + transport_mock_notification_sink->getSourceFilter())); EXPECT_EQ( + AsString::serialize(transport_mock_notification_source->getMessage() + .attributes() + .sink()), AsString::serialize( - transportMockNotificationSource_->message_.attributes().sink()), - AsString::serialize( - transportMockNotificationSink->sink_filter_.value())); + transport_mock_notification_sink->getSinkFilter().value())); // Manually bridge the two transports - transportMockNotificationSink->mockMessage( - transportMockNotificationSource_->message_); + transport_mock_notification_sink->mockMessage( + transport_mock_notification_source->getMessage()); // Test - EXPECT_TRUE(MsgDiff::Equals(transportMockNotificationSource_->message_, - capture_msg)); - EXPECT_EQ(testPayloadStr, capture_msg.payload()); + EXPECT_TRUE(google::protobuf::util::MessageDifferencer::Equals( + transport_mock_notification_source->getMessage(), capture_msg)); + EXPECT_EQ(test_payload_str, capture_msg.payload()); } -} // namespace +} // namespace uprotocol::datamodel::serializer::uri diff --git a/test/extra/PublisherSubscriberTest.cpp b/test/extra/PublisherSubscriberTest.cpp index b29d0a17c..a14f346f8 100644 --- a/test/extra/PublisherSubscriberTest.cpp +++ b/test/extra/PublisherSubscriberTest.cpp @@ -12,39 +12,59 @@ #include #include +#include + #include "UTransportMock.h" #include "up-cpp/communication/Publisher.h" #include "up-cpp/communication/Subscriber.h" #include "up-cpp/datamodel/serializer/UUri.h" -using namespace uprotocol::communication; -using namespace uprotocol::v1; -using namespace uprotocol::datamodel::serializer::uri; -using MsgDiff = google::protobuf::util::MessageDifferencer; +constexpr uint32_t DEFAULT_SOURCE_UE_ID = 0x00011101; +constexpr uint32_t DEFAULT_TOPIC_UE_ID = 0x10010001; +constexpr uint32_t DEFAULT_RESOURCE_ID = 0x8101; +constexpr uint16_t DEFAULT_SOURCE_VERSION_MAJOR = 0xF1; +constexpr uint16_t DEFAULT_TOPIC_VERSION_MAJOR = 0xF8; +constexpr std::chrono::milliseconds THOUSAND_MILLISECONDS(1000); -namespace { -using namespace uprotocol::datamodel::builder; +namespace uprotocol::v1 { class TestPublisherSubscriber : public testing::Test { +private: + std::shared_ptr transportMock_; + UUri source_; + UUri topic_; + UPayloadFormat format_ = UPayloadFormat::UPAYLOAD_FORMAT_TEXT; + std::optional priority_; + std::optional ttl_; + protected: + std::shared_ptr getTransportMock() const { + return transportMock_; + } + UUri getSource() const { return source_; } + UUri getTopic() const { return topic_; } + UPayloadFormat getFormat() const { return format_; } + std::optional& getPriority() { return priority_; } + std::optional getTTL() const { return ttl_; } + // Run once per TEST_F. // Used to set up clean environments per test. void SetUp() override { source_.set_authority_name("10.0.0.1"); - source_.set_ue_id(0x00011101); - source_.set_ue_version_major(0xF1); + source_.set_ue_id(DEFAULT_SOURCE_UE_ID); + source_.set_ue_version_major(DEFAULT_SOURCE_VERSION_MAJOR); source_.set_resource_id(0x0); topic_.set_authority_name("10.0.0.1"); - topic_.set_ue_id(0x10010001); - topic_.set_ue_version_major(0xF8); - topic_.set_resource_id(0x8101); + topic_.set_ue_id(DEFAULT_TOPIC_UE_ID); + topic_.set_ue_version_major(DEFAULT_TOPIC_VERSION_MAJOR); + topic_.set_resource_id(DEFAULT_RESOURCE_ID); transportMock_ = std::make_shared(source_); format_ = UPayloadFormat::UPAYLOAD_FORMAT_TEXT; priority_ = UPriority::UPRIORITY_CS2; - ttl_ = std::chrono::milliseconds(1000); + ttl_ = THOUSAND_MILLISECONDS; } void TearDown() override {} @@ -52,58 +72,57 @@ class TestPublisherSubscriber : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. TestPublisherSubscriber() = default; - ~TestPublisherSubscriber() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} - std::shared_ptr transportMock_; - UUri source_; - UUri topic_; - UPayloadFormat format_; - std::optional priority_; - std::optional ttl_; +public: + ~TestPublisherSubscriber() override = default; }; -TEST_F(TestPublisherSubscriber, PubSubSuccess) { +TEST_F(TestPublisherSubscriber, PubSubSuccess) { // NOLINT // sub - auto transportSub = - std::make_shared(source_); + auto transport_sub = + std::make_shared(getSource()); uprotocol::v1::UMessage captured_message; auto callback = [&captured_message](auto message) { - captured_message = message; + captured_message = std::move(message); }; - auto result = - Subscriber::subscribe(transportSub, topic_, std::move(callback)); + auto result = uprotocol::communication::Subscriber::subscribe( + transport_sub, getTopic(), std::move(callback)); // pub - std::string testPayloadStr = "test_payload"; - auto movableTopic = topic_; - Publisher publisher(transportMock_, std::move(movableTopic), format_, - priority_, ttl_); + std::string test_payload_str = "test_payload"; + auto movable_topic = getTopic(); + uprotocol::communication::Publisher publisher( + getTransportMock(), std::move(movable_topic), getFormat(), + getPriority(), getTTL()); uprotocol::v1::UStatus retval; retval.set_code(uprotocol::v1::UCode::OK); - transportMock_->send_status_ = retval; + getTransportMock()->getSendStatus() = retval; - Payload testPayload(testPayloadStr, format_); - auto status = publisher.publish(std::move(testPayload)); + uprotocol::datamodel::builder::Payload test_payload(test_payload_str, + getFormat()); + auto status = publisher.publish(std::move(test_payload)); // Test - EXPECT_EQ( - AsString::serialize(transportMock_->message_.attributes().source()), - AsString::serialize(transportSub->source_filter_)); + EXPECT_EQ(uprotocol::datamodel::serializer::uri::AsString::serialize( + getTransportMock()->getMessage().attributes().source()), + uprotocol::datamodel::serializer::uri::AsString::serialize( + transport_sub->getSourceFilter())); // Manually bridge the two transports - transportSub->mockMessage(transportMock_->message_); + transport_sub->mockMessage(getTransportMock()->getMessage()); // Test - EXPECT_TRUE(MsgDiff::Equals(transportMock_->message_, captured_message)); - EXPECT_EQ(testPayloadStr, captured_message.payload()); + EXPECT_TRUE(google::protobuf::util::MessageDifferencer::Equals( + getTransportMock()->getMessage(), captured_message)); + EXPECT_EQ(test_payload_str, captured_message.payload()); } -} // namespace \ No newline at end of file +} // namespace uprotocol::v1 diff --git a/test/extra/RpcClientServerTest.cpp b/test/extra/RpcClientServerTest.cpp index eaf54ce9c..3b57abd2a 100644 --- a/test/extra/RpcClientServerTest.cpp +++ b/test/extra/RpcClientServerTest.cpp @@ -19,24 +19,41 @@ #include #include -#include - using namespace std::chrono_literals; -namespace { +namespace uprotocol::v1 { -using namespace uprotocol::v1; -using uprotocol::communication::RpcClient; -using uprotocol::communication::RpcServer; -using uprotocol::test::UTransportMock; +struct UeDetails { + uint32_t ue_id; + uint32_t ue_version_major; +}; struct MyUUri { - std::string auth = ""; - uint32_t ue_id = 0x8000; - uint32_t ue_version_major = 1; - uint32_t resource_id = 1; + static constexpr uint32_t DEFAULT_UE_ID = 0x8000; + +public: + MyUUri(std::string auth_val, UeDetails ue_details, uint32_t resource_id_val) + : auth(std::move(auth_val)), + ue_id(ue_details.ue_id), + ue_version_major(ue_details.ue_version_major), + resource_id(resource_id_val) {} + + [[nodiscard]] const std::string& get_auth() const { return auth; } + + void set_ue_details(UeDetails ue_details) { + ue_id = ue_details.ue_id; + ue_version_major = ue_details.ue_version_major; + } - operator uprotocol::v1::UUri() const { + [[nodiscard]] uint32_t get_ue_id() const { return ue_id; } + [[nodiscard]] uint32_t get_ue_version_major() const { + return ue_version_major; + } + + void set_resource_id(uint32_t resource) { resource_id = resource; } + [[nodiscard]] uint32_t get_resource_id() const { return resource_id; } + + explicit operator uprotocol::v1::UUri() const { UUri ret; ret.set_authority_name(auth); ret.set_ue_id(ue_id); @@ -45,13 +62,16 @@ struct MyUUri { return ret; } - std::string to_string() const { + [[nodiscard]] std::string to_string() const { return std::string("<< ") + UUri(*this).ShortDebugString() + " >>"; } -}; -const MyUUri rpc_service_uuri{"me_authority", 65538, 1, 32600}; -const MyUUri ident{"me_authority", 65538, 1, 0}; +private: + std::string auth; + uint32_t ue_id = DEFAULT_UE_ID; + uint32_t ue_version_major = 1; + uint32_t resource_id = 1; +}; class RpcClientServerTest : public testing::Test { protected: @@ -64,17 +84,23 @@ class RpcClientServerTest : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. RpcClientServerTest() = default; - ~RpcClientServerTest() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} + +public: + ~RpcClientServerTest() override = default; }; TEST_F(RpcClientServerTest, SimpleRoundTrip) { // NOLINT - auto server_transport = std::make_shared(ident); - auto client_transport = std::make_shared(ident); + const MyUUri ident{"me_authority", {65538, 1}, 0}; + const MyUUri rpc_service_uuri{"me_authority", {65538, 1}, 32600}; + auto server_transport = std::make_shared( + static_cast(ident)); + auto client_transport = std::make_shared( + static_cast(ident)); // if the client and server try to share the transport handle, this test no // longer works auto client_transport = server_transport; @@ -92,8 +118,8 @@ TEST_F(RpcClientServerTest, SimpleRoundTrip) { // NOLINT server_response, UPayloadFormat::UPAYLOAD_FORMAT_TEXT); auto server_or_status = uprotocol::communication::RpcServer::create( - server_transport, rpc_service_uuri, - [this, &server_called, &server_capture, + server_transport, v1::UUri(rpc_service_uuri), + [&server_called, &server_capture, &server_response_payload](const UMessage& message) { server_called = true; server_capture = message; @@ -102,31 +128,32 @@ TEST_F(RpcClientServerTest, SimpleRoundTrip) { // NOLINT UPayloadFormat::UPAYLOAD_FORMAT_TEXT); ASSERT_TRUE(server_or_status.has_value()); ASSERT_NE(server_or_status.value(), nullptr); - EXPECT_TRUE(server_transport->listener_); + EXPECT_TRUE(server_transport->getListener()); - auto client = RpcClient(client_transport, rpc_service_uuri, - UPriority::UPRIORITY_CS4, 1000ms); + auto client = uprotocol::communication::RpcClient( + client_transport, v1::UUri(rpc_service_uuri), UPriority::UPRIORITY_CS4, + 1000ms); - uprotocol::communication::RpcClient::InvokeHandle client_handle; // NOLINT - EXPECT_NO_THROW( + uprotocol::communication::RpcClient::InvokeHandle client_handle; + EXPECT_NO_THROW( // NOLINT client_handle = client.invokeMethod( std::move(client_request_payload), - [this, &client_called, &client_capture](auto maybe_response) { + [&client_called, &client_capture](auto maybe_response) { client_called = true; if (maybe_response.has_value()) { client_capture = maybe_response.value(); } })); - EXPECT_TRUE(client_transport->send_count_ == 1); - EXPECT_TRUE(client_transport->listener_); + EXPECT_TRUE(client_transport->getSendCount() == 1); + EXPECT_TRUE(client_transport->getListener()); - (*server_transport->listener_)(client_transport->message_); + (*server_transport->getListener())(client_transport->getMessage()); EXPECT_TRUE(server_called); EXPECT_EQ(client_request, server_capture.payload()); - client_transport->mockMessage(server_transport->message_); + client_transport->mockMessage(server_transport->getMessage()); EXPECT_TRUE(client_called); EXPECT_EQ(server_response, client_capture.payload()); } -} // namespace +} // namespace uprotocol::v1 diff --git a/test/extra/UTransportMockTest.cpp b/test/extra/UTransportMockTest.cpp index 349486193..e0249978c 100644 --- a/test/extra/UTransportMockTest.cpp +++ b/test/extra/UTransportMockTest.cpp @@ -18,25 +18,33 @@ #include #include -#include -using MsgDiff = google::protobuf::util::MessageDifferencer; +constexpr uint16_t STR_MAX_LEN = 32; +constexpr uint16_t PAYLOAD_STR_MAX_LEN = 1400; +constexpr uint16_t RANDOM_INT_MAX = 100; +constexpr uint32_t DEFAULT_UE_ID = 0x00010001; +constexpr uint32_t DEFAULT_RESOURCE_ID = 0x8000; +constexpr uint16_t ATTR_TTL = 1000; -static std::random_device random_dev; -static std::mt19937 random_gen(random_dev()); -static std::uniform_int_distribution char_dist('A', 'z'); +using MsgDiff = google::protobuf::util::MessageDifferencer; -std::string get_random_string(size_t max_len = 32) { +std::string get_random_string(size_t max_len = STR_MAX_LEN) { + std::random_device random_dev; + std::mt19937 random_gen(random_dev()); + std::uniform_int_distribution char_dist('A', 'z'); std::uniform_int_distribution len_dist(1, static_cast(max_len)); - size_t len = len_dist(random_gen); + auto len = static_cast(len_dist(random_gen)); std::string retval; retval.reserve(len); - for (size_t i = 0; i < len; i++) + for (size_t i = 0; i < len; i++) { retval += static_cast(char_dist(random_gen)); + } return retval; } -int get_random_int(int mn = 0, int mx = 100) { +int get_random_int(int mn = 0, int mx = RANDOM_INT_MAX) { + std::random_device random_dev; + std::mt19937 random_gen(random_dev()); std::uniform_int_distribution int_dist(mn, mx); return int_dist(random_gen); } @@ -59,20 +67,24 @@ class TestMockUTransport : public testing::Test { // Run once per execution of the test application. // Used for setup of all tests. Has access to this instance. TestMockUTransport() = default; - ~TestMockUTransport() = default; // Run once per execution of the test application. // Used only for global setup outside of tests. static void SetUpTestSuite() {} static void TearDownTestSuite() {} + +public: + ~TestMockUTransport() override = default; }; -TEST_F(TestMockUTransport, Send) { - using namespace std; +TEST_F(TestMockUTransport, Send) { // NOLINT + constexpr uint32_t DEF_SRC_UE_ID = 0x18000; + constexpr uint16_t CODE_MAX = 15; + constexpr uint16_t CODE_MOD = 16; uprotocol::v1::UUri def_src_uuri; def_src_uuri.set_authority_name(get_random_string()); - def_src_uuri.set_ue_id(0x18000); + def_src_uuri.set_ue_id(DEF_SRC_UE_ID); def_src_uuri.set_ue_version_major(1); def_src_uuri.set_resource_id(0); @@ -81,13 +93,13 @@ TEST_F(TestMockUTransport, Send) { EXPECT_NE(nullptr, transport); EXPECT_TRUE(MsgDiff::Equals(def_src_uuri, transport->getDefaultSource())); - const size_t max_count = 1000 * 100; + const size_t max_count = 100000; for (size_t i = 0; i < max_count; i++) { - auto src = new uprotocol::v1::UUri(); + auto src = std::make_unique(); src->set_authority_name("10.0.0.1"); - src->set_ue_id(0x00010001); + src->set_ue_id(DEFAULT_UE_ID); src->set_ue_version_major(1); - src->set_resource_id(0x8000); + src->set_resource_id(DEFAULT_RESOURCE_ID); // auto sink = new uprotocol::v1::UUri(); // sink->set_authority_name("10.0.0.2"); @@ -95,34 +107,33 @@ TEST_F(TestMockUTransport, Send) { // sink->set_ue_version_major(2); // sink->set_resource_id(2); - auto attr = new uprotocol::v1::UAttributes(); + auto attr = std::make_unique(); attr->set_type(uprotocol::v1::UMESSAGE_TYPE_PUBLISH); *attr->mutable_id() = make_uuid(); - attr->set_allocated_source(src); + attr->set_allocated_source(src.release()); // attr->set_allocated_sink(sink); attr->set_payload_format(uprotocol::v1::UPAYLOAD_FORMAT_PROTOBUF); - attr->set_ttl(1000); + attr->set_ttl(ATTR_TTL); uprotocol::v1::UMessage msg; - msg.set_allocated_attributes(attr); - msg.set_payload(get_random_string(1400)); - transport->send_status_.set_code( - static_cast(15 - (i % 16))); - transport->send_status_.set_message(get_random_string()); + msg.set_allocated_attributes(attr.release()); + msg.set_payload(get_random_string(PAYLOAD_STR_MAX_LEN)); + transport->getSendStatus().set_code( + static_cast(CODE_MAX - (i % CODE_MOD))); + transport->getSendStatus().set_message(get_random_string()); auto result = transport->send(msg); - EXPECT_EQ(i + 1, transport->send_count_); - EXPECT_TRUE(MsgDiff::Equals(result, transport->send_status_)); - EXPECT_TRUE(MsgDiff::Equals(msg, transport->message_)); + EXPECT_EQ(i + 1, transport->getSendCount()); + EXPECT_TRUE(MsgDiff::Equals(result, transport->getSendStatus())); + EXPECT_TRUE(MsgDiff::Equals(msg, transport->getMessage())); } } -TEST_F(TestMockUTransport, registerListener) { - using namespace std; - +TEST_F(TestMockUTransport, registerListener) { // NOLINT + constexpr uint32_t DEF_SRC_UE_ID = 0x18000; uprotocol::v1::UUri def_src_uuri; def_src_uuri.set_authority_name(get_random_string()); - def_src_uuri.set_ue_id(0x18000); + def_src_uuri.set_ue_id(DEF_SRC_UE_ID); def_src_uuri.set_ue_version_major(1); def_src_uuri.set_resource_id(0); @@ -133,15 +144,15 @@ TEST_F(TestMockUTransport, registerListener) { uprotocol::v1::UUri sink_filter; sink_filter.set_authority_name(get_random_string()); - sink_filter.set_ue_id(0x00010001); + sink_filter.set_ue_id(DEFAULT_UE_ID); sink_filter.set_ue_version_major(1); - sink_filter.set_resource_id(0x8000); + sink_filter.set_resource_id(DEFAULT_RESOURCE_ID); uprotocol::v1::UUri source_filter; source_filter.set_authority_name(get_random_string()); - source_filter.set_ue_id(0x00010001); + source_filter.set_ue_id(DEFAULT_UE_ID); source_filter.set_ue_version_major(1); - source_filter.set_resource_id(0x8000); + source_filter.set_resource_id(DEFAULT_RESOURCE_ID); uprotocol::v1::UMessage capture_msg; size_t capture_count = 0; @@ -151,22 +162,22 @@ TEST_F(TestMockUTransport, registerListener) { }; auto lhandle = transport->registerListener(sink_filter, action, source_filter); - EXPECT_TRUE(transport->listener_); + EXPECT_TRUE(transport->getListener()); // EXPECT_EQ(*mock_info.listener, action); // need exposed target_type() to // make comparable. EXPECT_TRUE(lhandle.has_value()); auto handle = std::move(lhandle).value(); EXPECT_TRUE(handle); - EXPECT_TRUE(transport->sink_filter_); - EXPECT_TRUE(MsgDiff::Equals(sink_filter, *transport->sink_filter_)); - EXPECT_TRUE(MsgDiff::Equals(source_filter, transport->source_filter_)); + EXPECT_TRUE(transport->getSinkFilter()); + EXPECT_TRUE(MsgDiff::Equals(sink_filter, *transport->getSinkFilter())); + EXPECT_TRUE(MsgDiff::Equals(source_filter, transport->getSourceFilter())); - const size_t max_count = 1000 * 100; + const size_t max_count = 100000; for (size_t i = 0; i < max_count; i++) { uprotocol::v1::UMessage msg; - auto attr = new uprotocol::v1::UAttributes(); - msg.set_allocated_attributes(attr); - msg.set_payload(get_random_string(1400)); + auto attr = std::make_unique(); + msg.set_allocated_attributes(attr.release()); + msg.set_payload(get_random_string(PAYLOAD_STR_MAX_LEN)); transport->mockMessage(msg); EXPECT_EQ(i + 1, capture_count); EXPECT_TRUE(MsgDiff::Equals(msg, capture_msg)); diff --git a/test/include/UTransportMock.h b/test/include/UTransportMock.h index 0121dac55..45ac64223 100644 --- a/test/include/UTransportMock.h +++ b/test/include/UTransportMock.h @@ -9,8 +9,8 @@ // // SPDX-License-Identifier: Apache-2.0 -#ifndef UP_CPP_TEST_UTRANSPORTMOCK_H -#define UP_CPP_TEST_UTRANSPORTMOCK_H +#ifndef UTRANSPORTMOCK_H +#define UTRANSPORTMOCK_H #include #include @@ -33,6 +33,32 @@ class UTransportMock : public uprotocol::transport::UTransport { (*listener_)(msg); } + size_t getSendCount() const { return send_count_.load(); } + uprotocol::v1::UStatus& getSendStatus() { return send_status_; } + uprotocol::v1::UStatus& getRegisterListenerStatus() { + return registerListener_status_; + } + std::optional> + getListener() const { + return listener_; + } + std::optional> + getCleanupListener() const { + return cleanup_listener_; + } + std::optional getSinkFilter() const { + return sink_filter_; + } + v1::UUri getSourceFilter() const { return source_filter_; } + std::mutex& getRegisterMtx() { return register_mtx_; } + v1::UMessage getMessage() const { return message_; } + std::mutex& getMessageMtx() { return message_mtx_; } + + ~UTransportMock() override = default; + +private: std::atomic send_count_; uprotocol::v1::UStatus send_status_; @@ -50,10 +76,6 @@ class UTransportMock : public uprotocol::transport::UTransport { v1::UMessage message_; std::mutex message_mtx_; - - virtual ~UTransportMock() = default; - -private: [[nodiscard]] v1::UStatus sendImpl(const v1::UMessage& message) override { { std::lock_guard lock(message_mtx_); @@ -80,4 +102,4 @@ class UTransportMock : public uprotocol::transport::UTransport { }; // namespace uprotocol::test -#endif // UP_CPP_TEST_UTRANSPORTMOCK_H +#endif // UTRANSPORTMOCK_H From ef4babf20288070b3bb72ae383b259a6120588b9 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 23 Apr 2025 17:00:18 +0200 Subject: [PATCH 2/6] added first headers --- CMakeLists.txt | 6 +++- .../core/usubscription/handlers/subscribe.h | 20 +++++++++++++ .../up-cpp/core/usubscription/usubscription.h | 30 +++++++++++++++++++ src/core/usubscription/handlers/subscribe.cpp | 5 ++++ src/core/usubscription/usubscription.cpp | 8 +++++ 5 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 include/up-cpp/core/usubscription/handlers/subscribe.h create mode 100644 include/up-cpp/core/usubscription/usubscription.h create mode 100644 src/core/usubscription/handlers/subscribe.cpp create mode 100644 src/core/usubscription/usubscription.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 256391aae..00f73b34c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -48,7 +48,11 @@ endif() file(GLOB_RECURSE SRC_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") -add_library(${PROJECT_NAME} ${SRC_FILES}) +add_library(${PROJECT_NAME} ${SRC_FILES} + src/core/usubscription/usubscription.cpp + include/up-cpp/core/usubscription/usubscription.h + src/core/usubscription/handlers/subscribe.cpp + include/up-cpp/core/usubscription/handlers/subscribe.h) add_library(up-cpp::${PROJECT_NAME} ALIAS ${PROJECT_NAME}) target_include_directories(${PROJECT_NAME} diff --git a/include/up-cpp/core/usubscription/handlers/subscribe.h b/include/up-cpp/core/usubscription/handlers/subscribe.h new file mode 100644 index 000000000..f55a39aeb --- /dev/null +++ b/include/up-cpp/core/usubscription/handlers/subscribe.h @@ -0,0 +1,20 @@ +// +// Created by max on 23.04.25. +// + +#ifndef SUBSCRIBE_H +#define SUBSCRIBE_H +#include + +#include "up-cpp/communication/NotificationSink.h" +#include "up-cpp/datamodel/builder/Payload.h" +#include "uprotocol/v1/umessage.pb.h" + +// std::function( +// const v1::UMessage&)>; +namespace uprotocol::core::usubscription::handlers{ + +std::optional subscribe(const v1::UMessage&); + +} // namespace uprotocol::core::usubscription::handlers +#endif //SUBSCRIBE_H diff --git a/include/up-cpp/core/usubscription/usubscription.h b/include/up-cpp/core/usubscription/usubscription.h new file mode 100644 index 000000000..18128b8a1 --- /dev/null +++ b/include/up-cpp/core/usubscription/usubscription.h @@ -0,0 +1,30 @@ +// +// Created by max on 23.04.25. +// + +#ifndef USUBSCRIPTION_H +#define USUBSCRIPTION_H + +#include +#include + +#include "up-cpp/communication/RpcServer.h" + +namespace uprotocol::core::usubscription::v3 { + + struct USubscriptionStopper; + + struct USubscriptionConfig; + + struct USubscriptionService : communication::RpcServer{ + + explicit USubscriptionService(std::shared_ptr transport, USubscriptionConfig config); + + //TODO(max) make async + utils::Expected run(); + }; + + +} // namespace uprotocol::core::usubscription::v3 + +#endif //USUBSCRIPTION_H diff --git a/src/core/usubscription/handlers/subscribe.cpp b/src/core/usubscription/handlers/subscribe.cpp new file mode 100644 index 000000000..b4421a05f --- /dev/null +++ b/src/core/usubscription/handlers/subscribe.cpp @@ -0,0 +1,5 @@ +// +// Created by max on 23.04.25. +// + +#include "../../../../include/up-cpp/core/usubscription/handlers/subscribe.h" diff --git a/src/core/usubscription/usubscription.cpp b/src/core/usubscription/usubscription.cpp new file mode 100644 index 000000000..9c2da309a --- /dev/null +++ b/src/core/usubscription/usubscription.cpp @@ -0,0 +1,8 @@ +// +// Created by max on 23.04.25. +// + +#include "../../../include/up-cpp/core/usubscription/usubscription.h" + +#include "up-cpp/transport/UTransport.h" + From 3a98df8cb6766ca360ff985d5b2de32c73d3362f Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 23 Apr 2025 18:17:42 +0200 Subject: [PATCH 3/6] done for today --- CMakeLists.txt | 4 +++- .../up-cpp/core/usubscription/configuration.h | 22 +++++++++++++++++++ src/core/usubscription/configuration.cpp | 5 +++++ src/core/usubscription/handlers/subscribe.cpp | 4 ++++ src/core/usubscription/usubscription.cpp | 7 ++++++ 5 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 include/up-cpp/core/usubscription/configuration.h create mode 100644 src/core/usubscription/configuration.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 00f73b34c..b4c84f420 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -52,7 +52,9 @@ add_library(${PROJECT_NAME} ${SRC_FILES} src/core/usubscription/usubscription.cpp include/up-cpp/core/usubscription/usubscription.h src/core/usubscription/handlers/subscribe.cpp - include/up-cpp/core/usubscription/handlers/subscribe.h) + include/up-cpp/core/usubscription/handlers/subscribe.h + src/core/usubscription/configuration.cpp + include/up-cpp/core/usubscription/configuration.h) add_library(up-cpp::${PROJECT_NAME} ALIAS ${PROJECT_NAME}) target_include_directories(${PROJECT_NAME} diff --git a/include/up-cpp/core/usubscription/configuration.h b/include/up-cpp/core/usubscription/configuration.h new file mode 100644 index 000000000..77cf83378 --- /dev/null +++ b/include/up-cpp/core/usubscription/configuration.h @@ -0,0 +1,22 @@ +// +// Created by max on 23.04.25. +// + +#ifndef CONFIGURATION_H +#define CONFIGURATION_H +#include + +namespace uprotocol::core::usubscription { + struct USubscriptionConfiguration { + + USubscriptionConfiguration create(std::string, size_t, size_t); + + private: + std::string authority_name; + size_t subscription_command_buffer_size; + size_t notification_command_buffer_size; + }; + + +} +#endif //CONFIGURATION_H diff --git a/src/core/usubscription/configuration.cpp b/src/core/usubscription/configuration.cpp new file mode 100644 index 000000000..e6fb92b00 --- /dev/null +++ b/src/core/usubscription/configuration.cpp @@ -0,0 +1,5 @@ +// +// Created by max on 23.04.25. +// + +#include "../../../include/up-cpp/core/usubscription/configuration.h" diff --git a/src/core/usubscription/handlers/subscribe.cpp b/src/core/usubscription/handlers/subscribe.cpp index b4421a05f..f291b5f33 100644 --- a/src/core/usubscription/handlers/subscribe.cpp +++ b/src/core/usubscription/handlers/subscribe.cpp @@ -3,3 +3,7 @@ // #include "../../../../include/up-cpp/core/usubscription/handlers/subscribe.h" +std::optional subscribe( + const uprotocol::v1::UMessage&) { + +}; diff --git a/src/core/usubscription/usubscription.cpp b/src/core/usubscription/usubscription.cpp index 9c2da309a..15f71cbcd 100644 --- a/src/core/usubscription/usubscription.cpp +++ b/src/core/usubscription/usubscription.cpp @@ -6,3 +6,10 @@ #include "up-cpp/transport/UTransport.h" +namespace uprotocol::core::usubscription::v3 { + + utils::Expected run() { + + }; + +}// uprotocol::core::usubscription::v3 From 03edae8502f06b4b8efe05d35efff18b1886a527 Mon Sep 17 00:00:00 2001 From: Lennart Becker Date: Thu, 24 Apr 2025 16:36:59 +0200 Subject: [PATCH 4/6] Started with subscribe.cpp. Added subscription_manager --- CMakeLists.txt | 2 + .../up-cpp/core/usubscription/configuration.h | 4 +- .../core/usubscription/handlers/subscribe.h | 4 +- src/core/usubscription/handlers/subscribe.cpp | 72 +++++++++++++++++-- 4 files changed, 72 insertions(+), 10 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b4c84f420..7378e35ef 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -51,6 +51,8 @@ file(GLOB_RECURSE SRC_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") add_library(${PROJECT_NAME} ${SRC_FILES} src/core/usubscription/usubscription.cpp include/up-cpp/core/usubscription/usubscription.h + src/core/usubscription/subscription_manager.cpp + include/up-cpp/core/usubscription/subscription_manager.h src/core/usubscription/handlers/subscribe.cpp include/up-cpp/core/usubscription/handlers/subscribe.h src/core/usubscription/configuration.cpp diff --git a/include/up-cpp/core/usubscription/configuration.h b/include/up-cpp/core/usubscription/configuration.h index 77cf83378..c8cb41b73 100644 --- a/include/up-cpp/core/usubscription/configuration.h +++ b/include/up-cpp/core/usubscription/configuration.h @@ -6,7 +6,7 @@ #define CONFIGURATION_H #include -namespace uprotocol::core::usubscription { +namespace uprotocol::core::usubscription::v3 { struct USubscriptionConfiguration { USubscriptionConfiguration create(std::string, size_t, size_t); @@ -18,5 +18,5 @@ namespace uprotocol::core::usubscription { }; -} +} // namespace uprotocol::core::usubscription::v3 #endif //CONFIGURATION_H diff --git a/include/up-cpp/core/usubscription/handlers/subscribe.h b/include/up-cpp/core/usubscription/handlers/subscribe.h index f55a39aeb..351c2b07c 100644 --- a/include/up-cpp/core/usubscription/handlers/subscribe.h +++ b/include/up-cpp/core/usubscription/handlers/subscribe.h @@ -5,7 +5,6 @@ #ifndef SUBSCRIBE_H #define SUBSCRIBE_H #include - #include "up-cpp/communication/NotificationSink.h" #include "up-cpp/datamodel/builder/Payload.h" #include "uprotocol/v1/umessage.pb.h" @@ -14,7 +13,8 @@ // const v1::UMessage&)>; namespace uprotocol::core::usubscription::handlers{ -std::optional subscribe(const v1::UMessage&); +std::optional subscribe(const v1::UMessage& message); } // namespace uprotocol::core::usubscription::handlers + #endif //SUBSCRIBE_H diff --git a/src/core/usubscription/handlers/subscribe.cpp b/src/core/usubscription/handlers/subscribe.cpp index f291b5f33..7bb445c40 100644 --- a/src/core/usubscription/handlers/subscribe.cpp +++ b/src/core/usubscription/handlers/subscribe.cpp @@ -1,9 +1,69 @@ -// -// Created by max on 23.04.25. -// - #include "../../../../include/up-cpp/core/usubscription/handlers/subscribe.h" -std::optional subscribe( - const uprotocol::v1::UMessage&) { + +// EXCEPTION HANDLING + +// Exception Type for ServiceInvocationError +class ServiceInvocationError : public std::runtime_error { +public: + explicit ServiceInvocationError(const std::string& message) : std::runtime_error(message) {} + + static ServiceInvocationError InvalidArgument(const std::string& message) { + return ServiceInvocationError("InvalidArgument: " + message); + } }; + + + +// Extracting inputs +std::pair extract_inputs( + uint16_t expected_resource_id, + uint16_t resource_id, + const uprotocol::v1::UMessage& message) { + + auto payload = message.has_payload() ? std::make_optional(message.payload()) : std::nullopt; + auto message_attributes = message.has_attributes() ? std::optional(message.attributes()) : std::nullopt; + + if (resource_id != expected_resource_id) { + throw ServiceInvocationError::InvalidArgument( + "Wrong resource ID (expected " + std::to_string(expected_resource_id) + ", got " + std::to_string(resource_id) + ")"); + } + + if (!payload) { + throw ServiceInvocationError::InvalidArgument("No request payload"); + } + auto request = payload; + try { + // TODO(lennart) + // request = payload.extract_protobuf() + } catch (const std::exception& e) { + throw ServiceInvocationError::InvalidArgument( + "Expected NotificationsRequest payload, error when unpacking: " + std::string(e.what())); + } + + const auto& source = message_attributes->source(); + if (!message_attributes) { + throw ServiceInvocationError::InvalidArgument("No request source uri"); + } + + return {uprotocol::datamodel::builder::Payload(request), uprotocol::v1::UUri(source)}; + +} + + +namespace uprotocol::core::usubscription::handlers { + +std::optional subscribe(const v1::UMessage& message) { + uint16_t expected_resource_id = 0; + uint16_t received_resource_id = 0; + + auto extracted_data = extract_inputs(expected_resource_id, received_resource_id, message); + + std::string test_payload_str = "test_payload"; + uprotocol::datamodel::builder::Payload response_payload(test_payload_str, + uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT); + + return std::make_optional(response_payload); +}; + +} // namespace uprotocol::core::usubscription::handlers From 1ed3cfb7b704975c0ce2e663cbfd5f9a10be10bc Mon Sep 17 00:00:00 2001 From: Lennart Becker Date: Fri, 25 Apr 2025 12:56:42 +0200 Subject: [PATCH 5/6] Added subscription_manager. Added SubscriptionEvent. Continued with subscribe method --- .../core/usubscription/handlers/subscribe.h | 5 +- .../core/usubscription/subscription_manager.h | 37 ++++++++++++ src/core/usubscription/handlers/subscribe.cpp | 56 ++++++++++++++++--- .../usubscription/subscription_manager.cpp | 6 ++ 4 files changed, 91 insertions(+), 13 deletions(-) create mode 100644 include/up-cpp/core/usubscription/subscription_manager.h create mode 100644 src/core/usubscription/subscription_manager.cpp diff --git a/include/up-cpp/core/usubscription/handlers/subscribe.h b/include/up-cpp/core/usubscription/handlers/subscribe.h index 351c2b07c..0ec74ac34 100644 --- a/include/up-cpp/core/usubscription/handlers/subscribe.h +++ b/include/up-cpp/core/usubscription/handlers/subscribe.h @@ -1,13 +1,10 @@ -// -// Created by max on 23.04.25. -// - #ifndef SUBSCRIBE_H #define SUBSCRIBE_H #include #include "up-cpp/communication/NotificationSink.h" #include "up-cpp/datamodel/builder/Payload.h" #include "uprotocol/v1/umessage.pb.h" +#include "../subscription_manager.h" // std::function( // const v1::UMessage&)>; diff --git a/include/up-cpp/core/usubscription/subscription_manager.h b/include/up-cpp/core/usubscription/subscription_manager.h new file mode 100644 index 000000000..ea8aa9aa7 --- /dev/null +++ b/include/up-cpp/core/usubscription/subscription_manager.h @@ -0,0 +1,37 @@ +#ifndef SUBSCRIPTION_MANAGER_H +#define SUBSCRIPTION_MANAGER_H + +#include +#include + +namespace uprotocol::core::usubscription::v3 { + +// Define events +struct AddSubscription { + v1::UUri subscriber; + v1::UUri topic; + // Sender respond_to; +}; + +struct RemoveSubscription { + v1::UUri subscriber; + v1::UUri topic; + // Sender respond_to; +}; + +// struct FetchSubscribers { +// v1::UUri topic; +// std::optional offset; +// // Sender respond_to; +// }; + +// struct FetchSubscriptions { +// int request{}; // Assuming some type RequestKind +// std::optional offset; +// // Sender respond_to{}; +// }; +using SubscriptionEvent = std::variant; + +} // namespace uprotocol::core::usubscription::v3 + +#endif //SUBSCRIPTION_MANAGER_H \ No newline at end of file diff --git a/src/core/usubscription/handlers/subscribe.cpp b/src/core/usubscription/handlers/subscribe.cpp index 7bb445c40..025b90732 100644 --- a/src/core/usubscription/handlers/subscribe.cpp +++ b/src/core/usubscription/handlers/subscribe.cpp @@ -1,8 +1,7 @@ #include "../../../../include/up-cpp/core/usubscription/handlers/subscribe.h" +#include "up-cpp/datamodel/builder/Payload.h" -// EXCEPTION HANDLING - // Exception Type for ServiceInvocationError class ServiceInvocationError : public std::runtime_error { public: @@ -14,8 +13,8 @@ class ServiceInvocationError : public std::runtime_error { }; - -// Extracting inputs +// From helpers.rs +// template std::pair extract_inputs( uint16_t expected_resource_id, uint16_t resource_id, @@ -57,13 +56,52 @@ std::optional subscribe(const v1::UMessage& message uint16_t expected_resource_id = 0; uint16_t received_resource_id = 0; - auto extracted_data = extract_inputs(expected_resource_id, received_resource_id, message); + auto extracted_data = extract_inputs(expected_resource_id, received_resource_id, message); + auto subscription_request = extracted_data.first; + auto source = extracted_data.second; - std::string test_payload_str = "test_payload"; - uprotocol::datamodel::builder::Payload response_payload(test_payload_str, - uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT); + // TODO(lennart) + // if (!subscription_request.topic) { + // throw ServiceInvocationError::InvalidArgument("No topic defined in request"); + // } + + // Interact with subscription manager backend + // let (respond_to, receive_from) = oneshot::channel::(); + v3::SubscriptionEvent se = v3::AddSubscription{ + source, + source // should be topic, please change as soon it exists + // Missing respond_to + }; - return std::make_optional(response_payload); + try { + // Send subscription with se from v3::SubscriptionEvent + } catch (const std::exception& e) { + std::cerr << "Error communicating with subscription manager: " << e.what() << std::endl; + throw ServiceInvocationError("Error processing request"); + } + try { + // Receive asynchronos response, retrieve subscription status (UStatus?) + } catch (const std::exception& e) { + std::cerr << "Error processing request: " << e.what() << std::endl; + throw ServiceInvocationError("Error processing request"); + } + + // Notify update channel + // -> NotificationEvent StateChange + + // Build and return result + std::string test_payload_str = "test_payload"; + std::optional response_payload; + try { + uprotocol::datamodel::builder::Payload response_payload( + test_payload_str, + uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT); + } catch (const std::exception& e) { + std::cerr << "Error building response payload: " << e.what() << std::endl; + throw ServiceInvocationError("Error building response payload"); + } + + return response_payload; }; } // namespace uprotocol::core::usubscription::handlers diff --git a/src/core/usubscription/subscription_manager.cpp b/src/core/usubscription/subscription_manager.cpp new file mode 100644 index 000000000..eab7c3ab4 --- /dev/null +++ b/src/core/usubscription/subscription_manager.cpp @@ -0,0 +1,6 @@ +#include "../../../include/up-cpp/core/usubscription/subscription_manager.h" + + +namespace uprotocol::core::usubscription::v3 { + +}// uprotocol::core::usubscription::v3 \ No newline at end of file From 309506a2beec99b43de048b6be1c0735e21fe9a6 Mon Sep 17 00:00:00 2001 From: Lennart Becker Date: Fri, 25 Apr 2025 17:27:38 +0200 Subject: [PATCH 6/6] Done for the week --- .../core/usubscription/handlers/subscribe.h | 2 +- .../core/usubscription/subscription_manager.h | 14 +++----------- src/core/usubscription/handlers/subscribe.cpp | 17 ++++++++++------- src/core/usubscription/subscription_manager.cpp | 4 ++++ 4 files changed, 18 insertions(+), 19 deletions(-) diff --git a/include/up-cpp/core/usubscription/handlers/subscribe.h b/include/up-cpp/core/usubscription/handlers/subscribe.h index 0ec74ac34..87c7c9a09 100644 --- a/include/up-cpp/core/usubscription/handlers/subscribe.h +++ b/include/up-cpp/core/usubscription/handlers/subscribe.h @@ -10,7 +10,7 @@ // const v1::UMessage&)>; namespace uprotocol::core::usubscription::handlers{ -std::optional subscribe(const v1::UMessage& message); +utils::Expected subscribe(const v1::UMessage& message); } // namespace uprotocol::core::usubscription::handlers diff --git a/include/up-cpp/core/usubscription/subscription_manager.h b/include/up-cpp/core/usubscription/subscription_manager.h index ea8aa9aa7..3e73a6c4c 100644 --- a/include/up-cpp/core/usubscription/subscription_manager.h +++ b/include/up-cpp/core/usubscription/subscription_manager.h @@ -3,6 +3,7 @@ #include #include +#include "configuration.h" namespace uprotocol::core::usubscription::v3 { @@ -19,19 +20,10 @@ struct RemoveSubscription { // Sender respond_to; }; -// struct FetchSubscribers { -// v1::UUri topic; -// std::optional offset; -// // Sender respond_to; -// }; - -// struct FetchSubscriptions { -// int request{}; // Assuming some type RequestKind -// std::optional offset; -// // Sender respond_to{}; -// }; using SubscriptionEvent = std::variant; + void handle_message(const USubscriptionConfiguration& configuration, const transport::UTransport& transport, const SubscriptionEvent& command_receiver); + } // namespace uprotocol::core::usubscription::v3 #endif //SUBSCRIPTION_MANAGER_H \ No newline at end of file diff --git a/src/core/usubscription/handlers/subscribe.cpp b/src/core/usubscription/handlers/subscribe.cpp index 025b90732..5f066c5c4 100644 --- a/src/core/usubscription/handlers/subscribe.cpp +++ b/src/core/usubscription/handlers/subscribe.cpp @@ -1,4 +1,5 @@ #include "../../../../include/up-cpp/core/usubscription/handlers/subscribe.h" +#include #include "up-cpp/datamodel/builder/Payload.h" @@ -31,7 +32,8 @@ std::pair extract_i if (!payload) { throw ServiceInvocationError::InvalidArgument("No request payload"); } - auto request = payload; + + std::optional request; try { // TODO(lennart) // request = payload.extract_protobuf() @@ -45,6 +47,7 @@ std::pair extract_i throw ServiceInvocationError::InvalidArgument("No request source uri"); } + // TODO(lennart) get corresponding request Payload Constructor, in Rust MessageFull is used, that originates from: request = payload.extract_protobuf()... return {uprotocol::datamodel::builder::Payload(request), uprotocol::v1::UUri(source)}; } @@ -52,7 +55,7 @@ std::pair extract_i namespace uprotocol::core::usubscription::handlers { -std::optional subscribe(const v1::UMessage& message) { +utils::Expected subscribe(const v1::UMessage& message) { uint16_t expected_resource_id = 0; uint16_t received_resource_id = 0; @@ -74,20 +77,20 @@ std::optional subscribe(const v1::UMessage& message }; try { - // Send subscription with se from v3::SubscriptionEvent + // Send subscription with se from v3::SubscriptionEvent with subscription_sender from struct SubscriptionRequestHandler } catch (const std::exception& e) { std::cerr << "Error communicating with subscription manager: " << e.what() << std::endl; - throw ServiceInvocationError("Error processing request"); + return ServiceInvocationError("Error processing request"); // UStatus zurückgeben } try { // Receive asynchronos response, retrieve subscription status (UStatus?) } catch (const std::exception& e) { std::cerr << "Error processing request: " << e.what() << std::endl; - throw ServiceInvocationError("Error processing request"); + return ServiceInvocationError("Error processing request"); } // Notify update channel - // -> NotificationEvent StateChange + // -> NotificationEvent StateChange/ Use notification_sender from struct SubscriptionRequestHandler // Build and return result std::string test_payload_str = "test_payload"; @@ -98,7 +101,7 @@ std::optional subscribe(const v1::UMessage& message uprotocol::v1::UPayloadFormat::UPAYLOAD_FORMAT_TEXT); } catch (const std::exception& e) { std::cerr << "Error building response payload: " << e.what() << std::endl; - throw ServiceInvocationError("Error building response payload"); + return ServiceInvocationError("Error building response payload"); } return response_payload; diff --git a/src/core/usubscription/subscription_manager.cpp b/src/core/usubscription/subscription_manager.cpp index eab7c3ab4..aa7849849 100644 --- a/src/core/usubscription/subscription_manager.cpp +++ b/src/core/usubscription/subscription_manager.cpp @@ -3,4 +3,8 @@ namespace uprotocol::core::usubscription::v3 { +void handle_message(const USubscriptionConfiguration& configuration, const transport::UTransport& transport, const SubscriptionEvent& command_receiver){ + +}; + }// uprotocol::core::usubscription::v3 \ No newline at end of file