diff options
author | Ivo Stoilov (GitHub) <istoilov@luxoft.com> | 2017-02-06 20:05:13 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-02-06 20:05:13 +0200 |
commit | 1e4a4c8caf35a5d360bcdee518320639bb0a166d (patch) | |
tree | 4b53c7e3671ee4818db96e92294081f65a5edc12 | |
parent | 01abd065059248084a666d7a63c71195d0a6c5b3 (diff) | |
parent | 34d9a93570e0a5cfe9d613b196403adf229a7fec (diff) | |
download | sdl_core-1e4a4c8caf35a5d360bcdee518320639bb0a166d.tar.gz |
Merge pull request #1244 from istoilovgithub/fix/remove_gmock_patches
Remove gmock patches and fix async unit tests
13 files changed, 892 insertions, 357 deletions
diff --git a/src/3rd_party-static/gmock-1.7.0/include/gmock/gmock-spec-builders.h b/src/3rd_party-static/gmock-1.7.0/include/gmock/gmock-spec-builders.h index ec7a9bd000..17d223dcde 100644 --- a/src/3rd_party-static/gmock-1.7.0/include/gmock/gmock-spec-builders.h +++ b/src/3rd_party-static/gmock-1.7.0/include/gmock/gmock-spec-builders.h @@ -418,12 +418,6 @@ class GTEST_API_ Mock { static bool VerifyAndClear(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); - // Asynchronously verifies all expectations of all registered mock objects - // and clears there default actions and expectations. Returns true if the - // verification was successful. - static bool AsyncVerifyAndClearExpectations(int timeout) - GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); - private: friend class internal::UntypedFunctionMockerBase; @@ -473,12 +467,6 @@ class GTEST_API_ Mock { static bool VerifyAndClearExpectationsLocked(void* mock_obj) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); - // Asynchronously verifies that all expectations of all registered - // mock objects have been satisfied. Reports one or more Google - // Test non-fatal failures and returns false if not. - static bool AsyncVerifyAndClearExpectationsLocked(int timeout_msec) - GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); - // Clears all ON_CALL()s set on the given mock object. static void ClearDefaultActionsLocked(void* mock_obj) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); diff --git a/src/3rd_party-static/gmock-1.7.0/src/gmock-spec-builders.cc b/src/3rd_party-static/gmock-1.7.0/src/gmock-spec-builders.cc index 1219a3a3c9..3943d09276 100644 --- a/src/3rd_party-static/gmock-1.7.0/src/gmock-spec-builders.cc +++ b/src/3rd_party-static/gmock-1.7.0/src/gmock-spec-builders.cc @@ -755,108 +755,6 @@ bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj) return expectations_met; } -bool Mock::AsyncVerifyAndClearExpectations(int timeout_msec) - GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { - internal::MutexLock l(&internal::g_gmock_mutex); - return AsyncVerifyAndClearExpectationsLocked(timeout_msec); -} - -bool Mock::AsyncVerifyAndClearExpectationsLocked(const int timeout_msec_in) - GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { - internal::g_gmock_mutex.AssertHeld(); - MockObjectRegistry::StateMap& state_map = g_mock_object_registry.states(); - if (state_map.empty()) { - // No EXPECT_CALL() was set on the given mock object. - return true; - } - - // TODO(ezamakhov@gmail.com): refactor the next loops - bool expectations_met = true; - timeval first_register_time {0, 0}; - int timeout_msec = timeout_msec_in; - for (MockObjectRegistry::StateMap::iterator mock_it = state_map.begin(); - state_map.end() != mock_it; ++mock_it) { - MockObjectState& state = mock_it->second; - - // Verifies the expectations on each mock method in the - // given mock object. - FunctionMockers& mockers = state.function_mockers; - if (mockers.empty()) { - internal::Assert(!mockers.empty(), __FILE__, __LINE__, - "No functions mocked"); - return true; - } - - for (FunctionMockers::const_iterator it = mockers.begin(); - it != mockers.end(); ++it) { - internal::UntypedFunctionMockerBase* base = *it; - - const timeval register_time = base->RegisteredTime(); - if (!timerisset(&first_register_time) || - timercmp(®ister_time, &first_register_time, <)) { - first_register_time = register_time; - } - - // Waiting expectations loop - do { - const internal::ExpectationResult result = - base->VerifyExpectationsLocked(); - if (result == internal::OverSaturated) { - expectations_met = false; - // break waiting procedure - break; - } - if (result == internal::Satisfied) { - // break waiting procedure - break; - } - if (result == internal::NotSatisfied) { - // If timeout expared - if (timeout_msec <= 0) { - expectations_met = false; - // break waiting procedure - break; - } - // Unlock callbacks procedures - static const int sleep_msec = 10; - internal::UnlockAndSleep(sleep_msec * 1000); - timeout_msec -= sleep_msec; - } - } while (true); - } // mockers iteration - - if (expectations_met) { - const long elapsed_usecs = - // first_register_time is empty on no expectations in mocks - timerisset(&first_register_time) - ? internal::UsecsElapsed(first_register_time) - : 100 * 1000; - // To avoid waitings very long times. - const long max_sleep_time = timeout_msec_in * 10 * 1000; - if (max_sleep_time > elapsed_usecs * 2) { - // Wait double times - internal::UnlockAndSleep(elapsed_usecs * 2); - } - } - - // Verifies and clears the expectations on each mock method in the - // given mock object. - for (FunctionMockers::const_iterator it = mockers.begin(); - it != mockers.end(); ++it) { - internal::UntypedFunctionMockerBase* base = *it; - // Get finial result and clear expectation - const bool final_verification = base->VerifyAndClearExpectationsLocked(); - if (!final_verification) { - expectations_met = false; - } - } - } // state_map iteration - - // We don't clear the content of mockers, as they may still be - // needed by ClearDefaultActionsLocked(). - return expectations_met; -} - // Registers a mock object and a mock method it owns. void Mock::Register(const void* mock_obj, internal::UntypedFunctionMockerBase* mocker) diff --git a/src/components/application_manager/test/app_launch/app_launch_ctrl_test.cc b/src/components/application_manager/test/app_launch/app_launch_ctrl_test.cc index 329b54f78d..1b90f29647 100644 --- a/src/components/application_manager/test/app_launch/app_launch_ctrl_test.cc +++ b/src/components/application_manager/test/app_launch/app_launch_ctrl_test.cc @@ -41,10 +41,12 @@ #include "application_manager/mock_application_manager.h" #include "connection_handler/mock_connection_handler.h" #include "utils/make_shared.h" +#include "utils/test_async_waiter.h" namespace test { namespace components { namespace app_launch_test { + using ::testing::Return; using ::testing::ReturnRef; using ::testing::Truly; @@ -52,6 +54,7 @@ using ::testing::NiceMock; using ::testing::Invoke; using ::testing::AtLeast; using ::testing::InSequence; +using ::testing::DoAll; namespace ch_test = test::components::connection_handler_test; namespace am_test = test::components::application_manager_test; @@ -198,6 +201,7 @@ TEST_F(AppLaunchCtrlTest, StoredAppIsLaunchedAfterDeviceConnected) { app_launch::ApplicationDataPtr app_to_launch = GetTestAppData(0); MockAppPtr app = GetTestApp(0); + TestAsyncWaiter waiter; applications_on_device.push_back(app_to_launch); EXPECT_CALL(app_launch_data_mock_, GetApplicationDataByDevice(app_to_launch->device_mac_)) @@ -206,17 +210,21 @@ TEST_F(AppLaunchCtrlTest, StoredAppIsLaunchedAfterDeviceConnected) { connection_handler_mock_, RunAppOnDevice(app_to_launch->device_mac_, app_to_launch->bundle_id_)) .Times(AtLeast(1)) - .WillOnce(InvokeOnAppRegistered(app_launch_ctrl_.get(), app.get())); + .WillOnce(DoAll(InvokeOnAppRegistered(app_launch_ctrl_.get(), app.get()), + NotifyTestAsyncWaiter(&waiter))); app_launch_ctrl_->OnDeviceConnected(app_to_launch->device_mac_); const uint32_t wait_time = MAX_TEST_DURATION + settings_.app_launch_wait_time(); - testing::Mock::AsyncVerifyAndClearExpectations(wait_time); + EXPECT_TRUE(waiter.WaitFor(1, wait_time)); } TEST_F(AppLaunchCtrlTest, RelaunchAppIfNotRegisteredMultipleTimes) { std::vector<app_launch::ApplicationDataPtr> applications_on_device; app_launch::ApplicationDataPtr app_to_launch = GetTestAppData(0); applications_on_device.push_back(app_to_launch); + + TestAsyncWaiter waiter; + const uint32_t times = settings_.app_launch_max_retry_attempt(); EXPECT_CALL(app_launch_data_mock_, GetApplicationDataByDevice(app_to_launch->device_mac_)) .WillOnce(Return(applications_on_device)); @@ -224,14 +232,15 @@ TEST_F(AppLaunchCtrlTest, RelaunchAppIfNotRegisteredMultipleTimes) { EXPECT_CALL( connection_handler_mock_, RunAppOnDevice(app_to_launch->device_mac_, app_to_launch->bundle_id_)) - .Times(settings_.app_launch_max_retry_attempt()); + .Times(times) + .WillRepeatedly(NotifyTestAsyncWaiter(&waiter)); app_launch_ctrl_->OnDeviceConnected(app_to_launch->device_mac_); const uint32_t wait_time = MAX_TEST_DURATION + settings_.app_launch_wait_time() + settings_.app_launch_max_retry_attempt() * settings_.app_launch_retry_wait_time(); - testing::Mock::AsyncVerifyAndClearExpectations(wait_time); + EXPECT_TRUE(waiter.WaitFor(times, wait_time)); } TEST_F(AppLaunchCtrlTest, LaunchMultipleApps) { @@ -243,6 +252,8 @@ TEST_F(AppLaunchCtrlTest, LaunchMultipleApps) { apps.push_back(it->second); } + TestAsyncWaiter waiter; + const uint32_t times = apps_and_data.size(); EXPECT_CALL(app_launch_data_mock_, GetApplicationDataByDevice(DeviceMac(1))) .WillOnce(Return(apps)); @@ -250,13 +261,18 @@ TEST_F(AppLaunchCtrlTest, LaunchMultipleApps) { for (std::vector<AppAndAppData>::iterator it = apps_and_data.begin(); it != apps_and_data.end(); ++it) { - ExpectRegisteration(*it); + EXPECT_CALL(connection_handler_mock_, + RunAppOnDevice(it->second->device_mac_, it->second->bundle_id_)) + .Times(AtLeast(1)) + .WillOnce(DoAll( + InvokeOnAppRegistered(app_launch_ctrl_.get(), it->first.get()), + NotifyTestAsyncWaiter(&waiter))); } app_launch_ctrl_->OnDeviceConnected(DeviceMac(1)); const uint32_t wait_time = MAX_TEST_DURATION + settings_.app_launch_wait_time() + apps.size() * settings_.wait_time_between_apps(); - testing::Mock::AsyncVerifyAndClearExpectations(wait_time); + waiter.WaitFor(times, wait_time); } TEST_F(AppLaunchCtrlTest, LaunchMultipleAppsNoRegister) { @@ -268,6 +284,9 @@ TEST_F(AppLaunchCtrlTest, LaunchMultipleAppsNoRegister) { apps.push_back(it->second); } + TestAsyncWaiter waiter; + const uint32_t times = + settings_.app_launch_max_retry_attempt() * apps_and_data.size(); EXPECT_CALL(app_launch_data_mock_, GetApplicationDataByDevice(DeviceMac(1))) .WillOnce(Return(apps)); @@ -279,13 +298,14 @@ TEST_F(AppLaunchCtrlTest, LaunchMultipleAppsNoRegister) { EXPECT_CALL(connection_handler_mock_, RunAppOnDevice(app_data.second->device_mac_, app_data.second->bundle_id_)) - .Times(settings_.app_launch_max_retry_attempt()); + .Times(settings_.app_launch_max_retry_attempt()) + .WillRepeatedly(NotifyTestAsyncWaiter(&waiter)); } app_launch_ctrl_->OnDeviceConnected(DeviceMac(1)); const uint32_t wait_time = MAX_TEST_DURATION + settings_.app_launch_wait_time() + apps.size() * settings_.wait_time_between_apps(); - testing::Mock::AsyncVerifyAndClearExpectations(wait_time); + waiter.WaitFor(times, wait_time); } TEST_F(AppLaunchCtrlTest, LaunchMultipleAppsInHMILevelOrder) { @@ -322,31 +342,28 @@ TEST_F(AppLaunchCtrlTest, LaunchMultipleAppsInHMILevelOrder) { apps.push_back(app_data); } + TestAsyncWaiter waiter; + const uint32_t times = apps_and_data.size(); EXPECT_CALL(app_launch_data_mock_, GetApplicationDataByDevice(DeviceMac(1))) .WillOnce(Return(apps)); - { - InSequence s; - - ExpectRegisteration(apps_and_data[0]); - ExpectRegisteration(apps_and_data[1]); - ExpectRegisteration(apps_and_data[2]); + // Expect multiple call + for (std::vector<AppAndAppData>::iterator it = apps_and_data.begin(); + it != apps_and_data.end(); + ++it) { + EXPECT_CALL(connection_handler_mock_, + RunAppOnDevice(it->second->device_mac_, it->second->bundle_id_)) + .Times(AtLeast(1)) + .WillRepeatedly(DoAll( + InvokeOnAppRegistered(app_launch_ctrl_.get(), it->first.get()), + NotifyTestAsyncWaiter(&waiter))); } app_launch_ctrl_->OnDeviceConnected(DeviceMac(1)); + const uint32_t wait_time = MAX_TEST_DURATION + settings_.app_launch_wait_time() + apps.size() * settings_.wait_time_between_apps(); - testing::Mock::AsyncVerifyAndClearExpectations(wait_time); -} - -void AppLaunchCtrlTest::ExpectRegisteration( - const AppLaunchCtrlTest::AppAndAppData& app_data) { - EXPECT_CALL( - connection_handler_mock_, - RunAppOnDevice(app_data.second->device_mac_, app_data.second->bundle_id_)) - .Times(AtLeast(1)) - .WillOnce( - InvokeOnAppRegistered(app_launch_ctrl_.get(), app_data.first.get())); + waiter.WaitFor(times, wait_time); } } // namespace app_launch_test diff --git a/src/components/application_manager/test/request_controller/request_controller_test.cc b/src/components/application_manager/test/request_controller/request_controller_test.cc index f93240aeae..e053d51c34 100644 --- a/src/components/application_manager/test/request_controller/request_controller_test.cc +++ b/src/components/application_manager/test/request_controller/request_controller_test.cc @@ -50,6 +50,7 @@ #include "application_manager/resumption/resume_ctrl.h" #include "application_manager/mock_request_controller_settings.h" #include "application_manager/mock_application_manager.h" +#include "utils/test_async_waiter.h" namespace test { namespace components { @@ -246,15 +247,17 @@ TEST_F(RequestControllerTestClass, OnTimer_SUCCESS) { RequestPtr mock_request = GetMockRequest( kDefaultCorrelationID, kDefaultConnectionKey, request_timeout); + TestAsyncWaiter waiter; EXPECT_EQ(RequestController::SUCCESS, AddRequest(default_settings_, mock_request, RequestInfo::RequestType::MobileRequest)); - EXPECT_CALL(*mock_request, onTimeOut()); + EXPECT_CALL(*mock_request, onTimeOut()) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); // Waiting for call of `onTimeOut` for `kTimeScale` seconds - testing::Mock::AsyncVerifyAndClearExpectations(kTimeScale); + EXPECT_TRUE(waiter.WaitFor(1, kTimeScale)); } } // namespace request_controller_test diff --git a/src/components/connection_handler/test/connection_handler_impl_test.cc b/src/components/connection_handler/test/connection_handler_impl_test.cc index f1a67f9ba8..6b5c2c89ad 100644 --- a/src/components/connection_handler/test/connection_handler_impl_test.cc +++ b/src/components/connection_handler/test/connection_handler_impl_test.cc @@ -44,6 +44,7 @@ #include "connection_handler/mock_connection_handler_settings.h" #include "transport_manager/mock_transport_manager.h" #include "encryption/hashing.h" +#include "utils/test_async_waiter.h" namespace test { namespace components { @@ -58,6 +59,10 @@ using ::testing::Mock; using ::testing::Return; using ::testing::ReturnRefOfCopy; +namespace { +const uint32_t kAsyncExpectationsTimeout = 10000u; +} + // For service types and PROTECTION_ON/OFF enum UnnamedService { kServedService1 = 0x06, kServedService2 = 0x08 }; @@ -811,21 +816,34 @@ TEST_F(ConnectionHandlerTest, CloseSessionWithCommonReason) { &mock_connection_handler_observer); connection_handler_->set_protocol_handler(&mock_protocol_handler_); + + TestAsyncWaiter waiter; + uint32_t times = 0; EXPECT_CALL(mock_protocol_handler_, SendEndSession(uid_, start_session_id_)) - .Times(1); + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; + InSequence seq; EXPECT_CALL(mock_connection_handler_observer, OnServiceEndedCallback(connection_key_, kMobileNav, kCommon)) - .Times(1); + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; EXPECT_CALL(mock_connection_handler_observer, OnServiceEndedCallback(connection_key_, kAudio, kCommon)) - .Times(1); + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; EXPECT_CALL(mock_connection_handler_observer, - OnServiceEndedCallback(connection_key_, kBulk, kCommon)).Times(1); + OnServiceEndedCallback(connection_key_, kBulk, kCommon)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; EXPECT_CALL(mock_connection_handler_observer, - OnServiceEndedCallback(connection_key_, kRpc, kCommon)).Times(1); + OnServiceEndedCallback(connection_key_, kRpc, kCommon)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; + connection_handler_->CloseSession(connection_key_, kCommon); - Mock::AsyncVerifyAndClearExpectations(10000); + + EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout)); } TEST_F(ConnectionHandlerTest, CloseSessionWithFloodReason) { @@ -839,21 +857,34 @@ TEST_F(ConnectionHandlerTest, CloseSessionWithFloodReason) { &mock_connection_handler_observer); connection_handler_->set_protocol_handler(&mock_protocol_handler_); + + TestAsyncWaiter waiter; + uint32_t times = 0; EXPECT_CALL(mock_protocol_handler_, SendEndSession(uid_, start_session_id_)) - .Times(1); + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; InSequence seq; EXPECT_CALL(mock_connection_handler_observer, OnServiceEndedCallback(connection_key_, kMobileNav, kFlood)) - .Times(1); + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; EXPECT_CALL(mock_connection_handler_observer, - OnServiceEndedCallback(connection_key_, kAudio, kFlood)).Times(1); + OnServiceEndedCallback(connection_key_, kAudio, kFlood)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; EXPECT_CALL(mock_connection_handler_observer, - OnServiceEndedCallback(connection_key_, kBulk, kFlood)).Times(1); + OnServiceEndedCallback(connection_key_, kBulk, kFlood)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; EXPECT_CALL(mock_connection_handler_observer, - OnServiceEndedCallback(connection_key_, kRpc, kFlood)).Times(1); + OnServiceEndedCallback(connection_key_, kRpc, kFlood)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; + connection_handler_->CloseSession(connection_key_, kFlood); - Mock::AsyncVerifyAndClearExpectations(10000); + + EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout)); } TEST_F(ConnectionHandlerTest, CloseSessionWithMalformedMessage) { @@ -868,23 +899,32 @@ TEST_F(ConnectionHandlerTest, CloseSessionWithMalformedMessage) { connection_handler_->set_protocol_handler(&mock_protocol_handler_); + TestAsyncWaiter waiter; + uint32_t times = 0; EXPECT_CALL(mock_protocol_handler_, SendEndSession(uid_, start_session_id_)) .Times(0); + InSequence seq; EXPECT_CALL(mock_connection_handler_observer, OnServiceEndedCallback(connection_key_, kMobileNav, kMalformed)) - .Times(1); + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; EXPECT_CALL(mock_connection_handler_observer, OnServiceEndedCallback(connection_key_, kAudio, kMalformed)) - .Times(1); + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; EXPECT_CALL(mock_connection_handler_observer, OnServiceEndedCallback(connection_key_, kBulk, kMalformed)) - .Times(1); + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; EXPECT_CALL(mock_connection_handler_observer, OnServiceEndedCallback(connection_key_, kRpc, kMalformed)) - .Times(1); + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; + connection_handler_->CloseSession(connection_key_, kMalformed); - Mock::AsyncVerifyAndClearExpectations(10000); + + EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout)); } TEST_F(ConnectionHandlerTest, CloseConnectionSessionsWithMalformedMessage) { @@ -899,23 +939,32 @@ TEST_F(ConnectionHandlerTest, CloseConnectionSessionsWithMalformedMessage) { connection_handler_->set_protocol_handler(&mock_protocol_handler_); + TestAsyncWaiter waiter; + uint32_t times = 0; EXPECT_CALL(mock_protocol_handler_, SendEndSession(uid_, start_session_id_)) .Times(0); + InSequence seq; EXPECT_CALL(mock_connection_handler_observer, OnServiceEndedCallback(connection_key_, kMobileNav, kMalformed)) - .Times(1); + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; EXPECT_CALL(mock_connection_handler_observer, OnServiceEndedCallback(connection_key_, kAudio, kMalformed)) - .Times(1); + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; EXPECT_CALL(mock_connection_handler_observer, OnServiceEndedCallback(connection_key_, kBulk, kMalformed)) - .Times(1); + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; EXPECT_CALL(mock_connection_handler_observer, OnServiceEndedCallback(connection_key_, kRpc, kMalformed)) - .Times(1); + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; + connection_handler_->CloseConnectionSessions(uid_, kMalformed); - Mock::AsyncVerifyAndClearExpectations(10000); + + EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout)); } TEST_F(ConnectionHandlerTest, CloseConnectionSessionsWithCommonReason) { @@ -930,21 +979,33 @@ TEST_F(ConnectionHandlerTest, CloseConnectionSessionsWithCommonReason) { connection_handler_->set_protocol_handler(&mock_protocol_handler_); + TestAsyncWaiter waiter; + uint32_t times = 0; EXPECT_CALL(mock_protocol_handler_, SendEndSession(uid_, start_session_id_)) - .Times(1); + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; + InSequence seq; EXPECT_CALL(mock_connection_handler_observer, OnServiceEndedCallback(connection_key_, kMobileNav, kCommon)) - .Times(1); + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; EXPECT_CALL(mock_connection_handler_observer, OnServiceEndedCallback(connection_key_, kAudio, kCommon)) - .Times(1); + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; EXPECT_CALL(mock_connection_handler_observer, - OnServiceEndedCallback(connection_key_, kBulk, kCommon)).Times(1); + OnServiceEndedCallback(connection_key_, kBulk, kCommon)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; EXPECT_CALL(mock_connection_handler_observer, - OnServiceEndedCallback(connection_key_, kRpc, kCommon)).Times(1); + OnServiceEndedCallback(connection_key_, kRpc, kCommon)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; + connection_handler_->CloseConnectionSessions(uid_, kCommon); - Mock::AsyncVerifyAndClearExpectations(10000); + + EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout)); } TEST_F(ConnectionHandlerTest, StartService_withServices) { diff --git a/src/components/connection_handler/test/heart_beat_monitor_test.cc b/src/components/connection_handler/test/heart_beat_monitor_test.cc index 2c928fe458..4c67c97191 100644 --- a/src/components/connection_handler/test/heart_beat_monitor_test.cc +++ b/src/components/connection_handler/test/heart_beat_monitor_test.cc @@ -37,6 +37,7 @@ #include "connection_handler/connection.h" #include "connection_handler/connection_handler.h" #include "connection_handler/mock_connection_handler.h" +#include "utils/test_async_waiter.h" namespace { const int32_t MILLISECONDS_IN_SECOND = 1000; @@ -47,6 +48,8 @@ const int32_t MICROSECONDS_IN_SECOND = 1000 * 1000; namespace test { namespace components { namespace connection_handler_test { + +using ::testing::DoAll; using ::testing::_; class HeartBeatMonitorTest : public testing::Test { @@ -83,8 +86,6 @@ TEST_F(HeartBeatMonitorTest, TimerNotStarted) { EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, _)).Times(0); conn->AddNewSession(); - testing::Mock::AsyncVerifyAndClearExpectations( - kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND); } TEST_F(HeartBeatMonitorTest, TimerNotElapsed) { @@ -94,21 +95,29 @@ TEST_F(HeartBeatMonitorTest, TimerNotElapsed) { const uint32_t session = conn->AddNewSession(); conn->StartHeartBeat(session); - testing::Mock::AsyncVerifyAndClearExpectations( - kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND); } TEST_F(HeartBeatMonitorTest, TimerElapsed) { const uint32_t session = conn->AddNewSession(); + TestAsyncWaiter waiter; + uint32_t times = 0; EXPECT_CALL(connection_handler_mock, CloseSession(_, session, _)) - .WillOnce(RemoveSession(conn, session)); - EXPECT_CALL(connection_handler_mock, CloseConnection(_)); - EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, session)); + .WillOnce( + DoAll(NotifyTestAsyncWaiter(&waiter), RemoveSession(conn, session))); + times++; + EXPECT_CALL(connection_handler_mock, CloseConnection(_)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; + EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, session)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; conn->StartHeartBeat(session); - testing::Mock::AsyncVerifyAndClearExpectations( - 2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND); + + EXPECT_TRUE(waiter.WaitFor( + times, + 2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND)); } TEST_F(HeartBeatMonitorTest, KeptAlive) { @@ -130,10 +139,18 @@ TEST_F(HeartBeatMonitorTest, KeptAlive) { TEST_F(HeartBeatMonitorTest, NotKeptAlive) { const uint32_t session = conn->AddNewSession(); - EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, session)); + TestAsyncWaiter waiter; + uint32_t times = 0; + EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, session)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; EXPECT_CALL(connection_handler_mock, CloseSession(_, session, _)) - .WillOnce(RemoveSession(conn, session)); - EXPECT_CALL(connection_handler_mock, CloseConnection(_)); + .WillOnce( + DoAll(NotifyTestAsyncWaiter(&waiter), RemoveSession(conn, session))); + times++; + EXPECT_CALL(connection_handler_mock, CloseConnection(_)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; conn->StartHeartBeat(session); usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND); @@ -143,24 +160,42 @@ TEST_F(HeartBeatMonitorTest, NotKeptAlive) { usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND); conn->KeepAlive(session); usleep(2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND); + + EXPECT_TRUE(waiter.WaitFor( + times, + 2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND)); } TEST_F(HeartBeatMonitorTest, TwoSessionsElapsed) { const uint32_t kSession1 = conn->AddNewSession(); const uint32_t kSession2 = conn->AddNewSession(); + TestAsyncWaiter waiter; + uint32_t times = 0; EXPECT_CALL(connection_handler_mock, CloseSession(_, kSession1, _)) - .WillOnce(RemoveSession(conn, kSession1)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), + RemoveSession(conn, kSession1))); + times++; EXPECT_CALL(connection_handler_mock, CloseSession(_, kSession2, _)) - .WillOnce(RemoveSession(conn, kSession2)); - EXPECT_CALL(connection_handler_mock, CloseConnection(_)); - EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, kSession1)); - EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, kSession2)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), + RemoveSession(conn, kSession2))); + times++; + EXPECT_CALL(connection_handler_mock, CloseConnection(_)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; + EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, kSession1)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; + EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, kSession2)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; conn->StartHeartBeat(kSession1); conn->StartHeartBeat(kSession2); - testing::Mock::AsyncVerifyAndClearExpectations( - 2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND); + + EXPECT_TRUE(waiter.WaitFor( + times, + 2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND)); } TEST_F(HeartBeatMonitorTest, IncreaseHeartBeatTimeout) { @@ -173,25 +208,31 @@ TEST_F(HeartBeatMonitorTest, IncreaseHeartBeatTimeout) { const uint32_t kNewTimeout = kTimeout + MICROSECONDS_IN_MILLISECONDS; conn->StartHeartBeat(kSession); conn->SetHeartBeatTimeout(kNewTimeout, kSession); - // new timeout greater by old timeout so mock object shouldn't be invoked - testing::Mock::AsyncVerifyAndClearExpectations(kTimeout * - MICROSECONDS_IN_MILLISECONDS); } TEST_F(HeartBeatMonitorTest, DecreaseHeartBeatTimeout) { const uint32_t kSession = conn->AddNewSession(); + TestAsyncWaiter waiter; + uint32_t times = 0; EXPECT_CALL(connection_handler_mock, CloseSession(_, kSession, _)) - .WillOnce(RemoveSession(conn, kSession)); - EXPECT_CALL(connection_handler_mock, CloseConnection(_)); - EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, kSession)); + .WillOnce( + DoAll(NotifyTestAsyncWaiter(&waiter), RemoveSession(conn, kSession))); + times++; + EXPECT_CALL(connection_handler_mock, CloseConnection(_)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; + EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, kSession)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; const uint32_t kNewTimeout = kTimeout - MICROSECONDS_IN_MILLISECONDS; conn->StartHeartBeat(kSession); conn->SetHeartBeatTimeout(kNewTimeout, kSession); - // new timeout less than old timeout so mock object should be invoked - testing::Mock::AsyncVerifyAndClearExpectations(kTimeout * 2 * - MICROSECONDS_IN_MILLISECONDS); + + EXPECT_TRUE(waiter.WaitFor( + times, + 2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND)); } } // namespace connection_handler_test diff --git a/src/components/hmi_message_handler/test/hmi_message_handler_impl_test.cc b/src/components/hmi_message_handler/test/hmi_message_handler_impl_test.cc index b81ba5d4ed..09f20ed75d 100644 --- a/src/components/hmi_message_handler/test/hmi_message_handler_impl_test.cc +++ b/src/components/hmi_message_handler/test/hmi_message_handler_impl_test.cc @@ -37,6 +37,7 @@ #include "hmi_message_handler/mock_hmi_message_observer.h" #include "hmi_message_handler/mock_hmi_message_handler_settings.h" #include "hmi_message_handler/mock_hmi_message_adapter_impl.h" +#include "utils/test_async_waiter.h" namespace test { namespace components { @@ -172,15 +173,19 @@ TEST_F(HMIMessageHandlerImplTest, OnMessageReceived_InvalidObserver_Cancelled) { TEST_F(HMIMessageHandlerImplTest, SendMessageToHMI_Success) { hmi_message_handler::MessageSharedPointer message = CreateMessage(); + TestAsyncWaiter waiter; + MockHMIMessageAdapterImpl message_adapter(hmi_handler_); - EXPECT_CALL(message_adapter, SendMessageToHMI(message)); + EXPECT_CALL(message_adapter, SendMessageToHMI(message)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); hmi_handler_->AddHMIMessageAdapter(&message_adapter); hmi_handler_->SendMessageToHMI(message); // Wait for the message to be processed hmi_handler_->messages_to_hmi()->WaitDumpQueue(); - testing::Mock::AsyncVerifyAndClearExpectations(100); + + EXPECT_TRUE(waiter.WaitFor(1, 100)); } } // namespace hmi_message_handler_test diff --git a/src/components/include/test/utils/test_async_waiter.h b/src/components/include/test/utils/test_async_waiter.h new file mode 100644 index 0000000000..2d53d5d7c8 --- /dev/null +++ b/src/components/include/test/utils/test_async_waiter.h @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2017, Ford Motor Company + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following + * disclaimer in the documentation and/or other materials provided with the + * distribution. + * + * Neither the name of the Ford Motor Company nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include <stdint.h> + +#include "utils/lock.h" +#include "utils/conditional_variable.h" + +namespace test { + +/** + * @brief The TestAsyncWaiter class + * Tool with condition variable style interface + * to be used in unit tests for asynchronous calls waiting. + * Could wait specified number of calls, waiting for timeout is also supported + * + * Usage example: + * TEST() { + * TestAsyncWaiter waiter; + * EXPECT_CALL(mock, InterestingCall()) + * .Times(n) + * .WillRepeatedly(NotifyTestAsyncWaiter(&waiter)); + * EXPECT_TRUE(waiter.WaitFor(n, 1000)); + * } + */ +class TestAsyncWaiter { + public: + TestAsyncWaiter() : notified_(false), count_(0), lock_(), cond_var_() {} + + /** + * @brief WaitFor + * Waits for specified number of notifications but not longer + * than given timeout for each notification + * @param wait_count Number of notifications to wait for + * @param milliseconds Timeout in milliseconds + * @return True if specified number of notifications have been received, + * false otherwise (return by timeout) + */ + bool WaitFor(const uint32_t wait_count, const uint32_t milliseconds) { + sync_primitives::AutoLock auto_lock(lock_); + while (count_ < wait_count) { + notified_ = false; + if (sync_primitives::ConditionalVariable::kTimeout == + cond_var_.WaitFor(auto_lock, milliseconds)) { + return false; + } + } + return true; + } + + /** + * @brief Notify + * Notifies async waiter + */ + void Notify() { + sync_primitives::AutoLock auto_lock(lock_); + notified_ = true; + ++count_; + cond_var_.Broadcast(); + } + + private: + bool notified_; + uint32_t count_; + sync_primitives::Lock lock_; + sync_primitives::ConditionalVariable cond_var_; +}; + +ACTION_P(NotifyTestAsyncWaiter, test_async_waiter) { + test_async_waiter->Notify(); +} + +} // namespace test diff --git a/src/components/protocol_handler/include/protocol_handler/protocol_handler_impl.h b/src/components/protocol_handler/include/protocol_handler/protocol_handler_impl.h index cd50f98bdb..b18ee07d4d 100644 --- a/src/components/protocol_handler/include/protocol_handler/protocol_handler_impl.h +++ b/src/components/protocol_handler/include/protocol_handler/protocol_handler_impl.h @@ -297,6 +297,16 @@ class ProtocolHandlerImpl SessionObserver& get_session_observer() OVERRIDE; +#ifdef BUILD_TESTS + const impl::FromMobileQueue& get_from_mobile_queue() const { + return raw_ford_messages_from_mobile_; + } + + const impl::ToMobileQueue& get_to_mobile_queue() const { + return raw_ford_messages_to_mobile_; + } +#endif + private: void SendEndServicePrivate(int32_t connection_id, uint8_t session_id, diff --git a/src/components/protocol_handler/test/protocol_handler_tm_test.cc b/src/components/protocol_handler/test/protocol_handler_tm_test.cc index 5aa7ae48dd..e69a37b374 100644 --- a/src/components/protocol_handler/test/protocol_handler_tm_test.cc +++ b/src/components/protocol_handler/test/protocol_handler_tm_test.cc @@ -44,6 +44,7 @@ #include "security_manager/mock_ssl_context.h" #include "transport_manager/mock_transport_manager.h" #include "utils/make_shared.h" +#include "utils/test_async_waiter.h" namespace test { namespace components { @@ -104,6 +105,10 @@ using ::testing::SetArgPointee; typedef std::vector<uint8_t> UCharDataVector; +namespace { +const uint32_t kAsyncExpectationsTimeout = 10000u; +} + class ProtocolHandlerImplTest : public ::testing::Test { protected: void InitProtocolHandlerImpl(const size_t period_msec, @@ -156,8 +161,10 @@ class ProtocolHandlerImplTest : public ::testing::Test { } void TearDown() OVERRIDE { - // Wait call methods in thread - testing::Mock::AsyncVerifyAndClearExpectations(10000); + const_cast<protocol_handler::impl::FromMobileQueue&>( + protocol_handler_impl->get_from_mobile_queue()).WaitDumpQueue(); + const_cast<protocol_handler::impl::ToMobileQueue&>( + protocol_handler_impl->get_to_mobile_queue()).WaitDumpQueue(); } // Emulate connection establish @@ -168,9 +175,13 @@ class ProtocolHandlerImplTest : public ::testing::Test { std::string("BTMAC")), connection_id); } - void AddSession() { + + void AddSession(const ::utils::SharedPtr<TestAsyncWaiter>& waiter, uint32_t& times) { + ASSERT_TRUE(NULL != waiter.get()); + AddConnection(); const ServiceType start_service = kRpc; + #ifdef ENABLE_SECURITY // For enabled protection callback shall use protection ON const bool callback_protection_flag = PROTECTION_ON; @@ -179,6 +190,7 @@ class ProtocolHandlerImplTest : public ::testing::Test { // use protection OFF const bool callback_protection_flag = PROTECTION_OFF; #endif // ENABLE_SECURITY + // Expect ConnectionHandler check EXPECT_CALL(session_observer_mock, OnSessionStartedCallback(connection_id, @@ -188,13 +200,15 @@ class ProtocolHandlerImplTest : public ::testing::Test { _)) . // Return sessions start success - WillOnce(Return(session_id)); + WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(session_id))); + times++; // Expect send Ack with PROTECTION_OFF (on no Security Manager) EXPECT_CALL(transport_manager_mock, - SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_ACK, - PROTECTION_OFF))) - .WillOnce(Return(E_SUCCESS)); + SendMessageToDevice(ControlMessage( + FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF))) + .WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS))); + times++; SendControlMessage( PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE); @@ -206,6 +220,7 @@ class ProtocolHandlerImplTest : public ::testing::Test { protocol_handler_impl->set_security_manager(&security_manager_mock); } #endif // ENABLE_SECURITY + void SendTMMessage(uint8_t connection_id, uint8_t version, bool protection, @@ -327,6 +342,9 @@ TEST_F(ProtocolHandlerImplTest, StartSession_Unprotected_SessionObserverReject) { const int call_times = 5; AddConnection(); + + TestAsyncWaiter waiter; + uint32_t times = 0; // Expect ConnectionHandler check EXPECT_CALL( session_observer_mock, @@ -338,14 +356,17 @@ TEST_F(ProtocolHandlerImplTest, .Times(call_times) . // Return sessions start rejection - WillRepeatedly(Return(SESSION_START_REJECT)); + WillRepeatedly( + DoAll(NotifyTestAsyncWaiter(&waiter), Return(SESSION_START_REJECT))); + times += call_times; // Expect send NAck EXPECT_CALL(transport_manager_mock, SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_NACK, PROTECTION_OFF))) .Times(call_times) - .WillRepeatedly(Return(E_SUCCESS)); + .WillRepeatedly(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS))); + times += call_times; SendControlMessage( PROTECTION_OFF, kControl, NEW_SESSION_ID, FRAME_DATA_START_SERVICE); @@ -357,6 +378,8 @@ TEST_F(ProtocolHandlerImplTest, PROTECTION_OFF, kMobileNav, NEW_SESSION_ID, FRAME_DATA_START_SERVICE); SendControlMessage( PROTECTION_OFF, kBulk, NEW_SESSION_ID, FRAME_DATA_START_SERVICE); + + EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout)); } /* * ProtocolHandler shall send NAck on session_observer rejection @@ -375,6 +398,9 @@ TEST_F(ProtocolHandlerImplTest, StartSession_Protected_SessionObserverReject) { // use protection OFF const bool callback_protection_flag = PROTECTION_OFF; #endif // ENABLE_SECURITY + + TestAsyncWaiter waiter; + uint32_t times = 0; // Expect ConnectionHandler check EXPECT_CALL( session_observer_mock, @@ -386,14 +412,17 @@ TEST_F(ProtocolHandlerImplTest, StartSession_Protected_SessionObserverReject) { .Times(call_times) . // Return sessions start rejection - WillRepeatedly(Return(SESSION_START_REJECT)); + WillRepeatedly( + DoAll(NotifyTestAsyncWaiter(&waiter), Return(SESSION_START_REJECT))); + times += call_times; // Expect send NAck with encryption OFF EXPECT_CALL(transport_manager_mock, SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_NACK, PROTECTION_OFF))) .Times(call_times) - .WillRepeatedly(Return(E_SUCCESS)); + .WillRepeatedly(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS))); + times += call_times; SendControlMessage( PROTECTION_ON, kControl, NEW_SESSION_ID, FRAME_DATA_START_SERVICE); @@ -405,6 +434,8 @@ TEST_F(ProtocolHandlerImplTest, StartSession_Protected_SessionObserverReject) { PROTECTION_ON, kMobileNav, NEW_SESSION_ID, FRAME_DATA_START_SERVICE); SendControlMessage( PROTECTION_ON, kBulk, NEW_SESSION_ID, FRAME_DATA_START_SERVICE); + + EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout)); } /* * ProtocolHandler shall send Ack on session_observer accept @@ -414,6 +445,9 @@ TEST_F(ProtocolHandlerImplTest, StartSession_Unprotected_SessionObserverAccept) { AddConnection(); const ServiceType start_service = kRpc; + + TestAsyncWaiter waiter; + uint32_t times = 0; // Expect ConnectionHandler check EXPECT_CALL( session_observer_mock, @@ -421,17 +455,21 @@ TEST_F(ProtocolHandlerImplTest, connection_id, NEW_SESSION_ID, start_service, PROTECTION_OFF, _)) . // Return sessions start success - WillOnce(Return(session_id)); + WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(session_id))); + times++; SetProtocolVersion2(); // Expect send Ack EXPECT_CALL(transport_manager_mock, SendMessageToDevice( ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF))) - .WillOnce(Return(E_SUCCESS)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS))); + times++; SendControlMessage( PROTECTION_OFF, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE); + + EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout)); } /* * ProtocolHandler shall send Ack on session_observer accept @@ -441,7 +479,14 @@ TEST_F(ProtocolHandlerImplTest, */ TEST_F(ProtocolHandlerImplTest, StartSession_Protected_SessionObserverAccept) { SetProtocolVersion2(); - AddSession(); + + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); + + + EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout)); } // TODO(EZamakhov): add test for get_hash_id/set_hash_id from // protocol_handler_impl.cc @@ -449,7 +494,11 @@ TEST_F(ProtocolHandlerImplTest, StartSession_Protected_SessionObserverAccept) { * ProtocolHandler shall send NAck on session_observer rejection */ TEST_F(ProtocolHandlerImplTest, EndSession_SessionObserverReject) { - AddSession(); + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); + const ServiceType service = kRpc; // Expect ConnectionHandler check @@ -457,23 +506,32 @@ TEST_F(ProtocolHandlerImplTest, EndSession_SessionObserverReject) { OnSessionEndedCallback(connection_id, session_id, _, service)) . // reject session start - WillOnce(Return(SESSION_START_REJECT)); + WillOnce( + DoAll(NotifyTestAsyncWaiter(waiter), Return(SESSION_START_REJECT))); + times++; SetProtocolVersion2(); // Expect send NAck EXPECT_CALL(transport_manager_mock, SendMessageToDevice( ControlMessage(FRAME_DATA_END_SERVICE_NACK, PROTECTION_OFF))) - .WillOnce(Return(E_SUCCESS)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS))); + times++; SendControlMessage( PROTECTION_OFF, service, session_id, FRAME_DATA_END_SERVICE); + + EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout)); } /* * ProtocolHandler shall send NAck on wrong hash code */ TEST_F(ProtocolHandlerImplTest, EndSession_Success) { - AddSession(); + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); + const ServiceType service = kRpc; // Expect ConnectionHandler check @@ -481,17 +539,21 @@ TEST_F(ProtocolHandlerImplTest, EndSession_Success) { OnSessionEndedCallback(connection_id, session_id, _, service)) . // return sessions start success - WillOnce(Return(connection_key)); + WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(connection_key))); + times++; SetProtocolVersion2(); // Expect send Ack EXPECT_CALL(transport_manager_mock, SendMessageToDevice( ControlMessage(FRAME_DATA_END_SERVICE_ACK, PROTECTION_OFF))) - .WillOnce(Return(E_SUCCESS)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS))); + times++; SendControlMessage( PROTECTION_OFF, service, session_id, FRAME_DATA_END_SERVICE); + + EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout)); } #ifdef ENABLE_SECURITY @@ -500,7 +562,11 @@ TEST_F(ProtocolHandlerImplTest, EndSession_Success) { * Check session_observer with PROTECTION_OFF and Ack with PROTECTION_OFF */ TEST_F(ProtocolHandlerImplTest, SecurityEnable_StartSessionProtocoloV1) { - AddConnection(); + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); + // Add security manager AddSecurityManager(); const ServiceType start_service = kRpc; @@ -511,14 +577,17 @@ TEST_F(ProtocolHandlerImplTest, SecurityEnable_StartSessionProtocoloV1) { connection_id, NEW_SESSION_ID, start_service, PROTECTION_OFF, _)) . // Return sessions start success - WillOnce(Return(session_id)); + WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(session_id))); + times++; SetProtocolVersion2(); // Expect send Ack with PROTECTION_OFF (on no Security Manager) EXPECT_CALL(transport_manager_mock, SendMessageToDevice( ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF))) - .WillOnce(Return(E_SUCCESS)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS))) + .RetiresOnSaturation(); + times++; SendTMMessage(connection_id, PROTOCOL_VERSION_1, @@ -529,6 +598,8 @@ TEST_F(ProtocolHandlerImplTest, SecurityEnable_StartSessionProtocoloV1) { NEW_SESSION_ID, 0, message_id); + + EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout)); } /* * ProtocolHandler shall not call Security logics on start session with @@ -539,6 +610,9 @@ TEST_F(ProtocolHandlerImplTest, SecurityEnable_StartSessionUnprotected) { // Add security manager AddSecurityManager(); const ServiceType start_service = kRpc; + + TestAsyncWaiter waiter; + uint32_t times = 0; // Expect ConnectionHandler check EXPECT_CALL( session_observer_mock, @@ -546,17 +620,21 @@ TEST_F(ProtocolHandlerImplTest, SecurityEnable_StartSessionUnprotected) { connection_id, NEW_SESSION_ID, start_service, PROTECTION_OFF, _)) . // Return sessions start success - WillOnce(Return(session_id)); + WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(session_id))); + times++; SetProtocolVersion2(); // Expect send Ack with PROTECTION_OFF (on no Security Manager) EXPECT_CALL(transport_manager_mock, SendMessageToDevice( ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF))) - .WillOnce(Return(E_SUCCESS)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS))); + times++; SendControlMessage( PROTECTION_OFF, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE); + + EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout)); } /* * ProtocolHandler shall send Ack with PROTECTION_OFF on fail SLL creation @@ -565,6 +643,9 @@ TEST_F(ProtocolHandlerImplTest, SecurityEnable_StartSessionProtected_Fail) { AddConnection(); AddSecurityManager(); const ServiceType start_service = kRpc; + + TestAsyncWaiter waiter; + uint32_t times = 0; // Expect ConnectionHandler check EXPECT_CALL( session_observer_mock, @@ -572,23 +653,28 @@ TEST_F(ProtocolHandlerImplTest, SecurityEnable_StartSessionProtected_Fail) { connection_id, NEW_SESSION_ID, start_service, PROTECTION_ON, _)) . // Return sessions start success - WillOnce(Return(session_id)); + WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(session_id))); + times++; SetProtocolVersion2(); // Expect start protection for unprotected session EXPECT_CALL(security_manager_mock, CreateSSLContext(connection_key)) . // Return fail protection - WillOnce(ReturnNull()); + WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), ReturnNull())); + times++; // Expect send Ack with PROTECTION_OFF (on fail SLL creation) EXPECT_CALL(transport_manager_mock, SendMessageToDevice( ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF))) - .WillOnce(Return(E_SUCCESS)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS))); + times++; SendControlMessage( PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE); + + EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout)); } /* * ProtocolHandler shall send Ack with PROTECTION_ON on already established and @@ -599,6 +685,9 @@ TEST_F(ProtocolHandlerImplTest, AddConnection(); AddSecurityManager(); const ServiceType start_service = kRpc; + + TestAsyncWaiter waiter; + uint32_t times = 0; // Expect ConnectionHandler check EXPECT_CALL( session_observer_mock, @@ -606,33 +695,42 @@ TEST_F(ProtocolHandlerImplTest, connection_id, NEW_SESSION_ID, start_service, PROTECTION_ON, _)) . // Return sessions start success - WillOnce(Return(session_id)); + WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(session_id))); + times++; SetProtocolVersion2(); // call new SSLContext creation EXPECT_CALL(security_manager_mock, CreateSSLContext(connection_key)) . // Return new SSLContext - WillOnce(Return(&ssl_context_mock)); + WillOnce( + DoAll(NotifyTestAsyncWaiter(&waiter), Return(&ssl_context_mock))); + times++; // Initilization check EXPECT_CALL(ssl_context_mock, IsInitCompleted()) . // emulate SSL is initilized - WillOnce(Return(true)); + WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(true))); + times++; // Expect service protection enable EXPECT_CALL(session_observer_mock, - SetProtectionFlag(connection_key, start_service)); + SetProtectionFlag(connection_key, start_service)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; // Expect send Ack with PROTECTION_ON (on SSL is initilized) EXPECT_CALL(transport_manager_mock, SendMessageToDevice( ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_ON))) - .WillOnce(Return(E_SUCCESS)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS))); + times++; SendControlMessage( PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE); + + EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout)); } /* * ProtocolHandler shall send Ack with PROTECTION_OFF on session handshhake fail @@ -642,6 +740,9 @@ TEST_F(ProtocolHandlerImplTest, AddConnection(); AddSecurityManager(); const ServiceType start_service = kRpc; + + TestAsyncWaiter waiter; + uint32_t times = 0; // Expect ConnectionHandler check EXPECT_CALL( session_observer_mock, @@ -649,7 +750,8 @@ TEST_F(ProtocolHandlerImplTest, connection_id, NEW_SESSION_ID, start_service, PROTECTION_ON, _)) . // Return sessions start success - WillOnce(Return(session_id)); + WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(session_id))); + times++; std::vector<int> services; // TODO(AKutsan) : APPLINK-21398 use named constants instead of magic numbers @@ -668,13 +770,15 @@ TEST_F(ProtocolHandlerImplTest, EXPECT_CALL(ssl_context_mock, IsInitCompleted()) . // emulate SSL is not initilized - WillOnce(Return(false)); + WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(false))); + times++; // Pending handshake check EXPECT_CALL(ssl_context_mock, IsHandshakePending()) . // emulate is pending - WillOnce(Return(true)); + WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(true))); + times++; // Expect add listener for handshake result EXPECT_CALL(security_manager_mock, AddListener(_)) @@ -694,10 +798,13 @@ TEST_F(ProtocolHandlerImplTest, EXPECT_CALL(transport_manager_mock, SendMessageToDevice( ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF))) - .WillOnce(Return(E_SUCCESS)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS))); + times++; SendControlMessage( PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE); + + EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout)); } /* * ProtocolHandler shall send Ack with PROTECTION_ON on session handshhake @@ -714,6 +821,8 @@ TEST_F(ProtocolHandlerImplTest, ON_CALL(protocol_handler_settings_mock, force_protected_service()) .WillByDefault(ReturnRefOfCopy(services)); + TestAsyncWaiter waiter; + uint32_t times = 0; // Expect ConnectionHandler check EXPECT_CALL( session_observer_mock, @@ -721,52 +830,66 @@ TEST_F(ProtocolHandlerImplTest, connection_id, NEW_SESSION_ID, start_service, PROTECTION_ON, _)) . // Return sessions start success - WillOnce(Return(session_id)); + WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(session_id))); + times++; // call new SSLContext creation EXPECT_CALL(security_manager_mock, CreateSSLContext(connection_key)) . // Return new SSLContext - WillOnce(Return(&ssl_context_mock)); + WillOnce( + DoAll(NotifyTestAsyncWaiter(&waiter), Return(&ssl_context_mock))); + times++; // Initilization check EXPECT_CALL(ssl_context_mock, IsInitCompleted()) . // emulate SSL is not initilized - WillOnce(Return(false)); + WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(false))); + times++; // Pending handshake check EXPECT_CALL(ssl_context_mock, IsHandshakePending()) . // emulate is pending - WillOnce(Return(true)); + WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(true))); + times++; // Expect add listener for handshake result EXPECT_CALL(security_manager_mock, AddListener(_)) // Emulate handshake fail - .WillOnce(Invoke(OnHandshakeDoneFunctor( - connection_key, - security_manager::SSLContext::Handshake_Result_Success))); + .WillOnce( + DoAll(NotifyTestAsyncWaiter(&waiter), + Invoke(OnHandshakeDoneFunctor( + connection_key, + security_manager::SSLContext::Handshake_Result_Success)))); + times++; // Listener check SSLContext EXPECT_CALL(session_observer_mock, GetSSLContext(connection_key, start_service)) . // Emulate protection for service is not enabled - WillOnce(ReturnNull()); + WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), ReturnNull())); + times++; // Expect service protection enable EXPECT_CALL(session_observer_mock, - SetProtectionFlag(connection_key, start_service)); + SetProtectionFlag(connection_key, start_service)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; // Expect send Ack with PROTECTION_OFF (on fail handshake) EXPECT_CALL(transport_manager_mock, SendMessageToDevice( ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_ON))) - .WillOnce(Return(E_SUCCESS)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS))); + times++; SendControlMessage( PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE); + + EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout)); } /* * ProtocolHandler shall send Ack with PROTECTION_ON on session handshhake @@ -783,6 +906,8 @@ TEST_F( ON_CALL(protocol_handler_settings_mock, force_protected_service()) .WillByDefault(ReturnRefOfCopy(services)); + TestAsyncWaiter waiter; + uint32_t times = 0; // Expect ConnectionHandler check EXPECT_CALL( session_observer_mock, @@ -790,13 +915,16 @@ TEST_F( connection_id, NEW_SESSION_ID, start_service, PROTECTION_ON, _)) . // Return sessions start success - WillOnce(Return(session_id)); + WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(session_id))); + times++; // call new SSLContext creation EXPECT_CALL(security_manager_mock, CreateSSLContext(connection_key)) . // Return new SSLContext - WillOnce(Return(&ssl_context_mock)); + WillOnce( + DoAll(NotifyTestAsyncWaiter(&waiter), Return(&ssl_context_mock))); + times++; // Initilization check EXPECT_CALL(ssl_context_mock, IsInitCompleted()) @@ -808,34 +936,44 @@ TEST_F( EXPECT_CALL(ssl_context_mock, IsHandshakePending()) . // emulate is pending - WillOnce(Return(true)); + WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(true))); + times++; // Expect add listener for handshake result EXPECT_CALL(security_manager_mock, AddListener(_)) // Emulate handshake fail - .WillOnce(Invoke(OnHandshakeDoneFunctor( - connection_key, - security_manager::SSLContext::Handshake_Result_Success))); + .WillOnce( + DoAll(NotifyTestAsyncWaiter(&waiter), + Invoke(OnHandshakeDoneFunctor( + connection_key, + security_manager::SSLContext::Handshake_Result_Success)))); + times++; // Listener check SSLContext EXPECT_CALL(session_observer_mock, GetSSLContext(connection_key, start_service)) . // Emulate protection for service is not enabled - WillOnce(ReturnNull()); + WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), ReturnNull())); + times++; // Expect service protection enable EXPECT_CALL(session_observer_mock, - SetProtectionFlag(connection_key, start_service)); + SetProtectionFlag(connection_key, start_service)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; // Expect send Ack with PROTECTION_OFF (on fail handshake) EXPECT_CALL(transport_manager_mock, SendMessageToDevice( ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_ON))) - .WillOnce(Return(E_SUCCESS)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS))); + times++; SendControlMessage( PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE); + + EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout)); } /* * ProtocolHandler shall send Ack with PROTECTION_ON on session handshhake @@ -851,6 +989,8 @@ TEST_F(ProtocolHandlerImplTest, ON_CALL(protocol_handler_settings_mock, force_protected_service()) .WillByDefault(ReturnRefOfCopy(services)); + TestAsyncWaiter waiter; + uint32_t times = 0; // Expect ConnectionHandler check EXPECT_CALL( session_observer_mock, @@ -858,28 +998,35 @@ TEST_F(ProtocolHandlerImplTest, connection_id, NEW_SESSION_ID, start_service, PROTECTION_ON, _)) . // Return sessions start success - WillOnce(Return(session_id)); + WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(session_id))); + times++; // call new SSLContext creation EXPECT_CALL(security_manager_mock, CreateSSLContext(connection_key)) . // Return new SSLContext - WillOnce(Return(&ssl_context_mock)); + WillOnce( + DoAll(NotifyTestAsyncWaiter(&waiter), Return(&ssl_context_mock))); + times++; // Initilization check EXPECT_CALL(ssl_context_mock, IsInitCompleted()) . // emulate SSL is not initilized - WillOnce(Return(false)); + WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(false))); + times++; // Pending handshake check EXPECT_CALL(ssl_context_mock, IsHandshakePending()) . // emulate is pending - WillOnce(Return(false)); + WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(false))); + times++; // Wait restart handshake operation - EXPECT_CALL(security_manager_mock, StartHandshake(connection_key)); + EXPECT_CALL(security_manager_mock, StartHandshake(connection_key)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; // Expect add listener for handshake result EXPECT_CALL(security_manager_mock, AddListener(_)) @@ -903,10 +1050,13 @@ TEST_F(ProtocolHandlerImplTest, EXPECT_CALL(transport_manager_mock, SendMessageToDevice( ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_ON))) - .WillOnce(Return(E_SUCCESS)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS))); + times++; SendControlMessage( PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE); + + EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout)); } #endif // ENABLE_SECURITY @@ -915,11 +1065,16 @@ TEST_F(ProtocolHandlerImplTest, FloodVerification) { const size_t max_messages = 1000; InitProtocolHandlerImpl(period_msec, max_messages); AddConnection(); - AddSession(); + + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); // Expect flood notification to CH EXPECT_CALL(session_observer_mock, OnApplicationFloodCallBack(connection_key)) - .Times(1); + .WillOnce(NotifyTestAsyncWaiter(waiter)); + times++; ON_CALL(protocol_handler_settings_mock, message_frequency_time()) .WillByDefault(Return(period_msec)); @@ -938,13 +1093,20 @@ TEST_F(ProtocolHandlerImplTest, FloodVerification) { message_id, &some_data[0]); } + + EXPECT_TRUE(waiter->WaitFor(times, period_msec)); } + TEST_F(ProtocolHandlerImplTest, FloodVerification_ThresholdValue) { const size_t period_msec = 10000; const size_t max_messages = 1000; InitProtocolHandlerImpl(period_msec, max_messages); AddConnection(); - AddSession(); + + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); ON_CALL(protocol_handler_settings_mock, message_frequency_time()) .WillByDefault(Return(period_msec)); @@ -954,6 +1116,7 @@ TEST_F(ProtocolHandlerImplTest, FloodVerification_ThresholdValue) { // Expect NO flood notification to CH EXPECT_CALL(session_observer_mock, OnApplicationFloodCallBack(connection_key)) .Times(0); + for (size_t i = 0; i < max_messages - 1; ++i) { SendTMMessage(connection_id, PROTOCOL_VERSION_3, @@ -966,13 +1129,20 @@ TEST_F(ProtocolHandlerImplTest, FloodVerification_ThresholdValue) { message_id, &some_data[0]); } + + EXPECT_TRUE(waiter->WaitFor(times, period_msec)); } + TEST_F(ProtocolHandlerImplTest, FloodVerification_VideoFrameSkip) { const size_t period_msec = 10000; const size_t max_messages = 1000; InitProtocolHandlerImpl(period_msec, max_messages); AddConnection(); - AddSession(); + + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); // Expect NO flood notification to CH on video data streaming for (size_t i = 0; i < max_messages + 1; ++i) { @@ -987,13 +1157,20 @@ TEST_F(ProtocolHandlerImplTest, FloodVerification_VideoFrameSkip) { message_id, &some_data[0]); } + + EXPECT_TRUE(waiter->WaitFor(times, period_msec)); } + TEST_F(ProtocolHandlerImplTest, FloodVerification_AudioFrameSkip) { const size_t period_msec = 10000; const size_t max_messages = 1000; InitProtocolHandlerImpl(period_msec, max_messages); AddConnection(); - AddSession(); + + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); // Expect NO flood notification to CH on video data streaming for (size_t i = 0; i < max_messages + 1; ++i) { @@ -1008,13 +1185,20 @@ TEST_F(ProtocolHandlerImplTest, FloodVerification_AudioFrameSkip) { message_id, &some_data[0]); } + + EXPECT_TRUE(waiter->WaitFor(times, period_msec)); } + TEST_F(ProtocolHandlerImplTest, FloodVerificationDisable) { const size_t period_msec = 0; const size_t max_messages = 0; InitProtocolHandlerImpl(period_msec, max_messages); AddConnection(); - AddSession(); + + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); // Expect NO flood notification to session observer for (size_t i = 0; i < max_messages + 1; ++i) { @@ -1029,6 +1213,8 @@ TEST_F(ProtocolHandlerImplTest, FloodVerificationDisable) { message_id, &some_data[0]); } + + EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout)); } TEST_F(ProtocolHandlerImplTest, MalformedVerificationDisable) { @@ -1036,7 +1222,11 @@ TEST_F(ProtocolHandlerImplTest, MalformedVerificationDisable) { const size_t max_messages = 100; InitProtocolHandlerImpl(0u, 0u, false, period_msec, max_messages); AddConnection(); - AddSession(); + + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); // Expect malformed notification to CH EXPECT_CALL(session_observer_mock, OnMalformedMessageCallback(connection_id)) @@ -1055,6 +1245,8 @@ TEST_F(ProtocolHandlerImplTest, MalformedVerificationDisable) { message_id, &some_data[0]); } + + EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout)); } TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification) { @@ -1062,11 +1254,16 @@ TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification) { const size_t max_messages = 100; InitProtocolHandlerImpl(0u, 0u, true, period_msec, max_messages); AddConnection(); - AddSession(); + + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); // Expect malformed notification to CH EXPECT_CALL(session_observer_mock, OnMalformedMessageCallback(connection_id)) - .Times(1); + .WillOnce(NotifyTestAsyncWaiter(waiter)); + times++; // Sending malformed packets const uint8_t malformed_version = PROTOCOL_VERSION_MAX; @@ -1094,6 +1291,8 @@ TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification) { message_id, &some_data[0]); } + + EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout)); } TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification_MalformedStock) { @@ -1101,11 +1300,16 @@ TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification_MalformedStock) { const size_t max_messages = 100; InitProtocolHandlerImpl(0u, 0u, true, period_msec, max_messages); AddConnection(); - AddSession(); + + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); // Expect malformed notification to CH EXPECT_CALL(session_observer_mock, OnMalformedMessageCallback(connection_id)) - .Times(1); + .WillOnce(NotifyTestAsyncWaiter(waiter)); + times++; // Sending malformed packets const uint8_t malformed_version = PROTOCOL_VERSION_MAX; @@ -1158,6 +1362,8 @@ TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification_MalformedStock) { message_id, &some_data[0]); } + + EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout)); } TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification_MalformedOnly) { @@ -1165,7 +1371,11 @@ TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification_MalformedOnly) { const size_t max_messages = 100; InitProtocolHandlerImpl(0u, 0u, true, period_msec, max_messages); AddConnection(); - AddSession(); + + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); // Expect NO malformed notification to CH EXPECT_CALL(session_observer_mock, OnMalformedMessageCallback(connection_id)) @@ -1212,6 +1422,8 @@ TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification_MalformedOnly) { // No common message } + + EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout)); } TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification_NullTimePeriod) { @@ -1219,7 +1431,11 @@ TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification_NullTimePeriod) { const size_t max_messages = 1000; InitProtocolHandlerImpl(0u, 0u, true, period_msec, max_messages); AddConnection(); - AddSession(); + + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); // Expect no malformed notification to CH EXPECT_CALL(session_observer_mock, OnMalformedMessageCallback(connection_id)) @@ -1239,13 +1455,20 @@ TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification_NullTimePeriod) { message_id, &some_data[0]); } + + EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout)); } + TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification_NullCount) { const size_t period_msec = 10000; const size_t max_messages = 0; InitProtocolHandlerImpl(0u, 0u, true, period_msec, max_messages); AddConnection(); - AddSession(); + + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); // Expect no malformed notification to CH EXPECT_CALL(session_observer_mock, OnMalformedMessageCallback(connection_id)) @@ -1265,6 +1488,8 @@ TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification_NullCount) { message_id, &some_data[0]); } + + EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout)); } TEST_F(ProtocolHandlerImplTest, @@ -1275,13 +1500,18 @@ TEST_F(ProtocolHandlerImplTest, .WillOnce(Return(false)); // Expect not send End Service EXPECT_CALL(transport_manager_mock, SendMessageToDevice(_)).Times(0); + // Act protocol_handler_impl->SendEndSession(connection_id, session_id); } TEST_F(ProtocolHandlerImplTest, SendEndServicePrivate_EndSession_MessageSent) { // Arrange - AddSession(); + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); + // Expect check connection with ProtocolVersionUsed EXPECT_CALL(session_observer_mock, ProtocolVersionUsed(connection_id, session_id, _)) @@ -1294,12 +1524,18 @@ TEST_F(ProtocolHandlerImplTest, SendEndServicePrivate_EndSession_MessageSent) { .WillOnce(Return(E_SUCCESS)); // Act protocol_handler_impl->SendEndSession(connection_id, session_id); + + EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout)); } TEST_F(ProtocolHandlerImplTest, SendEndServicePrivate_ServiceTypeControl_MessageSent) { // Arrange - AddSession(); + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); + // Expect check connection with ProtocolVersionUsed EXPECT_CALL(session_observer_mock, ProtocolVersionUsed(connection_id, session_id, _)) @@ -1310,9 +1546,13 @@ TEST_F(ProtocolHandlerImplTest, FRAME_DATA_END_SERVICE, PROTECTION_OFF, kControl))) - .WillOnce(Return(E_SUCCESS)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS))); + times++; + // Act protocol_handler_impl->SendEndService(connection_id, session_id, kControl); + + EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout)); } TEST_F(ProtocolHandlerImplTest, SendHeartBeat_NoConnection_NotSent) { @@ -1322,13 +1562,18 @@ TEST_F(ProtocolHandlerImplTest, SendHeartBeat_NoConnection_NotSent) { .WillOnce(Return(false)); // Expect not send HeartBeat EXPECT_CALL(transport_manager_mock, SendMessageToDevice(_)).Times(0); + // Act protocol_handler_impl->SendHeartBeat(connection_id, session_id); } TEST_F(ProtocolHandlerImplTest, SendHeartBeat_Successful) { // Arrange - AddSession(); + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); + // Expect check connection with ProtocolVersionUsed EXPECT_CALL(session_observer_mock, ProtocolVersionUsed(connection_id, session_id, _)) @@ -1339,13 +1584,20 @@ TEST_F(ProtocolHandlerImplTest, SendHeartBeat_Successful) { SendMessageToDevice(ExpectedMessage( FRAME_TYPE_CONTROL, FRAME_DATA_HEART_BEAT, PROTECTION_OFF, kControl))) .WillOnce(Return(E_SUCCESS)); + // Act protocol_handler_impl->SendHeartBeat(connection_id, session_id); + + EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout)); } TEST_F(ProtocolHandlerImplTest, SendHeartBeatAck_Successful) { // Arrange - AddSession(); + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); + // Expect double check connection and protocol version with // ProtocolVersionUsed EXPECT_CALL(session_observer_mock, ProtocolVersionUsed(connection_id, _, _)) @@ -1357,15 +1609,23 @@ TEST_F(ProtocolHandlerImplTest, SendHeartBeatAck_Successful) { FRAME_DATA_HEART_BEAT_ACK, PROTECTION_OFF, kControl))) - .WillOnce(Return(E_SUCCESS)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS))); + times++; + // Act SendControlMessage( PROTECTION_OFF, kControl, session_id, FRAME_DATA_HEART_BEAT); + + EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout)); } TEST_F(ProtocolHandlerImplTest, SendHeartBeatAck_WrongProtocolVersion_NotSent) { // Arrange - AddSession(); + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); + // Expect two checks of connection and protocol version with // ProtocolVersionUsed EXPECT_CALL(session_observer_mock, ProtocolVersionUsed(connection_id, _, _)) @@ -1383,12 +1643,18 @@ TEST_F(ProtocolHandlerImplTest, SendHeartBeatAck_WrongProtocolVersion_NotSent) { PROTECTION_OFF, kControl, session_id, FRAME_DATA_HEART_BEAT); SendControlMessage( PROTECTION_OFF, kControl, session_id, FRAME_DATA_HEART_BEAT); + + EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout)); } TEST_F(ProtocolHandlerImplTest, SendMessageToMobileApp_SendSingleControlMessage) { // Arrange - AddSession(); + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); + const bool is_final = true; const uint32_t total_data_size = 1; UCharDataVector data(total_data_size); @@ -1399,8 +1665,8 @@ TEST_F(ProtocolHandlerImplTest, PairFromKey(message->connection_key(), _, _)) .WillOnce( DoAll(SetArgPointee<1>(connection_id), SetArgPointee<2>(session_id))); -// Expect getting ssl context #ifdef ENABLE_SECURITY + // Expect getting ssl context EXPECT_CALL(session_observer_mock, GetSSLContext(message->connection_key(), message->service_type())) .WillOnce(Return(&ssl_context_mock)); @@ -1411,14 +1677,21 @@ TEST_F(ProtocolHandlerImplTest, SendMessageToDevice(ExpectedMessage( FRAME_TYPE_SINGLE, FRAME_DATA_SINGLE, PROTECTION_OFF, kControl))) .WillOnce(Return(E_SUCCESS)); + // Act protocol_handler_impl->SendMessageToMobileApp(message, is_final); + + EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout)); } TEST_F(ProtocolHandlerImplTest, SendMessageToMobileApp_SendSingleNonControlMessage) { // Arrange - AddSession(); + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); + const bool is_final = true; const uint32_t total_data_size = 1; UCharDataVector data(total_data_size); @@ -1429,26 +1702,38 @@ TEST_F(ProtocolHandlerImplTest, PairFromKey(message->connection_key(), _, _)) .WillOnce( DoAll(SetArgPointee<1>(connection_id), SetArgPointee<2>(session_id))); -// Expect getting ssl context + #ifdef ENABLE_SECURITY + // Expect getting ssl context EXPECT_CALL(session_observer_mock, GetSSLContext(message->connection_key(), message->service_type())) .Times(2) - .WillRepeatedly(Return(&ssl_context_mock)); + .WillRepeatedly( + DoAll(NotifyTestAsyncWaiter(waiter), Return(&ssl_context_mock))); + times += 2; AddSecurityManager(); #endif // ENABLE_SECURITY + // Expect send message to mobile EXPECT_CALL(transport_manager_mock, SendMessageToDevice(ExpectedMessage( FRAME_TYPE_SINGLE, FRAME_DATA_SINGLE, PROTECTION_OFF, kRpc))) - .WillOnce(Return(E_SUCCESS)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS))); + times++; + // Act protocol_handler_impl->SendMessageToMobileApp(message, is_final); + + EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout)); } TEST_F(ProtocolHandlerImplTest, SendMessageToMobileApp_SendMultiframeMessage) { // Arrange - AddSession(); + ::utils::SharedPtr<TestAsyncWaiter> waiter = utils::MakeShared<TestAsyncWaiter>(); + uint32_t times = 0; + + AddSession(waiter, times); + const bool is_final = true; const uint32_t total_data_size = MAXIMUM_FRAME_DATA_V2_SIZE * 2; UCharDataVector data(total_data_size); @@ -1460,33 +1745,41 @@ TEST_F(ProtocolHandlerImplTest, SendMessageToMobileApp_SendMultiframeMessage) { PairFromKey(message->connection_key(), _, _)) .WillOnce( DoAll(SetArgPointee<1>(connection_id), SetArgPointee<2>(session_id))); -// Expect getting ssl context #ifdef ENABLE_SECURITY + // Expect getting ssl context EXPECT_CALL(session_observer_mock, GetSSLContext(message->connection_key(), message->service_type())) .Times(4) - .WillRepeatedly(Return(&ssl_context_mock)); + .WillRepeatedly( + DoAll(NotifyTestAsyncWaiter(waiter), Return(&ssl_context_mock))); + times += 4; AddSecurityManager(); #endif // ENABLE_SECURITY // Expect sending message frame by frame to mobile EXPECT_CALL(transport_manager_mock, SendMessageToDevice(ExpectedMessage( FRAME_TYPE_FIRST, FRAME_DATA_FIRST, PROTECTION_OFF, kBulk))) - .WillOnce(Return(E_SUCCESS)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS))); + times++; EXPECT_CALL(transport_manager_mock, SendMessageToDevice(ExpectedMessage(FRAME_TYPE_CONSECUTIVE, first_consecutive_frame, PROTECTION_OFF, kBulk))) - .WillOnce(Return(E_SUCCESS)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS))); + times++; EXPECT_CALL(transport_manager_mock, SendMessageToDevice(ExpectedMessage(FRAME_TYPE_CONSECUTIVE, FRAME_DATA_LAST_CONSECUTIVE, PROTECTION_OFF, kBulk))) - .WillOnce(Return(E_SUCCESS)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS))); + times++; + // Act protocol_handler_impl->SendMessageToMobileApp(message, is_final); + + EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout)); } } // namespace protocol_handler_test diff --git a/src/components/security_manager/test/crypto_manager_impl_test.cc b/src/components/security_manager/test/crypto_manager_impl_test.cc index 27f91866ac..7fef33f1df 100644 --- a/src/components/security_manager/test/crypto_manager_impl_test.cc +++ b/src/components/security_manager/test/crypto_manager_impl_test.cc @@ -91,7 +91,6 @@ class CryptoManagerTest : public testing::Test { void TearDown() OVERRIDE { delete mock_security_manager_settings_; - testing::Mock::AsyncVerifyAndClearExpectations(1000); } void InitSecurityManager() { diff --git a/src/components/security_manager/test/security_manager_test.cc b/src/components/security_manager/test/security_manager_test.cc index b5f9ae2e78..7c1958ad9c 100644 --- a/src/components/security_manager/test/security_manager_test.cc +++ b/src/components/security_manager/test/security_manager_test.cc @@ -44,6 +44,7 @@ #include "security_manager/mock_crypto_manager.h" #include "security_manager/mock_security_manager_listener.h" #include "utils/make_shared.h" +#include "utils/test_async_waiter.h" namespace test { namespace components { @@ -72,6 +73,7 @@ using ::testing::DoAll; using ::testing::SetArgPointee; using ::testing::_; +namespace { // Sample data for handshake data emulation const int32_t key = 0x1; const int32_t seq_number = 0x2; @@ -87,6 +89,8 @@ uint8_t handshake_data_out[] = {0x6, 0x7, 0x8}; uint8_t* handshake_data_out_pointer = handshake_data_out; const size_t handshake_data_out_size = sizeof(handshake_data_out) / sizeof(handshake_data_out[0]); +const uint32_t kAsyncExpectationsTimeout = 10000u; +} class SecurityManagerTest : public ::testing::Test { protected: @@ -96,10 +100,6 @@ class SecurityManagerTest : public ::testing::Test { security_manager_->set_protocol_handler(&mock_protocol_handler); security_manager_->AddListener(&mock_sm_listener); } - void TearDown() OVERRIDE { - // Wait call methods in thread - testing::Mock::AsyncVerifyAndClearExpectations(1000); - } void SetMockCryptoManager() { EXPECT_CALL(mock_crypto_manager, IsCertificateUpdateRequired()) @@ -268,7 +268,8 @@ TEST_F(SecurityManagerTest, SecurityManager_NULLCryptoManager) { // Expect InternalError with ERROR_ID uint32_t connection_id = 0; uint8_t session_id = 0; - // uint8_t protocol_version = 0; + + TestAsyncWaiter waiter; EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _)); EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id, _)) @@ -277,12 +278,14 @@ TEST_F(SecurityManagerTest, SecurityManager_NULLCryptoManager) { EXPECT_CALL(mock_protocol_handler, SendMessageToMobileApp( InternalErrorWithErrId(SecurityManager::ERROR_NOT_SUPPORTED), - is_final)); + is_final)).WillOnce(NotifyTestAsyncWaiter(&waiter)); const SecurityQuery::QueryHeader header(SecurityQuery::REQUEST, // It could be any query id SecurityQuery::INVALID_QUERY_ID); const uint8_t data = 0; EmulateMobileMessage(header, &data, 1); + + EXPECT_TRUE(waiter.WaitFor(1, kAsyncExpectationsTimeout)); } /* * Shall skip all OnMobileMessageSent @@ -354,21 +357,30 @@ TEST_F(SecurityManagerTest, GetInvalidQueryId) { SetMockCryptoManager(); uint32_t connection_id = 0; uint8_t session_id = 0; - // uint8_t protocol_version = 0; - EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _)); + + TestAsyncWaiter waiter; + uint32_t times = 0; + EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id, _)) - .WillOnce(Return(true)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(true))); + times++; + // Expect InternalError with ERROR_ID EXPECT_CALL( mock_protocol_handler, SendMessageToMobileApp( InternalErrorWithErrId(SecurityManager::ERROR_INVALID_QUERY_ID), - is_final)); + is_final)).WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; const SecurityQuery::QueryHeader header(SecurityQuery::REQUEST, SecurityQuery::INVALID_QUERY_ID); const uint8_t data = 0; EmulateMobileMessage(header, &data, 1); + + EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout)); } /* * Shall send Internall Error on call @@ -608,7 +620,8 @@ TEST_F(SecurityManagerTest, ProccessHandshakeData_WrongDataSize) { SetMockCryptoManager(); uint32_t connection_id = 0; uint8_t session_id = 0; - // uint8_t protocol_version = 0; + + TestAsyncWaiter waiter; EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _)); EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id, _)) @@ -619,8 +632,11 @@ TEST_F(SecurityManagerTest, ProccessHandshakeData_WrongDataSize) { mock_protocol_handler, SendMessageToMobileApp( InternalErrorWithErrId(SecurityManager::ERROR_INVALID_QUERY_SIZE), - is_final)); + is_final)).WillOnce(NotifyTestAsyncWaiter(&waiter)); + EmulateMobileMessageHandshake(NULL, 0); + + EXPECT_TRUE(waiter.WaitFor(1, kAsyncExpectationsTimeout)); } /* * Shall send InternallError on @@ -632,28 +648,38 @@ TEST_F(SecurityManagerTest, ProccessHandshakeData_ServiceNotProtected) { // Expect InternalError with ERROR_ID uint32_t connection_id = 0; uint8_t session_id = 0; - // uint8_t protocol_version = 0; - EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _)); + + TestAsyncWaiter waiter; + uint32_t times = 0; + EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id, _)) - .WillOnce(Return(true)); - + .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(true))); + times++; EXPECT_CALL( mock_protocol_handler, SendMessageToMobileApp( InternalErrorWithErrId(SecurityManager::ERROR_SERVICE_NOT_PROTECTED), - is_final)); + is_final)).WillOnce(NotifyTestAsyncWaiter(&waiter)); + times++; + // Expect notifying listeners (unsuccess) EXPECT_CALL(mock_sm_listener, OnHandshakeDone(key, SSLContext::Handshake_Result_Fail)) - .WillOnce(Return(true)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(true))); + times++; // Emulate SessionObserver result EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl)) - .WillOnce(ReturnNull()); + .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), ReturnNull())); + times++; const uint8_t data[] = {0x1, 0x2}; EmulateMobileMessageHandshake(data, sizeof(data) / sizeof(data[0])); + + EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout)); } /* * Shall send InternallError on getting @@ -668,29 +694,39 @@ TEST_F(SecurityManagerTest, ProccessHandshakeData_InvalidData) { uint32_t connection_id = 0; uint8_t session_id = 0; - // uint8_t protocol_version = 0; + + TestAsyncWaiter waiter; + uint32_t times = 0; EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _)) - .Times(handshake_emulates); + .Times(handshake_emulates) + .WillRepeatedly(NotifyTestAsyncWaiter(&waiter)); + times += handshake_emulates; EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id, _)) .Times(handshake_emulates) - .WillRepeatedly(Return(true)); + .WillRepeatedly(DoAll(NotifyTestAsyncWaiter(&waiter), Return(true))); + times += handshake_emulates; // Expect InternalError with ERROR_ID EXPECT_CALL( mock_protocol_handler, SendMessageToMobileApp( InternalErrorWithErrId(SecurityManager::ERROR_SSL_INVALID_DATA), - is_final)).Times(handshake_emulates); + is_final)) + .Times(handshake_emulates) + .WillRepeatedly(NotifyTestAsyncWaiter(&waiter)); + times += handshake_emulates; // Expect notifying listeners (unsuccess) EXPECT_CALL(mock_sm_listener, OnHandshakeDone(key, SSLContext::Handshake_Result_Fail)) - .WillOnce(Return(true)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(true))); + times++; // Emulate SessionObserver and CryptoManager result EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl)) .Times(handshake_emulates) .WillRepeatedly(Return(&mock_ssl_context_exists)); + // Emulate DoHandshakeStep fail logics EXPECT_CALL( mock_ssl_context_exists, @@ -700,16 +736,21 @@ TEST_F(SecurityManagerTest, ProccessHandshakeData_InvalidData) { _)) .WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer), SetArgPointee<3>(handshake_data_out_size), + NotifyTestAsyncWaiter(&waiter), Return(SSLContext::Handshake_Result_AbnormalFail))) .WillOnce(DoAll(SetArgPointee<2>((uint8_t*)NULL), SetArgPointee<3>(handshake_data_out_size), + NotifyTestAsyncWaiter(&waiter), Return(SSLContext::Handshake_Result_AbnormalFail))) .WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer), SetArgPointee<3>(0), + NotifyTestAsyncWaiter(&waiter), Return(SSLContext::Handshake_Result_AbnormalFail))) .WillOnce(DoAll(SetArgPointee<2>((uint8_t*)NULL), SetArgPointee<3>(0), + NotifyTestAsyncWaiter(&waiter), Return(SSLContext::Handshake_Result_AbnormalFail))); + times += 4; // matches to each single call above // On each wrong handshake will be asked error EXPECT_CALL(mock_ssl_context_exists, LastError()).Times(handshake_emulates); @@ -717,6 +758,8 @@ TEST_F(SecurityManagerTest, ProccessHandshakeData_InvalidData) { // Emulate handshare #handshake_emulates times for 5 cases EmulateMobileMessageHandshake( handshake_data, handshake_data_size, handshake_emulates); + + EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout)); } /* * Shall send HandshakeData on getting SEND_HANDSHAKE_DATA from mobile side @@ -729,31 +772,44 @@ TEST_F(SecurityManagerTest, ProccessHandshakeData_Answer) { uint32_t connection_id = 0; uint8_t session_id = 0; - // uint8_t protocol_version = 0; + + TestAsyncWaiter waiter; + uint32_t times = 0; EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _)) - .Times(handshake_emulates); + .Times(handshake_emulates) + .WillRepeatedly(NotifyTestAsyncWaiter(&waiter)); + times += handshake_emulates; EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id, _)) .Times(handshake_emulates) - .WillRepeatedly(Return(true)); + .WillRepeatedly(DoAll(NotifyTestAsyncWaiter(&waiter), Return(true))); + times += handshake_emulates; // Get size of raw message after const size_t raw_message_size = 15; - EXPECT_CALL(mock_protocol_handler, - SendMessageToMobileApp(RawMessageEqSize(raw_message_size), - is_final)).Times(handshake_emulates); + EXPECT_CALL( + mock_protocol_handler, + SendMessageToMobileApp(RawMessageEqSize(raw_message_size), is_final)) + .Times(handshake_emulates) + .WillRepeatedly(NotifyTestAsyncWaiter(&waiter)); + times += handshake_emulates; + // Expect notifying listeners (unsuccess) EXPECT_CALL(mock_sm_listener, OnHandshakeDone(key, SSLContext::Handshake_Result_Fail)) - .WillOnce(Return(true)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(true))); + times++; // Emulate SessionObserver and CryptoManager result EXPECT_CALL(mock_ssl_context_exists, IsInitCompleted()) .Times(handshake_emulates) - .WillRepeatedly(Return(false)); + .WillRepeatedly(DoAll(NotifyTestAsyncWaiter(&waiter), Return(false))); + times += handshake_emulates; EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl)) .Times(handshake_emulates) - .WillRepeatedly(Return(&mock_ssl_context_exists)); + .WillRepeatedly(DoAll(NotifyTestAsyncWaiter(&waiter), + Return(&mock_ssl_context_exists))); + times += handshake_emulates; // Emulate DoHandshakeStep correct logics EXPECT_CALL( @@ -764,13 +820,18 @@ TEST_F(SecurityManagerTest, ProccessHandshakeData_Answer) { _)) .WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer), SetArgPointee<3>(handshake_data_out_size), + NotifyTestAsyncWaiter(&waiter), Return(SSLContext::Handshake_Result_Success))) .WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer), SetArgPointee<3>(handshake_data_out_size), + NotifyTestAsyncWaiter(&waiter), Return(SSLContext::Handshake_Result_Fail))); + times += 2; // matches to each single call above EmulateMobileMessageHandshake( handshake_data, handshake_data_size, handshake_emulates); + + EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout)); } /* * Shall call all listeners on success end handshake @@ -781,19 +842,26 @@ TEST_F(SecurityManagerTest, ProccessHandshakeData_HandshakeFinished) { SetMockCryptoManager(); // Count handshake calls const int handshake_emulates = 6; + + TestAsyncWaiter waiter; + uint32_t times = 0; // Expect no errors // Expect notifying listeners (success) EXPECT_CALL(mock_sm_listener, OnHandshakeDone(key, SSLContext::Handshake_Result_Success)) - .WillOnce(Return(true)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(true))); + times++; // Emulate SessionObserver and CryptoManager result EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl)) .Times(handshake_emulates) - .WillRepeatedly(Return(&mock_ssl_context_exists)); + .WillRepeatedly(DoAll(NotifyTestAsyncWaiter(&waiter), + Return(&mock_ssl_context_exists))); + times += handshake_emulates; EXPECT_CALL(mock_ssl_context_exists, IsInitCompleted()) .Times(handshake_emulates) - .WillRepeatedly(Return(true)); + .WillRepeatedly(DoAll(NotifyTestAsyncWaiter(&waiter), Return(true))); + times += handshake_emulates; EXPECT_CALL( mock_ssl_context_exists, @@ -805,26 +873,33 @@ TEST_F(SecurityManagerTest, ProccessHandshakeData_HandshakeFinished) { // two states with correct out data WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer), SetArgPointee<3>(handshake_data_out_size), + NotifyTestAsyncWaiter(&waiter), Return(SSLContext::Handshake_Result_Success))) .WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer), SetArgPointee<3>(handshake_data_out_size), + NotifyTestAsyncWaiter(&waiter), Return(SSLContext::Handshake_Result_Fail))) . // two states with with null pointer data WillOnce(DoAll(SetArgPointee<2>((uint8_t*)NULL), SetArgPointee<3>(handshake_data_out_size), + NotifyTestAsyncWaiter(&waiter), Return(SSLContext::Handshake_Result_Success))) .WillOnce(DoAll(SetArgPointee<2>((uint8_t*)NULL), SetArgPointee<3>(handshake_data_out_size), + NotifyTestAsyncWaiter(&waiter), Return(SSLContext::Handshake_Result_Fail))) . // two states with with null data size WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer), SetArgPointee<3>(0), + NotifyTestAsyncWaiter(&waiter), Return(SSLContext::Handshake_Result_Success))) .WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer), SetArgPointee<3>(0), + NotifyTestAsyncWaiter(&waiter), Return(SSLContext::Handshake_Result_Success))); + times += 6; // matches to each single call above // Expect send two message (with correct pointer and size data) @@ -835,14 +910,19 @@ TEST_F(SecurityManagerTest, ProccessHandshakeData_HandshakeFinished) { EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id, _)) .Times(2) - .WillRepeatedly(Return(true)); + .WillRepeatedly(DoAll(NotifyTestAsyncWaiter(&waiter), Return(true))); + times += 2; // matches to the number above EXPECT_CALL(mock_protocol_handler, SendMessageToMobileApp(_, is_final)) - .Times(2); + .Times(2) + .WillRepeatedly(NotifyTestAsyncWaiter(&waiter)); + times += 2; // matches to the number above // Expect NO InternalError with ERROR_ID EmulateMobileMessageHandshake( handshake_data, handshake_data_size, handshake_emulates); + + EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout)); } /* * Shall not any query on getting empty SEND_INTERNAL_ERROR diff --git a/src/components/transport_manager/test/transport_manager_impl_test.cc b/src/components/transport_manager/test/transport_manager_impl_test.cc index 6700eab7fb..f3b32c214d 100644 --- a/src/components/transport_manager/test/transport_manager_impl_test.cc +++ b/src/components/transport_manager/test/transport_manager_impl_test.cc @@ -35,23 +35,22 @@ #include "protocol/raw_message.h" #include "transport_manager/common.h" #include "transport_manager/transport_manager_impl.h" - #include "transport_manager/mock_telemetry_observer.h" #include "transport_manager/mock_transport_manager_listener.h" #include "transport_manager/mock_telemetry_observer.h" #include "transport_manager/transport_adapter/mock_transport_adapter.h" #include "transport_manager/mock_transport_manager_impl.h" #include "transport_manager/mock_transport_manager_settings.h" -#include "utils/make_shared.h" -#include "utils/shared_ptr.h" - #include "resumption/last_state_impl.h" +#include "utils/shared_ptr.h" #include "utils/make_shared.h" +#include "utils/test_async_waiter.h" using ::testing::_; using ::testing::AtLeast; using ::testing::Return; using ::testing::ReturnRef; +using ::testing::DoAll; using ::protocol_handler::RawMessage; using ::protocol_handler::RawMessagePtr; @@ -62,9 +61,11 @@ namespace test { namespace components { namespace transport_manager_test { +namespace { const std::string kAppStorageFolder = "app_storage_folder"; const std::string kAppInfoFolder = "app_info_folder"; -const int kAsyncExpectationsTimeout = 10000; +const uint32_t kAsyncExpectationsTimeout = 10000u; +} class TransportManagerImplTest : public ::testing::Test { protected: @@ -126,6 +127,7 @@ class TransportManagerImplTest : public ::testing::Test { EXPECT_CALL(*tm_listener_, OnDeviceFound(dev_info_)); EXPECT_CALL(*tm_listener_, OnDeviceAdded(dev_info_)); + EXPECT_CALL(*tm_listener_, OnDeviceListUpdated(vector_dev_info)); tm_.TestHandle(test_event); device_list_.pop_back(); @@ -490,16 +492,19 @@ TEST_F(TransportManagerImplTest, SendMessageToDevice) { // Arrange HandleConnection(); + TestAsyncWaiter waiter; EXPECT_CALL(*mock_adapter_, SendData(mac_address_, application_id_, test_message_)) - .WillOnce(Return(TransportAdapter::OK)); + .WillOnce( + DoAll(NotifyTestAsyncWaiter(&waiter), Return(TransportAdapter::OK))); #ifdef TELEMETRY_MONITOR EXPECT_CALL(mock_metric_observer_, StartRawMsg(test_message_.get())); #endif // TELEMETRY_MONITOR EXPECT_EQ(E_SUCCESS, tm_.SendMessageToDevice(test_message_)); - testing::Mock::AsyncVerifyAndClearExpectations(kAsyncExpectationsTimeout); + + EXPECT_TRUE(waiter.WaitFor(1, kAsyncExpectationsTimeout)); } TEST_F(TransportManagerImplTest, SendMessageToDevice_SendingFailed) { @@ -510,66 +515,81 @@ TEST_F(TransportManagerImplTest, SendMessageToDevice_SendingFailed) { EXPECT_CALL(mock_metric_observer_, StartRawMsg(_)); #endif // TELEMETRY_MONITOR + TestAsyncWaiter waiter; EXPECT_CALL(*mock_adapter_, SendData(mac_address_, application_id_, test_message_)) .WillOnce(Return(TransportAdapter::FAIL)); - EXPECT_CALL(*tm_listener_, OnTMMessageSendFailed(_, test_message_)); + EXPECT_CALL(*tm_listener_, OnTMMessageSendFailed(_, test_message_)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); EXPECT_EQ(E_SUCCESS, tm_.SendMessageToDevice(test_message_)); #ifdef TELEMETRY_MONITOR EXPECT_CALL(mock_metric_observer_, StopRawMsg(_)).Times(0); #endif // TELEMETRY_MONITOR - testing::Mock::AsyncVerifyAndClearExpectations(kAsyncExpectationsTimeout); + EXPECT_TRUE(waiter.WaitFor(1, kAsyncExpectationsTimeout)); } TEST_F(TransportManagerImplTest, SendMessageToDevice_StartTimeObserver) { // Arrange HandleConnection(); + + TestAsyncWaiter waiter; EXPECT_CALL(*mock_adapter_, SendData(mac_address_, application_id_, test_message_)) - .WillOnce(Return(TransportAdapter::OK)); + .WillOnce( + DoAll(NotifyTestAsyncWaiter(&waiter), Return(TransportAdapter::OK))); #ifdef TELEMETRY_MONITOR EXPECT_CALL(mock_metric_observer_, StartRawMsg(_)); #endif // TELEMETRY_MONITOR EXPECT_EQ(E_SUCCESS, tm_.SendMessageToDevice(test_message_)); - testing::Mock::AsyncVerifyAndClearExpectations(kAsyncExpectationsTimeout); + + EXPECT_TRUE(waiter.WaitFor(1, kAsyncExpectationsTimeout)); } TEST_F(TransportManagerImplTest, SendMessageToDevice_SendDone) { // Arrange HandleConnection(); + TestAsyncWaiter waiter; EXPECT_CALL(*mock_adapter_, SendData(mac_address_, application_id_, test_message_)) - .WillOnce(Return(TransportAdapter::OK)); + .WillOnce( + DoAll(NotifyTestAsyncWaiter(&waiter), Return(TransportAdapter::OK))); + #ifdef TELEMETRY_MONITOR EXPECT_CALL(mock_metric_observer_, StartRawMsg(test_message_.get())); #endif // TELEMETRY_MONITOR + EXPECT_EQ(E_SUCCESS, tm_.SendMessageToDevice(test_message_)); HandleSendDone(); - testing::Mock::AsyncVerifyAndClearExpectations(kAsyncExpectationsTimeout); + EXPECT_TRUE(waiter.WaitFor(1, kAsyncExpectationsTimeout)); } TEST_F(TransportManagerImplTest, SendMessageFailed_GetHandleSendFailed) { // Arrange HandleConnection(); + TestAsyncWaiter waiter; EXPECT_CALL(*mock_adapter_, SendData(mac_address_, application_id_, test_message_)) - .WillOnce(Return(TransportAdapter::FAIL)); + .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), + Return(TransportAdapter::FAIL))); + #ifdef TELEMETRY_MONITOR EXPECT_CALL(mock_metric_observer_, StartRawMsg(test_message_.get())); #endif // TELEMETRY_MONITOR + EXPECT_CALL(*tm_listener_, OnTMMessageSendFailed(_, test_message_)); EXPECT_EQ(E_SUCCESS, tm_.SendMessageToDevice(test_message_)); HandleSendFailed(); - testing::Mock::AsyncVerifyAndClearExpectations(kAsyncExpectationsTimeout); + + EXPECT_TRUE(waiter.WaitFor(1, kAsyncExpectationsTimeout)); } TEST_F(TransportManagerImplTest, RemoveDevice_DeviceWasAdded) { @@ -660,6 +680,7 @@ TEST_F(TransportManagerImplTest, ReceiveEventFromDevice_OnSearchDeviceDone) { const int type = static_cast<int>( TransportAdapterListenerImpl::EventTypeEnum::ON_SEARCH_DONE); + TestAsyncWaiter waiter; TransportAdapterEvent test_event(type, mock_adapter_, mac_address_, @@ -667,16 +688,19 @@ TEST_F(TransportManagerImplTest, ReceiveEventFromDevice_OnSearchDeviceDone) { test_message_, error_); - EXPECT_CALL(*tm_listener_, OnScanDevicesFinished()); + EXPECT_CALL(*tm_listener_, OnScanDevicesFinished()) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); tm_.ReceiveEventFromDevice(test_event); - testing::Mock::AsyncVerifyAndClearExpectations(kAsyncExpectationsTimeout); + + EXPECT_TRUE(waiter.WaitFor(1, kAsyncExpectationsTimeout)); } TEST_F(TransportManagerImplTest, ReceiveEventFromDevice_OnSearchDeviceFail) { const int type = static_cast<int>( TransportAdapterListenerImpl::EventTypeEnum::ON_SEARCH_FAIL); + TestAsyncWaiter waiter; TransportAdapterEvent test_event(type, mock_adapter_, mac_address_, @@ -684,10 +708,12 @@ TEST_F(TransportManagerImplTest, ReceiveEventFromDevice_OnSearchDeviceFail) { test_message_, error_); - EXPECT_CALL(*tm_listener_, OnScanDevicesFailed(_)); + EXPECT_CALL(*tm_listener_, OnScanDevicesFailed(_)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); tm_.ReceiveEventFromDevice(test_event); - testing::Mock::AsyncVerifyAndClearExpectations(kAsyncExpectationsTimeout); + + EXPECT_TRUE(waiter.WaitFor(1, kAsyncExpectationsTimeout)); } TEST_F(TransportManagerImplTest, ReceiveEventFromDevice_DeviceListUpdated) { @@ -704,6 +730,7 @@ TEST_F(TransportManagerImplTest, ReceiveEventFromDevice_DeviceListUpdated) { std::vector<DeviceInfo> vector_dev_info; vector_dev_info.push_back(dev_info_); + TestAsyncWaiter waiter; EXPECT_CALL(*mock_adapter_, GetDeviceList()) .Times(AtLeast(1)) .WillRepeatedly(Return(device_list_)); @@ -714,12 +741,17 @@ TEST_F(TransportManagerImplTest, ReceiveEventFromDevice_DeviceListUpdated) { .Times(AtLeast(1)) .WillRepeatedly(Return(dev_info_.connection_type())); - EXPECT_CALL(*tm_listener_, OnDeviceFound(dev_info_)); - EXPECT_CALL(*tm_listener_, OnDeviceAdded(dev_info_)); + EXPECT_CALL(*tm_listener_, OnDeviceFound(dev_info_)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + EXPECT_CALL(*tm_listener_, OnDeviceAdded(dev_info_)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); + EXPECT_CALL(*tm_listener_, OnDeviceListUpdated(vector_dev_info)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); tm_.ReceiveEventFromDevice(test_event); device_list_.pop_back(); - testing::Mock::AsyncVerifyAndClearExpectations(kAsyncExpectationsTimeout); + + EXPECT_TRUE(waiter.WaitFor(3, kAsyncExpectationsTimeout)); } TEST_F(TransportManagerImplTest, CheckEvents) { @@ -877,10 +909,14 @@ TEST_F(TransportManagerImplTest, Visibility_TMIsNotInitialized) { TEST_F(TransportManagerImplTest, HandleMessage_ConnectionNotExist) { EXPECT_CALL(*mock_adapter_, SendData(mac_address_, application_id_, test_message_)).Times(0); - EXPECT_CALL(*tm_listener_, OnTMMessageSendFailed(_, test_message_)); + + TestAsyncWaiter waiter; + EXPECT_CALL(*tm_listener_, OnTMMessageSendFailed(_, test_message_)) + .WillOnce(NotifyTestAsyncWaiter(&waiter)); tm_.TestHandle(test_message_); - testing::Mock::AsyncVerifyAndClearExpectations(kAsyncExpectationsTimeout); + + EXPECT_TRUE(waiter.WaitFor(1, kAsyncExpectationsTimeout)); } TEST_F(TransportManagerImplTest, SearchDevices_TMIsNotInitialized) { |