diff options
Diffstat (limited to 'src')
56 files changed, 12111 insertions, 537 deletions
diff --git a/src/components/application_manager/include/application_manager/application_manager_impl.h b/src/components/application_manager/include/application_manager/application_manager_impl.h index 9159737f8a..c9a3e5b551 100644 --- a/src/components/application_manager/include/application_manager/application_manager_impl.h +++ b/src/components/application_manager/include/application_manager/application_manager_impl.h @@ -1146,6 +1146,10 @@ class ApplicationManagerImpl : public ApplicationManager, */ bool IsAppsQueriedFrom(const connection_handler::DeviceHandle handle) const; + bool IsStopping() const { + return is_stopping_; + } + private: /** * @brief PullLanguagesInfo allows to pull information about languages. @@ -1481,6 +1485,8 @@ class ApplicationManagerImpl : public ApplicationManager, bool is_low_voltage_; + bool is_stopping_; + DISALLOW_COPY_AND_ASSIGN(ApplicationManagerImpl); FRIEND_BASE_SINGLETON_CLASS(ApplicationManagerImpl); diff --git a/src/components/application_manager/src/application_manager_impl.cc b/src/components/application_manager/src/application_manager_impl.cc index f3e8896b42..749fe28af6 100644 --- a/src/components/application_manager/src/application_manager_impl.cc +++ b/src/components/application_manager/src/application_manager_impl.cc @@ -120,7 +120,9 @@ ApplicationManagerImpl::ApplicationManagerImpl() this, &ApplicationManagerImpl::OnTimerSendTTSGlobalProperties, true), - is_low_voltage_(false) { + is_low_voltage_(false), + is_stopping_(false) { + std::srand(std::time(0)); AddPolicyObserver(this); @@ -141,6 +143,7 @@ ApplicationManagerImpl::ApplicationManagerImpl() ApplicationManagerImpl::~ApplicationManagerImpl() { LOG4CXX_INFO(logger_, "Destructing ApplicationManager."); + is_stopping_ = true; SendOnSDLClose(); media_manager_ = NULL; hmi_handler_ = NULL; @@ -168,6 +171,7 @@ ApplicationManagerImpl::~ApplicationManagerImpl() { bool ApplicationManagerImpl::Stop() { LOG4CXX_INFO(logger_, "Stop ApplicationManager."); + is_stopping_ = true; application_list_update_timer_->stop(); try { UnregisterAllApplications(); @@ -176,6 +180,7 @@ bool ApplicationManagerImpl::Stop() { "An error occurred during unregistering applications."); } + request_ctrl_.DestroyThreadpool(); // for PASA customer policy backup should happen :AllApp(SUSPEND) LOG4CXX_INFO(logger_, "Unloading policy library."); diff --git a/src/components/application_manager/src/commands/mobile/on_vehicle_data_notification.cc b/src/components/application_manager/src/commands/mobile/on_vehicle_data_notification.cc index b499d9aff8..dc3f8ad39f 100644 --- a/src/components/application_manager/src/commands/mobile/on_vehicle_data_notification.cc +++ b/src/components/application_manager/src/commands/mobile/on_vehicle_data_notification.cc @@ -52,36 +52,59 @@ OnVehicleDataNotification::~OnVehicleDataNotification() { void OnVehicleDataNotification::Run() { LOG4CXX_AUTO_TRACE(logger_); + std::vector<ApplicationSharedPtr> appNotification; + std::vector<ApplicationSharedPtr>::iterator appNotification_it = + appNotification.begin(); + std::vector<smart_objects::SmartObject> appSO; + const VehicleData& vehicle_data = MessageHelper::vehicle_data(); VehicleData::const_iterator it = vehicle_data.begin(); for (; vehicle_data.end() != it; ++it) { if (true == (*message_)[strings::msg_params].keyExists(it->first)) { - const std::vector<utils::SharedPtr<Application>>& applications = - ApplicationManagerImpl::instance()->IviInfoUpdated(it->second, - (*message_)[strings::msg_params][it->first].asInt()); + const std::vector<ApplicationSharedPtr>& applications = + ApplicationManagerImpl::instance()->IviInfoUpdated(it->second, + (*message_)[strings::msg_params][it->first].asInt()); + + std::vector<ApplicationSharedPtr>::const_iterator app_it = + applications.begin(); - std::vector<utils::SharedPtr<Application>>::const_iterator it = applications.begin(); - for (; applications.end() != it; ++it) { - utils::SharedPtr<Application> app = *it; + for (; applications.end() != app_it; ++app_it) { + const ApplicationSharedPtr app = *app_it; if (!app) { LOG4CXX_ERROR(logger_, "NULL pointer"); continue; - } - - LOG4CXX_INFO( - logger_, - "Send OnVehicleData PRNDL notification to " << app->name() - << " application id " << app->app_id()); +} - (*message_)[strings::params][strings::connection_key] = app->app_id(); + appNotification_it = find(appNotification.begin(), appNotification.end(), app); + if (appNotification_it == appNotification.end()) { + appNotification.push_back(app); + smart_objects::SmartObject msg_param = smart_objects::SmartObject( + smart_objects::SmartType_Map); + msg_param[it->first] = (*message_)[strings::msg_params][it->first]; + appSO.push_back(msg_param); + } else { + size_t idx = std::distance(appNotification.begin(), appNotification_it); + appSO[idx][it->first] = (*message_)[strings::msg_params][it->first]; - SendNotification(); + } } - - return; } } + + LOG4CXX_DEBUG(logger_, "Number of Notifications to be send: " << + appNotification.size()); + + for (size_t idx = 0; idx < appNotification.size(); idx++) { + LOG4CXX_INFO( + logger_, + "Send OnVehicleData PRNDL notification to " << appNotification[idx]->name() + << " application id " << appNotification[idx]->app_id()); + (*message_)[strings::params][strings::connection_key] = + appNotification[idx]->app_id(); + (*message_)[strings::msg_params] = appSO[idx]; + SendNotification(); + } } } // namespace commands diff --git a/src/components/application_manager/src/commands/mobile/register_app_interface_request.cc b/src/components/application_manager/src/commands/mobile/register_app_interface_request.cc index 42fce5e05b..bec90f788e 100644 --- a/src/components/application_manager/src/commands/mobile/register_app_interface_request.cc +++ b/src/components/application_manager/src/commands/mobile/register_app_interface_request.cc @@ -157,12 +157,26 @@ void RegisterAppInterfaceRequest::Run() { // FIXME(EZamakhov): on shutdown - get freez // wait till HMI started - while (!ApplicationManagerImpl::instance()->IsHMICooperating()) { - sleep(1); - // TODO(DK): timer_->StartWait(1); + while (ApplicationManagerImpl::exists() && + !ApplicationManagerImpl::instance()->IsStopping() && + !ApplicationManagerImpl::instance()->IsHMICooperating()) { + LOG4CXX_DEBUG(logger_, "Waiting for the HMI... conn_key=" + << connection_key() << ", correlation_id=" << correlation_id() + << ", default_timeout=" << default_timeout() + << ", thread=" << pthread_self()); ApplicationManagerImpl::instance()->updateRequestTimeout(connection_key(), correlation_id(), default_timeout()); + sleep(1); + // TODO(DK): timer_->StartWait(1); + } + + if (!ApplicationManagerImpl::exists()) { + LOG4CXX_WARN(logger_, "The ApplicationManager doesn't exist!"); + return; + } else if (ApplicationManagerImpl::instance()->IsStopping()) { + LOG4CXX_WARN(logger_, "The ApplicationManager is stopping!"); + return; } const std::string mobile_app_id = (*message_)[strings::msg_params][strings::app_id] diff --git a/src/components/application_manager/test/mock/include/application_manager/application_manager_impl.h b/src/components/application_manager/test/mock/include/application_manager/application_manager_impl.h index 29ba9e0c96..450469567c 100644 --- a/src/components/application_manager/test/mock/include/application_manager/application_manager_impl.h +++ b/src/components/application_manager/test/mock/include/application_manager/application_manager_impl.h @@ -316,6 +316,7 @@ class ApplicationManagerImpl : public ApplicationManager, MOCK_METHOD3(set_state, void(ApplicationSharedPtr app, mobile_apis::HMILevel::eType, mobile_apis::AudioStreamingState::eType)); +MOCK_CONST_METHOD0(IsStopping, bool()); struct ApplicationsAppIdSorter { bool operator() (const ApplicationSharedPtr lhs, diff --git a/src/components/application_manager/test/resumption/include/application_mock.h b/src/components/application_manager/test/resumption/include/application_mock.h new file mode 100644 index 0000000000..39c4b33539 --- /dev/null +++ b/src/components/application_manager/test/resumption/include/application_mock.h @@ -0,0 +1,266 @@ +/* +* Copyright (c) 2015, 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. +*/ +#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_RESUMPTION_INCLUDE_APPLICATION_MOCK_H_ +#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_RESUMPTION_INCLUDE_APPLICATION_MOCK_H_ +#include <string> +#include "gmock/gmock.h" +#include "application_manager/application.h" + +namespace test { +namespace components { +namespace resumption_test { + +class ApplicationMock : public ::application_manager::Application { + public: + MOCK_CONST_METHOD0(active_message, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(curHash, const std::string&()); + MOCK_METHOD0(UpdateHash, void()); + MOCK_CONST_METHOD0(flag_sending_hash_change_after_awake, bool()); + MOCK_METHOD1(set_flag_sending_hash_change_after_awake, void(bool flag)); + MOCK_CONST_METHOD0(is_application_data_changed, bool()); + MOCK_METHOD1(set_is_application_data_changed, + void(bool state_application_data)); + MOCK_METHOD0(CloseActiveMessage, void()); + MOCK_CONST_METHOD0(IsFullscreen, bool()); + MOCK_METHOD0(ChangeSupportingAppHMIType, void()); + MOCK_CONST_METHOD0(is_navi, bool()); + MOCK_METHOD1(set_is_navi, void(bool allow)); + MOCK_CONST_METHOD0(video_streaming_approved, bool()); + MOCK_METHOD1(set_video_streaming_approved, void(bool state)); + MOCK_CONST_METHOD0(audio_streaming_approved, bool()); + MOCK_METHOD1(set_audio_streaming_approved, void(bool state)); + MOCK_CONST_METHOD0(video_streaming_allowed, bool()); + MOCK_METHOD1(set_video_streaming_allowed, void(bool state)); + MOCK_CONST_METHOD0(audio_streaming_allowed, bool()); + MOCK_METHOD1(set_audio_streaming_allowed, void(bool state)); + MOCK_METHOD1(StartStreaming, + void(protocol_handler::ServiceType service_type)); + MOCK_METHOD1(StopStreaming, void(protocol_handler::ServiceType service_type)); + MOCK_METHOD1(SuspendStreaming, + void(protocol_handler::ServiceType service_type)); + MOCK_METHOD1(WakeUpStreaming, + void(protocol_handler::ServiceType service_type)); + MOCK_CONST_METHOD0(is_voice_communication_supported, bool()); + MOCK_METHOD1(set_voice_communication_supported, + void(bool is_voice_communication_supported)); + MOCK_CONST_METHOD0(app_allowed, bool()); + MOCK_CONST_METHOD0(has_been_activated, bool()); + MOCK_METHOD1(set_activated, bool(bool is_active)); + MOCK_CONST_METHOD0(version, const ::application_manager::Version&()); + MOCK_METHOD1(set_hmi_application_id, void(uint32_t hmi_app_id)); + MOCK_CONST_METHOD0(hmi_app_id, uint32_t()); + MOCK_CONST_METHOD0(name, const std::string&()); + MOCK_METHOD1(set_folder_name, void(const std::string& folder_name)); + MOCK_CONST_METHOD0(folder_name, const std::string()); + MOCK_CONST_METHOD0(is_media_application, bool()); + MOCK_CONST_METHOD0(hmi_level, const mobile_apis::HMILevel::eType()); + MOCK_CONST_METHOD0(put_file_in_none_count, const uint32_t()); + MOCK_CONST_METHOD0(delete_file_in_none_count, const uint32_t()); + MOCK_CONST_METHOD0(list_files_in_none_count, const uint32_t()); + MOCK_CONST_METHOD0(system_context, const mobile_apis::SystemContext::eType()); + MOCK_CONST_METHOD0(audio_streaming_state, + const mobile_apis::AudioStreamingState::eType()); + MOCK_CONST_METHOD0(app_icon_path, const std::string&()); + MOCK_CONST_METHOD0(device, connection_handler::DeviceHandle()); + MOCK_METHOD0(tts_speak_state, bool()); + MOCK_CONST_METHOD0(CurrentHmiState, + ::application_manager::HmiStatePtr()); + MOCK_CONST_METHOD0(RegularHmiState, + ::application_manager::HmiStatePtr()); + MOCK_CONST_METHOD0(PostponedHmiState, + ::application_manager::HmiStatePtr()); + MOCK_METHOD1(set_tts_properties_in_none, void(bool active)); + MOCK_METHOD0(tts_properties_in_none, bool()); + MOCK_METHOD1(set_tts_properties_in_full, void(bool active)); + MOCK_METHOD0(tts_properties_in_full, bool()); + MOCK_METHOD1(set_version, + void(const ::application_manager::Version& version)); + MOCK_METHOD1(set_name, void(const std::string& name)); + MOCK_METHOD1(set_is_media_application, void(bool is_media)); + MOCK_METHOD0(increment_put_file_in_none_count, void()); + MOCK_METHOD0(increment_delete_file_in_none_count, void()); + MOCK_METHOD0(increment_list_files_in_none_count, void()); + MOCK_METHOD1(set_app_icon_path, bool(const std::string& file_name)); + MOCK_METHOD1(set_app_allowed, void(const bool& allowed)); + MOCK_METHOD1(set_device, void(connection_handler::DeviceHandle device)); + MOCK_CONST_METHOD0(get_grammar_id, uint32_t()); + MOCK_METHOD1(set_grammar_id, void(uint32_t value)); + MOCK_METHOD1( + set_protocol_version, + void(const ::application_manager::ProtocolVersion& protocol_version)); + MOCK_CONST_METHOD0(protocol_version, + ::application_manager::ProtocolVersion()); + MOCK_METHOD1(set_is_resuming, void(bool)); + MOCK_CONST_METHOD0(is_resuming, bool()); + MOCK_METHOD1(AddFile, bool(const ::application_manager::AppFile& file)); + MOCK_CONST_METHOD0(getAppFiles, const ::application_manager::AppFilesMap&()); + MOCK_METHOD1(UpdateFile, bool(const ::application_manager::AppFile& file)); + MOCK_METHOD1(DeleteFile, bool(const std::string& file_name)); + MOCK_METHOD1(GetFile, const ::application_manager::AppFile*( + const std::string& file_name)); + MOCK_METHOD1(SubscribeToButton, + bool(mobile_apis::ButtonName::eType btn_name)); + MOCK_METHOD1(IsSubscribedToButton, + bool(mobile_apis::ButtonName::eType btn_name)); + MOCK_METHOD1(UnsubscribeFromButton, + bool(mobile_apis::ButtonName::eType btn_name)); + MOCK_METHOD1(SubscribeToIVI, bool(uint32_t vehicle_info_type)); + MOCK_CONST_METHOD1(IsSubscribedToIVI, bool(uint32_t vehicle_info_type)); + MOCK_METHOD1(UnsubscribeFromIVI, bool(uint32_t vehicle_info_type)); + MOCK_METHOD0(ResetDataInNone, void()); + MOCK_METHOD2(IsCommandLimitsExceeded, + bool(mobile_apis::FunctionID::eType cmd_id, + ::application_manager::TLimitSource source)); + MOCK_METHOD0(usage_report, ::application_manager::UsageStatistics&()); + MOCK_METHOD1(SetRegularState, void(::application_manager::HmiStatePtr state)); + MOCK_METHOD1(SetPostponedState, void(::application_manager::HmiStatePtr state)); + MOCK_METHOD1(AddHMIState, void(::application_manager::HmiStatePtr state)); + MOCK_METHOD1(RemoveHMIState, + void(::application_manager::HmiState::StateID state_id)); + MOCK_METHOD2(SubscribeToSoftButtons, + void(int32_t cmd_id, + const ::application_manager::SoftButtonID& softbuttons_id)); + MOCK_METHOD1(IsSubscribedToSoftButton, bool(const uint32_t softbutton_id)); + MOCK_METHOD1(UnsubscribeFromSoftButtons, void(int32_t cmd_id)); + MOCK_CONST_METHOD0(IsAudioApplication, bool()); + MOCK_METHOD0(LoadPersistentFiles, void()); + // InitialApplicationData methods + MOCK_CONST_METHOD0(app_types, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(vr_synonyms, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(policy_app_id, std::string()); + MOCK_CONST_METHOD0(tts_name, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(ngn_media_screen_name, + const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(language, const mobile_apis::Language::eType&()); + MOCK_CONST_METHOD0(ui_language, const mobile_apis::Language::eType&()); + MOCK_METHOD1(set_app_types, + void(const smart_objects::SmartObject& app_types)); + MOCK_METHOD1(set_vr_synonyms, + void(const smart_objects::SmartObject& vr_synonyms)); + MOCK_METHOD1(set_policy_app_id, void(const std::string& policy_app_id)); + MOCK_METHOD1(set_tts_name, void(const smart_objects::SmartObject& tts_name)); + MOCK_METHOD1(set_ngn_media_screen_name, + void(const smart_objects::SmartObject& ngn_name)); + MOCK_METHOD1(set_language, + void(const mobile_apis::Language::eType& language)); + MOCK_METHOD1(set_ui_language, + void(const mobile_apis::Language::eType& ui_language)); + // DynamicApplicationData methods + MOCK_CONST_METHOD0(help_prompt, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(timeout_prompt, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(vr_help_title, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(vr_help, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(tbt_state, const mobile_apis::TBTState::eType&()); + MOCK_CONST_METHOD0(show_command, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(tbt_show_command, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0( + SubscribedButtons, + DataAccessor< ::application_manager::ButtonSubscriptions >()); + MOCK_CONST_METHOD0( + SubscribedIVI, + DataAccessor< ::application_manager::VehicleInfoSubscriptions >()); + MOCK_CONST_METHOD0(keyboard_props, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(menu_title, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(menu_icon, const smart_objects::SmartObject*()); + MOCK_METHOD1(load_global_properties, + void(const smart_objects::SmartObject& so)); + MOCK_METHOD1(set_help_prompt, + void(const smart_objects::SmartObject& help_prompt)); + MOCK_METHOD1(set_timeout_prompt, + void(const smart_objects::SmartObject& timeout_prompt)); + MOCK_METHOD1(set_vr_help_title, + void(const smart_objects::SmartObject& vr_help_title)); + MOCK_METHOD0(reset_vr_help_title, void()); + MOCK_METHOD1(set_vr_help, void(const smart_objects::SmartObject& vr_help)); + MOCK_METHOD0(reset_vr_help, void()); + MOCK_METHOD1(set_tbt_state, + void(const mobile_apis::TBTState::eType& tbt_state)); + MOCK_METHOD1(set_show_command, + void(const smart_objects::SmartObject& show_command)); + MOCK_METHOD1(set_tbt_show_command, + void(const smart_objects::SmartObject& tbt_show)); + MOCK_METHOD1(set_keyboard_props, + void(const smart_objects::SmartObject& keyboard_props)); + MOCK_METHOD1(set_menu_title, + void(const smart_objects::SmartObject& menu_title)); + MOCK_METHOD1(set_menu_icon, + void(const smart_objects::SmartObject& menu_icon)); + MOCK_CONST_METHOD0(audio_stream_retry_number, uint32_t()); + MOCK_METHOD1(set_audio_stream_retry_number, + void(const uint32_t& audio_stream_retry_number)); + MOCK_CONST_METHOD0(video_stream_retry_number, uint32_t()); + MOCK_METHOD1(set_video_stream_retry_number, + void(const uint32_t& video_stream_retry_number)); + MOCK_METHOD2(AddCommand, void(uint32_t cmd_id, + const smart_objects::SmartObject& command)); + MOCK_METHOD1(RemoveCommand, void(uint32_t cmd_id)); + MOCK_METHOD1(FindCommand, smart_objects::SmartObject*(uint32_t cmd_id)); + MOCK_METHOD2(AddSubMenu, + void(uint32_t menu_id, const smart_objects::SmartObject& menu)); + MOCK_METHOD1(RemoveSubMenu, void(uint32_t menu_id)); + MOCK_CONST_METHOD1(FindSubMenu, + smart_objects::SmartObject*(uint32_t menu_id)); + MOCK_METHOD1(IsSubMenuNameAlreadyExist, bool(const std::string& name)); + MOCK_METHOD2(AddChoiceSet, + void(uint32_t choice_set_id, + const smart_objects::SmartObject& choice_set)); + MOCK_METHOD1(RemoveChoiceSet, void(uint32_t choice_set_id)); + MOCK_METHOD1(FindChoiceSet, + smart_objects::SmartObject*(uint32_t choice_set_id)); + MOCK_METHOD3(AddPerformInteractionChoiceSet, + void(uint32_t correlation_id, uint32_t choice_set_id, + const smart_objects::SmartObject& choice_set)); + MOCK_METHOD1(DeletePerformInteractionChoiceSet, + void(uint32_t correlation_id)); + MOCK_CONST_METHOD0( + performinteraction_choice_set_map, + DataAccessor< ::application_manager::PerformChoiceSetMap >()); + MOCK_CONST_METHOD0(commands_map, + DataAccessor< ::application_manager::CommandsMap >()); + MOCK_CONST_METHOD0(sub_menu_map, + DataAccessor< ::application_manager::SubMenuMap >()); + MOCK_CONST_METHOD0(choice_set_map, + DataAccessor< ::application_manager::ChoiceSetMap >()); + MOCK_METHOD1(set_perform_interaction_active, void(uint32_t active)); + MOCK_CONST_METHOD0(is_perform_interaction_active, uint32_t()); + MOCK_METHOD1(set_perform_interaction_mode, void(int32_t mode)); + MOCK_CONST_METHOD0(perform_interaction_mode, int32_t()); + MOCK_METHOD1(set_reset_global_properties_active, void(bool active)); + MOCK_CONST_METHOD0(is_reset_global_properties_active, bool()); + MOCK_CONST_METHOD0(app_id, uint32_t()); +}; + +} // namespace resumption_test +} // namespace components +} // namespace test + +#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_RESUMPTION_INCLUDE_APPLICATION_MOCK_H_ diff --git a/src/components/application_manager/test/resumption/include/resumption_data_mock.h b/src/components/application_manager/test/resumption/include/resumption_data_mock.h new file mode 100644 index 0000000000..2c9285b025 --- /dev/null +++ b/src/components/application_manager/test/resumption/include/resumption_data_mock.h @@ -0,0 +1,86 @@ +/* +* Copyright (c) 2015, 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. +*/ +#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_RESUMPTION_INCLUDE_RESUMPTION_DATA_MOCK_H_ +#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_RESUMPTION_INCLUDE_RESUMPTION_DATA_MOCK_H_ +#include <string> +#include "gmock/gmock.h" +#include "application_manager/resumption/resumption_data.h" +#include "application_manager/application.h" + +namespace test { +namespace components { +namespace resumption_test { +namespace app_mngr = application_manager; +namespace smart_objects = NsSmartDeviceLink::NsSmartObjects; + +class ResumptionDataMock : public ::resumption::ResumptionData { + public: + MOCK_METHOD1(SaveApplication, + void(app_mngr::ApplicationSharedPtr application)); + MOCK_CONST_METHOD2(GetStoredHMILevel, + int32_t(const std::string& policy_app_id, + const std::string& device_id)); + MOCK_CONST_METHOD1(IsHMIApplicationIdExist, bool(uint32_t hmi_app_id)); + MOCK_METHOD2(CheckSavedApplication, bool(const std::string& policy_app_id, + const std::string& device_id)); + MOCK_CONST_METHOD2(GetHMIApplicationID, + uint32_t(const std::string& policy_app_id, + const std::string& device_id)); + MOCK_METHOD0(OnSuspend, void()); + MOCK_CONST_METHOD3(GetHashId, + bool(const std::string& policy_app_id, + const std::string& device_id, std::string& hash_id)); + MOCK_METHOD0(OnAwake, void()); + MOCK_CONST_METHOD3(GetSavedApplication, + bool(const std::string& policy_app_id, + const std::string& device_id, + smart_objects::SmartObject& saved_app)); + MOCK_METHOD2(RemoveApplicationFromSaved, + bool(const std::string& policy_app_id, + const std::string& device_id)); + MOCK_CONST_METHOD0(GetIgnOffTime, uint32_t()); + MOCK_CONST_METHOD2(IsApplicationSaved, + ssize_t(const std::string& policy_app_id, + const std::string& device_id)); + MOCK_CONST_METHOD1(GetDataForLoadResumeData, + void(smart_objects::SmartObject& saved_data)); + MOCK_METHOD3(UpdateHmiLevel, void(const std::string& policy_app_id, + const std::string& device_id, + mobile_apis::HMILevel::eType hmi_level)); + MOCK_METHOD0(Init, bool()); +}; + +} // namespace resumption_test +} // namespace components +} // namespace test + +#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_RESUMPTION_INCLUDE_RESUMPTION_DATA_MOCK_H_ diff --git a/src/components/application_manager/test/resumption/include/resumption_data_test.h b/src/components/application_manager/test/resumption/include/resumption_data_test.h new file mode 100644 index 0000000000..55767225b5 --- /dev/null +++ b/src/components/application_manager/test/resumption/include/resumption_data_test.h @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2015, 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. + */ + +#include <string> +#include <algorithm> +#include "gtest/gtest.h" +#include "application_manager/usage_statistics.h" +#include "application_mock.h" +#include "application_manager/application_manager_impl.h" +#include "utils/data_accessor.h" + +namespace test { +namespace components { +namespace resumption_test { + +using ::testing::NiceMock; +namespace am = application_manager; +namespace sm = smart_objects; +using namespace Json; + +using namespace resumption; +using namespace mobile_apis; + +class ResumptionDataTest : public ::testing::Test { + protected: + // Check structure in saved application + void CheckSavedApp(sm::SmartObject& saved_data); + + // Set data for resumption + virtual void PrepareData(); + utils::SharedPtr<NiceMock<ApplicationMock>> app_mock; + + HMILevel::eType hmi_level_; + size_t app_id_; + size_t hmi_app_id_; + std::string policy_app_id_; + size_t ign_off_count_; + const size_t tts_chunks_count = 4; + + size_t grammar_id_; + std::string hash_; + bool is_audio_; + const connection_handler::DeviceHandle device_handle_ = 10; + + sm::SmartObject* help_prompt_; + sm::SmartObject* timeout_prompt_; + sm::SmartObject* vr_help_; + sm::SmartObject* vr_help_title_; + sm::SmartObject* vr_synonyms_; + sm::SmartObject* keyboard_props_; + sm::SmartObject* menu_title_; + sm::SmartObject* menu_icon_; + + void SetCommands(); + void SetSubmenues(); + void SetChoiceSet(); + void SetAppFiles(); + void SetGlobalProporties(); + void SetKeyboardProperties(); + void SetMenuTitleAndIcon(); + void SetHelpAndTimeoutPrompt(); + void SetVRHelpTitle(); + void SetSubscriptions(); + + void CheckCommands(sm::SmartObject& res_list); + void CheckGlobalProporties(sm::SmartObject& res_list); + void CheckSubmenues(sm::SmartObject& res_list); + void CheckChoiceSet(sm::SmartObject& res_list); + void CheckAppFiles(sm::SmartObject& res_list); + void CheckKeyboardProperties(sm::SmartObject& res_list); + void CheckMenuTitle(sm::SmartObject& res_list); + void CheckMenuIcon(sm::SmartObject& res_list); + void CheckHelpPrompt(sm::SmartObject& res_list); + void CheckTimeoutPrompt(sm::SmartObject& res_list); + void CheckVRHelp(NsSmartDeviceLink::NsSmartObjects::SmartObject& res_list); + void CheckVRTitle(sm::SmartObject& res_list); + void CheckSubscriptions(sm::SmartObject& res_list); + + const size_t count_of_commands = 5; + const size_t count_of_choice = 2; + const size_t count_of_choice_sets = 4; + const size_t count_of_submenues = 3; + const size_t count_of_files = 8; + const size_t count_of_vrhelptitle = 2; + const std::string device_id_ = "12345"; + + am::CommandsMap test_commands_map; + am::SubMenuMap test_submenu_map; + am::ChoiceSetMap test_choiceset_map; + am::AppFilesMap app_files_map_; + + am::ButtonSubscriptions btn_subscr; + am::VehicleInfoSubscriptions ivi; + + sync_primitives::Lock sublock_; + sync_primitives::Lock comlock_; + sync_primitives::Lock setlock_; + sync_primitives::Lock btnlock_; + sync_primitives::Lock ivilock_; +}; + +} // namespace resumption_test +} // namespace components +} // namespace test diff --git a/src/components/application_manager/test/resumption/resume_ctrl_test.cc b/src/components/application_manager/test/resumption/resume_ctrl_test.cc new file mode 100644 index 0000000000..bfd41b0f08 --- /dev/null +++ b/src/components/application_manager/test/resumption/resume_ctrl_test.cc @@ -0,0 +1,937 @@ +/* + * Copyright (c) 2015, 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. + */ + +#include "application_manager/resumption/resume_ctrl.h" +#include <string> +#include <algorithm> +#include "gtest/gtest.h" +#include "application_manager/usage_statistics.h" +#include "include/application_mock.h" +#include "include/resumption_data_mock.h" +#include "interfaces/MOBILE_API.h" +#include "application_manager/application_manager_impl.h" +#include "application_manager/application.h" +#include "config_profile/profile.h" +#include "utils/data_accessor.h" +#include "application_manager/test/mock_message_helper.h" + +namespace test { +namespace components { +namespace resumption_test { + +using ::testing::_; +using ::testing::Return; +using ::testing::DoAll; +using ::testing::SetArgReferee; +using ::testing::Mock; +using ::testing::NiceMock; +using ::testing::AtLeast; + +using namespace resumption; +using namespace mobile_apis::HMILevel; + +class ResumeCtrlTest : public ::testing::Test { + public: + virtual void SetUp() OVERRIDE { + app_mngr = application_manager::ApplicationManagerImpl::instance(); + // Singleton should not be destroyed + Mock::AllowLeak(app_mngr); + mock_storage = new NiceMock<ResumptionDataMock>(); + app_mock = new NiceMock<ApplicationMock>(); + res_ctrl.set_resumption_storage(mock_storage); + test_audio_state = mobile_apis::AudioStreamingState::NOT_AUDIBLE; + test_app_id = 10; + default_testType = eType::HMI_NONE; + test_dev_id = 5; + test_policy_app_id = "test_policy_app_id"; + test_grammar_id = 10; + hash = "saved_hash"; + } + + protected: + application_manager::ApplicationManagerImpl* app_mngr; + ResumeCtrl res_ctrl; + NiceMock<ResumptionDataMock>* mock_storage; + NiceMock<ApplicationMock>* app_mock; + mobile_apis::AudioStreamingState::eType test_audio_state; + // app_mock.app_id() will return this value + uint32_t test_app_id; + std::string test_policy_app_id; + mobile_apis::HMILevel::eType default_testType; + + // app_mock.Device() will return this value + uint32_t test_dev_id; + uint32_t test_grammar_id; + std::string hash; +}; + +/** + * @brief Group of tests which check starting resumption with different data + */ + +TEST_F(ResumeCtrlTest, StartResumption_AppWithGrammarId) { + smart_objects::SmartObject saved_app; + saved_app[application_manager::strings::hash_id] = hash; + saved_app[application_manager::strings::grammar_id] = test_grammar_id; + + // Check RestoreApplicationData + EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _)) + .Times(3) + .WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true))); + EXPECT_CALL(*app_mock, UpdateHash()); + EXPECT_CALL(*app_mock, set_grammar_id(test_grammar_id)); + + bool res = res_ctrl.StartResumption(app_mock, hash); + EXPECT_TRUE(res); +} + +MATCHER_P4(CheckAppFile, is_persistent, is_download, file_name, file_type, "") { + application_manager::AppFile app_file = arg; + return app_file.is_persistent == is_persistent && + app_file.is_download_complete == is_download && + app_file.file_name == file_name && app_file.file_type == file_type; +} + +TEST_F(ResumeCtrlTest, StartResumption_WithoutGrammarId) { + smart_objects::SmartObject saved_app; + saved_app[application_manager::strings::hash_id] = hash; + + // Check RestoreApplicationData + EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _)) + .Times(3) + .WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true))); + EXPECT_CALL(*app_mock, UpdateHash()); + EXPECT_CALL(*app_mock, set_grammar_id(test_grammar_id)).Times(0); + + bool res = res_ctrl.StartResumption(app_mock, hash); + EXPECT_FALSE(res); +} + +TEST_F(ResumeCtrlTest, StartResumption_AppWithFiles) { + smart_objects::SmartObject test_application_files; + smart_objects::SmartObject test_file; + const uint32_t count_of_files = 8; + + int file_types[count_of_files]; + std::string file_names[count_of_files]; + const size_t max_size = 12; + char numb[max_size]; + for (uint32_t i = 0; i < count_of_files; i++) { + file_types[i] = i; + std::snprintf(numb, max_size, "%d", i); + file_names[i] = "test_file" + std::string(numb); + } + + // Should not been added + test_file[application_manager::strings::persistent_file] = false; + test_application_files[0] = test_file; + + for (uint32_t i = 0; i < count_of_files; ++i) { + test_file[application_manager::strings::persistent_file] = true; + test_file[application_manager::strings::is_download_complete] = true; + test_file[application_manager::strings::file_type] = file_types[i]; + test_file[application_manager::strings::sync_file_name] = file_names[i]; + test_application_files[i + 1] = test_file; + } + + smart_objects::SmartObject saved_app; + saved_app[application_manager::strings::hash_id] = hash; + saved_app[application_manager::strings::grammar_id] = test_grammar_id; + saved_app[application_manager::strings::application_files] = + test_application_files; + + // Check RestoreApplicationData + EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _)) + .Times(3) + .WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true))); + EXPECT_CALL(*app_mock, UpdateHash()); + EXPECT_CALL(*app_mock, set_grammar_id(test_grammar_id)); + for (uint32_t i = 0; i < count_of_files; ++i) { + EXPECT_CALL(*app_mock, + AddFile(CheckAppFile( + true, true, file_names[i], + static_cast<mobile_apis::FileType::eType>(file_types[i])))); + } + + bool res = res_ctrl.StartResumption(app_mock, hash); + EXPECT_TRUE(res); +} + +TEST_F(ResumeCtrlTest, StartResumption_AppWithSubmenues) { + smart_objects::SmartObject test_application_submenues; + smart_objects::SmartObject test_submenu; + + const uint32_t count_of_submenues = 20; + for (uint32_t i = 0; i < count_of_submenues; ++i) { + test_submenu[application_manager::strings::menu_id] = i; + test_application_submenues[i] = test_submenu; + } + + smart_objects::SmartObject saved_app; + saved_app[application_manager::strings::hash_id] = hash; + saved_app[application_manager::strings::grammar_id] = test_grammar_id; + saved_app[application_manager::strings::application_submenus] = + test_application_submenues; + + // Check RestoreApplicationData + EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _)) + .Times(3) + .WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true))); + + EXPECT_CALL(*app_mock, set_grammar_id(test_grammar_id)); + + for (uint32_t i = 0; i < count_of_submenues; ++i) { + EXPECT_CALL(*app_mock, AddSubMenu(i, test_application_submenues[i])); + } + smart_objects::SmartObjectList requests; + EXPECT_CALL(*application_manager::MockMessageHelper::message_helper_mock(), + CreateAddSubMenuRequestToHMI(_)).WillRepeatedly(Return(requests)); + + EXPECT_CALL(*app_mock, UpdateHash()); + bool res = res_ctrl.StartResumption(app_mock, hash); + EXPECT_TRUE(res); +} + +TEST_F(ResumeCtrlTest, StartResumption_AppWithCommands) { + smart_objects::SmartObject test_application_commands; + smart_objects::SmartObject test_commands; + const uint32_t count_of_commands = 20; + + for (uint32_t i = 0; i < count_of_commands; ++i) { + test_commands[application_manager::strings::cmd_id] = i; + test_application_commands[i] = test_commands; + } + + smart_objects::SmartObject saved_app; + saved_app[application_manager::strings::hash_id] = hash; + saved_app[application_manager::strings::grammar_id] = test_grammar_id; + saved_app[application_manager::strings::application_commands] = + test_application_commands; + + // Check RestoreApplicationData + EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _)) + .Times(3) + .WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true))); + EXPECT_CALL(*app_mock, UpdateHash()); + EXPECT_CALL(*app_mock, set_grammar_id(test_grammar_id)); + + for (uint32_t i = 0; i < count_of_commands; ++i) { + EXPECT_CALL(*app_mock, AddCommand(i, test_application_commands[i])); + } + + smart_objects::SmartObjectList requests; + EXPECT_CALL(*application_manager::MockMessageHelper::message_helper_mock(), + CreateAddCommandRequestToHMI(_)).WillRepeatedly(Return(requests)); + + bool res = res_ctrl.StartResumption(app_mock, hash); + EXPECT_TRUE(res); +} + +TEST_F(ResumeCtrlTest, StartResumption_AppWithChoiceSet) { + smart_objects::SmartObject application_choice_sets; + smart_objects::SmartObject app_choice_set; + + const uint32_t count_of_choice = 10; + smart_objects::SmartObject choice_vector; + smart_objects::SmartObject choice; + const size_t max_size = 12; + char numb[max_size]; + for (uint32_t i = 0; i < count_of_choice; ++i) { + std::snprintf(numb, max_size, "%d", i); + choice[application_manager::strings::vr_commands] = + "VrCommand" + std::string(numb); + choice[application_manager::strings::choice_id] = i; + choice_vector[i] = choice; + } + const uint32_t count_of_choice_sets = 5; + for (uint32_t i = 0; i < count_of_choice_sets; ++i) { + app_choice_set[application_manager::strings::interaction_choice_set_id] = i; + app_choice_set[application_manager::strings::choice_set] = choice_vector; + application_choice_sets[i] = app_choice_set; + } + + smart_objects::SmartObject saved_app; + saved_app[application_manager::strings::hash_id] = hash; + saved_app[application_manager::strings::grammar_id] = test_grammar_id; + saved_app[application_manager::strings::application_choice_sets] = + application_choice_sets; + + // Check RestoreApplicationData + EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _)) + .Times(3) + .WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true))); + EXPECT_CALL(*app_mock, UpdateHash()); + EXPECT_CALL(*app_mock, set_grammar_id(test_grammar_id)); + + for (uint32_t i = 0; i < count_of_choice_sets; ++i) { + EXPECT_CALL(*app_mock, AddChoiceSet(i, application_choice_sets[i])); + } + + smart_objects::SmartObjectList requests; + EXPECT_CALL(*application_manager::MockMessageHelper::message_helper_mock(), + CreateAddVRCommandRequestFromChoiceToHMI(_)) + .WillRepeatedly(Return(requests)); + + bool res = res_ctrl.StartResumption(app_mock, hash); + EXPECT_TRUE(res); +} + +TEST_F(ResumeCtrlTest, StartResumption_AppWithGlobalProperties) { + // Prepare Data + smart_objects::SmartObject test_global_properties; + smart_objects::SmartObject saved_app; + saved_app[application_manager::strings::hash_id] = hash; + saved_app[application_manager::strings::grammar_id] = test_grammar_id; + saved_app[application_manager::strings::application_global_properties] = + test_global_properties; + + // Check RestoreApplicationData + EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _)) + .Times(3) + .WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true))); + + EXPECT_CALL(*app_mock, set_grammar_id(test_grammar_id)); + + EXPECT_CALL(*application_manager::MockMessageHelper::message_helper_mock(), + SendGlobalPropertiesToHMI(_)); + + EXPECT_CALL(*app_mock, load_global_properties(test_global_properties)); + + EXPECT_CALL(*app_mock, UpdateHash()); + bool res = res_ctrl.StartResumption(app_mock, hash); + EXPECT_TRUE(res); +} + +TEST_F(ResumeCtrlTest, StartResumption_AppWithSubscribeOnButtons) { + // Prepare Data + smart_objects::SmartObject test_subscriptions; + smart_objects::SmartObject app_buttons; + + uint32_t count_of_buttons = 17; + for (uint32_t i = 0; i < count_of_buttons; ++i) { + app_buttons[i] = i; + } + + test_subscriptions[application_manager::strings::application_buttons] = + app_buttons; + + smart_objects::SmartObject saved_app; + saved_app[application_manager::strings::hash_id] = hash; + saved_app[application_manager::strings::grammar_id] = test_grammar_id; + saved_app[application_manager::strings::application_subscribtions] = + test_subscriptions; + + // Check RestoreApplicationData + EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _)) + .Times(3) + .WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true))); + + EXPECT_CALL(*app_mock, set_grammar_id(test_grammar_id)); + + for (uint32_t i = 0; i < count_of_buttons; ++i) { + EXPECT_CALL(*app_mock, SubscribeToButton( + static_cast<mobile_apis::ButtonName::eType>(i))); + } + EXPECT_CALL(*app_mock, UpdateHash()); + + EXPECT_CALL(*application_manager::MockMessageHelper::message_helper_mock(), + SendAllOnButtonSubscriptionNotificationsForApp(_)).Times(2); + + bool res = res_ctrl.StartResumption(app_mock, hash); + EXPECT_TRUE(res); +} + +TEST_F(ResumeCtrlTest, StartResumption_AppWithSubscriptionToIVI) { + // Prepare Data + smart_objects::SmartObject test_subscriptions; + smart_objects::SmartObject app_vi; + + int vtype = application_manager::VehicleDataType::GPS; + uint i = 0; + for (; vtype < application_manager::VehicleDataType::STEERINGWHEEL; + ++i, ++vtype) { + app_vi[i] = vtype; + } + + test_subscriptions[application_manager::strings::application_vehicle_info] = + app_vi; + + smart_objects::SmartObject saved_app; + saved_app[application_manager::strings::hash_id] = hash; + saved_app[application_manager::strings::grammar_id] = test_grammar_id; + saved_app[application_manager::strings::application_subscribtions] = + test_subscriptions; + + // Check RestoreApplicationData + EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _)) + .Times(3) + .WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true))); + + EXPECT_CALL(*app_mock, set_grammar_id(test_grammar_id)); + + for (size_t i = 0; i < app_vi.length(); ++i) { + EXPECT_CALL( + *app_mock, + SubscribeToIVI(static_cast<application_manager::VehicleDataType>(i))); + } + + ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id)); + + smart_objects::SmartObjectList requests; + EXPECT_CALL(*application_manager::MockMessageHelper::message_helper_mock(), + GetIVISubscriptionRequests(_)).WillRepeatedly(Return(requests)); + + EXPECT_CALL(*app_mock, UpdateHash()); + bool res = res_ctrl.StartResumption(app_mock, hash); + EXPECT_TRUE(res); +} + +TEST_F(ResumeCtrlTest, StartResumptionOnlyHMILevel) { + smart_objects::SmartObject saved_app; + ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(false)); + + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(app_mock)); + ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(test_policy_app_id)); + EXPECT_CALL(*mock_storage, GetSavedApplication(test_policy_app_id, _, _)) + .WillOnce(DoAll(SetArgReferee<2>(saved_app), Return(true))); + + EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_)) + .Times(3) + .WillRepeatedly(Return(default_testType)); + ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id)); + EXPECT_CALL(*app_mngr, SetState(test_app_id, default_testType, + test_audio_state)).Times(2); + bool res = res_ctrl.StartResumptionOnlyHMILevel(app_mock); + EXPECT_TRUE(res); +} + +TEST_F(ResumeCtrlTest, StartAppHmiStateResumption_AppInFull) { + mobile_apis::HMILevel::eType restored_testType = eType::HMI_FULL; + uint32_t ign_off_count = 0; + smart_objects::SmartObject saved_app; + saved_app[application_manager::strings::ign_off_count] = ign_off_count; + saved_app[application_manager::strings::hmi_level] = restored_testType; + + ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(true)); + + ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(test_policy_app_id)); + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + EXPECT_CALL(*app_mngr, + SetHmiState(test_app_id, restored_testType)).Times(AtLeast(1)); + ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id)); + EXPECT_CALL(*mock_storage, GetSavedApplication(test_policy_app_id, _, _)) + .Times(2) + .WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true))); + + EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_)) + .WillOnce(Return(default_testType)); + + EXPECT_CALL(*mock_storage, RemoveApplicationFromSaved(_, _)) + .WillOnce(Return(true)); + + EXPECT_CALL(*app_mngr, GetUserConsentForDevice("12345")) + .WillRepeatedly(Return(policy::kDeviceAllowed)); + EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(app_mock)); + EXPECT_CALL(*app_mngr, + SetState(test_app_id, default_testType, test_audio_state)); + EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_)) + .WillOnce(Return(true)); + + res_ctrl.StartAppHmiStateResumption(app_mock); +} + +TEST_F(ResumeCtrlTest, StartAppHmiStateResumption_AppInBackground) { + uint32_t ign_off_count = 0; + smart_objects::SmartObject saved_app; + + mobile_apis::HMILevel::eType restored_testType = eType::HMI_BACKGROUND; + saved_app[application_manager::strings::ign_off_count] = ign_off_count; + saved_app[application_manager::strings::hmi_level] = restored_testType; + + ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(test_policy_app_id)); + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + EXPECT_CALL(*mock_storage, GetSavedApplication(test_policy_app_id, _, _)) + .WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true))); + + EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_)) + .WillOnce(Return(default_testType)); + + EXPECT_CALL(*app_mngr, GetUserConsentForDevice("12345")) + .WillOnce(Return(policy::kDeviceAllowed)); + EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(app_mock)); + EXPECT_CALL(*app_mngr, + SetState(test_app_id, default_testType, test_audio_state)); + EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_)) + .WillOnce(Return(true)); + + res_ctrl.StartAppHmiStateResumption(app_mock); +} + +/** + * @brief Group of tests which check restoring resumption with different data + */ + +TEST_F(ResumeCtrlTest, RestoreAppHMIState_RestoreHMILevelFull) { + mobile_apis::HMILevel::eType restored_testType = eType::HMI_FULL; + + smart_objects::SmartObject saved_app; + saved_app[application_manager::strings::hash_id] = hash; + saved_app[application_manager::strings::grammar_id] = test_grammar_id; + saved_app[application_manager::strings::hmi_level] = restored_testType; + + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(test_policy_app_id)); + EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _)) + .WillOnce(DoAll(SetArgReferee<2>(saved_app), Return(true))); + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + + EXPECT_CALL(*app_mngr, GetUserConsentForDevice("")) + .WillOnce(Return(policy::kDeviceAllowed)); + EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_)) + .WillRepeatedly(Return(false)); + + utils::SharedPtr<application_manager::Application> null_app; + EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(null_app)); + + ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(false)); + ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id)); + + EXPECT_CALL(*app_mngr, + SetState(test_app_id, restored_testType, test_audio_state)); + + bool res = res_ctrl.RestoreAppHMIState(app_mock); + EXPECT_TRUE(res); +} + +TEST_F(ResumeCtrlTest, SetupDefaultHMILevel) { + smart_objects::SmartObject saved_app; + + saved_app[application_manager::strings::hmi_level] = default_testType; + + EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_)) + .WillRepeatedly(Return(default_testType)); + + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + EXPECT_CALL(*app_mngr, GetUserConsentForDevice("")).Times(0); + EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_)) + .WillOnce(Return(true)); + EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(app_mock)); + EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_)) + .WillOnce(Return(default_testType)); + EXPECT_CALL(*app_mngr, + SetHmiState(test_app_id, default_testType)).Times(AtLeast(1)); + + ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(false)); + + ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id)); + EXPECT_CALL(*app_mngr, SetState(test_app_id, default_testType, + test_audio_state)).Times(2); + + res_ctrl.SetupDefaultHMILevel(app_mock); +} + +/** + * @brief group of tests which check correct SetAppHMIState +*/ + +TEST_F(ResumeCtrlTest, SetAppHMIState_HMINone_NotMedia_WithoutCheckPolicy) { + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + EXPECT_CALL(*app_mngr, GetUserConsentForDevice("")).Times(0); + EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_)) + .WillOnce(Return(true)); + EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(app_mock)); + EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_)) + .WillOnce(Return(default_testType)); + + ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(false)); + + ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id)); + EXPECT_CALL(*app_mngr, SetState(test_app_id, default_testType, + test_audio_state)).Times(2); + + bool res = res_ctrl.SetAppHMIState(app_mock, default_testType, false); + EXPECT_TRUE(res); +} + +// TODO(VVeremjova) APPLINK-16718 +TEST_F(ResumeCtrlTest, + DISABLED_SetAppHMIState_HMILimited_NotMedia_WithoutCheckPolicy) { + mobile_apis::HMILevel::eType testType = eType::HMI_LIMITED; + + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + + ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id)); + ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(false)); + ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id)); + + EXPECT_CALL(*app_mngr, GetUserConsentForDevice("")) + .WillRepeatedly(Return(policy::DeviceConsent::kDeviceAllowed)); + EXPECT_CALL(*app_mngr, SetState(test_app_id, testType, test_audio_state)); + + bool res = res_ctrl.SetAppHMIState(app_mock, testType, false); + EXPECT_TRUE(res); +} + +TEST_F(ResumeCtrlTest, SetAppHMIState_HMIFull_NotMedia_WithoutCheckPolicy) { + mobile_apis::HMILevel::eType testType = eType::HMI_FULL; + ::testing::InSequence seq; + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_)) + .WillOnce(Return(false)); + + // Only mocked application is exist + utils::SharedPtr<application_manager::Application> null_app; + EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(null_app)); + + ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(false)); + + // GetDefaultHmiLevel should not be called + EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_)).Times(0); + ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id)); + + EXPECT_CALL(*app_mngr, SetState(test_app_id, testType, test_audio_state)); + + EXPECT_CALL(*app_mngr, GetUserConsentForDevice("")).Times(0); + bool res = res_ctrl.SetAppHMIState(app_mock, testType, false); + EXPECT_TRUE(res); +} + +TEST_F(ResumeCtrlTest, + SetAppHMIState_HMIFull_NotMedia_WithoutPolicy_AnotherFullActiveExists) { + mobile_apis::HMILevel::eType testType = eType::HMI_FULL; + ::testing::InSequence seq; + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_)) + .WillOnce(Return(false)); + + EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(app_mock)); + EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_)) + .WillOnce(Return(default_testType)); + + ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(false)); + + ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id)); + + // Expect set default HMI state + EXPECT_CALL(*app_mngr, + SetState(test_app_id, default_testType, test_audio_state)); + + EXPECT_CALL(*app_mngr, GetUserConsentForDevice("")).Times(0); + bool res = res_ctrl.SetAppHMIState(app_mock, testType, false); + EXPECT_TRUE(res); +} + +TEST_F(ResumeCtrlTest, + SetAppHMIState_HMIFull_MediaAudio_WithoutPolicy_AnotherActiveAppExists) { + mobile_apis::HMILevel::eType testType = eType::HMI_FULL; + + // In case application is media, audio state will be AUDIBLE + test_audio_state = mobile_apis::AudioStreamingState::AUDIBLE; + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + + // Only our app in FULL + EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_)) + .WillOnce(Return(false)); + + // Active app exists + EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(app_mock)); + + EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_)).Times(0); + ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id)); + + ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(true)); + ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id)); + + mobile_apis::HMILevel::eType expected_testType = eType::HMI_LIMITED; + EXPECT_CALL(*app_mngr, + SetState(test_app_id, expected_testType, test_audio_state)); + + EXPECT_CALL(*app_mngr, GetUserConsentForDevice("")).Times(0); + bool res = res_ctrl.SetAppHMIState(app_mock, testType, false); + EXPECT_TRUE(res); +} + +TEST_F(ResumeCtrlTest, SetAppHMIState_HMIFull_Media_WithoutPolicy_FullExists) { + default_testType = eType::HMI_FULL; + + // In case application is media, audio state will be AUDIBLE + test_audio_state = mobile_apis::AudioStreamingState::AUDIBLE; + ::testing::InSequence seq; + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_)) + .WillOnce(Return(true)); + EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(app_mock)); + EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_)) + .WillOnce(Return(default_testType)); + + ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(true)); + + ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id)); + EXPECT_CALL(*app_mngr, + SetState(test_app_id, default_testType, test_audio_state)); + + EXPECT_CALL(*app_mngr, GetUserConsentForDevice("")).Times(0); + bool res = res_ctrl.SetAppHMIState(app_mock, default_testType, false); + EXPECT_TRUE(res); +} + +TEST_F(ResumeCtrlTest, SetAppHMIState_HMIFull_NotMedia_WithPolicy_DevAllowed) { + mobile_apis::HMILevel::eType testType = eType::HMI_FULL; + + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + + EXPECT_CALL(*app_mngr, GetUserConsentForDevice("12345")) + .WillOnce(Return(policy::kDeviceAllowed)); + + EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_)) + .WillOnce(Return(true)); + EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(app_mock)); + EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_)) + .WillOnce(Return(default_testType)); + + ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(false)); + + ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id)); + EXPECT_CALL(*app_mngr, + SetState(test_app_id, default_testType, test_audio_state)); + + bool res = res_ctrl.SetAppHMIState(app_mock, testType, true); + EXPECT_TRUE(res); +} + +TEST_F(ResumeCtrlTest, SetAppHMIState_HMIFull_Media_WithCheckPolicy) { + mobile_apis::HMILevel::eType testType = eType::HMI_FULL; + + // In case application is media, audio state will be AUDIBLE + test_audio_state = mobile_apis::AudioStreamingState::AUDIBLE; + ::testing::InSequence seq; + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + + // App is allowed + EXPECT_CALL(*app_mngr, GetUserConsentForDevice("12345")) + .WillOnce(Return(policy::kDeviceAllowed)); + EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_)) + .WillOnce(Return(false)); + EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(app_mock)); + EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_)).Times(0); + ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id)); + + ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(true)); + + ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id)); + + mobile_apis::HMILevel::eType expected_testType = eType::HMI_LIMITED; + EXPECT_CALL(*app_mngr, + SetState(test_app_id, expected_testType, test_audio_state)); + + bool res = res_ctrl.SetAppHMIState(app_mock, testType, true); + EXPECT_TRUE(res); +} + +TEST_F(ResumeCtrlTest, SetAppHMIState_HMIFull_Media_WithPolicy_DevDisallowed) { + mobile_apis::HMILevel::eType testType = eType::HMI_FULL; + + ::testing::InSequence seq; + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + EXPECT_CALL(*app_mngr, GetUserConsentForDevice("12345")) + .WillOnce(Return(policy::kDeviceDisallowed)); + + EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_)) + .WillOnce(Return(default_testType)); + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(true)); + ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id)); + EXPECT_CALL(*app_mngr, + SetState(test_app_id, default_testType, test_audio_state)); + + bool res = res_ctrl.SetAppHMIState(app_mock, testType, true); + EXPECT_FALSE(res); +} + +TEST_F(ResumeCtrlTest, SaveApplication) { + utils::SharedPtr<application_manager::Application> app_sh_mock = + new ApplicationMock(); + + EXPECT_CALL(*mock_storage, SaveApplication(app_sh_mock)); + res_ctrl.SaveApplication(app_sh_mock); +} + +TEST_F(ResumeCtrlTest, OnAppActivated_ResumptionHasStarted) { + ::profile::Profile::instance()->config_file_name("smartDeviceLink_test.ini"); + + smart_objects::SmartObject saved_app; + EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_)) + .WillOnce(Return(default_testType)); + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(false)); + ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id)); + EXPECT_CALL(*app_mngr, + SetState(test_app_id, default_testType, test_audio_state)); + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(test_policy_app_id)); + EXPECT_CALL(*mock_storage, GetSavedApplication(test_policy_app_id, _, _)) + .WillOnce(DoAll(SetArgReferee<2>(saved_app), Return(true))); + ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id)); + + bool res = res_ctrl.StartResumptionOnlyHMILevel(app_mock); + EXPECT_TRUE(res); + + utils::SharedPtr<ApplicationMock> app_sh_mock = new ApplicationMock(); + + EXPECT_CALL(*app_sh_mock, app_id()).WillOnce(Return(test_app_id)); + res_ctrl.OnAppActivated(app_sh_mock); +} + +TEST_F(ResumeCtrlTest, OnAppActivated_ResumptionNotActive) { + utils::SharedPtr<ApplicationMock> app_sh_mock = new ApplicationMock(); + EXPECT_CALL(*app_sh_mock, app_id()).Times(0); + res_ctrl.OnAppActivated(app_sh_mock); +} + +TEST_F(ResumeCtrlTest, IsHMIApplicationIdExist) { + uint32_t hmi_app_id = 10; + + EXPECT_CALL(*mock_storage, IsHMIApplicationIdExist(hmi_app_id)) + .WillOnce(Return(true)); + EXPECT_TRUE(res_ctrl.IsHMIApplicationIdExist(hmi_app_id)); +} + +TEST_F(ResumeCtrlTest, GetHMIApplicationID) { + uint32_t hmi_app_id = 10; + std::string device_id = "test_device_id"; + + EXPECT_CALL(*mock_storage, GetHMIApplicationID(test_policy_app_id, device_id)) + .WillOnce(Return(hmi_app_id)); + EXPECT_EQ(hmi_app_id, + res_ctrl.GetHMIApplicationID(test_policy_app_id, device_id)); +} + +TEST_F(ResumeCtrlTest, IsApplicationSaved) { + std::string policy_app_id = "policy_app_id"; + std::string device_id = "device_id"; + + EXPECT_CALL(*mock_storage, IsApplicationSaved(policy_app_id, device_id)) + .WillOnce(Return(true)); + EXPECT_TRUE(res_ctrl.IsApplicationSaved(policy_app_id, device_id)); +} + +TEST_F(ResumeCtrlTest, CheckPersistenceFiles_WithoutCommandAndChoiceSets) { + uint32_t ign_off_count = 0; + smart_objects::SmartObject saved_app; + saved_app[application_manager::strings::ign_off_count] = ign_off_count; + saved_app[application_manager::strings::hmi_level] = HMI_FULL; + + ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(test_policy_app_id)); + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + + EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _)) + .WillOnce(DoAll(SetArgReferee<2>(saved_app), Return(true))); + + EXPECT_TRUE(res_ctrl.CheckPersistenceFilesForResumption(app_mock)); +} + +TEST_F(ResumeCtrlTest, CheckPersistenceFilesForResumption_WithCommands) { + smart_objects::SmartObject test_application_commands; + uint32_t ign_off_count = 0; + smart_objects::SmartObject saved_app; + saved_app[application_manager::strings::ign_off_count] = ign_off_count; + saved_app[application_manager::strings::hmi_level] = HMI_FULL; + saved_app[application_manager::strings::application_commands] = + test_application_commands; + + ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(test_policy_app_id)); + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + + EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _)) + .WillOnce(DoAll(SetArgReferee<2>(saved_app), Return(true))); + + EXPECT_CALL(*application_manager::MockMessageHelper::message_helper_mock(), + VerifyImageFiles(_, _)) + .WillRepeatedly(Return(mobile_apis::Result::SUCCESS)); + + EXPECT_TRUE(res_ctrl.CheckPersistenceFilesForResumption(app_mock)); +} + +TEST_F(ResumeCtrlTest, CheckPersistenceFilesForResumption_WithChoiceSet) { + smart_objects::SmartObject test_choice_sets; + uint32_t ign_off_count = 0; + smart_objects::SmartObject saved_app; + saved_app[application_manager::strings::ign_off_count] = ign_off_count; + saved_app[application_manager::strings::hmi_level] = HMI_FULL; + saved_app[application_manager::strings::application_choice_sets] = + test_choice_sets; + + ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(test_policy_app_id)); + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + + EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _)) + .WillOnce(DoAll(SetArgReferee<2>(saved_app), Return(true))); + + EXPECT_TRUE(res_ctrl.CheckPersistenceFilesForResumption(app_mock)); +} + +// TODO (VVeremjova) APPLINK-16718 +TEST_F(ResumeCtrlTest, DISABLED_OnSuspend) { + EXPECT_CALL(*mock_storage, OnSuspend()); + res_ctrl.OnSuspend(); +} + +TEST_F(ResumeCtrlTest, OnAwake) { + EXPECT_CALL(*mock_storage, OnAwake()); + res_ctrl.OnAwake(); +} + +TEST_F(ResumeCtrlTest, RemoveApplicationFromSaved) { + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(test_policy_app_id)); + EXPECT_CALL(*mock_storage, RemoveApplicationFromSaved(_, _)) + .WillOnce(Return(true)); + EXPECT_TRUE(res_ctrl.RemoveApplicationFromSaved(app_mock)); +} + +TEST_F(ResumeCtrlTest, CheckApplicationHash) { + smart_objects::SmartObject saved_app; + + std::string test_hash = "saved_hash"; + saved_app[application_manager::strings::hash_id] = test_hash; + + ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id)); + ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(test_policy_app_id)); + EXPECT_CALL(*mock_storage, GetSavedApplication(test_policy_app_id, _, _)) + .WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true))); + EXPECT_TRUE(res_ctrl.CheckApplicationHash(app_mock, test_hash)); +} + +} // namespace resumption_test +} // namespace components +} // namespace test diff --git a/src/components/application_manager/test/resumption/resumption_data_db_test.cc b/src/components/application_manager/test/resumption/resumption_data_db_test.cc new file mode 100644 index 0000000000..a6ced14349 --- /dev/null +++ b/src/components/application_manager/test/resumption/resumption_data_db_test.cc @@ -0,0 +1,837 @@ +/* + * Copyright (c) 2015, 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. + */ + +#include <string> +#include <algorithm> +#include "gtest/gtest.h" +#include "include/application_mock.h" +#include "interfaces/MOBILE_API.h" +#include "sql_database.h" +#include "sql_query.h" + +#include "application_manager/application_manager_impl.h" +#include "config_profile/profile.h" +#include "utils/file_system.h" +#include "include/resumption_data_test.h" + +#include "application_manager/resumption/resumption_sql_queries.h" +#include "application_manager/resumption/resumption_data_db.h" + +namespace test { +namespace components { +namespace resumption_test { + +using ::testing::NiceMock; + +namespace am = application_manager; +using namespace file_system; + +using namespace resumption; +using namespace mobile_apis; + +class TestResumptionDataDB : public ResumptionDataDB { + public: + utils::dbms::SQLDatabase* get_db_handle() { return db(); } + + TestResumptionDataDB(DbStorage db_storage) : ResumptionDataDB(db_storage) {} +}; + +class ResumptionDataDBTest : public ResumptionDataTest { + protected: + virtual void SetUp() { + app_mock = new NiceMock<ApplicationMock>(); + policy_app_id_ = "test_policy_app_id"; + app_id_ = 10; + is_audio_ = true; + hash_ = "saved_hash"; + hmi_level_ = HMILevel::eType::HMI_FULL; + hmi_app_id_ = 8; + ign_off_count_ = 0; + grammar_id_ = 16; + } + virtual void TearDown() { + utils::dbms::SQLQuery query(test_db()); + EXPECT_TRUE(query.Prepare(remove_all_tables)); + EXPECT_TRUE(query.Exec()); + } + + static void SetUpTestCase() { + kDatabaseName = "resumption"; + if (is_in_file) { + ::profile::Profile::instance()->config_file_name( + "smartDeviceLink_test.ini"); + path_ = profile::Profile::instance()->app_storage_folder(); + CreateDirectory("./" + path_); + test_db_ = new utils::dbms::SQLDatabase(kDatabaseName); + test_db_->set_path(path_ + "/"); + res_db_ = new TestResumptionDataDB(In_File_Storage); + } else { + res_db_ = new TestResumptionDataDB(In_Memory_Storage); + test_db_ = res_db_->get_db_handle(); + } + + EXPECT_TRUE(test_db_->Open()); + EXPECT_TRUE(test_db_->IsReadWrite()); + } + + static utils::dbms::SQLDatabase* test_db_; + static std::string kDatabaseName; + static std::string path_; + + static void TearDownTestCase() { + test_db_->Close(); + if (is_in_file) { + ::profile::Profile::instance()->config_file_name("smartDeviceLink.ini"); + RemoveDirectory("./" + path_, true); + } + delete res_db_; + } + + utils::dbms::SQLDatabase* test_db() { return test_db_; } + std::string path() { return path_; } + + void SetZeroIgnOffTime() { + utils::dbms::SQLQuery query(test_db()); + EXPECT_TRUE(query.Prepare(KUpdateLastIgnOffTime)); + query.Bind(0, 0); + EXPECT_TRUE(query.Exec()); + } + + static TestResumptionDataDB* res_db_; + + TestResumptionDataDB* res_db() { return res_db_; } + + // Check that db includes tables with given elements + void CheckSavedDB(); + + static const bool is_in_file = false; + const std::string tables_exist = + "SELECT COUNT(*) FROM sqlite_master WHERE `type` = 'table';"; + const std::string init_last_ign_count = + "SELECT `last_ign_off_time` FROM resumption;"; + const std::string internal_data = "SELECT COUNT(*) FROM _internal_data;"; + + const std::string remove_all_tables = + "DELETE FROM `resumption`; " + "DELETE FROM `image`; " + "DELETE FROM `applicationChoiceSet`; " + "DELETE FROM `file`; " + "DELETE FROM `subMenu`; " + "DELETE FROM `TTSChunk`; " + "DELETE FROM `vrHelpItem`; " + "DELETE FROM `tableLimitedCharacterList`; " + "DELETE FROM `characterArray`; " + "DELETE FROM `choice`; " + "DELETE FROM `command`; " + "DELETE FROM `globalProperties`; " + "DELETE FROM `choiceArray`; " + "DELETE FROM `vrCommandsArray`; " + "DELETE FROM `helpTimeoutPromptArray`; " + "DELETE FROM `vrHelpItemArray`; " + "DELETE FROM `application`; " + "DELETE FROM `applicationChoiceSetArray`; " + "DELETE FROM `applicationCommandsArray`; " + "DELETE FROM `applicationFilesArray`; " + "DELETE FROM `applicationSubMenuArray`; " + "DELETE FROM `applicationSubscribtionsArray`; " + "DELETE FROM `_internal_data`; "; + + private: + void CheckExistenceApplication(); + void CheckAppData(); + void CheckAppFilesData(); + void CheckSubmenuData(); + void CheckCommandsData(); + void CheckChoiceSetData(); + + void CheckGlobalProportiesData(); + void CheckCharacters(int64_t global_properties_key); + void CheckVRHelpItem(int64_t global_properties_key); + + void BindId(utils::dbms::SQLQuery& query); +}; + +utils::dbms::SQLDatabase* ResumptionDataDBTest::test_db_ = NULL; +TestResumptionDataDB* ResumptionDataDBTest::res_db_ = NULL; +std::string ResumptionDataDBTest::kDatabaseName = ""; +std::string ResumptionDataDBTest::path_ = ""; + +void ResumptionDataDBTest::CheckSavedDB() { + utils::dbms::SQLQuery query_checks(test_db()); + EXPECT_TRUE(query_checks.Prepare(kChecksResumptionData)); + EXPECT_TRUE(query_checks.Exec()); + EXPECT_EQ(1, query_checks.GetInteger(0)); + + CheckExistenceApplication(); + CheckAppData(); + + CheckAppFilesData(); + CheckSubmenuData(); + CheckCommandsData(); + + CheckChoiceSetData(); + CheckGlobalProportiesData(); +} + +void ResumptionDataDBTest::CheckExistenceApplication() { + utils::dbms::SQLQuery query(test_db()); + EXPECT_TRUE(query.Prepare(kCheckApplication)); + query.Bind(0, device_id_); + query.Bind(1, policy_app_id_); + EXPECT_TRUE(query.Exec()); + EXPECT_EQ(1, query.GetInteger(0)); +} + +void ResumptionDataDBTest::CheckAppData() { + utils::dbms::SQLQuery query(test_db()); + EXPECT_TRUE(query.Prepare(kSelectAppTable)); + BindId(query); + EXPECT_TRUE(query.Exec()); + EXPECT_EQ(policy_app_id_, query.GetString(0)); + EXPECT_EQ(app_id_, query.GetUInteger(1)); + EXPECT_EQ(grammar_id_, query.GetUInteger(2)); + EXPECT_EQ(hash_, query.GetString(3)); + EXPECT_EQ(hmi_app_id_, query.GetUInteger(4)); + EXPECT_EQ(hmi_level_, query.GetInteger(5)); + + EXPECT_EQ(ign_off_count_, query.GetUInteger(6)); + + EXPECT_EQ(device_id_, query.GetString(8)); + EXPECT_EQ(is_audio_, query.GetBoolean(9)); +} + +void ResumptionDataDBTest::CheckGlobalProportiesData() { + utils::dbms::SQLQuery select_globalproperties(test_db()); + + EXPECT_TRUE(select_globalproperties.Prepare(kSelectCountGlobalProperties)); + BindId(select_globalproperties); + EXPECT_TRUE(select_globalproperties.Exec()); + EXPECT_EQ(1, select_globalproperties.GetInteger(0)); + + EXPECT_TRUE(select_globalproperties.Prepare(kSelectGlobalProperties)); + BindId(select_globalproperties); + + size_t help_prompt_idx = 0; + size_t timeout_prompt_idx = 0; + int64_t global_properties_key = 0; + while (select_globalproperties.Next()) { + if (global_properties_key != select_globalproperties.GetLongInt(0)) { + global_properties_key = select_globalproperties.GetLongInt(0); + EXPECT_EQ((*vr_help_title_).asString(), + select_globalproperties.GetString(1)); + EXPECT_EQ((*menu_title_).asString(), + select_globalproperties.GetString(2)); + EXPECT_EQ((*keyboard_props_)[am::strings::language].asInt(), + select_globalproperties.GetInteger(4)); + EXPECT_EQ((*keyboard_props_)[am::hmi_request::keyboard_layout].asInt(), + select_globalproperties.GetInteger(5)); + EXPECT_EQ((*keyboard_props_)[am::strings::key_press_mode].asInt(), + select_globalproperties.GetInteger(6)); + EXPECT_EQ((*keyboard_props_)[am::strings::auto_complete_text].asString(), + select_globalproperties.GetString(7)); + + EXPECT_FALSE(select_globalproperties.IsNull(3)); + utils::dbms::SQLQuery select_image(test_db()); + EXPECT_TRUE(select_image.Prepare(kSelectImage)); + select_image.Bind(0, select_globalproperties.GetLongInt(3)); + EXPECT_TRUE(select_image.Exec()); + EXPECT_EQ((*menu_icon_)[am::strings::image_type].asInt(), + select_image.GetInteger(0)); + EXPECT_EQ((*menu_icon_)[am::strings::value].asString(), + select_image.GetString(1)); + } + if (!select_globalproperties.IsNull(8)) { + utils::dbms::SQLQuery select_tts_chunk(test_db()); + EXPECT_TRUE(select_tts_chunk.Prepare(kSelectTTSChunk)); + select_tts_chunk.Bind(0, select_globalproperties.GetLongInt(8)); + EXPECT_TRUE(select_tts_chunk.Exec()); + + std::string text = + (*help_prompt_)[help_prompt_idx][am::strings::text].asString(); + int type = (*help_prompt_)[help_prompt_idx][am::strings::type].asInt(); + EXPECT_EQ(text, select_tts_chunk.GetString(0)); + EXPECT_EQ(type, select_tts_chunk.GetInteger(1)); + help_prompt_idx++; + } + if (!select_globalproperties.IsNull(9)) { + utils::dbms::SQLQuery select_tts_chunk(test_db()); + EXPECT_TRUE(select_tts_chunk.Prepare(kSelectTTSChunk)); + select_tts_chunk.Bind(0, select_globalproperties.GetLongInt(9)); + EXPECT_TRUE(select_tts_chunk.Exec()); + + std::string text = + (*timeout_prompt_)[timeout_prompt_idx][am::strings::text].asString(); + int type = + (*timeout_prompt_)[timeout_prompt_idx][am::strings::type].asInt(); + EXPECT_EQ(text, select_tts_chunk.GetString(0)); + EXPECT_EQ(type, select_tts_chunk.GetInteger(1)); + timeout_prompt_idx++; + } + CheckCharacters(global_properties_key); + CheckVRHelpItem(global_properties_key); + } +} +void ResumptionDataDBTest::CheckVRHelpItem(int64_t global_properties_key) { + utils::dbms::SQLQuery checks_vrhelp_item(test_db()); + EXPECT_TRUE(checks_vrhelp_item.Prepare(kChecksVrHelpItem)); + checks_vrhelp_item.Bind(0, global_properties_key); + EXPECT_TRUE(checks_vrhelp_item.Exec()); + EXPECT_NE(0, checks_vrhelp_item.GetInteger(0)); + if (!checks_vrhelp_item.GetInteger(0)) { + utils::dbms::SQLQuery select_vrhelp_item(test_db()); + EXPECT_TRUE(select_vrhelp_item.Prepare(kSelectVrHelpItem)); + select_vrhelp_item.Bind(0, global_properties_key); + size_t vr_help_item_idx = 0; + while (select_vrhelp_item.Next()) { + std::string vr_text = + (*vr_help_)[vr_help_item_idx][am::strings::text].asString(); + std::string vr_position = + (*vr_help_)[vr_help_item_idx++][am::strings::position].asString(); + EXPECT_EQ(vr_text, select_vrhelp_item.GetString(0)); + EXPECT_EQ(vr_position, select_vrhelp_item.GetString(1)); + } + } +} + +void ResumptionDataDBTest::CheckCharacters(int64_t global_properties_key) { + utils::dbms::SQLQuery checks_characters(test_db()); + EXPECT_TRUE(checks_characters.Prepare(kChecksCharacter)); + checks_characters.Bind(0, global_properties_key); + EXPECT_TRUE(checks_characters.Exec()); + EXPECT_NE(0, checks_characters.GetInteger(0)); + if (!checks_characters.GetInteger(0)) { + utils::dbms::SQLQuery select_characters(test_db()); + EXPECT_TRUE(select_characters.Prepare(kSelectCharacter)); + select_characters.Bind(0, global_properties_key); + size_t characters_idx = 0; + while (select_characters.Next()) { + std::string character = + (*keyboard_props_)[am::strings::limited_character_list] + [characters_idx++].asString(); + EXPECT_EQ(character, select_characters.GetString(0)); + } + } +} + +void ResumptionDataDBTest::CheckSubmenuData() { + utils::dbms::SQLQuery select_submenu(test_db()); + + EXPECT_TRUE(select_submenu.Prepare(kSelectCountSubMenu)); + BindId(select_submenu); + EXPECT_TRUE(select_submenu.Exec()); + EXPECT_EQ(count_of_submenues, select_submenu.GetUInteger(0)); + + EXPECT_TRUE(select_submenu.Prepare(kSelectSubMenu)); + BindId(select_submenu); + int i = 10; + while (select_submenu.Next()) { + uint32_t test_id = (*test_submenu_map[i])[am::strings::menu_id].asUInt(); + std::string name = + (*test_submenu_map[i])[am::strings::menu_name].asString(); + int position = (*test_submenu_map[i])[am::strings::position].asInt(); + EXPECT_EQ(test_id, select_submenu.GetUInteger(0)); + EXPECT_EQ(name, select_submenu.GetString(1)); + EXPECT_EQ(position, select_submenu.GetInteger(2)); + i++; + } +} + +void ResumptionDataDBTest::CheckCommandsData() { + utils::dbms::SQLQuery select_commands(test_db()); + + EXPECT_TRUE(select_commands.Prepare(kSelectCountCommands)); + BindId(select_commands); + EXPECT_TRUE(select_commands.Exec()); + EXPECT_EQ(count_of_commands, select_commands.GetUInteger(0)); + + EXPECT_TRUE(select_commands.Prepare(kSelectCommands)); + BindId(select_commands); + + int32_t i = -1; + int64_t command_key = 0; + int j = 0; + while (select_commands.Next()) { + if (command_key != select_commands.GetLongInt(0)) { + ++i; + uint cmd = (*test_commands_map[i])[am::strings::cmd_id].asUInt(); + EXPECT_EQ(cmd, select_commands.GetUInteger(1)); + std::string name = + (*test_commands_map[i])[am::strings::menu_params] + [am::strings::menu_name].asString(); + EXPECT_EQ(name, select_commands.GetString(2)); + int position = (*test_commands_map[i])[am::strings::menu_params] + [am::strings::position].asInt(); + EXPECT_EQ(position, select_commands.GetInteger(4)); + int parent_id = + (*test_commands_map[i])[am::strings::menu_params] + [am::hmi_request::parent_id].asInt(); + EXPECT_EQ(parent_id, select_commands.GetInteger(3)); + std::string icon_name = + (*test_commands_map[i])[am::strings::cmd_icon][am::strings::value] + .asString(); + EXPECT_EQ(icon_name, select_commands.GetString(5)); + + int icon_type = (*test_commands_map[i])[am::strings::cmd_icon] + [am::strings::image_type].asInt(); + EXPECT_EQ(icon_type, select_commands.GetInteger(6)); + + j = 0; + command_key = select_commands.GetLongInt(0); + } + std::string vr = + (*test_commands_map[i])[am::strings::vr_commands][j].asString(); + EXPECT_EQ(vr, select_commands.GetString(7)); + j++; + } +} + +void ResumptionDataDBTest::CheckChoiceSetData() { + utils::dbms::SQLQuery select_choice_set(test_db()); + EXPECT_TRUE(select_choice_set.Prepare(kSelectCountChoiceSet)); + BindId(select_choice_set); + EXPECT_TRUE(select_choice_set.Exec()); + EXPECT_EQ(count_of_choice_sets, select_choice_set.GetUInteger(0)); + + EXPECT_TRUE(select_choice_set.Prepare(kSelectChoiceSets)); + int64_t app_set_key = 0; + int64_t choice_key = 0; + int32_t choice_set_idx = -1; + int32_t choice_idx = -1; + size_t vr_cmd_idx = 0; + sm::SmartObject command; + while (select_choice_set.Next()) { + if (app_set_key != select_choice_set.GetLongInt(0)) { + command = (*test_choiceset_map[app_set_key]); + ++choice_set_idx; + + int choice_set_id = + command[am::strings::interaction_choice_set_id].asUInt(); + int grammar_id = command[am::strings::grammar_id].asUInt(); + + EXPECT_EQ(grammar_id, select_choice_set.GetInteger(1)); + EXPECT_EQ(choice_set_id, select_choice_set.GetInteger(2)); + + app_set_key = select_choice_set.GetLongInt(0); + choice_idx = -1; + } + + if (choice_key != select_choice_set.GetLongInt(3)) { + ++choice_idx; + choice_key = select_choice_set.GetLongInt(3); + int choice_id = + command[am::strings::choice_set][choice_idx][am::strings::choice_id] + .asUInt(); + std::string menu_name = + command[am::strings::choice_set][choice_idx][am::strings::menu_name] + .asString(); + std::string secondary_text = + command[am::strings::choice_set][choice_idx] + [am::strings::secondary_text].asString(); + std::string tertiary_text = + command[am::strings::choice_set][choice_idx] + [am::strings::tertiary_text].asString(); + + EXPECT_EQ(choice_id, select_choice_set.GetInteger(4)); + EXPECT_EQ(menu_name, select_choice_set.GetString(5)); + EXPECT_EQ(secondary_text, select_choice_set.GetString(6)); + EXPECT_EQ(tertiary_text, select_choice_set.GetString(7)); + + EXPECT_FALSE(select_choice_set.IsNull(8)); + utils::dbms::SQLQuery select_image(test_db()); + EXPECT_TRUE(select_image.Prepare(kSelectImage)); + select_image.Bind(0, select_choice_set.GetLongInt(8)); + EXPECT_TRUE(select_image.Exec()); + std::string image_value = + command[am::strings::choice_set][choice_idx][am::strings::image] + [am::strings::value].asString(); + int image_type = + command[am::strings::choice_set][choice_idx][am::strings::image] + [am::strings::image_type].asInt(); + EXPECT_EQ(image_value, select_image.GetString(1)); + EXPECT_EQ(image_type, select_image.GetInteger(0)); + + EXPECT_FALSE(select_choice_set.IsNull(9)); + EXPECT_TRUE(select_image.Prepare(kSelectImage)); + select_image.Bind(0, select_choice_set.GetLongInt(9)); + EXPECT_TRUE(select_image.Exec()); + image_value = + command[am::strings::choice_set][choice_idx] + [am::strings::secondary_image][am::strings::value].asString(); + image_type = + command[am::strings::choice_set][choice_idx] + [am::strings::secondary_image][am::strings::image_type] + .asInt(); + EXPECT_EQ(image_value, select_image.GetString(1)); + EXPECT_EQ(image_type, select_image.GetInteger(0)); + + vr_cmd_idx = 0; + } + std::string vr_comm = + command[am::strings::choice_set][choice_idx][am::strings::vr_commands] + [vr_cmd_idx++].asString(); + EXPECT_EQ(vr_comm, select_choice_set.GetString(10)); + } +} + +void ResumptionDataDBTest::CheckAppFilesData() { + utils::dbms::SQLQuery query(test_db()); + EXPECT_TRUE(query.Prepare(kSelectCountFiles)); + BindId(query); + EXPECT_TRUE(query.Exec()); + EXPECT_EQ(count_of_files, query.GetUInteger(0)); + + EXPECT_TRUE(query.Prepare(kSelectFiles)); + BindId(query); + am::AppFile check_file; + int i = 0; + while (query.Next()) { + char numb[12]; + std::snprintf(numb, 12, "%d", i); + check_file = app_files_map_["test_file " + std::string(numb)]; + + EXPECT_EQ(check_file.file_type, query.GetInteger(0)); + EXPECT_EQ(check_file.is_download_complete, query.GetBoolean(1)); + EXPECT_EQ(check_file.is_persistent, query.GetBoolean(2)); + EXPECT_EQ(check_file.file_name, query.GetString(3)); + i++; + } +} + +void ResumptionDataDBTest::BindId(utils::dbms::SQLQuery& query) { + query.Bind(0, policy_app_id_); + query.Bind(1, device_id_); +} + +TEST_F(ResumptionDataDBTest, Init) { + utils::dbms::SQLQuery query_checks(test_db()); + + EXPECT_TRUE(res_db()->Init()); + + EXPECT_TRUE(query_checks.Prepare(tables_exist)); + EXPECT_TRUE(query_checks.Exec()); + EXPECT_NE(0, query_checks.GetInteger(0)); + + EXPECT_TRUE(query_checks.Prepare(kChecksResumptionData)); + EXPECT_TRUE(query_checks.Exec()); + EXPECT_NE(0, query_checks.GetInteger(0)); + + EXPECT_TRUE(query_checks.Prepare(init_last_ign_count)); + EXPECT_TRUE(query_checks.Exec()); + EXPECT_EQ(0, query_checks.GetInteger(0)); + + EXPECT_TRUE(query_checks.Prepare(internal_data)); + EXPECT_TRUE(query_checks.Exec()); + EXPECT_LE(0, query_checks.GetInteger(0)); +} + +TEST_F(ResumptionDataDBTest, SaveApplication) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + res_db()->SaveApplication(app_mock); + CheckSavedDB(); +} + +TEST_F(ResumptionDataDBTest, RemoveApplicationFromSaved) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + res_db()->SaveApplication(app_mock); + CheckSavedDB(); + EXPECT_TRUE(res_db()->RemoveApplicationFromSaved(policy_app_id_, device_id_)); + + sm::SmartObject remove_app; + EXPECT_FALSE( + res_db()->GetSavedApplication(policy_app_id_, device_id_, remove_app)); + EXPECT_TRUE(remove_app.empty()); +} + +TEST_F(ResumptionDataDBTest, RemoveApplicationFromSaved_AppNotSaved) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + res_db()->SaveApplication(app_mock); + + sm::SmartObject saved_app; + EXPECT_FALSE( + res_db()->GetSavedApplication(policy_app_id_, "54321", saved_app)); + EXPECT_TRUE(saved_app.empty()); +} + +TEST_F(ResumptionDataDBTest, SavedApplicationTwice) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + res_db()->SaveApplication(app_mock); + CheckSavedDB(); + res_db()->SaveApplication(app_mock); + CheckSavedDB(); +} + +TEST_F(ResumptionDataDBTest, SavedApplicationTwice_UpdateApp) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + res_db()->SaveApplication(app_mock); + CheckSavedDB(); + (*vr_help_)[0][am::strings::position] = 2; + + res_db()->SaveApplication(app_mock); + CheckSavedDB(); +} + +TEST_F(ResumptionDataDBTest, IsApplicationSaved_ApplicationSaved) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + res_db()->SaveApplication(app_mock); + ssize_t result = res_db()->IsApplicationSaved(policy_app_id_, device_id_); + EXPECT_EQ(0, result); +} + +TEST_F(ResumptionDataDBTest, IsApplicationSaved_ApplicationRemoved) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + res_db()->SaveApplication(app_mock); + EXPECT_TRUE(res_db()->RemoveApplicationFromSaved(policy_app_id_, device_id_)); + ssize_t result = res_db()->IsApplicationSaved(policy_app_id_, device_id_); + EXPECT_EQ(-1, result); +} + +TEST_F(ResumptionDataDBTest, GetSavedApplication) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + res_db()->SaveApplication(app_mock); + CheckSavedDB(); + + sm::SmartObject saved_app; + EXPECT_TRUE( + res_db()->GetSavedApplication(policy_app_id_, device_id_, saved_app)); + CheckSavedApp(saved_app); +} + +TEST_F(ResumptionDataDBTest, GetSavedApplication_AppNotSaved) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + sm::SmartObject saved_app; + EXPECT_FALSE( + res_db()->GetSavedApplication(policy_app_id_, "54321", saved_app)); + EXPECT_TRUE(saved_app.empty()); +} + +TEST_F(ResumptionDataDBTest, GetDataForLoadResumeData) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + res_db()->SaveApplication(app_mock); + CheckSavedDB(); + sm::SmartObject saved_app; + res_db()->GetDataForLoadResumeData(saved_app); + + EXPECT_EQ(policy_app_id_, saved_app[0][am::strings::app_id].asString()); + EXPECT_EQ(device_id_, saved_app[0][am::strings::device_id].asString()); + EXPECT_EQ(hmi_level_, static_cast<HMILevel::eType>( + saved_app[0][am::strings::hmi_level].asInt())); + EXPECT_EQ(ign_off_count_, saved_app[0][am::strings::ign_off_count].asUInt()); +} + +TEST_F(ResumptionDataDBTest, GetDataForLoadResumeData_AppRemove) { + sm::SmartObject saved_app; + + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + res_db()->SaveApplication(app_mock); + CheckSavedDB(); + EXPECT_TRUE(res_db()->RemoveApplicationFromSaved(policy_app_id_, device_id_)); + res_db()->GetDataForLoadResumeData(saved_app); + EXPECT_TRUE(saved_app.empty()); +} + +TEST_F(ResumptionDataDBTest, UpdateHmiLevel) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + res_db()->SaveApplication(app_mock); + CheckSavedDB(); + HMILevel::eType new_hmi_level = HMILevel::HMI_LIMITED; + res_db()->UpdateHmiLevel(policy_app_id_, device_id_, new_hmi_level); + hmi_level_ = new_hmi_level; + CheckSavedDB(); +} + +TEST_F(ResumptionDataDBTest, IsHMIApplicationIdExist_AppIsSaved) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + res_db()->SaveApplication(app_mock); + CheckSavedDB(); + EXPECT_TRUE(res_db()->IsHMIApplicationIdExist(hmi_app_id_)); +} + +TEST_F(ResumptionDataDBTest, IsHMIApplicationIdExist_AppNotSaved) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + res_db()->SaveApplication(app_mock); + CheckSavedDB(); + uint32_t new_hmi_app_id_ = hmi_app_id_ + 10; + EXPECT_FALSE(res_db()->IsHMIApplicationIdExist(new_hmi_app_id_)); +} + +TEST_F(ResumptionDataDBTest, GetHMIApplicationID) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + res_db()->SaveApplication(app_mock); + CheckSavedDB(); + EXPECT_EQ(hmi_app_id_, + res_db()->GetHMIApplicationID(policy_app_id_, device_id_)); +} + +TEST_F(ResumptionDataDBTest, GetHMIApplicationID_AppNotSaved) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + res_db()->SaveApplication(app_mock); + CheckSavedDB(); + EXPECT_EQ(0u, res_db()->GetHMIApplicationID(policy_app_id_, "other_dev_id")); +} + +TEST_F(ResumptionDataDBTest, OnSuspend) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + SetZeroIgnOffTime(); + res_db()->SaveApplication(app_mock); + CheckSavedDB(); + + res_db()->OnSuspend(); + ign_off_count_++; + CheckSavedDB(); +} + +TEST_F(ResumptionDataDBTest, OnSuspendFourTimes) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + SetZeroIgnOffTime(); + res_db()->SaveApplication(app_mock); + CheckSavedDB(); + + res_db()->OnSuspend(); + ign_off_count_++; + CheckSavedDB(); + + res_db()->OnSuspend(); + ign_off_count_++; + CheckSavedDB(); + res_db()->OnSuspend(); + ign_off_count_++; + CheckSavedDB(); + + res_db()->OnSuspend(); + + ssize_t result = res_db()->IsApplicationSaved(policy_app_id_, device_id_); + EXPECT_EQ(-1, result); +} + +TEST_F(ResumptionDataDBTest, OnSuspendOnAwake) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + SetZeroIgnOffTime(); + + res_db()->SaveApplication(app_mock); + CheckSavedDB(); + + res_db()->OnSuspend(); + + ign_off_count_++; + CheckSavedDB(); + res_db()->OnAwake(); + ign_off_count_ = 0; + CheckSavedDB(); +} + +TEST_F(ResumptionDataDBTest, Awake_AppNotSuspended) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + SetZeroIgnOffTime(); + + res_db()->SaveApplication(app_mock); + CheckSavedDB(); + + res_db()->OnAwake(); + ign_off_count_ = 0; + CheckSavedDB(); +} + +TEST_F(ResumptionDataDBTest, TwiceAwake_AppNotSuspended) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + SetZeroIgnOffTime(); + + res_db()->SaveApplication(app_mock); + CheckSavedDB(); + + res_db()->OnSuspend(); + res_db()->OnAwake(); + ign_off_count_ = 0; + CheckSavedDB(); + + res_db()->OnAwake(); + CheckSavedDB(); +} + +TEST_F(ResumptionDataDBTest, GetHashId) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + + res_db()->SaveApplication(app_mock); + + std::string test_hash; + EXPECT_TRUE(res_db()->GetHashId(policy_app_id_, device_id_, test_hash)); + EXPECT_EQ(hash_, test_hash); +} + +TEST_F(ResumptionDataDBTest, GetIgnOffTime_AfterSuspendAndAwake) { + PrepareData(); + EXPECT_TRUE(res_db()->Init()); + SetZeroIgnOffTime(); + uint32_t last_ign_off_time; + + res_db()->SaveApplication(app_mock); + + last_ign_off_time = res_db()->GetIgnOffTime(); + EXPECT_EQ(0u, last_ign_off_time); + + res_db()->OnSuspend(); + + uint32_t after_suspend; + after_suspend = res_db()->GetIgnOffTime(); + EXPECT_LE(last_ign_off_time, after_suspend); + + uint32_t after_awake; + res_db()->OnAwake(); + + after_awake = res_db()->GetIgnOffTime(); + EXPECT_LE(after_suspend, after_awake); +} + +} // namespace resumption_test +} // namespace components +} // namespace test diff --git a/src/components/application_manager/test/resumption/resumption_data_json_test.cc b/src/components/application_manager/test/resumption/resumption_data_json_test.cc new file mode 100644 index 0000000000..24a16596eb --- /dev/null +++ b/src/components/application_manager/test/resumption/resumption_data_json_test.cc @@ -0,0 +1,394 @@ +/* + * Copyright (c) 2015, 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. + */ + +#include <string> +#include <algorithm> +#include "gtest/gtest.h" + +#include "application_manager/usage_statistics.h" +#include "include/application_mock.h" +#include "include/resumption_data_mock.h" +#include "interfaces/MOBILE_API.h" +#include "resumption/last_state.h" + +#include "include/resumption_data_test.h" +#include "formatters/CFormatterJsonBase.hpp" +#include "config_profile/profile.h" +#include "utils/file_system.h" + +#include "application_manager/resumption/resumption_data_json.h" +namespace test { +namespace components { +namespace resumption_test { + +using ::testing::_; +using ::testing::Return; +using ::testing::NiceMock; + +namespace am = application_manager; +using namespace Json; +using namespace file_system; + +using namespace resumption; +using namespace mobile_apis; +namespace Formatters = NsSmartDeviceLink::NsJSONHandler::Formatters; + +class ResumptionDataJsonTest : public ResumptionDataTest { + protected: + virtual void SetUp() { + app_mock = new NiceMock<ApplicationMock>(); + + policy_app_id_ = "test_policy_app_id"; + app_id_ = 10; + is_audio_ = true; + grammar_id_ = 20; + hash_ = "saved_hash"; + hmi_level_ = HMILevel::eType::HMI_FULL; + hmi_app_id_ = 8; + ign_off_count_ = 0; + } + + void CheckSavedJson() { + Value& dictionary = LastState::instance()->dictionary; + ASSERT_TRUE(dictionary[am::strings::resumption].isObject()); + ASSERT_TRUE( + dictionary[am::strings::resumption][am::strings::resume_app_list] + .isArray()); + Value& resume_app_list = + dictionary[am::strings::resumption][am::strings::resume_app_list]; + sm::SmartObject res_app_list; + for (uint32_t i = 0; i < resume_app_list.size(); i++) { + Formatters::CFormatterJsonBase::jsonValueToObj(resume_app_list[i], + res_app_list); + CheckSavedApp(res_app_list); + } + } + + void SetZeroIgnOff() { + Value& dictionary = LastState::instance()->dictionary; + Value& res = dictionary[am::strings::resumption]; + res[am::strings::last_ign_off_time] = 0; + LastState::instance()->SaveToFileSystem(); + } +}; + +TEST_F(ResumptionDataJsonTest, SaveApplication) { + ResumptionDataJson res_json; + PrepareData(); + res_json.SaveApplication(app_mock); + CheckSavedJson(); +} + +TEST_F(ResumptionDataJsonTest, SavedApplicationTwice) { + ResumptionDataJson res_json; + PrepareData(); + res_json.SaveApplication(app_mock); + CheckSavedJson(); + res_json.SaveApplication(app_mock); + CheckSavedJson(); +} + +TEST_F(ResumptionDataJsonTest, SavedApplicationTwice_UpdateApp) { + ResumptionDataJson res_json; + PrepareData(); + res_json.SaveApplication(app_mock); + CheckSavedJson(); + (*vr_help_)[0][am::strings::position] = 2; + + res_json.SaveApplication(app_mock); + CheckSavedJson(); +} + +TEST_F(ResumptionDataJsonTest, RemoveApplicationFromSaved) { + ResumptionDataJson res_json; + PrepareData(); + res_json.SaveApplication(app_mock); + EXPECT_TRUE(res_json.RemoveApplicationFromSaved(policy_app_id_, device_id_)); + + // Check that application was deleted + smart_objects::SmartObject remove_app; + EXPECT_FALSE( + res_json.GetSavedApplication(policy_app_id_, device_id_, remove_app)); + EXPECT_TRUE(remove_app.empty()); +} + +TEST_F(ResumptionDataJsonTest, RemoveApplicationFromSaved_AppNotSaved) { + ResumptionDataJson res_json; + EXPECT_FALSE(res_json.RemoveApplicationFromSaved(policy_app_id_, "54321")); +} + +TEST_F(ResumptionDataJsonTest, IsApplicationSaved_ApplicationSaved) { + ResumptionDataJson res_json; + PrepareData(); + res_json.SaveApplication(app_mock); + CheckSavedJson(); + ssize_t result = res_json.IsApplicationSaved(policy_app_id_, device_id_); + EXPECT_EQ(0, result); +} + +TEST_F(ResumptionDataJsonTest, IsApplicationSaved_ApplicationRemoved) { + ResumptionDataJson res_json; + PrepareData(); + res_json.SaveApplication(app_mock); + CheckSavedJson(); + EXPECT_TRUE(res_json.RemoveApplicationFromSaved(policy_app_id_, device_id_)); + ssize_t result = res_json.IsApplicationSaved(policy_app_id_, device_id_); + EXPECT_EQ(-1, result); +} + +TEST_F(ResumptionDataJsonTest, GetSavedApplication) { + ResumptionDataJson res_json; + PrepareData(); + res_json.SaveApplication(app_mock); + smart_objects::SmartObject saved_app; + EXPECT_TRUE( + res_json.GetSavedApplication(policy_app_id_, device_id_, saved_app)); + CheckSavedApp(saved_app); +} + +TEST_F(ResumptionDataJsonTest, GetSavedApplication_AppNotSaved) { + ResumptionDataJson res_json; + smart_objects::SmartObject saved_app; + EXPECT_FALSE( + res_json.GetSavedApplication(policy_app_id_, "54321", saved_app)); + EXPECT_TRUE(saved_app.empty()); +} + +TEST_F(ResumptionDataJsonTest, GetDataForLoadResumeData) { + ResumptionDataJson res_json; + PrepareData(); + res_json.SaveApplication(app_mock); + CheckSavedJson(); + smart_objects::SmartObject saved_app; + res_json.GetDataForLoadResumeData(saved_app); + + EXPECT_EQ(policy_app_id_, saved_app[0][am::strings::app_id].asString()); + EXPECT_EQ(device_id_, saved_app[0][am::strings::device_id].asString()); + EXPECT_EQ(hmi_level_, static_cast<HMILevel::eType>( + saved_app[0][am::strings::hmi_level].asInt())); + EXPECT_EQ(ign_off_count_, saved_app[0][am::strings::ign_off_count].asUInt()); +} + +TEST_F(ResumptionDataJsonTest, GetDataForLoadResumeData_AppRemove) { + ResumptionDataJson res_json; + smart_objects::SmartObject saved_app; + + PrepareData(); + res_json.SaveApplication(app_mock); + CheckSavedJson(); + EXPECT_TRUE(res_json.RemoveApplicationFromSaved(policy_app_id_, device_id_)); + res_json.GetDataForLoadResumeData(saved_app); + EXPECT_TRUE(saved_app.empty()); +} + +TEST_F(ResumptionDataJsonTest, UpdateHmiLevel) { + ResumptionDataJson res_json; + PrepareData(); + res_json.SaveApplication(app_mock); + CheckSavedJson(); + HMILevel::eType new_hmi_level = HMILevel::HMI_LIMITED; + res_json.UpdateHmiLevel(policy_app_id_, device_id_, new_hmi_level); + hmi_level_ = new_hmi_level; + + CheckSavedJson(); +} + +TEST_F(ResumptionDataJsonTest, IsHMIApplicationIdExist_AppIsSaved) { + ResumptionDataJson res_json; + PrepareData(); + res_json.SaveApplication(app_mock); + CheckSavedJson(); + EXPECT_TRUE(res_json.IsHMIApplicationIdExist(hmi_app_id_)); +} + +TEST_F(ResumptionDataJsonTest, IsHMIApplicationIdExist_AppNotSaved) { + ResumptionDataJson res_json; + PrepareData(); + res_json.SaveApplication(app_mock); + + CheckSavedJson(); + uint32_t new_hmi_app_id_ = hmi_app_id_ + 10; + EXPECT_FALSE(res_json.IsHMIApplicationIdExist(new_hmi_app_id_)); +} + +TEST_F(ResumptionDataJsonTest, GetHMIApplicationID) { + ResumptionDataJson res_json; + PrepareData(); + res_json.SaveApplication(app_mock); + CheckSavedJson(); + EXPECT_EQ(hmi_app_id_, + res_json.GetHMIApplicationID(policy_app_id_, device_id_)); +} + +TEST_F(ResumptionDataJsonTest, GetHMIApplicationID_AppNotSaved) { + ResumptionDataJson res_json; + PrepareData(); + res_json.SaveApplication(app_mock); + EXPECT_EQ(0u, res_json.GetHMIApplicationID(policy_app_id_, "other_dev_id")); +} + +TEST_F(ResumptionDataJsonTest, OnSuspend) { + ResumptionDataJson res_json; + ::profile::Profile::instance()->config_file_name("smartDeviceLink_test.ini"); + SetZeroIgnOff(); + PrepareData(); + + res_json.SaveApplication(app_mock); + CheckSavedJson(); + + res_json.OnSuspend(); + ign_off_count_++; + CheckSavedJson(); + + EXPECT_TRUE(FileExists("./test_app_info.dat")); + EXPECT_TRUE(DirectoryExists("./test_storage")); + EXPECT_TRUE(RemoveDirectory("./test_storage", true)); + EXPECT_TRUE(DeleteFile("./test_app_info.dat")); + ::profile::Profile::instance()->config_file_name("smartDeviceLink.ini"); +} + +TEST_F(ResumptionDataJsonTest, OnSuspendFourTimes) { + ResumptionDataJson res_json; + PrepareData(); + ::profile::Profile::instance()->config_file_name("smartDeviceLink_test.ini"); + SetZeroIgnOff(); + res_json.SaveApplication(app_mock); + CheckSavedJson(); + + res_json.OnSuspend(); + ign_off_count_++; + CheckSavedJson(); + + res_json.OnSuspend(); + res_json.OnSuspend(); + res_json.OnSuspend(); + + ssize_t result = res_json.IsApplicationSaved(policy_app_id_, device_id_); + EXPECT_EQ(-1, result); + + EXPECT_TRUE(FileExists("./test_app_info.dat")); + EXPECT_TRUE(DirectoryExists("./test_storage")); + EXPECT_TRUE(RemoveDirectory("./test_storage", true)); + EXPECT_TRUE(DeleteFile("./test_app_info.dat")); + ::profile::Profile::instance()->config_file_name("smartDeviceLink.ini"); +} + +TEST_F(ResumptionDataJsonTest, OnSuspendOnAwake) { + ResumptionDataJson res_json; + PrepareData(); + ::profile::Profile::instance()->config_file_name("smartDeviceLink_test.ini"); + SetZeroIgnOff(); + res_json.SaveApplication(app_mock); + CheckSavedJson(); + + res_json.OnSuspend(); + ign_off_count_++; + CheckSavedJson(); + + res_json.OnAwake(); + ign_off_count_ = 0; + CheckSavedJson(); + EXPECT_TRUE(RemoveDirectory("./test_storage", true)); + EXPECT_TRUE(DeleteFile("./test_app_info.dat")); + ::profile::Profile::instance()->config_file_name("smartDeviceLink.ini"); +} + +TEST_F(ResumptionDataJsonTest, Awake_AppNotSuspended) { + ResumptionDataJson res_json; + SetZeroIgnOff(); + PrepareData(); + res_json.SaveApplication(app_mock); + CheckSavedJson(); + + res_json.OnAwake(); + ign_off_count_ = 0; + CheckSavedJson(); +} + +TEST_F(ResumptionDataJsonTest, TwiceAwake_AppNotSuspended) { + ResumptionDataJson res_json; + SetZeroIgnOff(); + PrepareData(); + res_json.SaveApplication(app_mock); + CheckSavedJson(); + + res_json.OnSuspend(); + res_json.OnAwake(); + ign_off_count_ = 0; + CheckSavedJson(); + + res_json.OnAwake(); + CheckSavedJson(); +} + +TEST_F(ResumptionDataJsonTest, GetHashId) { + ResumptionDataJson res_json; + PrepareData(); + res_json.SaveApplication(app_mock); + CheckSavedJson(); + + std::string test_hash; + EXPECT_TRUE(res_json.GetHashId(policy_app_id_, device_id_, test_hash)); + EXPECT_EQ(hash_, test_hash); +} + +TEST_F(ResumptionDataJsonTest, GetIgnOffTime_AfterSuspendAndAwake) { + ResumptionDataJson res_json; + uint32_t last_ign_off_time; + PrepareData(); + ::profile::Profile::instance()->config_file_name("smartDeviceLink_test.ini"); + SetZeroIgnOff(); + res_json.SaveApplication(app_mock); + CheckSavedJson(); + last_ign_off_time = res_json.GetIgnOffTime(); + EXPECT_EQ(0u, last_ign_off_time); + + res_json.OnSuspend(); + + uint32_t after_suspend; + after_suspend = res_json.GetIgnOffTime(); + EXPECT_LE(last_ign_off_time, after_suspend); + + uint32_t after_awake; + res_json.OnAwake(); + + after_awake = res_json.GetIgnOffTime(); + EXPECT_LE(after_suspend, after_awake); + + EXPECT_TRUE(RemoveDirectory("./test_storage", true)); + EXPECT_TRUE(DeleteFile("./test_app_info.dat")); + ::profile::Profile::instance()->config_file_name("smartDeviceLink.ini"); +} + +} // namespace resumption_test +} // namespace components +} // namespace test diff --git a/src/components/application_manager/test/resumption/resumption_data_test.cc b/src/components/application_manager/test/resumption/resumption_data_test.cc new file mode 100644 index 0000000000..b8054b0d85 --- /dev/null +++ b/src/components/application_manager/test/resumption/resumption_data_test.cc @@ -0,0 +1,549 @@ +/* + * Copyright (c) 2015, 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. + */ + +#include <string> +#include <algorithm> +#include "gtest/gtest.h" + +#include "application_manager/usage_statistics.h" +#include "include/application_mock.h" +#include "include/resumption_data_mock.h" + +#include "application_manager/application_manager_impl.h" +#include "application_manager/application.h" +#include "utils/data_accessor.h" +#include "application_manager/message_helper.h" + +#include "include/resumption_data_test.h" + +std::string application_manager::MessageHelper::GetDeviceMacAddressForHandle( + const uint32_t device_handle) { + std::string device_mac_address = "12345"; + return device_mac_address; +} + +namespace test { +namespace components { +namespace resumption_test { + +using ::testing::Return; +using ::testing::ReturnRef; +using ::testing::ReturnPointee; + +void ResumptionDataTest::CheckSavedApp(sm::SmartObject& resume_app_list) { + EXPECT_EQ(policy_app_id_, resume_app_list[am::strings::app_id].asString()); + EXPECT_EQ(grammar_id_, resume_app_list[am::strings::grammar_id].asUInt()); + EXPECT_EQ(app_id_, resume_app_list[am::strings::connection_key].asUInt()); + EXPECT_EQ(hmi_app_id_, resume_app_list[am::strings::hmi_app_id].asUInt()); + EXPECT_EQ(ign_off_count_, + resume_app_list[am::strings::ign_off_count].asUInt()); + EXPECT_EQ(hmi_level_, static_cast<HMILevel::eType>( + resume_app_list[am::strings::hmi_level].asInt())); + EXPECT_EQ(is_audio_, + resume_app_list[am::strings::is_media_application].asBool()); + EXPECT_EQ("12345", resume_app_list[am::strings::device_id].asString()); + + CheckCommands(resume_app_list[am::strings::application_commands]); + CheckSubmenues(resume_app_list[am::strings::application_submenus]); + CheckChoiceSet(resume_app_list[am::strings::application_choice_sets]); + CheckAppFiles(resume_app_list[am::strings::application_files]); + + CheckGlobalProporties( + resume_app_list[am::strings::application_global_properties]); + CheckSubscriptions(resume_app_list[am::strings::application_subscribtions]); +} + +void ResumptionDataTest::CheckCommands(sm::SmartObject& res_list) { + for (uint32_t i = 0; i < count_of_commands; ++i) { + EXPECT_EQ(i, res_list[i][am::strings::cmd_id].asUInt()); + std::string name = + (*test_commands_map[i])[am::strings::menu_params] + [am::strings::menu_name].asString(); + EXPECT_EQ(name, + res_list[i][am::strings::menu_params][am::strings::menu_name] + .asString()); + int position = + (*test_commands_map[i])[am::strings::menu_params][am::strings::position] + .asInt(); + EXPECT_EQ( + position, + res_list[i][am::strings::menu_params][am::strings::position].asInt()); + + int parent_id = (*test_commands_map[i])[am::strings::menu_params] + [am::hmi_request::parent_id].asInt(); + EXPECT_EQ(parent_id, + res_list[i][am::strings::menu_params][am::hmi_request::parent_id] + .asInt()); + + std::string icon_name = + (*test_commands_map[i])[am::strings::cmd_icon][am::strings::value] + .asString(); + EXPECT_EQ( + icon_name, + res_list[i][am::strings::cmd_icon][am::strings::value].asString()); + + int icon_type = + (*test_commands_map[i])[am::strings::cmd_icon][am::strings::image_type] + .asInt(); + EXPECT_EQ( + icon_type, + res_list[i][am::strings::cmd_icon][am::strings::image_type].asInt()); + + for (uint32_t j = 0; j < count_of_choice; ++j) { + std::string vr = + (*test_commands_map[i])[am::strings::vr_commands][j].asString(); + EXPECT_EQ(vr, res_list[i][am::strings::vr_commands][j].asString()); + } + } +} + +void ResumptionDataTest::CheckSubmenues(sm::SmartObject& res_list) { + for (uint32_t i = 0; i < count_of_submenues; ++i) { + uint32_t test_id = + (*test_submenu_map[i + 10])[am::strings::menu_id].asUInt(); + std::string name = + (*test_submenu_map[i + 10])[am::strings::menu_name].asString(); + int position = (*test_submenu_map[i + 10])[am::strings::position].asInt(); + EXPECT_EQ(position, res_list[i][am::strings::position].asInt()); + EXPECT_EQ(test_id, res_list[i][am::strings::menu_id].asUInt()); + EXPECT_EQ(name, res_list[i][am::strings::menu_name].asString()); + } +} + +void ResumptionDataTest::CheckSubscriptions(sm::SmartObject& res_list) { + EXPECT_EQ(static_cast<uint32_t>(ButtonName::eType::OK), + res_list[am::strings::application_buttons][0].asUInt()); + EXPECT_EQ(static_cast<uint32_t>(ButtonName::eType::CUSTOM_BUTTON), + res_list[am::strings::application_buttons][1].asUInt()); + EXPECT_EQ(0u, res_list[am::strings::application_vehicle_info][0].asUInt()); + EXPECT_EQ(5u, res_list[am::strings::application_vehicle_info][1].asUInt()); +} + +void ResumptionDataTest::CheckChoiceSet(sm::SmartObject& res_list) { + for (uint32_t i = 0; i < res_list.length(); ++i) { + for (uint32_t j = 0; j < res_list[i][am::strings::choice_set].length(); + ++j) { + sm::SmartObject command = res_list[i][am::strings::choice_set][j]; + EXPECT_EQ(i + j, command[am::strings::choice_id].asUInt()); + char numb[12]; + std::snprintf(numb, 12, "%d", i + j); + std::string test_choice = + (*test_choiceset_map[i])[am::strings::choice_set][j] + [am::strings::vr_commands][0].asString(); + EXPECT_EQ(test_choice, command[am::strings::vr_commands][0].asString()); + std::string menu_name = + (*test_choiceset_map[i])[am::strings::choice_set][j] + [am::strings::menu_name].asString(); + EXPECT_EQ(menu_name, command[am::strings::menu_name].asString()); + std::string secondary_text = + (*test_choiceset_map[i])[am::strings::choice_set][j] + [am::strings::secondary_text].asString(); + EXPECT_EQ(secondary_text, + command[am::strings::secondary_text].asString()); + std::string tertiary_text = + (*test_choiceset_map[i])[am::strings::choice_set][j] + [am::strings::tertiary_text].asString(); + EXPECT_EQ(tertiary_text, command[am::strings::tertiary_text].asString()); + + std::string image_value = + (*test_choiceset_map[i])[am::strings::choice_set][j] + [am::strings::image][am::strings::value] + .asString(); + EXPECT_EQ(image_value, + command[am::strings::image][am::strings::value].asString()); + int image_type = + (*test_choiceset_map[i])[am::strings::choice_set][j] + [am::strings::image][am::strings::image_type] + .asInt(); + EXPECT_EQ(image_type, + command[am::strings::image][am::strings::image_type].asInt()); + + image_value = (*test_choiceset_map[i])[am::strings::choice_set][j] + [am::strings::secondary_image] + [am::strings::value].asString(); + EXPECT_EQ( + image_value, + command[am::strings::secondary_image][am::strings::value].asString()); + image_type = (*test_choiceset_map[i])[am::strings::choice_set][j] + [am::strings::secondary_image] + [am::strings::image_type].asInt(); + EXPECT_EQ(image_type, + command[am::strings::secondary_image][am::strings::image_type] + .asInt()); + } + + int choice_set_id = + (*test_choiceset_map[i])[am::strings::interaction_choice_set_id] + .asUInt(); + EXPECT_EQ(choice_set_id, + res_list[i][am::strings::interaction_choice_set_id].asInt()); + + int grammar_id = (*test_choiceset_map[i])[am::strings::grammar_id].asUInt(); + EXPECT_EQ(grammar_id, res_list[i][am::strings::grammar_id].asInt()); + } +} + +void ResumptionDataTest::CheckAppFiles(sm::SmartObject& res_list) { + am::AppFile check_file; + + for (uint i = 0; i < count_of_files; ++i) { + char numb[12]; + std::snprintf(numb, 12, "%d", i); + check_file = app_files_map_["test_file " + std::string(numb)]; + EXPECT_EQ(check_file.file_name, + res_list[i][am::strings::sync_file_name].asString()); + EXPECT_EQ(check_file.file_type, + static_cast<FileType::eType>( + res_list[i][am::strings::file_type].asInt())); + EXPECT_EQ(check_file.is_download_complete, + res_list[i][am::strings::is_download_complete].asBool()); + EXPECT_EQ(check_file.is_persistent, + res_list[i][am::strings::persistent_file].asBool()); + } +} + +void ResumptionDataTest::CheckGlobalProporties(sm::SmartObject& res_list) { + CheckHelpPrompt(res_list[am::strings::help_prompt]); + CheckTimeoutPrompt(res_list[am::strings::timeout_prompt]); + CheckVRHelp(res_list[am::strings::vr_help]); + CheckVRTitle(res_list[am::strings::vr_help_title]); + CheckKeyboardProperties(res_list[am::strings::keyboard_properties]); + CheckMenuTitle(res_list[am::strings::menu_title]); + CheckMenuIcon(res_list[am::strings::menu_icon]); +} + +void ResumptionDataTest::CheckKeyboardProperties(sm::SmartObject& res_list) { + Language::eType testlanguage = static_cast<Language::eType>( + (*keyboard_props_)[am::strings::language].asInt()); + KeyboardLayout::eType testlayout = static_cast<KeyboardLayout::eType>( + (*keyboard_props_)[am::hmi_request::keyboard_layout].asInt()); + KeypressMode::eType testmode = static_cast<KeypressMode::eType>( + (*keyboard_props_)[am::strings::key_press_mode].asInt()); + + std::string auto_complete_text = + (*keyboard_props_)[am::strings::auto_complete_text].asString(); + + for (uint i = 0; + i < (*keyboard_props_)[am::strings::limited_character_list].length(); + i++) { + std::string character = + (*keyboard_props_)[am::strings::limited_character_list][i].asString(); + EXPECT_EQ(character, + res_list[am::strings::limited_character_list][i].asString()); + } + + EXPECT_EQ(testlanguage, static_cast<Language::eType>( + res_list[am::strings::language].asInt())); + EXPECT_EQ(testlayout, + static_cast<KeyboardLayout::eType>( + res_list[am::hmi_request::keyboard_layout].asInt())); + EXPECT_EQ(testmode, static_cast<KeypressMode::eType>( + res_list[am::strings::key_press_mode].asInt())); + EXPECT_EQ(auto_complete_text, + res_list[am::strings::auto_complete_text].asString()); +} + +void ResumptionDataTest::CheckMenuTitle(sm::SmartObject& res_list) { + std::string value = (*menu_title_)[am::strings::menu_title].asString(); + EXPECT_EQ(value, res_list[am::strings::menu_title].asString()); +} + +void ResumptionDataTest::CheckMenuIcon(sm::SmartObject& res_list) { + std::string value = (*menu_icon_)[am::strings::value].asString(); + ImageType::eType type = static_cast<ImageType::eType>( + (*menu_icon_)[am::strings::image_type].asInt()); + + EXPECT_EQ(value, res_list[am::strings::value].asString()); + EXPECT_EQ(type, static_cast<ImageType::eType>( + res_list[am::strings::image_type].asInt())); +} + +void ResumptionDataTest::CheckHelpPrompt(sm::SmartObject& res_list) { + for (uint i = 0; i < tts_chunks_count; ++i) { + std::string promt = (*help_prompt_)[i][am::strings::help_prompt].asString(); + std::string dict_promt = res_list[i][am::strings::help_prompt].asString(); + EXPECT_EQ(promt, dict_promt); + } +} + +void ResumptionDataTest::CheckTimeoutPrompt( + NsSmartDeviceLink::NsSmartObjects::SmartObject& res_list) { + for (uint i = 0; i < tts_chunks_count; ++i) { + std::string text = (*timeout_prompt_)[i][am::strings::text].asString(); + SpeechCapabilities::eType speech = static_cast<SpeechCapabilities::eType>( + (*timeout_prompt_)[i][am::strings::type].asInt()); + EXPECT_EQ(text, res_list[i][am::strings::text].asString()); + EXPECT_EQ(speech, static_cast<SpeechCapabilities::eType>( + res_list[i][am::strings::type].asInt())); + } +} + +void ResumptionDataTest::CheckVRHelp(sm::SmartObject& res_list) { + std::string text; + int position; + for (uint i = 0; i < count_of_vrhelptitle; ++i) { + text = (*vr_help_)[i][am::strings::text].asString(); + EXPECT_EQ(text, res_list[i][am::strings::text].asString()); + position = (*vr_help_)[i][am::strings::position].asInt(); + EXPECT_EQ(position, res_list[i][am::strings::position].asInt()); + } +} + +void ResumptionDataTest::CheckVRTitle( + NsSmartDeviceLink::NsSmartObjects::SmartObject& res_list) { + std::string vtitle = (*vr_help_title_)[am::strings::vr_help_title].asString(); + EXPECT_EQ(vtitle, res_list[am::strings::vr_help_title].asString()); +} + +void ResumptionDataTest::PrepareData() { + SetGlobalProporties(); + SetCommands(); + SetSubmenues(); + SetChoiceSet(); + SetAppFiles(); + + DataAccessor<am::SubMenuMap> sub_menu_m(test_submenu_map, sublock_); + DataAccessor<am::CommandsMap> commands_m(test_commands_map, comlock_); + DataAccessor<am::ChoiceSetMap> choice_set_m(test_choiceset_map, setlock_); + + SetSubscriptions(); + DataAccessor<am::ButtonSubscriptions> btn_sub(btn_subscr, btnlock_); + DataAccessor<am::VehicleInfoSubscriptions> ivi_access(ivi, ivilock_); + + ON_CALL(*app_mock, is_application_data_changed()).WillByDefault(Return(true)); + + ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(policy_app_id_)); + ON_CALL(*app_mock, curHash()).WillByDefault(ReturnRef(hash_)); + ON_CALL(*app_mock, get_grammar_id()).WillByDefault(Return(grammar_id_)); + ON_CALL(*app_mock, device()).WillByDefault(Return(device_handle_)); + ON_CALL(*app_mock, hmi_level()).WillByDefault(Return(hmi_level_)); + ON_CALL(*app_mock, app_id()).WillByDefault(Return(app_id_)); + ON_CALL(*app_mock, hmi_app_id()).WillByDefault(Return(hmi_app_id_)); + ON_CALL(*app_mock, IsAudioApplication()).WillByDefault(Return(is_audio_)); + ON_CALL(*app_mock, commands_map()).WillByDefault(Return(commands_m)); + ON_CALL(*app_mock, sub_menu_map()).WillByDefault(Return(sub_menu_m)); + ON_CALL(*app_mock, choice_set_map()).WillByDefault(Return(choice_set_m)); + + ON_CALL(*app_mock, help_prompt()).WillByDefault(ReturnPointee(&help_prompt_)); + ON_CALL(*app_mock, timeout_prompt()) + .WillByDefault(ReturnPointee(&timeout_prompt_)); + ON_CALL(*app_mock, vr_help()).WillByDefault(ReturnPointee(&vr_help_)); + ON_CALL(*app_mock, vr_help_title()) + .WillByDefault(ReturnPointee(&vr_help_title_)); + + ON_CALL(*app_mock, keyboard_props()) + .WillByDefault(ReturnPointee(&keyboard_props_)); + ON_CALL(*app_mock, menu_title()).WillByDefault(ReturnPointee(&menu_title_)); + ON_CALL(*app_mock, menu_icon()).WillByDefault(ReturnPointee(&menu_icon_)); + + ON_CALL(*app_mock, SubscribedButtons()).WillByDefault(Return(btn_sub)); + ON_CALL(*app_mock, SubscribedIVI()).WillByDefault(Return(ivi_access)); + + ON_CALL(*app_mock, getAppFiles()).WillByDefault(ReturnRef(app_files_map_)); +} + +void ResumptionDataTest::SetGlobalProporties() { + SetKeyboardProperties(); + SetMenuTitleAndIcon(); + SetHelpAndTimeoutPrompt(); + SetVRHelpTitle(); +} + +void ResumptionDataTest::SetMenuTitleAndIcon() { + sm::SmartObject sm_icon; + sm_icon[am::strings::value] = "test icon"; + sm_icon[am::strings::image_type] = ImageType::STATIC; + + sm::SmartObject sm_title; + sm_title = "test title"; + menu_title_ = new sm::SmartObject(sm_title); + menu_icon_ = new sm::SmartObject(sm_icon); +} + +void ResumptionDataTest::SetHelpAndTimeoutPrompt() { + sm::SmartObject help_prompt; + sm::SmartObject timeout_prompt; + + for (uint i = 0; i < tts_chunks_count + 3; ++i) { + char numb[12]; + std::snprintf(numb, 12, "%d", i); + help_prompt[i][am::strings::text] = "help prompt name" + std::string(numb); + help_prompt[i][am::strings::type] = SpeechCapabilities::PRE_RECORDED; + } + help_prompt_ = new sm::SmartObject(help_prompt); + for (uint i = 0; i < tts_chunks_count; ++i) { + char numb[12]; + std::snprintf(numb, 12, "%d", i); + timeout_prompt[i][am::strings::text] = "timeout test" + std::string(numb); + timeout_prompt[i][am::strings::type] = SpeechCapabilities::SC_TEXT; + } + + timeout_prompt_ = new sm::SmartObject(timeout_prompt); +} + +void ResumptionDataTest::SetVRHelpTitle() { + sm::SmartObject vr_help_title; + vr_help_title = "vr help title"; + + sm::SmartObject vr_help; + for (uint i = 0; i < count_of_vrhelptitle; ++i) { + char numb[12]; + std::snprintf(numb, 12, "%d", i); + vr_help[i][am::strings::text] = "vr help " + std::string(numb); + vr_help[i][am::strings::position] = i; + } + + vr_help_ = new sm::SmartObject(vr_help); + vr_help_title_ = new sm::SmartObject(vr_help_title); +} + +void ResumptionDataTest::SetCommands() { + sm::SmartObject sm_comm; + + sm::SmartObject vr_commandsvector; + sm::SmartObject sm_icon; + for (uint32_t i = 0; i < count_of_commands; ++i) { + char numb[12]; + std::snprintf(numb, 12, "%d", i); + sm_comm[am::strings::cmd_id] = i; + sm_comm[am::strings::menu_params][am::strings::position] = i; + sm_comm[am::strings::menu_params][am::hmi_request::parent_id] = i; + sm_comm[am::strings::menu_params][am::strings::menu_name] = + "Command" + std::string(numb); + + for (uint32_t j = 0; j < count_of_choice; ++j) { + char vr[12]; + std::snprintf(vr, 12, "%d", i + j); + vr_commandsvector[j] = "VrCommand " + std::string(vr); + } + sm_comm[am::strings::vr_commands] = vr_commandsvector; + + sm_icon[am::strings::value] = "command icon " + std::string(numb); + sm_icon[am::strings::image_type] = ImageType::STATIC; + + sm_comm[am::strings::cmd_icon] = sm_icon; + + test_commands_map[i] = new sm::SmartObject(sm_comm); + } +} + +void ResumptionDataTest::SetSubmenues() { + sm::SmartObject sm_comm; + for (uint32_t i = 10; i < count_of_submenues + 10; ++i) { + char numb[12]; + std::snprintf(numb, 12, "%d", i); + sm_comm[am::strings::menu_id] = i; + sm_comm[am::strings::position] = i; + sm_comm[am::strings::menu_name] = "SubMenu" + std::string(numb); + test_submenu_map[i] = new sm::SmartObject(sm_comm); + } +} + +void ResumptionDataTest::SetChoiceSet() { + sm::SmartObject choice_vector; + sm::SmartObject choice; + sm::SmartObject vr_commandsvector; + sm::SmartObject sm_icon; + sm::SmartObject sec_icon; + sm::SmartObject app_choice_set; + sm::SmartObject application_choice_sets; + for (uint32_t i = 0; i < count_of_choice_sets; ++i) { + for (uint32_t j = 0; j < count_of_choice; ++j) { + char numb[12]; + std::snprintf(numb, 12, "%d", i + j); + + choice[am::strings::choice_id] = i + j; + vr_commandsvector[0] = "ChoiceSet VrCommand " + std::string(numb); + choice[am::strings::vr_commands] = vr_commandsvector; + choice[am::strings::menu_name] = "Choice name " + std::string(numb); + choice[am::strings::secondary_text] = + "secondaryText " + std::string(numb); + choice[am::strings::tertiary_text] = "tertiaryText " + std::string(numb); + + sm_icon[am::strings::value] = "Choiceset icon " + std::string(numb); + sm_icon[am::strings::image_type] = ImageType::STATIC; + + sec_icon[am::strings::value] = + "Second choiceset icon " + std::string(numb); + sec_icon[am::strings::image_type] = ImageType::STATIC; + + choice[am::strings::image] = sm_icon; + choice[am::strings::secondary_image] = sec_icon; + + choice_vector[j] = choice; + } + app_choice_set[am::strings::interaction_choice_set_id] = i; + app_choice_set[am::strings::grammar_id] = 100 + i; + app_choice_set[am::strings::choice_set] = choice_vector; + application_choice_sets[i] = app_choice_set; + + test_choiceset_map[i] = new sm::SmartObject(application_choice_sets[i]); + } +} + +void ResumptionDataTest::SetAppFiles() { + am::AppFile test_file; + int file_types; + for (uint i = 0; i < count_of_files; ++i) { + char numb[12]; + std::snprintf(numb, 12, "%d", i); + file_types = i; + test_file.is_persistent = true; + test_file.is_download_complete = true; + test_file.file_type = static_cast<FileType::eType>(file_types); + test_file.file_name = "test_file " + std::string(numb); + + app_files_map_[test_file.file_name] = test_file; + } +} + +void ResumptionDataTest::SetKeyboardProperties() { + sm::SmartObject keyboard; + keyboard[am::strings::language] = Language::EN_US; + keyboard[am::hmi_request::keyboard_layout] = KeyboardLayout::QWERTY; + keyboard[am::strings::key_press_mode] = KeypressMode::SINGLE_KEYPRESS; + keyboard[am::strings::auto_complete_text] = "complete"; + keyboard[am::strings::limited_character_list][0] = "y"; + keyboard[am::strings::limited_character_list][1] = "n"; + keyboard_props_ = new sm::SmartObject(keyboard); +} + +void ResumptionDataTest::SetSubscriptions() { + btn_subscr.insert(ButtonName::eType::CUSTOM_BUTTON); + btn_subscr.insert(ButtonName::eType::OK); + ivi.insert(0); + ivi.insert(5); +} + +} // namespace resumption_test +} // namespace components +} // namespace test diff --git a/src/components/application_manager/test/resumption/smartDeviceLink_test.ini b/src/components/application_manager/test/resumption/smartDeviceLink_test.ini new file mode 100644 index 0000000000..cf51439d8c --- /dev/null +++ b/src/components/application_manager/test/resumption/smartDeviceLink_test.ini @@ -0,0 +1,37 @@ +[MAIN] + +; For resume_ctrl tests +LogsEnabled = false +; Contains .json/.ini files +AppConfigFolder = +; Contains output files, e.g. .wav. Changed for tests +AppStorageFolder = test_storage + +[AppInfo] +; The path for applications info storage. Changed for tests +AppInfoStorage = test_app_info.dat + +[Resumption] + +# Timeout in milliseconds for resumption Application HMILevel +# and resolving conflicts in case if multiple applications initiate resumption +# Time changed for test onAppActivated +ApplicationResumingTimeout = 30000000 + +# Timeout in milliseconds for periodical saving resumption persistent data +AppSavePersistentDataTimeout = 10000 + +# Timeout in seconds to store hmi_level for media app before ign_off +ResumptionDelayBeforeIgn = 30; + +# Timeout in seconds to restore hmi_level for media app after sdl run +ResumptionDelayAfterIgn = 30; + +# Resumption ctrl uses JSON if UseDBForResumption=false for store data otherwise uses DB +UseDBForResumption = false + +# Number of attempts to open resumption DB +AttemptsToOpenResumptionDB = 5 + +# Timeout between attempts during opening DB in milliseconds +OpenAttemptTimeoutMsResumptionDB = 500 diff --git a/src/components/application_manager/test/state_controller/CMakeLists.txt b/src/components/application_manager/test/state_controller/CMakeLists.txt new file mode 100644 index 0000000000..243e6218ed --- /dev/null +++ b/src/components/application_manager/test/state_controller/CMakeLists.txt @@ -0,0 +1,51 @@ +# Copyright (c) 2015, 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. + +if(BUILD_TESTS) + +set(appMain_DIR ${CMAKE_SOURCE_DIR}/src/appMain) + +include_directories( + ${GMOCK_INCLUDE_DIRECTORY} + ${COMPONENTS_DIR}/application_manager/test/state_controller/include +) + +set(LIBRARIES + gmock + ApplicationManager +) + +set(SOURCES + state_controller_test.cc +) + +create_test("state_controller_test" "${SOURCES}" "${LIBRARIES}") + +endif() diff --git a/src/components/application_manager/test/state_controller/include/application_manager_mock.h b/src/components/application_manager/test/state_controller/include/application_manager_mock.h new file mode 100644 index 0000000000..22ff93687a --- /dev/null +++ b/src/components/application_manager/test/state_controller/include/application_manager_mock.h @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2015, 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. + */ + +#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_APPLICATION_MANAGER_MOCK_H_ +#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_APPLICATION_MANAGER_MOCK_H_ +#include <string> +#include <vector> +#include "gmock/gmock.h" +#include "application_manager/application_manager.h" +#include "application_manager/usage_statistics.h" + +namespace state_controller_test { +namespace am = application_manager; + +class ApplicationManagerMock : public application_manager::ApplicationManager { + public: + MOCK_METHOD0(Init, bool()); + MOCK_METHOD0(Stop, bool()); + + MOCK_METHOD1(set_hmi_message_handler, + void(hmi_message_handler::HMIMessageHandler*)); + MOCK_METHOD1(set_protocol_handler, void(protocol_handler::ProtocolHandler*)); + MOCK_METHOD1(set_connection_handler, + void(connection_handler::ConnectionHandler*)); + MOCK_CONST_METHOD0(applications, DataAccessor<am::ApplicationSet>()); + MOCK_CONST_METHOD1(application_by_hmi_app, + am::ApplicationSharedPtr(uint32_t)); + MOCK_CONST_METHOD1(application, am::ApplicationSharedPtr(uint32_t)); + + MOCK_CONST_METHOD0(active_application, am::ApplicationSharedPtr()); + MOCK_CONST_METHOD1(application_by_policy_id, + am::ApplicationSharedPtr(const std::string&)); + MOCK_METHOD1(applications_by_button, + std::vector<am::ApplicationSharedPtr>(uint32_t)); + MOCK_METHOD0(applications_with_navi, std::vector<am::ApplicationSharedPtr>()); + MOCK_CONST_METHOD0(get_limited_media_application, am::ApplicationSharedPtr()); + MOCK_CONST_METHOD0(get_limited_navi_application, am::ApplicationSharedPtr()); + MOCK_CONST_METHOD0(get_limited_voice_application, am::ApplicationSharedPtr()); + MOCK_METHOD2(set_application_id, void(const int32_t, const uint32_t)); + MOCK_METHOD1(application_id, uint32_t(const int32_t)); + MOCK_METHOD3(OnHMILevelChanged, void(uint32_t, mobile_apis::HMILevel::eType, + mobile_apis::HMILevel::eType)); + MOCK_METHOD1(SendHMIStatusNotification, void(const am::ApplicationSharedPtr)); + MOCK_CONST_METHOD1(GetDefaultHmiLevel, mobile_apis::HMILevel::eType( + am::ApplicationConstSharedPtr)); + MOCK_METHOD0(hmi_capabilities, am::HMICapabilities&()); + MOCK_METHOD0(is_attenuated_supported, bool()); + MOCK_CONST_METHOD1(IsAppTypeExistsInFullOrLimited, bool(am::ApplicationConstSharedPtr)); +}; +} // namespace state_controller_test +#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_APPLICATION_MANAGER_MOCK_H_ diff --git a/src/components/application_manager/test/state_controller/include/application_mock.h b/src/components/application_manager/test/state_controller/include/application_mock.h new file mode 100644 index 0000000000..01dafd10f4 --- /dev/null +++ b/src/components/application_manager/test/state_controller/include/application_mock.h @@ -0,0 +1,252 @@ +/* + * Copyright (c) 2015, 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. + */ + +#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_APPLICATION_MOCK_H_ +#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_APPLICATION_MOCK_H_ + +#include <string> + +#include "gmock/gmock.h" +#include "application_manager/application.h" +namespace state_controller_test { +namespace am = application_manager; + +class ApplicationMock : public am::Application { + public: + MOCK_CONST_METHOD0(active_message, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(curHash, const std::string&()); + MOCK_METHOD0(UpdateHash, void()); + MOCK_CONST_METHOD0(flag_sending_hash_change_after_awake, bool()); + MOCK_METHOD1(set_flag_sending_hash_change_after_awake, void(bool flag)); + MOCK_CONST_METHOD0(is_application_data_changed, bool()); + MOCK_METHOD1(set_is_application_data_changed, + void(bool state_application_data)); + MOCK_METHOD0(CloseActiveMessage, void()); + MOCK_CONST_METHOD0(IsFullscreen, bool()); + MOCK_METHOD0(ChangeSupportingAppHMIType, void()); + MOCK_CONST_METHOD0(is_navi, bool()); + MOCK_METHOD1(set_is_navi, void(bool allow)); + MOCK_CONST_METHOD0(video_streaming_approved, bool()); + MOCK_METHOD1(set_video_streaming_approved, void(bool state)); + MOCK_CONST_METHOD0(audio_streaming_approved, bool()); + MOCK_METHOD1(set_audio_streaming_approved, void(bool state)); + MOCK_CONST_METHOD0(video_streaming_allowed, bool()); + MOCK_METHOD1(set_video_streaming_allowed, void(bool state)); + MOCK_CONST_METHOD0(audio_streaming_allowed, bool()); + MOCK_METHOD1(set_audio_streaming_allowed, void(bool state)); + MOCK_METHOD1(StartStreaming, + void(protocol_handler::ServiceType service_type)); + MOCK_METHOD1(StopStreaming, void(protocol_handler::ServiceType service_type)); + MOCK_METHOD1(SuspendStreaming, + void(protocol_handler::ServiceType service_type)); + MOCK_METHOD1(WakeUpStreaming, + void(protocol_handler::ServiceType service_type)); + MOCK_CONST_METHOD0(is_voice_communication_supported, bool()); + MOCK_METHOD1(set_voice_communication_supported, + void(bool is_voice_communication_supported)); + MOCK_CONST_METHOD0(app_allowed, bool()); + MOCK_CONST_METHOD0(has_been_activated, bool()); + MOCK_METHOD1(set_activated, bool(bool is_active)); + MOCK_CONST_METHOD0(version, const am::Version&()); + MOCK_METHOD1(set_hmi_application_id, void(uint32_t hmi_app_id)); + + MOCK_CONST_METHOD0(hmi_app_id, uint32_t()); + MOCK_CONST_METHOD0(name, const std::string&()); + MOCK_METHOD1(set_folder_name, void(const std::string& folder_name)); + MOCK_CONST_METHOD0(folder_name, const std::string()); + MOCK_CONST_METHOD0(is_media_application, bool()); + MOCK_CONST_METHOD0(hmi_level, const mobile_apis::HMILevel::eType()); + MOCK_CONST_METHOD0(put_file_in_none_count, const uint32_t()); + MOCK_CONST_METHOD0(delete_file_in_none_count, const uint32_t()); + MOCK_CONST_METHOD0(list_files_in_none_count, const uint32_t()); + MOCK_CONST_METHOD0(system_context, const mobile_apis::SystemContext::eType()); + MOCK_CONST_METHOD0(audio_streaming_state, + const mobile_apis::AudioStreamingState::eType()); + MOCK_CONST_METHOD0(app_icon_path, const std::string&()); + MOCK_CONST_METHOD0(device, connection_handler::DeviceHandle()); + MOCK_METHOD0(tts_speak_state, bool()); + MOCK_CONST_METHOD0(CurrentHmiState, am::HmiStatePtr()); + MOCK_CONST_METHOD0(RegularHmiState, am::HmiStatePtr()); + MOCK_CONST_METHOD0(PostponedHmiState, am::HmiStatePtr()); + MOCK_METHOD1(set_tts_properties_in_none, void(bool active)); + MOCK_METHOD0(tts_properties_in_none, bool()); + MOCK_METHOD1(set_tts_properties_in_full, void(bool active)); + MOCK_METHOD0(tts_properties_in_full, bool()); + MOCK_METHOD1(set_version, void(const am::Version& version)); + MOCK_METHOD1(set_name, void(const std::string& name)); + MOCK_METHOD1(set_is_media_application, void(bool is_media)); + MOCK_METHOD0(increment_put_file_in_none_count, void()); + MOCK_METHOD0(increment_delete_file_in_none_count, void()); + MOCK_METHOD0(increment_list_files_in_none_count, void()); + MOCK_METHOD1(set_app_icon_path, bool(const std::string& file_name)); + MOCK_METHOD1(set_app_allowed, void(const bool& allowed)); + MOCK_METHOD1(set_device, void(connection_handler::DeviceHandle device)); + MOCK_CONST_METHOD0(get_grammar_id, uint32_t()); + MOCK_METHOD1(set_grammar_id, void(uint32_t value)); + MOCK_METHOD1(set_protocol_version, + void(const am::ProtocolVersion& protocol_version)); + MOCK_CONST_METHOD0(protocol_version, am::ProtocolVersion()); + MOCK_METHOD1(set_is_resuming, void(bool)); + MOCK_CONST_METHOD0(is_resuming, bool()); + MOCK_METHOD1(AddFile, bool(const am::AppFile& file)); + MOCK_CONST_METHOD0(getAppFiles, const am::AppFilesMap&()); + MOCK_METHOD1(UpdateFile, bool(const am::AppFile& file)); + MOCK_METHOD1(DeleteFile, bool(const std::string& file_name)); + MOCK_METHOD1(GetFile, const am::AppFile*(const std::string& file_name)); + MOCK_METHOD1(SubscribeToButton, + bool(mobile_apis::ButtonName::eType btn_name)); + MOCK_METHOD1(IsSubscribedToButton, + bool(mobile_apis::ButtonName::eType btn_name)); + MOCK_METHOD1(UnsubscribeFromButton, + bool(mobile_apis::ButtonName::eType btn_name)); + MOCK_METHOD1(SubscribeToIVI, bool(uint32_t vehicle_info_type)); + MOCK_CONST_METHOD1(IsSubscribedToIVI, bool(uint32_t vehicle_info_type)); + MOCK_METHOD1(UnsubscribeFromIVI, bool(uint32_t vehicle_info_type)); + MOCK_METHOD0(ResetDataInNone, void()); + MOCK_METHOD2(IsCommandLimitsExceeded, + bool(mobile_apis::FunctionID::eType cmd_id, + am::TLimitSource source)); + MOCK_METHOD0(usage_report, am::UsageStatistics&()); + MOCK_METHOD1(SetRegularState, void(am::HmiStatePtr state)); + MOCK_METHOD1(SetPostponedState, void(am::HmiStatePtr state)); + MOCK_METHOD1(AddHMIState, void(am::HmiStatePtr state)); + MOCK_METHOD1(RemoveHMIState, void(am::HmiState::StateID state_id)); + MOCK_METHOD2(SubscribeToSoftButtons, + void(int32_t cmd_id, const am::SoftButtonID& softbuttons_id)); + MOCK_METHOD1(IsSubscribedToSoftButton, bool(const uint32_t softbutton_id)); + MOCK_METHOD1(UnsubscribeFromSoftButtons, void(int32_t cmd_id)); + MOCK_CONST_METHOD0(IsAudioApplication, bool()); + MOCK_METHOD0(LoadPersistentFiles, void()); + + // InitialApplicationData methods + MOCK_CONST_METHOD0(app_types, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(vr_synonyms, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(policy_app_id, std::string()); + MOCK_CONST_METHOD0(tts_name, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(ngn_media_screen_name, + const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(language, const mobile_apis::Language::eType&()); + MOCK_CONST_METHOD0(ui_language, const mobile_apis::Language::eType&()); + MOCK_METHOD1(set_app_types, + void(const smart_objects::SmartObject& app_types)); + MOCK_METHOD1(set_vr_synonyms, + void(const smart_objects::SmartObject& vr_synonyms)); + MOCK_METHOD1(set_policy_app_id, void(const std::string& policy_app_id)); + MOCK_METHOD1(set_tts_name, void(const smart_objects::SmartObject& tts_name)); + MOCK_METHOD1(set_ngn_media_screen_name, + void(const smart_objects::SmartObject& ngn_name)); + MOCK_METHOD1(set_language, + void(const mobile_apis::Language::eType& language)); + MOCK_METHOD1(set_ui_language, + void(const mobile_apis::Language::eType& ui_language)); + + // DynamicApplicationData methods + MOCK_CONST_METHOD0(help_prompt, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(timeout_prompt, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(vr_help_title, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(vr_help, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(tbt_state, const mobile_apis::TBTState::eType&()); + MOCK_CONST_METHOD0(show_command, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(tbt_show_command, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(SubscribedButtons, + DataAccessor<am::ButtonSubscriptions>()); + MOCK_CONST_METHOD0(SubscribedIVI, + DataAccessor<am::VehicleInfoSubscriptions>()); + MOCK_CONST_METHOD0(keyboard_props, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(menu_title, const smart_objects::SmartObject*()); + MOCK_CONST_METHOD0(menu_icon, const smart_objects::SmartObject*()); + MOCK_METHOD1(load_global_properties, + void(const smart_objects::SmartObject& so)); + MOCK_METHOD1(set_help_prompt, + void(const smart_objects::SmartObject& help_prompt)); + MOCK_METHOD1(set_timeout_prompt, + void(const smart_objects::SmartObject& timeout_prompt)); + MOCK_METHOD1(set_vr_help_title, + void(const smart_objects::SmartObject& vr_help_title)); + MOCK_METHOD0(reset_vr_help_title, void()); + MOCK_METHOD1(set_vr_help, void(const smart_objects::SmartObject& vr_help)); + MOCK_METHOD0(reset_vr_help, void()); + MOCK_METHOD1(set_tbt_state, + void(const mobile_apis::TBTState::eType& tbt_state)); + MOCK_METHOD1(set_show_command, + void(const smart_objects::SmartObject& show_command)); + MOCK_METHOD1(set_tbt_show_command, + void(const smart_objects::SmartObject& tbt_show)); + MOCK_METHOD1(set_keyboard_props, + void(const smart_objects::SmartObject& keyboard_props)); + MOCK_METHOD1(set_menu_title, + void(const smart_objects::SmartObject& menu_title)); + MOCK_METHOD1(set_menu_icon, + void(const smart_objects::SmartObject& menu_icon)); + MOCK_CONST_METHOD0(audio_stream_retry_number, uint32_t()); + MOCK_METHOD1(set_audio_stream_retry_number, + void(const uint32_t& audio_stream_retry_number)); + MOCK_CONST_METHOD0(video_stream_retry_number, uint32_t()); + MOCK_METHOD1(set_video_stream_retry_number, + void(const uint32_t& video_stream_retry_number)); + MOCK_METHOD2(AddCommand, void(uint32_t cmd_id, + const smart_objects::SmartObject& command)); + MOCK_METHOD1(RemoveCommand, void(uint32_t cmd_id)); + MOCK_METHOD1(FindCommand, smart_objects::SmartObject*(uint32_t cmd_id)); + MOCK_METHOD2(AddSubMenu, + void(uint32_t menu_id, const smart_objects::SmartObject& menu)); + MOCK_METHOD1(RemoveSubMenu, void(uint32_t menu_id)); + MOCK_CONST_METHOD1(FindSubMenu, + smart_objects::SmartObject*(uint32_t menu_id)); + MOCK_METHOD1(IsSubMenuNameAlreadyExist, bool(const std::string& name)); + MOCK_METHOD2(AddChoiceSet, + void(uint32_t choice_set_id, + const smart_objects::SmartObject& choice_set)); + MOCK_METHOD1(RemoveChoiceSet, void(uint32_t choice_set_id)); + MOCK_METHOD1(FindChoiceSet, + smart_objects::SmartObject*(uint32_t choice_set_id)); + MOCK_METHOD3(AddPerformInteractionChoiceSet, + void(uint32_t correlation_id, uint32_t choice_set_id, + const smart_objects::SmartObject& choice_set)); + MOCK_METHOD1(DeletePerformInteractionChoiceSet, + void(uint32_t correlation_id)); + MOCK_CONST_METHOD0(performinteraction_choice_set_map, + DataAccessor<am::PerformChoiceSetMap>()); + MOCK_CONST_METHOD0(commands_map, DataAccessor<am::CommandsMap>()); + MOCK_CONST_METHOD0(sub_menu_map, DataAccessor<am::SubMenuMap>()); + MOCK_CONST_METHOD0(choice_set_map, DataAccessor<am::ChoiceSetMap>()); + MOCK_METHOD1(set_perform_interaction_active, void(uint32_t active)); + MOCK_CONST_METHOD0(is_perform_interaction_active, uint32_t()); + MOCK_METHOD1(set_perform_interaction_mode, void(int32_t mode)); + MOCK_CONST_METHOD0(perform_interaction_mode, int32_t()); + MOCK_METHOD1(set_reset_global_properties_active, void(bool active)); + MOCK_CONST_METHOD0(is_reset_global_properties_active, bool()); + MOCK_CONST_METHOD0(app_id, uint32_t()); +}; + +} // namespace state_controller_test +#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_APPLICATION_MOCK_H_ diff --git a/src/components/application_manager/test/state_controller/include/state_controller_mock.h b/src/components/application_manager/test/state_controller/include/state_controller_mock.h new file mode 100644 index 0000000000..b9f7dd30dd --- /dev/null +++ b/src/components/application_manager/test/state_controller/include/state_controller_mock.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2015, 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. + */ + +#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_STATE_CONTROLLER_MOCK +#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_STATE_CONTROLLER_MOCK + +#include "gmock/gmock.h" +#include "application_manager/application.h" +#include "application_manager/hmi_state.h" +#include "application_manager/state_controller.h" +#include "application_manager/application_manager.h" +#include "interfaces/MOBILE_API.h" + +namespace state_controller_test { +namespace am = application_manager; + +class StateControllerMock :public am::StateController { + public: + MOCK_METHOD2(SetRegularState, void ( + am::ApplicationSharedPtr, const mobile_apis::AudioStreamingState::eType)); + MOCK_METHOD2(SetRegularState, void ( + am::ApplicationSharedPtr, const mobile_apis::SystemContext::eType)); + MOCK_METHOD3(OnStateChanged, void ( + am::ApplicationSharedPtr, am::HmiStatePtr, am::HmiStatePtr)); + MOCK_METHOD1(ApplyStatesForApp, void (am::ApplicationSharedPtr)); + MOCK_METHOD0(OnNaviStreamingStarted, void ()); + MOCK_METHOD0(OnNaviStreamingStopped, void ()); +}; + +} +#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_STATE_CONTROLLER_MOCK diff --git a/src/components/application_manager/test/state_controller/include/statistics_manager_mock.h b/src/components/application_manager/test/state_controller/include/statistics_manager_mock.h new file mode 100644 index 0000000000..4e2dae78d1 --- /dev/null +++ b/src/components/application_manager/test/state_controller/include/statistics_manager_mock.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2015, 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. + */ + +#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_STATISTICS_MANAGER_MOCK_H_ +#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_STATISTICS_MANAGER_MOCK_H_ + +#include <string> +#include "gmock/gmock.h" +#include "usage_statistics/statistics_manager.h" + +namespace state_controller_test { +namespace us = usage_statistics; + +class StatisticsManagerMock : public us::StatisticsManager { + public: + MOCK_METHOD1(Increment, void (us::GlobalCounterId)); + MOCK_METHOD2(Increment, void (const std::string&, us::AppCounterId)); + MOCK_METHOD3(Set, void (const std::string&, us::AppInfoId, const std::string&)); + MOCK_METHOD3(Add, void (const std::string&, us::AppStopwatchId, int32_t)); +}; + +} // namespace state_controller_test +#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_STATISTICS_MANAGER_MOCK_H_ diff --git a/src/components/application_manager/test/state_controller/state_controller_test.cc b/src/components/application_manager/test/state_controller/state_controller_test.cc new file mode 100644 index 0000000000..488d12b502 --- /dev/null +++ b/src/components/application_manager/test/state_controller/state_controller_test.cc @@ -0,0 +1,1483 @@ +/* + * Copyright (c) 2015, 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. + */ + +#include <gtest/gtest.h> +#include "application_manager/hmi_state.h" +#include "application_manager/state_controller.h" +#include "application_manager/usage_statistics.h" +#include "application_manager_mock.h" +#include "application_mock.h" +#include "statistics_manager_mock.h" +#include "utils/lock.h" +#include "utils/data_accessor.h" +#include "utils/make_shared.h" +#include "application_manager/message_helper.h" +#include "application_manager/event_engine/event.h" +#include "application_manager/smart_object_keys.h" + +namespace am = application_manager; +using ::testing::_; +using ::testing::Return; +using ::testing::ReturnRef; +using ::testing::ReturnPointee; +using ::testing::Mock; +using ::testing::NiceMock; +using ::testing::InSequence; +using ::testing::Truly; + +class MessageHelperMock { + public: + MOCK_METHOD3(SendActivateAppToHMI, + uint32_t(uint32_t const app_id, + hmi_apis::Common_HMILevel::eType level, + bool send_policy_priority)); + MOCK_METHOD1(SendOnResumeAudioSourceToHMI, void(const uint32_t app_id)); +}; + +static MessageHelperMock* message_helper_mock_; + +uint32_t application_manager::MessageHelper::SendActivateAppToHMI( + uint32_t const app_id, hmi_apis::Common_HMILevel::eType level, + bool send_policy_priority) { + return message_helper_mock_->SendActivateAppToHMI(app_id, level, + send_policy_priority); +} + +void application_manager::MessageHelper::SendOnResumeAudioSourceToHMI( + const uint32_t app_id) { + message_helper_mock_->SendOnResumeAudioSourceToHMI(app_id); +} + +namespace state_controller_test { + +struct HmiStatesComparator { + mobile_apis::HMILevel::eType hmi_level_; + mobile_apis::AudioStreamingState::eType audio_streaming_state_; + mobile_apis::SystemContext::eType system_context_; + + HmiStatesComparator( + mobile_apis::HMILevel::eType hmi_level, + mobile_apis::AudioStreamingState::eType audio_streaming_state, + mobile_apis::SystemContext::eType system_context) + : hmi_level_(hmi_level), + audio_streaming_state_(audio_streaming_state), + system_context_(system_context) {} + + HmiStatesComparator(am::HmiStatePtr state_ptr) + : hmi_level_(state_ptr->hmi_level()), + audio_streaming_state_(state_ptr->audio_streaming_state()), + system_context_(state_ptr->system_context()) {} + + bool operator()(am::HmiStatePtr state_ptr) const { + return state_ptr->hmi_level() == hmi_level_ && + state_ptr->audio_streaming_state() == audio_streaming_state_ && + state_ptr->system_context() == system_context_; + } +}; + +struct HmiStatesIDComparator { + am::HmiState::StateID state_id_; + + HmiStatesIDComparator(am::HmiState::StateID state_id) + : state_id_(state_id) {} + + bool operator()(am::HmiStatePtr state_ptr) const { + return state_ptr->state_id() == state_id_; + } +}; + +#define MEDIA true +#define NOT_MEDIA false +#define VC true +#define NOT_VC false +#define NAVI true +#define NOT_NAVI false + +class StateControllerTest : public ::testing::Test { + public: + StateControllerTest() + : ::testing::Test(), + usage_stat("0", utils::SharedPtr<us::StatisticsManager>( + new StatisticsManagerMock)), + applications_(application_set_, applications_lock_), + state_ctrl_(&app_manager_mock_) {} + NiceMock<ApplicationManagerMock> app_manager_mock_; + + am::UsageStatistics usage_stat; + + am::ApplicationSet application_set_; + mutable sync_primitives::Lock applications_lock_; + DataAccessor<am::ApplicationSet> applications_; + am::StateController state_ctrl_; + + am::ApplicationSharedPtr simple_app_; + NiceMock<ApplicationMock>* simple_app_ptr_; + uint32_t simple_app_id_ = 1721; + + am::ApplicationSharedPtr navi_app_; + NiceMock<ApplicationMock>* navi_app_ptr_; + uint32_t navi_app_id_ = 1762; + + am::ApplicationSharedPtr media_app_; + NiceMock<ApplicationMock>* media_app_ptr_; + uint32_t media_app_id_ = 1801; + + am::ApplicationSharedPtr vc_app_; + NiceMock<ApplicationMock>* vc_app_ptr_; + uint32_t vc_app_id_ = 1825; + + am::ApplicationSharedPtr media_navi_app_; + NiceMock<ApplicationMock>* media_navi_app_ptr_; + uint32_t media_navi_app_id_ = 1855; + + am::ApplicationSharedPtr media_vc_app_; + NiceMock<ApplicationMock>* media_vc_app_ptr_; + uint32_t media_vc_app_id_ = 1881; + + am::ApplicationSharedPtr navi_vc_app_; + NiceMock<ApplicationMock>* navi_vc_app_ptr_; + uint32_t navi_vc_app_id_ = 1894; + + am::ApplicationSharedPtr media_navi_vc_app_; + NiceMock<ApplicationMock>* media_navi_vc_app_ptr_; + uint32_t media_navi_vc_app_id_ = 1922; + + std::vector<am::HmiStatePtr> valid_states_for_audio_app_; + std::vector<am::HmiStatePtr> valid_states_for_not_audio_app_; + std::vector<am::HmiStatePtr> common_invalid_states_; + std::vector<am::HmiStatePtr> invalid_states_for_not_audio_app; + std::vector<am::HmiStatePtr> invalid_states_for_audio_app; + std::vector<am::HmiState::StateID> valid_state_ids_; + + am::HmiStatePtr createHmiState( + mobile_apis::HMILevel::eType hmi_level, + mobile_apis::AudioStreamingState::eType aidio_ss, + mobile_apis::SystemContext::eType system_context) { + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + + am::HmiStatePtr state = + utils::MakeShared<am::HmiState>(simple_app_id_, &app_manager_mock_); + state->set_hmi_level(hmi_level); + state->set_audio_streaming_state(aidio_ss); + state->set_system_context(system_context); + return state; + } + + protected: + am::ApplicationSharedPtr ConfigureApp(NiceMock<ApplicationMock>** app_mock, + uint32_t app_id, bool media, bool navi, + bool vc) { + *app_mock = new NiceMock<ApplicationMock>; + + Mock::AllowLeak(*app_mock); // WorkAround for gogletest bug + am::ApplicationSharedPtr app(*app_mock); + + ON_CALL(**app_mock, app_id()).WillByDefault(Return(app_id)); + ON_CALL(**app_mock, is_media_application()).WillByDefault(Return(media)); + ON_CALL(**app_mock, is_navi()).WillByDefault(Return(navi)); + ON_CALL(**app_mock, is_voice_communication_supported()) + .WillByDefault(Return(vc)); + ON_CALL(**app_mock, IsAudioApplication()) + .WillByDefault(Return(media || navi || vc)); + + EXPECT_CALL(**app_mock, usage_report()) + .WillRepeatedly(ReturnRef(usage_stat)); + + return app; + } + + void FillStatesLists() { + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + // Valid states for not audio app + message_helper_mock_ = new MessageHelperMock; + valid_states_for_not_audio_app_.push_back( + createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE, + SystemContext::SYSCTXT_MAIN)); + valid_states_for_not_audio_app_.push_back( + createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE, + SystemContext::SYSCTXT_VRSESSION)); + valid_states_for_not_audio_app_.push_back( + createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE, + SystemContext::SYSCTXT_MENU)); + valid_states_for_not_audio_app_.push_back( + createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE, + SystemContext::SYSCTXT_HMI_OBSCURED)); + valid_states_for_not_audio_app_.push_back( + createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE, + SystemContext::SYSCTXT_ALERT)); + valid_states_for_not_audio_app_.push_back(createHmiState( + HMILevel::HMI_BACKGROUND, AudioStreamingState::NOT_AUDIBLE, + SystemContext::SYSCTXT_MAIN)); + valid_states_for_not_audio_app_.push_back( + createHmiState(HMILevel::HMI_FULL, AudioStreamingState::NOT_AUDIBLE, + SystemContext::SYSCTXT_MAIN)); + + // Valid states audio app + valid_states_for_audio_app_.push_back( + createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE, + SystemContext::SYSCTXT_MAIN)); + valid_states_for_audio_app_.push_back( + createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE, + SystemContext::SYSCTXT_VRSESSION)); + valid_states_for_audio_app_.push_back( + createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE, + SystemContext::SYSCTXT_MENU)); + valid_states_for_audio_app_.push_back( + createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE, + SystemContext::SYSCTXT_HMI_OBSCURED)); + valid_states_for_audio_app_.push_back( + createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE, + SystemContext::SYSCTXT_ALERT)); + valid_states_for_audio_app_.push_back(createHmiState( + HMILevel::HMI_BACKGROUND, AudioStreamingState::NOT_AUDIBLE, + SystemContext::SYSCTXT_MAIN)); + valid_states_for_audio_app_.push_back( + createHmiState(HMILevel::HMI_LIMITED, AudioStreamingState::AUDIBLE, + SystemContext::SYSCTXT_MAIN)); + valid_states_for_audio_app_.push_back( + createHmiState(HMILevel::HMI_LIMITED, AudioStreamingState::ATTENUATED, + SystemContext::SYSCTXT_MAIN)); + valid_states_for_audio_app_.push_back( + createHmiState(HMILevel::HMI_FULL, AudioStreamingState::NOT_AUDIBLE, + SystemContext::SYSCTXT_MAIN)); + valid_states_for_audio_app_.push_back( + createHmiState(HMILevel::HMI_FULL, AudioStreamingState::AUDIBLE, + SystemContext::SYSCTXT_MAIN)); + + // Common Invalid States + common_invalid_states_.push_back( + createHmiState(HMILevel::INVALID_ENUM, AudioStreamingState::NOT_AUDIBLE, + SystemContext::SYSCTXT_MAIN)); + common_invalid_states_.push_back( + createHmiState(HMILevel::HMI_NONE, AudioStreamingState::INVALID_ENUM, + SystemContext::SYSCTXT_MAIN)); + common_invalid_states_.push_back( + createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE, + SystemContext::INVALID_ENUM)); + common_invalid_states_.push_back(createHmiState( + HMILevel::INVALID_ENUM, AudioStreamingState::INVALID_ENUM, + SystemContext::SYSCTXT_MAIN)); + common_invalid_states_.push_back( + createHmiState(HMILevel::HMI_NONE, AudioStreamingState::INVALID_ENUM, + SystemContext::INVALID_ENUM)); + common_invalid_states_.push_back(createHmiState( + HMILevel::INVALID_ENUM, AudioStreamingState::INVALID_ENUM, + SystemContext::INVALID_ENUM)); + common_invalid_states_.push_back(createHmiState( + HMILevel::INVALID_ENUM, AudioStreamingState::INVALID_ENUM, + SystemContext::INVALID_ENUM)); + // Invalid States for audio apps + invalid_states_for_audio_app.push_back( + createHmiState(HMILevel::HMI_LIMITED, AudioStreamingState::NOT_AUDIBLE, + SystemContext::SYSCTXT_MAIN)); + invalid_states_for_audio_app.push_back( + createHmiState(HMILevel::HMI_BACKGROUND, AudioStreamingState::AUDIBLE, + SystemContext::SYSCTXT_MAIN)); + invalid_states_for_audio_app.push_back(createHmiState( + HMILevel::HMI_BACKGROUND, AudioStreamingState::ATTENUATED, + SystemContext::SYSCTXT_MAIN)); + invalid_states_for_audio_app.push_back( + createHmiState(HMILevel::HMI_NONE, AudioStreamingState::AUDIBLE, + SystemContext::SYSCTXT_MAIN)); + invalid_states_for_audio_app.push_back( + createHmiState(HMILevel::HMI_NONE, AudioStreamingState::ATTENUATED, + SystemContext::SYSCTXT_MAIN)); + invalid_states_for_audio_app.push_back( + createHmiState(HMILevel::HMI_NONE, AudioStreamingState::ATTENUATED, + SystemContext::SYSCTXT_MAIN)); + // Invalid States for not audio apps + invalid_states_for_not_audio_app.push_back( + createHmiState(HMILevel::HMI_LIMITED, AudioStreamingState::ATTENUATED, + SystemContext::SYSCTXT_MAIN)); + invalid_states_for_not_audio_app.push_back( + createHmiState(HMILevel::HMI_LIMITED, AudioStreamingState::AUDIBLE, + SystemContext::SYSCTXT_MAIN)); + invalid_states_for_not_audio_app.push_back( + createHmiState(HMILevel::HMI_FULL, AudioStreamingState::ATTENUATED, + SystemContext::SYSCTXT_MAIN)); + invalid_states_for_not_audio_app.push_back( + createHmiState(HMILevel::HMI_FULL, AudioStreamingState::AUDIBLE, + SystemContext::SYSCTXT_MAIN)); + + // Valid state ids + valid_state_ids_.push_back(am::HmiState::StateID::STATE_ID_VR_SESSION); + valid_state_ids_.push_back(am::HmiState::StateID::STATE_ID_TTS_SESSION); + valid_state_ids_.push_back(am::HmiState::StateID::STATE_ID_PHONE_CALL); + valid_state_ids_.push_back(am::HmiState::StateID::STATE_ID_SAFETY_MODE); + valid_state_ids_.push_back(am::HmiState::StateID::STATE_ID_NAVI_STREAMING); + } + + void ConfigureApps() { + simple_app_ = ConfigureApp(&simple_app_ptr_, simple_app_id_, NOT_MEDIA, + NOT_NAVI, NOT_VC); + media_app_ = + ConfigureApp(&media_app_ptr_, media_app_id_, MEDIA, NOT_NAVI, NOT_VC); + navi_app_ = + ConfigureApp(&navi_app_ptr_, navi_app_id_, NOT_MEDIA, NAVI, NOT_VC); + vc_app_ = ConfigureApp(&vc_app_ptr_, vc_app_id_, NOT_MEDIA, NOT_NAVI, VC); + media_navi_app_ = ConfigureApp(&media_navi_app_ptr_, media_navi_app_id_, + MEDIA, NAVI, NOT_VC); + media_vc_app_ = + ConfigureApp(&media_vc_app_ptr_, media_vc_app_id_, MEDIA, NOT_NAVI, VC); + navi_vc_app_ = + ConfigureApp(&navi_vc_app_ptr_, navi_vc_app_id_, NOT_MEDIA, NAVI, VC); + media_navi_vc_app_ = ConfigureApp(&media_navi_vc_app_ptr_, + media_navi_vc_app_id_, MEDIA, NAVI, VC); + } + void CheckAppConfiguration() { + ASSERT_EQ(simple_app_.get(), simple_app_ptr_); + ASSERT_EQ(media_app_.get(), media_app_ptr_); + ASSERT_EQ(navi_app_.get(), navi_app_ptr_); + ASSERT_EQ(vc_app_.get(), vc_app_ptr_); + ASSERT_EQ(media_navi_app_.get(), media_navi_app_ptr_); + ASSERT_EQ(media_vc_app_.get(), media_vc_app_ptr_); + ASSERT_EQ(navi_vc_app_.get(), navi_vc_app_ptr_); + ASSERT_EQ(media_navi_vc_app_.get(), media_navi_vc_app_ptr_); + + ASSERT_EQ(simple_app_->app_id(), simple_app_id_); + ASSERT_EQ(media_app_->app_id(), media_app_id_); + ASSERT_EQ(navi_app_->app_id(), navi_app_id_); + ASSERT_EQ(vc_app_->app_id(), vc_app_id_); + ASSERT_EQ(media_navi_app_->app_id(), media_navi_app_id_); + ASSERT_EQ(media_vc_app_->app_id(), media_vc_app_id_); + ASSERT_EQ(navi_vc_app_->app_id(), navi_vc_app_id_); + ASSERT_EQ(media_navi_vc_app_->app_id(), media_navi_vc_app_id_); + + ASSERT_FALSE(simple_app_->IsAudioApplication()); + ASSERT_TRUE(media_app_->IsAudioApplication()); + ASSERT_TRUE(navi_app_->IsAudioApplication()); + ASSERT_TRUE(vc_app_->IsAudioApplication()); + ASSERT_TRUE(media_navi_app_->IsAudioApplication()); + ASSERT_TRUE(media_vc_app_->IsAudioApplication()); + ASSERT_TRUE(navi_vc_app_->IsAudioApplication()); + ASSERT_TRUE(media_navi_vc_app_->IsAudioApplication()); + + ASSERT_FALSE(simple_app_->is_media_application()); + ASSERT_TRUE(media_app_->is_media_application()); + ASSERT_FALSE(navi_app_->is_media_application()); + ASSERT_FALSE(vc_app_->is_media_application()); + ASSERT_TRUE(media_navi_app_->is_media_application()); + ASSERT_TRUE(media_vc_app_->is_media_application()); + ASSERT_FALSE(navi_vc_app_->is_media_application()); + ASSERT_TRUE(media_navi_vc_app_->is_media_application()); + + ASSERT_FALSE(simple_app_->is_navi()); + ASSERT_TRUE(navi_app_->is_navi()); + ASSERT_FALSE(media_app_->is_navi()); + ASSERT_FALSE(vc_app_->is_navi()); + ASSERT_TRUE(media_navi_app_->is_navi()); + ASSERT_FALSE(media_vc_app_->is_navi()); + ASSERT_TRUE(navi_vc_app_->is_navi()); + ASSERT_TRUE(media_navi_vc_app_->is_navi()); + + ASSERT_FALSE(simple_app_->is_voice_communication_supported()); + ASSERT_FALSE(navi_app_->is_voice_communication_supported()); + ASSERT_FALSE(media_app_->is_voice_communication_supported()); + ASSERT_TRUE(vc_app_->is_voice_communication_supported()); + ASSERT_FALSE(media_navi_app_->is_voice_communication_supported()); + ASSERT_TRUE(media_vc_app_->is_voice_communication_supported()); + ASSERT_TRUE(navi_vc_app_->is_voice_communication_supported()); + ASSERT_TRUE(media_navi_vc_app_->is_voice_communication_supported()); + } + + void SetUp() { + ON_CALL(app_manager_mock_, applications()) + .WillByDefault(Return(applications_)); + ConfigureApps(); + CheckAppConfiguration(); + FillStatesLists(); + } + + void TearDown() { delete message_helper_mock_; } + + void ExpectSuccesfullSetHmiState(am::ApplicationSharedPtr app, + NiceMock<ApplicationMock>* app_mock, + am::HmiStatePtr old_state, + am::HmiStatePtr new_state) { + EXPECT_CALL(*app_mock, CurrentHmiState()) + .WillOnce(Return(old_state)) + .WillOnce(Return(new_state)); + EXPECT_CALL(*app_mock, + SetRegularState(Truly(HmiStatesComparator(new_state)))); + if (!HmiStatesComparator(old_state)(new_state)) { + EXPECT_CALL(app_manager_mock_, SendHMIStatusNotification(app)); + EXPECT_CALL(app_manager_mock_, + OnHMILevelChanged(app->app_id(), old_state->hmi_level(), + new_state->hmi_level())); + } + } + + void ExpectAppChangeHmiStateDueToConflictResolving( + am::ApplicationSharedPtr app, NiceMock<ApplicationMock>* app_mock, + am::HmiStatePtr old_state, am::HmiStatePtr new_state) { + EXPECT_CALL(*app_mock, RegularHmiState()) + .WillOnce(Return(old_state)) + .WillOnce(Return(old_state)); + ExpectSuccesfullSetHmiState(app, app_mock, old_state, new_state); + } + + void ExpectAppWontChangeHmiStateDueToConflictResolving( + am::ApplicationSharedPtr app, NiceMock<ApplicationMock>* app_mock, + am::HmiStatePtr state) { + EXPECT_CALL(*app_mock, RegularHmiState()).WillOnce(Return(state)); + EXPECT_CALL(app_manager_mock_, SendHMIStatusNotification(app)).Times(0); + EXPECT_CALL(app_manager_mock_, OnHMILevelChanged(app->app_id(), _, _)) + .Times(0); + } + + void InsertApplication(am::ApplicationSharedPtr app) { + application_set_.insert(app); + ON_CALL(app_manager_mock_, application(app->app_id())) + .WillByDefault(Return(app)); + } + + am::HmiStatePtr NoneNotAudibleState() { + return createHmiState(mobile_apis::HMILevel::HMI_NONE, + mobile_apis::AudioStreamingState::NOT_AUDIBLE, + mobile_apis::SystemContext::SYSCTXT_MAIN); + } + + am::HmiStatePtr FullAudibleState() { + return createHmiState(mobile_apis::HMILevel::HMI_FULL, + mobile_apis::AudioStreamingState::AUDIBLE, + mobile_apis::SystemContext::SYSCTXT_MAIN); + } + + am::HmiStatePtr FullNotAudibleState() { + return createHmiState(mobile_apis::HMILevel::HMI_FULL, + mobile_apis::AudioStreamingState::NOT_AUDIBLE, + mobile_apis::SystemContext::SYSCTXT_MAIN); + } + + am::HmiStatePtr LimitedState() { + return createHmiState(mobile_apis::HMILevel::HMI_LIMITED, + mobile_apis::AudioStreamingState::AUDIBLE, + mobile_apis::SystemContext::SYSCTXT_MAIN); + } + + am::HmiStatePtr BackgroundState() { + return createHmiState(mobile_apis::HMILevel::HMI_BACKGROUND, + mobile_apis::AudioStreamingState::NOT_AUDIBLE, + mobile_apis::SystemContext::SYSCTXT_MAIN); + } + + void CheckStateApplyingForApplication( + NiceMock<ApplicationMock>& application, + std::vector<am::HmiState::StateID>& state_ids) { + using smart_objects::SmartObject; + using am::event_engine::Event; + namespace FunctionID = hmi_apis::FunctionID; + + EXPECT_CALL(application, CurrentHmiState()) + .WillRepeatedly(Return(NoneNotAudibleState())); + + for (uint32_t i = 0; i < state_ids.size(); ++i) { + am::HmiState::StateID state_id = state_ids[i]; + EXPECT_CALL(application, + AddHMIState(Truly(HmiStatesIDComparator(state_id)))).Times(1); + + switch (state_id) { + case am::HmiState::StateID::STATE_ID_VR_SESSION: { + Event vr_start_event(FunctionID::VR_Started); + state_ctrl_.on_event(vr_start_event); + break; + } + case am::HmiState::StateID::STATE_ID_TTS_SESSION: { + Event tts_start_event(FunctionID::TTS_Started); + state_ctrl_.on_event(tts_start_event); + break; + } + case am::HmiState::StateID::STATE_ID_PHONE_CALL: { + Event phone_call_event( + FunctionID::BasicCommunication_OnPhoneCall); + SmartObject message; + message[am::strings::msg_params][am::hmi_notification::is_active] = true; + phone_call_event.set_smart_object(message); + state_ctrl_.on_event(phone_call_event); + break; + } + case am::HmiState::StateID::STATE_ID_SAFETY_MODE: { + Event emergency_event( + FunctionID::BasicCommunication_OnEmergencyEvent); + SmartObject message; + message[am::strings::msg_params][am::hmi_response::enabled] = true; + emergency_event.set_smart_object(message); + state_ctrl_.on_event(emergency_event); + break; + } + case am::HmiState::StateID::STATE_ID_NAVI_STREAMING: { + state_ctrl_.OnNaviStreamingStarted(); + break; + } + default: + break; + } + + EXPECT_CALL(application, AddHMIState(_)).Times(0); + } + + for (uint32_t i = 0; i < state_ids.size(); ++i) { + am::HmiState::StateID state_id = state_ids[i]; + EXPECT_CALL(application, RemoveHMIState(state_id)).Times(1); + + switch (state_id) { + case am::HmiState::StateID::STATE_ID_VR_SESSION: { + Event vr_stop_event(FunctionID::VR_Stopped); + state_ctrl_.on_event(vr_stop_event); + break; + } + case am::HmiState::StateID::STATE_ID_TTS_SESSION: { + Event tts_stop_event(FunctionID::TTS_Stopped); + state_ctrl_.on_event(tts_stop_event); + break; + } + case am::HmiState::StateID::STATE_ID_PHONE_CALL: { + Event phone_call_event( + FunctionID::BasicCommunication_OnPhoneCall); + SmartObject message; + message[am::strings::msg_params][am::hmi_notification::is_active] = false; + phone_call_event.set_smart_object(message); + state_ctrl_.on_event(phone_call_event); + break; + } + case am::HmiState::StateID::STATE_ID_SAFETY_MODE: { + Event emergency_event( + FunctionID::BasicCommunication_OnEmergencyEvent); + SmartObject message; + message[am::strings::msg_params][am::hmi_response::enabled] = false; + emergency_event.set_smart_object(message); + state_ctrl_.on_event(emergency_event); + break; + } + case am::HmiState::StateID::STATE_ID_NAVI_STREAMING: { + state_ctrl_.OnNaviStreamingStopped(); + break; + } + default: + break; + } + + EXPECT_CALL(application, RemoveHMIState(_)).Times(0); + } + } +}; + +TEST_F(StateControllerTest, OnStateChangedWithEqualStates) { + EXPECT_CALL(app_manager_mock_, SendHMIStatusNotification(_)).Times(0); + EXPECT_CALL(app_manager_mock_, OnHMILevelChanged(_, _, _)).Times(0); + EXPECT_CALL(*simple_app_ptr_, ResetDataInNone()).Times(0); + + for (uint32_t i = 0; i < valid_states_for_not_audio_app_.size(); ++i) { + state_ctrl_.OnStateChanged(simple_app_, + valid_states_for_not_audio_app_[i], + valid_states_for_not_audio_app_[i]); + } +} + +TEST_F(StateControllerTest, OnStateChangedWithDifferentStates) { + for (uint32_t i = 0; i < valid_states_for_not_audio_app_.size(); ++i) { + for (uint32_t j = 0; j < valid_states_for_not_audio_app_.size(); ++j) { + HmiStatesComparator comp(valid_states_for_not_audio_app_[i]); + if (!comp(valid_states_for_not_audio_app_[j])) { + EXPECT_CALL(app_manager_mock_, + SendHMIStatusNotification(simple_app_)).Times(1); + EXPECT_CALL(app_manager_mock_, + OnHMILevelChanged( + simple_app_id_, + valid_states_for_not_audio_app_[i]->hmi_level(), + valid_states_for_not_audio_app_[j]->hmi_level())).Times(1); + if (mobile_apis::HMILevel::HMI_NONE == + valid_states_for_not_audio_app_[j]->hmi_level()) { + EXPECT_CALL(*simple_app_ptr_, ResetDataInNone()).Times(1); + } + state_ctrl_.OnStateChanged(simple_app_, + valid_states_for_not_audio_app_[i], + valid_states_for_not_audio_app_[j]); + + EXPECT_CALL(app_manager_mock_, SendHMIStatusNotification(_)).Times(0); + EXPECT_CALL(app_manager_mock_, OnHMILevelChanged(_, _, _)).Times(0); + EXPECT_CALL(*simple_app_ptr_, ResetDataInNone()).Times(0); + } + } + } +} + +TEST_F(StateControllerTest, OnStateChangedToNone) { + using namespace am; + using namespace mobile_apis; + + HmiStatePtr none_state = createHmiState(HMILevel::HMI_NONE, + AudioStreamingState::NOT_AUDIBLE, + SystemContext::SYSCTXT_MAIN); + HmiStatePtr not_none_state = createHmiState(HMILevel::HMI_FULL, + AudioStreamingState::NOT_AUDIBLE, + SystemContext::SYSCTXT_MAIN); + + EXPECT_CALL(*simple_app_ptr_, ResetDataInNone()).Times(0); + state_ctrl_.OnStateChanged(simple_app_, none_state, not_none_state); + + EXPECT_CALL(*simple_app_ptr_, ResetDataInNone()).Times(1); + state_ctrl_.OnStateChanged(simple_app_, not_none_state, none_state); +} + +TEST_F(StateControllerTest, MoveSimpleAppToValidStates) { + using am::HmiState; + using am::HmiStatePtr; + using am::UsageStatistics; + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + HmiStatePtr initial_state = + createHmiState(HMILevel::INVALID_ENUM, AudioStreamingState::INVALID_ENUM, + SystemContext::INVALID_ENUM); + + for (std::vector<HmiStatePtr>::iterator it = + valid_states_for_not_audio_app_.begin(); + it != valid_states_for_not_audio_app_.end(); ++it) { + HmiStatePtr state_to_setup = *it; + EXPECT_CALL(*simple_app_ptr_, CurrentHmiState()) + .WillOnce(Return(initial_state)) + .WillOnce(Return(state_to_setup)); + EXPECT_CALL(app_manager_mock_, SendHMIStatusNotification(simple_app_)); + EXPECT_CALL(app_manager_mock_, + OnHMILevelChanged(simple_app_id_, initial_state->hmi_level(), + state_to_setup->hmi_level())); + + EXPECT_CALL(*simple_app_ptr_, + SetRegularState(Truly(HmiStatesComparator(state_to_setup)))); + state_ctrl_.SetRegularState<false>(simple_app_, state_to_setup); + initial_state = state_to_setup; + } +} + +TEST_F(StateControllerTest, MoveAudioAppAppToValidStates) { + using am::HmiState; + using am::HmiStatePtr; + using am::UsageStatistics; + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + + am::ApplicationSharedPtr audio_app = media_navi_vc_app_; + NiceMock<ApplicationMock>* audio_app_mock = media_navi_vc_app_ptr_; + + HmiStatePtr initial_state = + createHmiState(HMILevel::INVALID_ENUM, AudioStreamingState::INVALID_ENUM, + SystemContext::INVALID_ENUM); + + for (std::vector<HmiStatePtr>::iterator it = + valid_states_for_audio_app_.begin(); + it != valid_states_for_audio_app_.end(); ++it) { + HmiStatePtr state_to_setup = *it; + EXPECT_CALL(*audio_app_mock, CurrentHmiState()) + .WillOnce(Return(initial_state)) + .WillOnce(Return(state_to_setup)); + EXPECT_CALL(app_manager_mock_, SendHMIStatusNotification(audio_app)); + EXPECT_CALL( + app_manager_mock_, + OnHMILevelChanged(audio_app->app_id(), initial_state->hmi_level(), + state_to_setup->hmi_level())); + + EXPECT_CALL(*audio_app_mock, + SetRegularState(Truly(HmiStatesComparator(state_to_setup)))); + state_ctrl_.SetRegularState<false>(media_navi_vc_app_, state_to_setup); + initial_state = state_to_setup; + } +} +/* +TEST_F(StateControllerTest, MoveAppFromValidStateToInvalid) { + using am::HmiState; + using am::HmiStatePtr; + using am::UsageStatistics; + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + + for (std::vector<HmiStatePtr>::iterator valid_state_it = + valid_states_for_not_audio_app_.begin(); + valid_state_it != valid_states_for_not_audio_app_.end(); + ++valid_state_it) { + for (std::vector<HmiStatePtr>::iterator invalid_state_it = + common_invalid_states_.begin(); + invalid_state_it != common_invalid_states_.end(); ++invalid_state_it) { + HmiStatePtr initial_state = *valid_state_it; + HmiStatePtr invalid_state = *invalid_state_it; + EXPECT_CALL(*simple_app_ptr_, CurrentHmiState()) + .WillOnce(Return(initial_state)); + EXPECT_CALL(app_manager_mock_, OnHMILevelChanged(_, _, _)).Times(0); + EXPECT_CALL(*simple_app_ptr_, SetRegularState(_)).Times(0); + state_ctrl_.SetRegularState<false>(simple_app_, invalid_state); + } + } + + NiceMock<ApplicationMock>* audio_app_mock = media_navi_vc_app_ptr_; + am::ApplicationSharedPtr audio_app = media_navi_vc_app_; + for (std::vector<HmiStatePtr>::iterator valid_state_it = + valid_states_for_audio_app_.begin(); + valid_state_it != valid_states_for_audio_app_.end(); ++valid_state_it) { + for (std::vector<HmiStatePtr>::iterator invalid_state_it = + invalid_states_for_audio_app.begin(); + invalid_state_it != invalid_states_for_audio_app.end(); + ++invalid_state_it) { + HmiStatePtr initial_state = *valid_state_it; + HmiStatePtr invalid_state = *invalid_state_it; + EXPECT_CALL(*audio_app_mock, CurrentHmiState()) + .WillOnce(Return(initial_state)); + EXPECT_CALL(app_manager_mock_, OnHMILevelChanged(_, _, _)).Times(0); + EXPECT_CALL(*audio_app_mock, SetRegularState(_)).Times(0); + state_ctrl_.SetRegularState<false>(audio_app, invalid_state); + } + } + + for (std::vector<HmiStatePtr>::iterator valid_state_it = + valid_states_for_not_audio_app_.begin(); + valid_state_it != valid_states_for_not_audio_app_.end(); + ++valid_state_it) { + for (std::vector<HmiStatePtr>::iterator invalid_state_it = + invalid_states_for_not_audio_app.begin(); + invalid_state_it != invalid_states_for_not_audio_app.end(); + ++invalid_state_it) { + HmiStatePtr initial_state = *valid_state_it; + HmiStatePtr invalid_state = *invalid_state_it; + EXPECT_CALL(*simple_app_ptr_, CurrentHmiState()) + .WillOnce(Return(initial_state)); + EXPECT_CALL(app_manager_mock_, OnHMILevelChanged(_, _, _)).Times(0); + EXPECT_CALL(*simple_app_ptr_, SetRegularState(_)).Times(0); + state_ctrl_.SetRegularState<false>(simple_app_, invalid_state); + } + } +} + +TEST_F(StateControllerTest, MoveAppFromInValidStateToValid) { + using am::HmiState; + using am::HmiStatePtr; + using am::UsageStatistics; + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + + NiceMock<ApplicationMock>* audio_app_mock = media_navi_vc_app_ptr_; + am::ApplicationSharedPtr audio_app = media_navi_vc_app_; + HmiStatePtr invalid_state = + createHmiState(HMILevel::INVALID_ENUM, AudioStreamingState::INVALID_ENUM, + SystemContext::INVALID_ENUM); + + for (std::vector<HmiStatePtr>::iterator it = + valid_states_for_audio_app_.begin(); + it != valid_states_for_audio_app_.end(); ++it) { + HmiStatePtr initial_state = *it; + EXPECT_CALL(*audio_app_mock, CurrentHmiState()) + .WillOnce(Return(initial_state)); + EXPECT_CALL(app_manager_mock_, OnHMILevelChanged(_, _, _)).Times(0); + EXPECT_CALL(*audio_app_mock, SetRegularState(_)).Times(0); + state_ctrl_.SetRegularState<false>(audio_app, invalid_state); + } + + for (std::vector<HmiStatePtr>::iterator it = + valid_states_for_not_audio_app_.begin(); + it != valid_states_for_not_audio_app_.end(); ++it) { + HmiStatePtr initial_state = *it; + EXPECT_CALL(*simple_app_ptr_, CurrentHmiState()) + .WillOnce(Return(initial_state)); + EXPECT_CALL(app_manager_mock_, OnHMILevelChanged(_, _, _)).Times(0); + EXPECT_CALL(*simple_app_ptr_, SetRegularState(_)).Times(0); + state_ctrl_.SetRegularState<false>(simple_app_, invalid_state); + } +} + +TEST_F(StateControllerTest, MoveAppFromInValidStateToInvalid) { + using am::HmiState; + using am::HmiStatePtr; + using am::UsageStatistics; + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + NiceMock<ApplicationMock>* audio_app_mock = media_navi_vc_app_ptr_; + am::ApplicationSharedPtr audio_app = media_navi_vc_app_; + HmiStatePtr initial_invalid_state = + createHmiState(HMILevel::INVALID_ENUM, AudioStreamingState::INVALID_ENUM, + SystemContext::INVALID_ENUM); + + am::ApplicationConstSharedPtr const_audio_app(audio_app); + + for (std::vector<HmiStatePtr>::iterator it = + invalid_states_for_audio_app.begin(); + it != invalid_states_for_audio_app.end(); ++it) { + HmiStatePtr state_to_setup = *it; + HmiStatePtr default_state = + createHmiState(HMILevel::HMI_LIMITED, AudioStreamingState::AUDIBLE, + SystemContext::SYSCTXT_MAIN); + EXPECT_CALL(app_manager_mock_, GetDefaultHmiLevel(const_audio_app)) + .WillOnce(Return(HMILevel::HMI_LIMITED)); + EXPECT_CALL(*audio_app_mock, CurrentHmiState()) + .WillOnce(Return(initial_invalid_state)) + .WillOnce(Return(initial_invalid_state)) + .WillOnce(Return(default_state)); + EXPECT_CALL(app_manager_mock_, + OnHMILevelChanged(audio_app->app_id(), + initial_invalid_state->hmi_level(), + default_state->hmi_level())); + EXPECT_CALL(*audio_app_mock, + SetRegularState(Truly(HmiStatesComparator(default_state)))); + state_ctrl_.SetRegularState<false>(audio_app, state_to_setup); + } + + for (std::vector<HmiStatePtr>::iterator it = + invalid_states_for_not_audio_app.begin(); + it != invalid_states_for_not_audio_app.end(); ++it) { + HmiStatePtr state_to_setup = *it; + HmiStatePtr default_state = createHmiState(HMILevel::HMI_BACKGROUND, + AudioStreamingState::NOT_AUDIBLE, + SystemContext::SYSCTXT_MAIN); + am::ApplicationConstSharedPtr const_simple_app(simple_app_); + EXPECT_CALL(app_manager_mock_, GetDefaultHmiLevel(const_simple_app)) + .WillOnce(Return(HMILevel::HMI_BACKGROUND)); + EXPECT_CALL(*simple_app_ptr_, CurrentHmiState()) + .WillOnce(Return(initial_invalid_state)) + .WillOnce(Return(initial_invalid_state)) + .WillOnce(Return(default_state)); + EXPECT_CALL(app_manager_mock_, + OnHMILevelChanged(simple_app_ptr_->app_id(), + initial_invalid_state->hmi_level(), + default_state->hmi_level())); + EXPECT_CALL(*simple_app_ptr_, + SetRegularState(Truly(HmiStatesComparator(default_state)))); + state_ctrl_.SetRegularState<false>(simple_app_, state_to_setup); + } +} +*/ +TEST_F(StateControllerTest, SetFullToSimpleAppWhileAnotherSimpleAppIsInFull) { + using am::HmiState; + using am::HmiStatePtr; + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + am::ApplicationSharedPtr app_in_full; + NiceMock<ApplicationMock>* app_in_full_mock; + + am::ApplicationSharedPtr app_moved_to_full; + NiceMock<ApplicationMock>* app_moved_to_full_mock; + + app_in_full = + ConfigureApp(&app_in_full_mock, 1761, NOT_MEDIA, NOT_NAVI, NOT_VC); + app_moved_to_full = + ConfigureApp(&app_moved_to_full_mock, 1796, NOT_MEDIA, NOT_NAVI, NOT_VC); + + InsertApplication(app_in_full); + InsertApplication(app_moved_to_full); + + ExpectSuccesfullSetHmiState(app_moved_to_full, app_moved_to_full_mock, + BackgroundState(), FullNotAudibleState()); + + ExpectAppChangeHmiStateDueToConflictResolving( + app_in_full, app_in_full_mock, FullNotAudibleState(), BackgroundState()); + + state_ctrl_.SetRegularState<false>(app_moved_to_full, FullNotAudibleState()); +} + +TEST_F(StateControllerTest, SetFullToSimpleAppWhileAudioAppAppIsInFull) { + using am::HmiState; + using am::HmiStatePtr; + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + am::ApplicationSharedPtr app_in_full = media_navi_vc_app_; + NiceMock<ApplicationMock>* app_in_full_mock = media_navi_vc_app_ptr_; + + am::ApplicationSharedPtr app_moved_to_full = simple_app_; + NiceMock<ApplicationMock>* app_moved_to_full_mock = simple_app_ptr_; + + InsertApplication(app_in_full); + InsertApplication(app_moved_to_full); + + ExpectSuccesfullSetHmiState(app_moved_to_full, app_moved_to_full_mock, + BackgroundState(), FullNotAudibleState()); + + ExpectAppChangeHmiStateDueToConflictResolving( + app_in_full, app_in_full_mock, FullAudibleState(), LimitedState()); + state_ctrl_.SetRegularState<false>(app_moved_to_full, FullNotAudibleState()); +} + +TEST_F(StateControllerTest, + SetFullToAudioAppAppWhileAnotherTypeAudioAppAppIsInFull) { + using am::HmiState; + using am::HmiStatePtr; + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + + am::ApplicationSharedPtr app_in_full = media_app_; + NiceMock<ApplicationMock>* app_in_full_mock = media_app_ptr_; + + am::ApplicationSharedPtr app_moved_to_full = navi_app_; + NiceMock<ApplicationMock>* app_moved_to_full_mock = navi_app_ptr_; + + InsertApplication(app_in_full); + InsertApplication(app_moved_to_full); + + ExpectSuccesfullSetHmiState(app_moved_to_full, app_moved_to_full_mock, + BackgroundState(), FullAudibleState()); + + ExpectAppChangeHmiStateDueToConflictResolving( + app_in_full, app_in_full_mock, FullAudibleState(), LimitedState()); + state_ctrl_.SetRegularState<false>(app_moved_to_full, FullAudibleState()); +} + +TEST_F(StateControllerTest, + SetFullToAudioAppAppWhileSameTypeAudioAppAppIsInFull) { + using am::HmiState; + using am::HmiStatePtr; + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + NiceMock<ApplicationMock>* app_in_full_mock; + am::ApplicationSharedPtr app_in_full = + ConfigureApp(&app_in_full_mock, 1761, MEDIA, NOT_NAVI, NOT_VC); + + NiceMock<ApplicationMock>* app_moved_to_full_mock; + am::ApplicationSharedPtr app_moved_to_full = + ConfigureApp(&app_moved_to_full_mock, 1796, MEDIA, NOT_NAVI, NOT_VC); + + InsertApplication(app_in_full); + InsertApplication(app_moved_to_full); + ExpectSuccesfullSetHmiState(app_moved_to_full, app_moved_to_full_mock, + BackgroundState(), FullAudibleState()); + + ExpectAppChangeHmiStateDueToConflictResolving( + app_in_full, app_in_full_mock, FullAudibleState(), BackgroundState()); + + state_ctrl_.SetRegularState<false>(app_moved_to_full, FullAudibleState()); +} + +TEST_F(StateControllerTest, + SetFullToAudioAppAppWhileSameTypeAudioAppAppIsInLimited) { + using am::HmiState; + using am::HmiStatePtr; + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + + NiceMock<ApplicationMock>* app_in_limited_mock; + am::ApplicationSharedPtr app_in_limited = + ConfigureApp(&app_in_limited_mock, 1761, NOT_MEDIA, NAVI, NOT_VC); + + NiceMock<ApplicationMock>* app_moved_to_full_mock; + am::ApplicationSharedPtr app_moved_to_full = + ConfigureApp(&app_moved_to_full_mock, 1796, NOT_MEDIA, NAVI, VC); + + InsertApplication(app_in_limited); + InsertApplication(app_moved_to_full); + ExpectSuccesfullSetHmiState(app_moved_to_full, app_moved_to_full_mock, + BackgroundState(), FullAudibleState()); + + ExpectAppChangeHmiStateDueToConflictResolving( + app_in_limited, app_in_limited_mock, LimitedState(), BackgroundState()); + + state_ctrl_.SetRegularState<false>(app_moved_to_full, FullAudibleState()); +} + +TEST_F(StateControllerTest, + SetLimitedToAudioAppAppWhileSameTypeAudioAppAppIsInLimited) { + using am::HmiState; + using am::HmiStatePtr; + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + NiceMock<ApplicationMock>* app_in_limited_mock; + am::ApplicationSharedPtr app_in_limited = + ConfigureApp(&app_in_limited_mock, 1761, NOT_MEDIA, NOT_NAVI, VC); + + NiceMock<ApplicationMock>* app_moved_to_limited_mock; + am::ApplicationSharedPtr app_moved_to_limited = + ConfigureApp(&app_moved_to_limited_mock, 1796, NOT_MEDIA, NOT_NAVI, VC); + + InsertApplication(app_in_limited); + InsertApplication(app_moved_to_limited); + + ExpectSuccesfullSetHmiState(app_moved_to_limited, app_moved_to_limited_mock, + BackgroundState(), LimitedState()); + + ExpectAppChangeHmiStateDueToConflictResolving( + app_in_limited, app_in_limited_mock, LimitedState(), BackgroundState()); + + state_ctrl_.SetRegularState<false>(app_moved_to_limited, LimitedState()); +} + +TEST_F(StateControllerTest, + SetLimitedToAudioAppAppWhileOtherTypeAudioAppAppIsInLimited) { + using am::HmiState; + using am::HmiStatePtr; + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + + am::ApplicationSharedPtr app_in_limited = navi_app_; + NiceMock<ApplicationMock>* app_in_limited_mock = navi_app_ptr_; + + am::ApplicationSharedPtr app_moved_to_limited = vc_app_; + NiceMock<ApplicationMock>* app_moved_to_limited_mock = vc_app_ptr_; + + InsertApplication(app_in_limited); + InsertApplication(app_moved_to_limited); + ExpectSuccesfullSetHmiState(app_moved_to_limited, app_moved_to_limited_mock, + BackgroundState(), LimitedState()); + ExpectAppWontChangeHmiStateDueToConflictResolving( + app_in_limited, app_in_limited_mock, LimitedState()); + state_ctrl_.SetRegularState<false>(app_moved_to_limited, LimitedState()); +} + +TEST_F(StateControllerTest, + SetLimitedToAudioAppAppWhileOtherTypeAudioAppAppIsInFull) { + using am::HmiState; + using am::HmiStatePtr; + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + am::ApplicationSharedPtr app_in_full = navi_app_; + NiceMock<ApplicationMock>* app_in_full_mock = navi_app_ptr_; + + am::ApplicationSharedPtr app_moved_to_limited = vc_app_; + NiceMock<ApplicationMock>* app_moved_to_limited_mock = vc_app_ptr_; + + InsertApplication(app_in_full); + InsertApplication(app_moved_to_limited); + + ExpectSuccesfullSetHmiState(app_moved_to_limited, app_moved_to_limited_mock, + BackgroundState(), LimitedState()); + + ExpectAppWontChangeHmiStateDueToConflictResolving( + app_in_full, app_in_full_mock, FullAudibleState()); + state_ctrl_.SetRegularState<false>(app_moved_to_limited, LimitedState()); +} + +TEST_F(StateControllerTest, SetFullToSimpleAppWhile2AudioAppsInLimited) { + using am::HmiState; + using am::HmiStatePtr; + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + + am::ApplicationSharedPtr app_moved_to_full = simple_app_; + NiceMock<ApplicationMock>* app_moved_to_full_mock = simple_app_ptr_; + + am::ApplicationSharedPtr limited_app1 = media_app_; + NiceMock<ApplicationMock>* limited_app1_mock = media_app_ptr_; + + am::ApplicationSharedPtr limited_app2 = navi_vc_app_; + NiceMock<ApplicationMock>* limited_app2_mock = navi_vc_app_ptr_; + + InsertApplication(app_moved_to_full); + InsertApplication(limited_app1); + InsertApplication(limited_app2); + + ExpectSuccesfullSetHmiState(app_moved_to_full, app_moved_to_full_mock, + BackgroundState(), FullNotAudibleState()); + + ExpectAppWontChangeHmiStateDueToConflictResolving( + limited_app1, limited_app1_mock, LimitedState()); + ExpectAppWontChangeHmiStateDueToConflictResolving( + limited_app2, limited_app2_mock, LimitedState()); + + state_ctrl_.SetRegularState<false>(app_moved_to_full, FullNotAudibleState()); +} + +TEST_F(StateControllerTest, + SetFullToSimpleAppWhile1AudioAppInLimitedAnd1AudioAppInFull) { + using am::HmiState; + using am::HmiStatePtr; + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + + am::ApplicationSharedPtr app_moved_to_full = simple_app_; + NiceMock<ApplicationMock>* app_moved_to_full_mock = simple_app_ptr_; + + am::ApplicationSharedPtr limited_app = media_app_; + NiceMock<ApplicationMock>* limited_app_mock = media_app_ptr_; + + am::ApplicationSharedPtr full_app = navi_vc_app_; + NiceMock<ApplicationMock>* full_app_mock = navi_vc_app_ptr_; + + InsertApplication(app_moved_to_full); + InsertApplication(limited_app); + InsertApplication(full_app); + + ExpectSuccesfullSetHmiState(app_moved_to_full, app_moved_to_full_mock, + BackgroundState(), FullNotAudibleState()); + + ExpectAppWontChangeHmiStateDueToConflictResolving( + limited_app, limited_app_mock, LimitedState()); + + ExpectAppChangeHmiStateDueToConflictResolving( + full_app, full_app_mock, FullAudibleState(), LimitedState()); + + state_ctrl_.SetRegularState<false>(app_moved_to_full, FullNotAudibleState()); +} + +TEST_F(StateControllerTest, + SetFullToSimpleAppWhile1AudioAppInLimitedAnd1SimpleAppInFull) { + using am::HmiState; + using am::HmiStatePtr; + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + + NiceMock<ApplicationMock>* app_moved_to_full_mock; + am::ApplicationSharedPtr app_moved_to_full = + ConfigureApp(&app_moved_to_full_mock, 1761, NOT_MEDIA, NOT_NAVI, NOT_VC); + + am::ApplicationSharedPtr limited_app = media_app_; + NiceMock<ApplicationMock>* limited_app_mock = media_app_ptr_; + + NiceMock<ApplicationMock>* full_app_mock; + am::ApplicationSharedPtr full_app = + ConfigureApp(&full_app_mock, 1796, NOT_MEDIA, NOT_NAVI, NOT_VC); + + InsertApplication(app_moved_to_full); + InsertApplication(limited_app); + InsertApplication(full_app); + + ExpectSuccesfullSetHmiState(app_moved_to_full, app_moved_to_full_mock, + BackgroundState(), FullNotAudibleState()); + + ExpectAppWontChangeHmiStateDueToConflictResolving( + limited_app, limited_app_mock, LimitedState()); + + ExpectAppChangeHmiStateDueToConflictResolving( + full_app, full_app_mock, FullNotAudibleState(), BackgroundState()); + + state_ctrl_.SetRegularState<false>(app_moved_to_full, FullNotAudibleState()); +} + +TEST_F( + StateControllerTest, + SetFullToAudioAppWhile1AudioAppWithSameTypeInLimitedAnd1SimpleAppInFull) { + using am::HmiState; + using am::HmiStatePtr; + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + + NiceMock<ApplicationMock>* app_moved_to_full_mock; + am::ApplicationSharedPtr app_moved_to_full = + ConfigureApp(&app_moved_to_full_mock, 1761, MEDIA, NOT_NAVI, NOT_VC); + + NiceMock<ApplicationMock>* limited_app_mock; + am::ApplicationSharedPtr limited_app = + ConfigureApp(&limited_app_mock, 1762, MEDIA, NOT_NAVI, NOT_VC); + + NiceMock<ApplicationMock>* full_app_mock; + am::ApplicationSharedPtr full_app = + ConfigureApp(&full_app_mock, 1796, NOT_MEDIA, NOT_NAVI, NOT_VC); + + InsertApplication(app_moved_to_full); + InsertApplication(limited_app); + InsertApplication(full_app); + + ExpectSuccesfullSetHmiState(app_moved_to_full, app_moved_to_full_mock, + BackgroundState(), FullAudibleState()); + + ExpectAppChangeHmiStateDueToConflictResolving( + limited_app, limited_app_mock, LimitedState(), BackgroundState()); + + ExpectAppChangeHmiStateDueToConflictResolving( + full_app, full_app_mock, FullNotAudibleState(), BackgroundState()); + + state_ctrl_.SetRegularState<false>(app_moved_to_full, FullAudibleState()); +} + +TEST_F( + StateControllerTest, + SetFullToAudioAppWhileAudioAppWithSameTypeInLimitedAndAudioAppWithOtherTypeInFull) { + using am::HmiState; + using am::HmiStatePtr; + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + + NiceMock<ApplicationMock>* app_moved_to_full_mock; + am::ApplicationSharedPtr app_moved_to_full = + ConfigureApp(&app_moved_to_full_mock, 1761, MEDIA, NOT_NAVI, NOT_VC); + + NiceMock<ApplicationMock>* limited_app_mock; + am::ApplicationSharedPtr limited_app = + ConfigureApp(&limited_app_mock, 1762, MEDIA, NOT_NAVI, NOT_VC); + + NiceMock<ApplicationMock>* full_app_mock; + am::ApplicationSharedPtr full_app = + ConfigureApp(&full_app_mock, 1796, NOT_MEDIA, NAVI, NOT_VC); + + InsertApplication(app_moved_to_full); + InsertApplication(limited_app); + InsertApplication(full_app); + + ExpectSuccesfullSetHmiState(app_moved_to_full, app_moved_to_full_mock, + BackgroundState(), FullAudibleState()); + + ExpectAppChangeHmiStateDueToConflictResolving( + limited_app, limited_app_mock, LimitedState(), BackgroundState()); + + ExpectAppChangeHmiStateDueToConflictResolving( + full_app, full_app_mock, FullAudibleState(), LimitedState()); + + state_ctrl_.SetRegularState<false>(app_moved_to_full, FullAudibleState()); +} + +TEST_F(StateControllerTest, + SetFullToAudioAppWhile3AudioAppsWithSameTypeInLimited) { + using am::HmiState; + using am::HmiStatePtr; + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + + InsertApplication(media_navi_vc_app_); + InsertApplication(media_app_); + InsertApplication(navi_app_); + InsertApplication(vc_app_); + ExpectSuccesfullSetHmiState(media_navi_vc_app_, media_navi_vc_app_ptr_, + BackgroundState(), FullAudibleState()); + ExpectAppChangeHmiStateDueToConflictResolving( + media_app_, media_app_ptr_, LimitedState(), BackgroundState()); + ExpectAppChangeHmiStateDueToConflictResolving( + navi_app_, navi_app_ptr_, LimitedState(), BackgroundState()); + ExpectAppChangeHmiStateDueToConflictResolving( + vc_app_, vc_app_ptr_, LimitedState(), BackgroundState()); + state_ctrl_.SetRegularState<false>(media_navi_vc_app_, FullAudibleState()); +} + +TEST_F(StateControllerTest, + SetFullToAudioAppWhile2AudioAppsWithSameTypeInLimitedAndOneInFull) { + using am::HmiState; + using am::HmiStatePtr; + namespace HMILevel = mobile_apis::HMILevel; + namespace AudioStreamingState = mobile_apis::AudioStreamingState; + namespace SystemContext = mobile_apis::SystemContext; + + InsertApplication(media_navi_vc_app_); + InsertApplication(media_app_); + InsertApplication(navi_app_); + InsertApplication(vc_app_); + ExpectSuccesfullSetHmiState(media_navi_vc_app_, media_navi_vc_app_ptr_, + BackgroundState(), FullAudibleState()); + ExpectAppChangeHmiStateDueToConflictResolving( + media_app_, media_app_ptr_, LimitedState(), BackgroundState()); + ExpectAppChangeHmiStateDueToConflictResolving( + navi_app_, navi_app_ptr_, LimitedState(), BackgroundState()); + ExpectAppChangeHmiStateDueToConflictResolving( + vc_app_, vc_app_ptr_, FullAudibleState(), BackgroundState()); + state_ctrl_.SetRegularState<false>(media_navi_vc_app_, FullAudibleState()); +} + +TEST_F(StateControllerTest, ActivateAppSuccessReceivedFromHMI) { + using namespace hmi_apis; + using namespace mobile_apis; + + const uint32_t corr_id = 314; + const uint32_t hmi_app_id = 2718; + typedef std::pair<am::HmiStatePtr, Common_HMILevel::eType> StateLevelPair; + std::vector<StateLevelPair> hmi_states; + hmi_states.push_back( + StateLevelPair(FullAudibleState(), Common_HMILevel::FULL)); + hmi_states.push_back( + StateLevelPair(FullNotAudibleState(), Common_HMILevel::FULL)); + hmi_states.push_back( + StateLevelPair(LimitedState(), Common_HMILevel::LIMITED)); + hmi_states.push_back( + StateLevelPair(BackgroundState(), Common_HMILevel::BACKGROUND)); + hmi_states.push_back(StateLevelPair( + createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE, + SystemContext::SYSCTXT_MAIN), + Common_HMILevel::NONE)); + std::vector<StateLevelPair> initial_hmi_states = hmi_states; + std::vector<StateLevelPair>::iterator it = hmi_states.begin(); + std::vector<StateLevelPair>::iterator it2 = initial_hmi_states.begin(); + for (; it != hmi_states.end(); ++it) { + for (; it2 != initial_hmi_states.end(); ++it2) { + am::HmiStatePtr hmi_state = it->first; + am::HmiStatePtr initial_hmi_state = it->first; + Common_HMILevel::eType hmi_level = it->second; + + EXPECT_CALL(*message_helper_mock_, + SendActivateAppToHMI(media_app_->app_id(), hmi_level, _)) + .WillOnce(Return(corr_id)); + EXPECT_CALL(app_manager_mock_, application_id(corr_id)) + .WillOnce(Return(hmi_app_id)); + EXPECT_CALL(app_manager_mock_, application_by_hmi_app(hmi_app_id)) + .WillOnce(Return(media_app_)); + ExpectSuccesfullSetHmiState(media_app_, media_app_ptr_, initial_hmi_state, + hmi_state); + state_ctrl_.SetRegularState<true>(media_app_, hmi_state); + smart_objects::SmartObject message; + message[am::strings::params][am::hmi_response::code] = + Common_Result::SUCCESS; + message[am::strings::params][am::strings::correlation_id] = corr_id; + am::event_engine::Event event( + hmi_apis::FunctionID::BasicCommunication_ActivateApp); + event.set_smart_object(message); + state_ctrl_.on_event(event); + } + } +} +/* +TEST_F(StateControllerTest, ActivateAppErrorReceivedFromHMI) { + using namespace hmi_apis; + const uint32_t corr_id = 314; + const uint32_t hmi_app_id = 2718; + std::vector<Common_Result::eType> hmi_results; + hmi_results.push_back(Common_Result::ABORTED); + hmi_results.push_back(Common_Result::APPLICATION_NOT_REGISTERED); + hmi_results.push_back(Common_Result::CHAR_LIMIT_EXCEEDED); + hmi_results.push_back(Common_Result::DATA_NOT_AVAILABLE); + hmi_results.push_back(Common_Result::DISALLOWED); + hmi_results.push_back(Common_Result::DUPLICATE_NAME); + hmi_results.push_back(Common_Result::GENERIC_ERROR); + hmi_results.push_back(Common_Result::IGNORED); + hmi_results.push_back(Common_Result::INVALID_DATA); + hmi_results.push_back(Common_Result::INVALID_ENUM); + hmi_results.push_back(Common_Result::INVALID_ID); + hmi_results.push_back(Common_Result::IN_USE); + hmi_results.push_back(Common_Result::NO_APPS_REGISTERED); + hmi_results.push_back(Common_Result::NO_DEVICES_CONNECTED); + hmi_results.push_back(Common_Result::OUT_OF_MEMORY); + hmi_results.push_back(Common_Result::REJECTED); + hmi_results.push_back(Common_Result::RETRY); + hmi_results.push_back(Common_Result::TIMED_OUT); + hmi_results.push_back(Common_Result::TOO_MANY_PENDING_REQUESTS); + hmi_results.push_back(Common_Result::TRUNCATED_DATA); + hmi_results.push_back(Common_Result::UNSUPPORTED_REQUEST); + hmi_results.push_back(Common_Result::UNSUPPORTED_RESOURCE); + hmi_results.push_back(Common_Result::USER_DISALLOWED); + hmi_results.push_back(Common_Result::WARNINGS); + hmi_results.push_back(Common_Result::WRONG_LANGUAGE); + + std::vector<Common_Result::eType>::iterator it = hmi_results.begin(); + for (; it != hmi_results.end(); ++it) { + EXPECT_CALL( + *message_helper_mock_, + SendActivateAppToHMI(simple_app_->app_id(), Common_HMILevel::FULL, _)) + .WillOnce(Return(corr_id)); + EXPECT_CALL(app_manager_mock_, application_id(corr_id)) + .WillOnce(Return(hmi_app_id)); + EXPECT_CALL(app_manager_mock_, application_by_hmi_app(hmi_app_id)) + .WillOnce(Return(simple_app_)); + EXPECT_CALL(*simple_app_ptr_, RegularHmiState()) + .WillOnce(Return(BackgroundState())); + EXPECT_CALL(*simple_app_ptr_, CurrentHmiState()) + .WillOnce(Return(BackgroundState())) + .WillOnce(Return(BackgroundState())); + EXPECT_CALL(*simple_app_ptr_, + SetRegularState(Truly(HmiStatesComparator(BackgroundState())))); + EXPECT_CALL(app_manager_mock_, SendHMIStatusNotification(simple_app_)) + .Times(0); + EXPECT_CALL(app_manager_mock_, + OnHMILevelChanged(simple_app_->app_id(), _, _)).Times(0); + state_ctrl_.SetRegularState<true>(simple_app_, FullNotAudibleState()); + smart_objects::SmartObject message; + message[am::strings::params][am::hmi_response::code] = *it; + message[am::strings::params][am::strings::correlation_id] = corr_id; + am::event_engine::Event event(FunctionID::BasicCommunication_ActivateApp); + event.set_smart_object(message); + state_ctrl_.on_event(event); + } +} +*/ +TEST_F(StateControllerTest, ActivateAppInvalidCorrelationId) { + using namespace hmi_apis; + const uint32_t corr_id = 314; + const uint32_t hmi_app_id = 2718; + EXPECT_CALL(*message_helper_mock_, + SendActivateAppToHMI(simple_app_->app_id(), Common_HMILevel::FULL, + _)).WillOnce(Return(hmi_app_id)); + EXPECT_CALL(app_manager_mock_, application_id(corr_id)) + .WillOnce(Return(hmi_app_id)); + EXPECT_CALL(app_manager_mock_, application_by_hmi_app(hmi_app_id)) + .WillOnce(Return(am::ApplicationSharedPtr())); + EXPECT_CALL(*simple_app_ptr_, SetRegularState(_)).Times(0); + EXPECT_CALL(app_manager_mock_, SendHMIStatusNotification(simple_app_)) + .Times(0); + EXPECT_CALL(app_manager_mock_, OnHMILevelChanged(simple_app_->app_id(), _, _)) + .Times(0); + state_ctrl_.SetRegularState<true>(simple_app_, FullNotAudibleState()); + smart_objects::SmartObject message; + message[am::strings::params][am::hmi_response::code] = Common_Result::SUCCESS; + message[am::strings::params][am::strings::correlation_id] = corr_id; + am::event_engine::Event event(FunctionID::BasicCommunication_ActivateApp); + event.set_smart_object(message); + state_ctrl_.on_event(event); +} +/* +TEST_F(StateControllerTest, ApplyTempStatesForSimpleApp) { + InsertApplication(simple_app_); + CheckStateApplyingForApplication(*simple_app_ptr_, valid_state_ids_); +} + +TEST_F(StateControllerTest, ApplyTempStatesForMediaApp) { + InsertApplication(media_app_); + CheckStateApplyingForApplication(*media_app_ptr_, valid_state_ids_); +} + +TEST_F(StateControllerTest, ApplyTempStatesForNaviApp) { + InsertApplication(navi_app_); + CheckStateApplyingForApplication(*navi_app_ptr_, valid_state_ids_); +} + +TEST_F(StateControllerTest, ApplyTempStatesForVCApp) { + InsertApplication(vc_app_); + CheckStateApplyingForApplication(*vc_app_ptr_, valid_state_ids_); +} + +TEST_F(StateControllerTest, ApplyTempStatesForMediaNaviApp) { + InsertApplication(media_navi_app_); + CheckStateApplyingForApplication(*media_navi_app_ptr_, valid_state_ids_); +} + +TEST_F(StateControllerTest, ApplyTempStatesForMediaVCApp) { + InsertApplication(media_vc_app_); + CheckStateApplyingForApplication(*media_vc_app_ptr_, valid_state_ids_); +} + +TEST_F(StateControllerTest, ApplyTempStatesForNaviVCApp) { + InsertApplication(navi_vc_app_); + CheckStateApplyingForApplication(*navi_vc_app_ptr_, valid_state_ids_); +} + +TEST_F(StateControllerTest, ApplyTempStatesForMediaNaviVCApp) { + InsertApplication(media_navi_vc_app_); + CheckStateApplyingForApplication(*media_navi_vc_app_ptr_, valid_state_ids_); +} +*/ +} // namespace state_controller_test diff --git a/src/components/config_profile/CMakeLists.txt b/src/components/config_profile/CMakeLists.txt index 7eb098a306..fe6f373b3a 100644 --- a/src/components/config_profile/CMakeLists.txt +++ b/src/components/config_profile/CMakeLists.txt @@ -42,3 +42,7 @@ set (SOURCES add_library("ConfigProfile" ${SOURCES}) target_link_libraries("ConfigProfile" Utils) + +if(BUILD_TESTS) + add_subdirectory(test) +endif()
\ No newline at end of file diff --git a/src/components/config_profile/test/CMakeLists.txt b/src/components/config_profile/test/CMakeLists.txt new file mode 100644 index 0000000000..e474d3fc20 --- /dev/null +++ b/src/components/config_profile/test/CMakeLists.txt @@ -0,0 +1,59 @@ +# Copyright (c) 2015, 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. + +if(BUILD_TESTS) + +include_directories ( + ${CMAKE_SOURCE_DIR}/src/3rd_party-static/gmock-1.7.0/include + ${CMAKE_SOURCE_DIR}/src/3rd_party-static/gmock-1.7.0/gtest/include + ${COMPONENTS_DIR}/include/utils + ${COMPONENTS_DIR}/config_profile/include + ) + + +set(testSources + profile_test.cc + ini_file_test.cc +) + +set(testLibraries + gmock + ConfigProfile +) + +file(COPY smartDeviceLink.ini DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) +file(COPY smartDeviceLink_test.ini DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) +file(COPY smartDeviceLink_invalid_pairs.ini DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) +file(COPY smartDeviceLink_invalid_string.ini DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) +file(COPY smartDeviceLink_invalid_int.ini DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) +file(COPY smartDeviceLink_invalid_boolean.ini DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) +create_test("config_profile_test" "${testSources}" "${testLibraries}") + +endif() diff --git a/src/components/config_profile/test/ini_file_test.cc b/src/components/config_profile/test/ini_file_test.cc new file mode 100644 index 0000000000..10d500df74 --- /dev/null +++ b/src/components/config_profile/test/ini_file_test.cc @@ -0,0 +1,335 @@ +/* + * Copyright (c) 2015, 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 + * FERRUPTION) 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. + */ + +#include "gtest/gtest.h" +#include "config_profile/ini_file.h" +#include "utils/file_system.h" + +namespace test { +namespace components { +namespace profile { + +using namespace ::profile; + +TEST(IniFileTest, DISABLED_WriteItemReadItem) { + // Write line in chapter + const char * fname = "./test_ini_file.ini"; + const char *chapter = "Chapter"; + const char * item = "Test_item"; + const char * value = "test_value"; + const bool write_result = ini_write_value(fname, chapter, item, value, + INI_FLAG_ITEM_UP_CREA); + EXPECT_TRUE(write_result); + + // Read value from file + char search_value[INI_LINE_LEN] = ""; + const bool read_result = ini_read_value(fname, chapter, item, search_value); + + EXPECT_TRUE(read_result); + EXPECT_EQ(*search_value, *value); + EXPECT_TRUE(file_system::DeleteFile("./test_ini_file.ini")); +} + +TEST(IniFileTest, DISABLED_WriteItemWithoutValueReadItem) { + // Write line in chapter + const char * fname = "./test_ini_file.ini"; + const char *chapter = "Chapter"; + const char * test_item = "Test_item"; + const char * value = ""; + const bool write_result = ini_write_value(fname, chapter, test_item, value, + INI_FLAG_ITEM_UP_CREA); + EXPECT_TRUE(write_result); + + // Read value from file + char search_value[INI_LINE_LEN] = ""; + const bool read_result = ini_read_value(fname, chapter, test_item, search_value); + + EXPECT_TRUE(read_result); + EXPECT_EQ(*search_value, *value); + + EXPECT_TRUE(file_system::DeleteFile("./test_ini_file.ini")); +} + +TEST(IniFileTest, DISABLED_WriteSameItemInDifferentChapters) { + // Write line in chapter + const char * fname = "./test_ini_file.ini"; + const char *chapter1 = "Chapter1"; + const char * test_item = "Test_item"; + const char * value = "test_value"; + const bool write_result = ini_write_value(fname, chapter1, test_item, value, + INI_FLAG_ITEM_UP_CREA); + EXPECT_TRUE(write_result); + + char search_value[INI_LINE_LEN] = ""; + const bool read_result = ini_read_value(fname, chapter1, test_item, search_value); + + EXPECT_TRUE(read_result); + EXPECT_EQ(*search_value, *value); + + // Create new chapter and write the same value + const char *chapter2 = "Chapter2"; + + const bool write_result2 = ini_write_value(fname, chapter2, test_item, value, + INI_FLAG_ITEM_UP_CREA); + + EXPECT_TRUE(write_result2); + + char value2[INI_LINE_LEN] = "test_value"; + const bool read_result2 = ini_read_value(fname, chapter2, test_item, value2); + + EXPECT_TRUE(read_result2); + EXPECT_EQ(*value2, *value); + + EXPECT_TRUE(file_system::DeleteFile("./test_ini_file.ini")); +} + +TEST(IniFileTest, DISABLED_RewriteItem) { + // Write line in chapter + const char * fname = "./test_ini_file.ini"; + const char *chapter = "Chapter"; + const char * item = "Test_item"; + const char * value = "test_value"; + bool write_result = ini_write_value(fname, chapter, item, value, + INI_FLAG_ITEM_UP_CREA); + + EXPECT_TRUE(write_result); + + char search_value[INI_LINE_LEN] = ""; + bool read_result = ini_read_value(fname, chapter, item, search_value); + + EXPECT_TRUE(read_result); + EXPECT_EQ(*search_value, *value); + + // Write item again + const char * newvalue = "new_test_value"; + write_result = ini_write_value(fname, chapter, item, newvalue, + INI_FLAG_ITEM_UP_CREA); + + EXPECT_TRUE(write_result); + + char new_search_value[INI_LINE_LEN] = ""; + read_result = ini_read_value(fname, chapter, item, new_search_value); + + EXPECT_TRUE(read_result); + EXPECT_EQ(*new_search_value, *newvalue); + EXPECT_TRUE(file_system::DeleteFile("./test_ini_file.ini")); +} + +TEST(IniFileTest, DISABLED_WriteTwoItemsInOneChapter) { + // Write line in chapter + const char * fname = "./test_ini_file.ini"; + const char *chapter = "Chapter"; + const char * item = "Test_item"; + const char * value1 = "test_value"; + + bool write_result = ini_write_value(fname, chapter, item, value1, + INI_FLAG_ITEM_UP_CREA); + EXPECT_TRUE(write_result); + + // Write another line in the same chapter + const char * item2 = "Test_item2"; + const char * value2 = "test_value2"; + + write_result = ini_write_value(fname, chapter, item2, value2, + INI_FLAG_ITEM_UP_CREA); + EXPECT_TRUE(write_result); + + // Search both values + char search_value[INI_LINE_LEN] = ""; + bool read_result = ini_read_value(fname, chapter, item, search_value); + + EXPECT_TRUE(read_result); + EXPECT_EQ(*search_value, *value1); + + char search_value2[INI_LINE_LEN] = ""; + read_result = ini_read_value(fname, chapter, item2, search_value2); + + EXPECT_TRUE(read_result); + EXPECT_EQ(*search_value2, *value2); + + EXPECT_TRUE(file_system::DeleteFile("./test_ini_file.ini")); +} + +TEST(IniFileTest, WriteEmptyItemWithValueReadItem) { + const char * fname = "./test_ini_file.ini"; + const char *chapter = "Chapter"; + const char * test_item = ""; + const char * value = "test_value"; + bool result = ini_write_value(fname, chapter, test_item, value, + INI_FLAG_ITEM_UP_CREA); + EXPECT_FALSE(result); +} + +TEST(IniFileTest, WriteEmptyItemWithEmptyValue_ExpectFalse) { + // Write empty line in chapter + const char * fname = "./test_ini_file.ini"; + const char *chapter = "Chapter"; + const char * test_item = ""; + const char * value = ""; + bool result = ini_write_value(fname, chapter, test_item, value, + INI_FLAG_ITEM_UP_CREA); + EXPECT_FALSE(result); +} + +TEST(IniFileTest, WriteItemInEmptyChapter_ExpectFalse) { + // Write line in empty chapter + const char * fname = "./test_ini_file.ini"; + const char *chapter = ""; + const char * test_item = "Test_item"; + const char * value = "test_value"; + bool result = ini_write_value(fname, chapter, test_item, value, + INI_FLAG_ITEM_UP_CREA); + EXPECT_FALSE(result); +} + +TEST(IniFileTest,ParseEmptyLine) { + char line[INI_LINE_LEN] = ""; + char val[INI_LINE_LEN] = ""; + char tag[INI_LINE_LEN] = "HMI"; + + Ini_search_id result; + result = ini_parse_line(line, tag, val); + EXPECT_EQ(INI_NOTHING, result); +} + +TEST(IniFileTest,ParseChapter) { + char line[INI_LINE_LEN] = "[HMI]"; + char val[INI_LINE_LEN] = ""; + char tag[INI_LINE_LEN] = "HMI"; + + Ini_search_id result; + result = ini_parse_line(line, tag, val); + EXPECT_EQ(INI_RIGHT_CHAPTER, result); +} + +TEST(IniFileTest,ParseChapterTagEmpty) { + char line[INI_LINE_LEN] = "[HMI]"; + char val[INI_LINE_LEN] = ""; + char tag[INI_LINE_LEN] = ""; + + Ini_search_id result; + result = ini_parse_line(line, tag, val); + EXPECT_EQ(INI_WRONG_CHAPTER, result); +} + +TEST(IniFileTest,ParseChapterWithUppercaseTag) { + char line[INI_LINE_LEN] = "[Security Manager]"; + char val[INI_LINE_LEN] = ""; + char tag[INI_LINE_LEN] = "SECURITY MANAGER"; + + Ini_search_id result; + result = ini_parse_line(line, tag, val); + EXPECT_EQ(INI_RIGHT_CHAPTER, result); +} + +TEST(IniFileTest,ParseChapterWithLowcaseTag) { + char line[INI_LINE_LEN] = "[Security Manager]"; + char val[INI_LINE_LEN] = ""; + char tag[INI_LINE_LEN] = "Security Manager"; + + Ini_search_id result; + result = ini_parse_line(line, tag, val); + EXPECT_EQ(INI_WRONG_CHAPTER, result); +} + +TEST(IniFileTest,ParseWithWrongChapter) { + char line[INI_LINE_LEN] = "[HMI]"; + char val[INI_LINE_LEN] = ""; + char tag[INI_LINE_LEN] = "MAIN"; + + Ini_search_id result; + result = ini_parse_line(line, tag, val); + EXPECT_EQ(INI_WRONG_CHAPTER, result); +} + +TEST(IniFileTest,ParseLineWithItem) { + char line[INI_LINE_LEN] = "LaunchHMI = true"; + char val[INI_LINE_LEN] = ""; + char tag[INI_LINE_LEN] = "LAUNCHHMI"; + + Ini_search_id result; + result = ini_parse_line(line, tag, val); + EXPECT_EQ(INI_RIGHT_ITEM, result); + + char check_val[INI_LINE_LEN] = "true"; + EXPECT_EQ(*check_val, *val); +} + +TEST(IniFileTest,ParseLineWithoutItem) { + char line[INI_LINE_LEN] = "LaunchHMI = "; + char val[INI_LINE_LEN] = ""; + char tag[INI_LINE_LEN] = "LAUNCHHMI"; + + Ini_search_id result; + result = ini_parse_line(line, tag, val); + EXPECT_EQ(INI_RIGHT_ITEM, result); + + char check_val[INI_LINE_LEN] = ""; + EXPECT_EQ(*check_val, *val); +} + +TEST(IniFileTest,ParseLineWithEmptytag) { + char line[INI_LINE_LEN] = "LaunchHMI = true"; + char val[INI_LINE_LEN] = ""; + char tag[INI_LINE_LEN] = ""; + + Ini_search_id result; + result = ini_parse_line(line, tag, val); + EXPECT_EQ(INI_WRONG_ITEM, result); +} + +TEST(IniFileTest,ParseLineWithLowcaseTag) { + char line[INI_LINE_LEN] = "LaunchHMI = true"; + char val[INI_LINE_LEN] = ""; + char tag[INI_LINE_LEN] = "LaunchHmi"; + + Ini_search_id result; + result = ini_parse_line(line, tag, val); + EXPECT_EQ(INI_WRONG_ITEM, result); +} + +TEST(IniFileTest,ParseLineWithComment) { + char line[INI_LINE_LEN] = "; [HMI]"; + char val[INI_LINE_LEN] = ""; + char tag[INI_LINE_LEN] = "HMI"; + + Ini_search_id result; + result = ini_parse_line(line, tag, val); + EXPECT_EQ(INI_REMARK, result); + + char check_val[INI_LINE_LEN] = ";"; + EXPECT_EQ(*check_val, *val); +} + +} // namespace profile +} // namespace components +} // namespace test diff --git a/src/components/config_profile/test/profile_test.cc b/src/components/config_profile/test/profile_test.cc new file mode 100644 index 0000000000..97f2a312af --- /dev/null +++ b/src/components/config_profile/test/profile_test.cc @@ -0,0 +1,789 @@ +/* + * Copyright (c) 2015, 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. + */ + +#include "gtest/gtest.h" +#include "config_profile/profile.h" +#include <algorithm> +#include "utils/file_system.h" +#include "utils/threads/thread.h" + +namespace test { +namespace components { +namespace profile { + +using namespace ::profile; + +class ProfileTest : public ::testing::Test { + protected: + virtual void SetUp() { + profile::Profile::destroy(); + } + virtual void TearDown() { + profile::Profile::destroy(); + } + +}; + +TEST_F(ProfileTest, SingletonProfile) { + Profile::instance(); + EXPECT_TRUE(Profile::exists()); + profile::Profile::destroy(); + EXPECT_FALSE(Profile::exists()); +} + +TEST_F(ProfileTest, UpdateConfigWithDefaultFile) { + // Default value + uint32_t thread_min_stack_size = threads::Thread::kMinStackSize; + EXPECT_EQ(thread_min_stack_size, + Profile::instance()->thread_min_stack_size()); + EXPECT_FALSE(profile::Profile::instance()->enable_policy()); + std::string vr_help_title_ = ""; + EXPECT_EQ(vr_help_title_, Profile::instance()->vr_help_title()); + EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name()); + + profile::Profile::instance()->UpdateValues(); + // Value was updated + thread_min_stack_size = 20480; + EXPECT_EQ(thread_min_stack_size, + Profile::instance()->thread_min_stack_size()); + EXPECT_TRUE(profile::Profile::instance()->enable_policy()); + vr_help_title_ = "Available Vr Commands List"; + EXPECT_EQ(vr_help_title_, Profile::instance()->vr_help_title()); +} + +TEST_F(ProfileTest, SetConfigFileWithoutCallUpdate) { + // Default value + uint32_t thread_min_stack_size = threads::Thread::kMinStackSize; + EXPECT_EQ(thread_min_stack_size, + Profile::instance()->thread_min_stack_size()); + EXPECT_FALSE(profile::Profile::instance()->enable_policy()); + std::string vr_help_title_ = ""; + EXPECT_EQ(vr_help_title_, Profile::instance()->vr_help_title()); + EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name()); + + Profile::instance()->config_file_name("smartDeviceLink.ini"); + EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name()); + + // Value was updated + thread_min_stack_size = 20480; + EXPECT_EQ(thread_min_stack_size, + Profile::instance()->thread_min_stack_size()); + EXPECT_TRUE(profile::Profile::instance()->enable_policy()); + vr_help_title_ = "Available Vr Commands List"; + EXPECT_EQ(vr_help_title_, Profile::instance()->vr_help_title()); +} + +TEST_F(ProfileTest, SetConfigFileWithUpdate) { + // Default value + uint32_t thread_min_stack_size = threads::Thread::kMinStackSize; + EXPECT_EQ(thread_min_stack_size, + Profile::instance()->thread_min_stack_size()); + Profile::instance()->config_file_name("smartDeviceLink.ini"); + EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name()); + + // Value was updated + thread_min_stack_size = 20480; + EXPECT_EQ(thread_min_stack_size, + Profile::instance()->thread_min_stack_size()); + + // Update config file again + profile::Profile::instance()->UpdateValues(); + + // Value should be the same + EXPECT_EQ(thread_min_stack_size, + Profile::instance()->thread_min_stack_size()); +} + +TEST_F(ProfileTest, UpdateManyTimesDefaultFile) { + //using for check logger's work - core dump when this test was started and log4cxx exists in test derictory + Profile::instance()->config_file_name("smartDeviceLink.ini"); + EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name()); + // Update config many times + for (int i = 0; i < 10; i++) { + profile::Profile::instance()->UpdateValues(); + } +} + +TEST_F(ProfileTest, UpdateIntValues) { + // Default value + EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name()); + uint32_t thread_min_stack_size = threads::Thread::kMinStackSize; + EXPECT_EQ(thread_min_stack_size, + Profile::instance()->thread_min_stack_size()); + + // Set config file with default name + Profile::instance()->config_file_name("smartDeviceLink.ini"); + EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name()); + + // Value changes + thread_min_stack_size = 20480; + EXPECT_EQ(thread_min_stack_size, + Profile::instance()->thread_min_stack_size()); + + // Update config file again + profile::Profile::instance()->UpdateValues(); + // Values are same + EXPECT_EQ(thread_min_stack_size, + Profile::instance()->thread_min_stack_size()); + + // Set new config file + Profile::instance()->config_file_name("smartDeviceLink_test.ini"); + EXPECT_EQ("smartDeviceLink_test.ini", + Profile::instance()->config_file_name()); + + // Value changes + thread_min_stack_size = 21000; + EXPECT_EQ(thread_min_stack_size, + Profile::instance()->thread_min_stack_size()); + + // Update config file again + profile::Profile::instance()->UpdateValues(); + EXPECT_EQ("smartDeviceLink_test.ini", + Profile::instance()->config_file_name()); + + // Value should be the same + EXPECT_EQ(thread_min_stack_size, + Profile::instance()->thread_min_stack_size()); + + // Set config file with default name again + Profile::instance()->config_file_name("smartDeviceLink.ini"); + EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name()); + + // Value should be changed + thread_min_stack_size = 20480; + EXPECT_EQ(thread_min_stack_size, + Profile::instance()->thread_min_stack_size()); +} + +TEST_F(ProfileTest, UpdateBoolValues) { + // Default values + EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name()); + EXPECT_TRUE(profile::Profile::instance()->launch_hmi()); + EXPECT_FALSE(profile::Profile::instance()->enable_policy()); + + // Set config file + Profile::instance()->config_file_name("smartDeviceLink.ini"); + // Check values + EXPECT_TRUE(profile::Profile::instance()->launch_hmi()); + EXPECT_TRUE(profile::Profile::instance()->enable_policy()); + EXPECT_FALSE(profile::Profile::instance()->is_redecoding_enabled()); + + // Update config file again + profile::Profile::instance()->UpdateValues(); + // Values are same + EXPECT_TRUE(profile::Profile::instance()->launch_hmi()); + EXPECT_TRUE(profile::Profile::instance()->enable_policy()); + EXPECT_FALSE(profile::Profile::instance()->is_redecoding_enabled()); + + // Change config file + Profile::instance()->config_file_name("smartDeviceLink_test.ini"); + EXPECT_EQ("smartDeviceLink_test.ini", + Profile::instance()->config_file_name()); + + // Parameters after updating + EXPECT_FALSE(profile::Profile::instance()->launch_hmi()); + EXPECT_FALSE(profile::Profile::instance()->enable_policy()); + EXPECT_TRUE(profile::Profile::instance()->is_redecoding_enabled()); + + // Update config file + profile::Profile::instance()->UpdateValues(); + + // Parameters are same + EXPECT_FALSE(profile::Profile::instance()->launch_hmi()); + EXPECT_FALSE(profile::Profile::instance()->enable_policy()); + EXPECT_TRUE(profile::Profile::instance()->is_redecoding_enabled()); +} + +TEST_F(ProfileTest, UpdateStringValue) { + // Default values + std::string config_folder = ""; + std::string tts_delimiter_ = ""; + std::string vr_help_title_ = ""; + std::string server_address = "127.0.0.1"; + std::string app_resourse_folder = ""; + EXPECT_EQ(config_folder, Profile::instance()->app_resourse_folder()); + EXPECT_EQ(server_address, profile::Profile::instance()->server_address()); + + Profile::instance()->config_file_name("smartDeviceLink.ini"); + EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name()); + + // Check values + config_folder = file_system::CurrentWorkingDirectory(); + EXPECT_EQ(config_folder, Profile::instance()->app_resourse_folder()); + tts_delimiter_ = ","; + EXPECT_EQ(tts_delimiter_, Profile::instance()->tts_delimiter()); + vr_help_title_ = "Available Vr Commands List"; + EXPECT_EQ(vr_help_title_, Profile::instance()->vr_help_title()); + + EXPECT_EQ(server_address, profile::Profile::instance()->server_address()); + app_resourse_folder = file_system::CurrentWorkingDirectory(); + EXPECT_EQ(app_resourse_folder, Profile::instance()->app_resourse_folder()); + + // Update config file + profile::Profile::instance()->UpdateValues(); + + // Values are the same + EXPECT_EQ(config_folder, Profile::instance()->app_resourse_folder()); + EXPECT_EQ(tts_delimiter_, Profile::instance()->tts_delimiter()); + EXPECT_EQ(vr_help_title_, Profile::instance()->vr_help_title()); + EXPECT_EQ(server_address, profile::Profile::instance()->server_address()); + EXPECT_EQ(app_resourse_folder, Profile::instance()->app_resourse_folder()); +} + +TEST_F(ProfileTest, UpdateInt_ValueAppearsInFileTwice) { + // Default values + uint32_t server_port = 8087; + EXPECT_EQ(server_port, Profile::instance()->server_port()); + // Change config file + Profile::instance()->config_file_name("smartDeviceLink_test.ini"); + EXPECT_EQ("smartDeviceLink_test.ini", + Profile::instance()->config_file_name()); + // Update config file + // First server_port = 8088 + server_port = 8088; + EXPECT_EQ(server_port, Profile::instance()->server_port()); +} + +TEST_F(ProfileTest, UpdateBool_ValueAppearsInFileTwice) { + // Default values + EXPECT_FALSE(Profile::instance()->is_mixing_audio_supported()); + // Change config file + Profile::instance()->config_file_name("smartDeviceLink_test.ini"); + EXPECT_EQ("smartDeviceLink_test.ini", + Profile::instance()->config_file_name()); + // Update config file + // First value is false + EXPECT_FALSE(profile::Profile::instance()->is_mixing_audio_supported()); +} + +TEST_F(ProfileTest, UpdateVectorOfString_ValueAppearsInFileTwice) { + // Default values + std::vector < std::string > time_out_promt; + EXPECT_EQ(time_out_promt, Profile::instance()->time_out_promt()); + // Change config file + Profile::instance()->config_file_name("smartDeviceLink_test.ini"); + EXPECT_EQ("smartDeviceLink_test.ini", + Profile::instance()->config_file_name()); + // Update config file + time_out_promt.push_back("Please say a command,"); + EXPECT_EQ(time_out_promt, Profile::instance()->time_out_promt()); +} + +TEST_F(ProfileTest, UpdateString_ValueAppearsInFileTwice) { + // Default values + std::string recording_file_name = "record.wav"; + EXPECT_EQ(recording_file_name, Profile::instance()->recording_file_name()); + // Change config file + Profile::instance()->config_file_name("smartDeviceLink_test.ini"); + EXPECT_EQ("smartDeviceLink_test.ini", + Profile::instance()->config_file_name()); + // Update config file + recording_file_name = "video.wav"; + EXPECT_EQ(recording_file_name, Profile::instance()->recording_file_name()); +} + +TEST_F(ProfileTest, UpdatePairsValue) { + // Default values + std::pair < uint32_t, int32_t > value; + value.first = 0; + value.second = 0; + EXPECT_EQ(value, Profile::instance()->get_vehicle_data_frequency()); + + Profile::instance()->config_file_name("smartDeviceLink.ini"); + EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name()); + + value.first = 5; + value.second = 1; + EXPECT_EQ(value, Profile::instance()->get_vehicle_data_frequency()); + + // Update config file + profile::Profile::instance()->UpdateValues(); + EXPECT_EQ(value, Profile::instance()->get_vehicle_data_frequency()); +} + +// Section with negative tests + +TEST_F(ProfileTest, PairsValueEmpty) { + // Default values + std::pair < uint32_t, int32_t > value; + value.first = 0; + value.second = 0; + EXPECT_EQ(value, Profile::instance()->read_did_frequency()); + + Profile::instance()->config_file_name("smartDeviceLink_invalid_pairs.ini"); + EXPECT_EQ("smartDeviceLink_invalid_pairs.ini", + Profile::instance()->config_file_name()); + + // Default values + value.first = 5; + value.second = 1; + EXPECT_EQ(value, Profile::instance()->read_did_frequency()); + + // Update config file + profile::Profile::instance()->UpdateValues(); + // Values are same + EXPECT_EQ(value, Profile::instance()->read_did_frequency()); +} + +TEST_F(ProfileTest, CharValueInPairInsteadOfInt) { + std::pair < uint32_t, int32_t > value; + value.first = 0; + value.second = 0; + EXPECT_EQ(value, Profile::instance()->get_vehicle_data_frequency()); + + Profile::instance()->config_file_name("smartDeviceLink_invalid_string.ini"); + EXPECT_EQ("smartDeviceLink_invalid_string.ini", + Profile::instance()->config_file_name()); + + EXPECT_EQ(value, Profile::instance()->get_vehicle_data_frequency()); + + // Update config file + profile::Profile::instance()->UpdateValues(); + // Values are same + EXPECT_EQ(value, Profile::instance()->get_vehicle_data_frequency()); +} + +TEST_F(ProfileTest, EmptyValuesInPair) { + Profile::instance()->config_file_name("smartDeviceLink_invalid_pairs.ini"); + EXPECT_EQ("smartDeviceLink_invalid_pairs.ini", + Profile::instance()->config_file_name()); + + std::pair < uint32_t, int32_t > value; + value.first = 0; + value.second = 0; + EXPECT_EQ(value, Profile::instance()->get_vehicle_data_frequency()); + + // Update config file + profile::Profile::instance()->UpdateValues(); + // Values are same + EXPECT_EQ(value, Profile::instance()->get_vehicle_data_frequency()); +} + +TEST_F(ProfileTest, DISABLED_IntInsteadOfPair) { + // Default values + std::pair < uint32_t, int32_t > value; + value.first = 0; + value.second = 0; + EXPECT_EQ(value, Profile::instance()->start_stream_retry_amount()); + + Profile::instance()->config_file_name("smartDeviceLink_invalid_pairs.ini"); + EXPECT_EQ("smartDeviceLink_invalid_pairs.ini", + Profile::instance()->config_file_name()); + // Ini file includes only one element + value.first = 9; + value.second = 1000; + EXPECT_EQ(value, Profile::instance()->start_stream_retry_amount()); + + // Update config file + profile::Profile::instance()->UpdateValues(); + // Values are same + EXPECT_EQ(value, Profile::instance()->start_stream_retry_amount()); +} + +TEST_F(ProfileTest, WrongIntValue) { + // Default value + uint32_t heart_beat_timeout = 0u; + EXPECT_EQ(heart_beat_timeout, Profile::instance()->heart_beat_timeout()); + + // Change config file + Profile::instance()->config_file_name("smartDeviceLink_invalid_int.ini"); + EXPECT_EQ("smartDeviceLink_invalid_int.ini", + Profile::instance()->config_file_name()); + + // Value in file includes letters. Check that value is default + heart_beat_timeout = 0; + EXPECT_EQ(heart_beat_timeout, Profile::instance()->heart_beat_timeout()); + + // Update config file + profile::Profile::instance()->UpdateValues(); + EXPECT_EQ(heart_beat_timeout, Profile::instance()->heart_beat_timeout()); +} + +TEST_F(ProfileTest, DISABLED_WrongMaxIntValue) { + // Default value + uint32_t maxvalue = 2000000000; + EXPECT_EQ(maxvalue, Profile::instance()->max_cmd_id()); + + // Change config file + Profile::instance()->config_file_name("smartDeviceLink_invalid_int.ini"); + EXPECT_EQ("smartDeviceLink_invalid_int.ini", + Profile::instance()->config_file_name()); + + // Value in file is more than could be saved. + // Check that value is default + EXPECT_EQ(maxvalue, Profile::instance()->max_cmd_id()); + + // Update config file + profile::Profile::instance()->UpdateValues(); + EXPECT_EQ(maxvalue, Profile::instance()->max_cmd_id()); +} + +TEST_F(ProfileTest, DISABLED_WrongMinIntValue) { + // Default value + uint32_t minvalue = threads::Thread::kMinStackSize; + EXPECT_EQ(minvalue, Profile::instance()->thread_min_stack_size()); + + uint16_t server_port = 8087; + EXPECT_EQ(server_port, Profile::instance()->server_port()); + + // Change config file + Profile::instance()->config_file_name("smartDeviceLink_invalid_int.ini"); + EXPECT_EQ("smartDeviceLink_invalid_int.ini", + Profile::instance()->config_file_name()); + + //File include 0, value should be lefted as default + EXPECT_EQ(minvalue, Profile::instance()->thread_min_stack_size()); + //File include -1, value should be lefted as default + EXPECT_EQ(server_port, Profile::instance()->server_port()); + + // Update config file + profile::Profile::instance()->UpdateValues(); + + // Default value should be lefted + EXPECT_EQ(minvalue, Profile::instance()->thread_min_stack_size()); + EXPECT_EQ(server_port, Profile::instance()->server_port()); +} + +TEST_F(ProfileTest, DISABLED_CheckCorrectValueWhenOtherValueInvalid) { + // Default value + uint32_t maxvalue = 2000000000; + EXPECT_EQ(maxvalue, Profile::instance()->max_cmd_id()); + + uint32_t thread_min_stack_size = threads::Thread::kMinStackSize; + EXPECT_EQ(thread_min_stack_size, + Profile::instance()->thread_min_stack_size()); + + // Change config file + Profile::instance()->config_file_name("smartDeviceLink_test.ini"); + EXPECT_EQ("smartDeviceLink_test.ini", + Profile::instance()->config_file_name()); + + // Check that value is default + maxvalue = 2000000000; + EXPECT_EQ(maxvalue, Profile::instance()->max_cmd_id()); + + // Other value is correct + thread_min_stack_size = 21000; + EXPECT_EQ(thread_min_stack_size, + Profile::instance()->thread_min_stack_size()); + + // Update config file + profile::Profile::instance()->UpdateValues(); + + // In file the number is bigger than can be, default value should be lefted + EXPECT_EQ(maxvalue, Profile::instance()->max_cmd_id()); + EXPECT_EQ(thread_min_stack_size, + Profile::instance()->thread_min_stack_size()); +} + +TEST_F(ProfileTest, PairsValueInsteadOfInt) { + // Set new config file + Profile::instance()->config_file_name("smartDeviceLink_invalid_int.ini"); + EXPECT_EQ("smartDeviceLink_invalid_int.ini", + Profile::instance()->config_file_name()); + // Get first number + uint32_t list_files_in_none = 5; + EXPECT_EQ(list_files_in_none, Profile::instance()->list_files_in_none()); + + // Update config file + profile::Profile::instance()->UpdateValues(); + // Values are same + EXPECT_EQ(list_files_in_none, Profile::instance()->list_files_in_none()); +} + +TEST_F(ProfileTest, DISABLED_StringValueIncludeSlashesAndRussianLetters) { + // Default values + std::string config_folder = ""; + EXPECT_EQ(config_folder, Profile::instance()->app_resourse_folder()); + std::string tts_delimiter_ = ""; + std::string app_resourse_folder = ""; + std::string app_storage_folder = ""; + + Profile::instance()->config_file_name("smartDeviceLink_invalid_string.ini"); + EXPECT_EQ("smartDeviceLink_invalid_string.ini", + Profile::instance()->config_file_name()); + + // Check values + config_folder = "///"; + EXPECT_EQ(config_folder, Profile::instance()->app_config_folder()); + tts_delimiter_ = "coma and point"; + EXPECT_EQ(tts_delimiter_, Profile::instance()->tts_delimiter()); + std::string server_address = "127.0.0.1 + слово"; + EXPECT_EQ(server_address, profile::Profile::instance()->server_address()); + app_resourse_folder = "new folder/"; + EXPECT_EQ(app_resourse_folder, Profile::instance()->app_resourse_folder()); + app_storage_folder = "\" \""; + EXPECT_EQ(app_storage_folder, Profile::instance()->app_storage_folder()); + + // Update config file + profile::Profile::instance()->UpdateValues(); + + // Values are the same + EXPECT_EQ(config_folder, Profile::instance()->app_config_folder()); + EXPECT_EQ(tts_delimiter_, Profile::instance()->tts_delimiter()); + EXPECT_EQ(server_address, profile::Profile::instance()->server_address()); + EXPECT_EQ(app_resourse_folder, Profile::instance()->app_resourse_folder()); +} + +TEST_F(ProfileTest, StringUpperBoundValue) { + // Default values + std::string vr_help_title = ""; + std::string recording_file_name = "record.wav"; + EXPECT_EQ(vr_help_title, Profile::instance()->vr_help_title()); + EXPECT_EQ(recording_file_name, Profile::instance()->recording_file_name()); + + Profile::instance()->config_file_name("smartDeviceLink_invalid_string.ini"); + EXPECT_EQ("smartDeviceLink_invalid_string.ini", + Profile::instance()->config_file_name()); + + // Total count of elements in ini file's string will be less 512 + vr_help_title = + "0/0/0/1/2345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890abc!def@ghi"; + EXPECT_EQ(vr_help_title, Profile::instance()->vr_help_title()); + EXPECT_NE(vr_help_title, Profile::instance()->recording_file_name()); + recording_file_name = + "0/0/0/1/2345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890abc"; + EXPECT_EQ(recording_file_name, Profile::instance()->recording_file_name()); + // Update config file + profile::Profile::instance()->UpdateValues(); + // Values are the same + EXPECT_EQ(vr_help_title, Profile::instance()->vr_help_title()); + EXPECT_EQ(recording_file_name, Profile::instance()->recording_file_name()); +} + +TEST_F(ProfileTest, CapitalLetterInBoolValue) { + // Default values + EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name()); + EXPECT_TRUE(profile::Profile::instance()->launch_hmi()); + EXPECT_FALSE(profile::Profile::instance()->enable_policy()); + + // Set config file + Profile::instance()->config_file_name("smartDeviceLink.ini"); + // Check values + EXPECT_TRUE(profile::Profile::instance()->launch_hmi()); + EXPECT_TRUE(profile::Profile::instance()->enable_policy()); + EXPECT_FALSE(profile::Profile::instance()->is_redecoding_enabled()); + + // Change config file + Profile::instance()->config_file_name("smartDeviceLink_invalid_boolean.ini"); + EXPECT_EQ("smartDeviceLink_invalid_boolean.ini", + Profile::instance()->config_file_name()); + + // Parameters after updating + // Parameter launch_hmi = True + EXPECT_FALSE(profile::Profile::instance()->launch_hmi()); + // EnablePolicy = TRUE + EXPECT_FALSE(profile::Profile::instance()->enable_policy()); + // EnableRedecoding = FALSE + EXPECT_FALSE(profile::Profile::instance()->is_redecoding_enabled()); +} + +TEST_F(ProfileTest, CheckReadStringValue) { + // Set new config file + Profile::instance()->config_file_name("smartDeviceLink_test.ini"); + EXPECT_EQ("smartDeviceLink_test.ini", + Profile::instance()->config_file_name()); + + std::string app_resourse_folder_; + profile::Profile::instance()->ReadStringValue( + &app_resourse_folder_, file_system::CurrentWorkingDirectory().c_str(), + "MAIN", "AppResourceFolder"); + // Get default value + EXPECT_EQ(app_resourse_folder_, file_system::CurrentWorkingDirectory()); + + // Get value from file + std::string server_address; + profile::Profile::instance()->ReadStringValue(&server_address, "", "HMI", + "ServerAddress"); + EXPECT_EQ("127.0.0.1", server_address); +} + +TEST_F(ProfileTest, DISABLED_CheckReadBoolValue) { + // Set new config file + Profile::instance()->config_file_name("smartDeviceLink_test.ini"); + EXPECT_EQ("smartDeviceLink_test.ini", + Profile::instance()->config_file_name()); + + bool enable_policy; + profile::Profile::instance()->ReadBoolValue(&enable_policy, false, "Policy", + "EnablePolicy"); + EXPECT_FALSE(enable_policy); + + // Change config back + profile::Profile::destroy(); + EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name()); + + //get default value + bool launch_hmi; + profile::Profile::instance()->ReadBoolValue(&launch_hmi, true, "HMI", + "LaunchHMI"); + EXPECT_TRUE(launch_hmi); +} + +TEST_F(ProfileTest, CheckReadIntValue) { + // Set new config file + Profile::instance()->config_file_name("smartDeviceLink_test.ini"); + EXPECT_EQ("smartDeviceLink_test.ini", + Profile::instance()->config_file_name()); + + int server_port = 0; + profile::Profile::instance()->ReadIntValue(&server_port, 0, "HMI", + "ServerPort"); + + EXPECT_EQ(8088, server_port); +} + +//TEST_F(ProfileTest, CheckIntContainer) { +// // Set new config file +// Profile::instance()->config_file_name("smartDeviceLink_test.ini"); +// EXPECT_EQ("smartDeviceLink_test.ini", +// Profile::instance()->config_file_name()); + +// bool isread = false; +// std::vector<int> diagmodes_list = +// profile::Profile::instance()->ReadIntContainer("MAIN", +// "SupportedDiagModes", +// &isread); +// EXPECT_TRUE(isread); + +// std::vector<int>::iterator diag_mode = std::find(diagmodes_list.begin(), +// diagmodes_list.end(), 0x12); + +// // This element doesn't appear in list +// EXPECT_EQ(diag_mode, diagmodes_list.end()); + +// // List includes 0x01 +// diag_mode = std::find(diagmodes_list.begin(), diagmodes_list.end(), 0x01); +// EXPECT_EQ(diag_mode, diagmodes_list.begin()); + +// // List includes 0x03 +// std::vector<int>::iterator element_mode = diagmodes_list.begin(); +// element_mode++; +// element_mode++; + +// diag_mode = std::find(diagmodes_list.begin(), diagmodes_list.end(), 0x03); +// EXPECT_EQ(diag_mode, element_mode); +//} + +//TEST_F(ProfileTest, CheckVectorContainer) { +// Profile::instance()->config_file_name("smartDeviceLink_test.ini"); +// EXPECT_EQ("smartDeviceLink_test.ini", +// Profile::instance()->config_file_name()); + +// // Get diag_modes after updating +// const std::vector<uint32_t> &diag_modes = profile::Profile::instance() +// ->supported_diag_modes(); + +// bool isread = false; +// std::vector<int> diagmodes_list = +// profile::Profile::instance()->ReadIntContainer("MAIN", +// "SupportedDiagModes", +// &isread); +// EXPECT_TRUE(isread); +// // Compare with result of ReadIntContainer +// ASSERT_EQ(diag_modes.size(), diagmodes_list.size()); +// bool isEqual = true; +// std::vector<int>::iterator iter = diagmodes_list.begin(); + +// for (std::vector<uint32_t>::const_iterator it = diag_modes.begin(); +// it != diag_modes.end(); it++) { + +// if ((uint32_t)(*iter) != (*it)) { +// isEqual = false; +// break; +// } +// iter++; +// } +// EXPECT_TRUE(isEqual); +//} + +//TEST_F(ProfileTest, CheckStringContainer) { +// // Set new config file +// Profile::instance()->config_file_name("smartDeviceLink_test.ini"); +// EXPECT_EQ("smartDeviceLink_test.ini", +// Profile::instance()->config_file_name()); + +// bool isread = false; +// std::vector < std::string > diagmodes_list = profile::Profile::instance() +// ->ReadStringContainer("MAIN", "SupportedDiagModes", &isread); +// EXPECT_TRUE(isread); + +// std::vector<std::string>::iterator diag_mode = +// std::find(diagmodes_list.begin(), diagmodes_list.end(), "0x12"); + +// // This element doesn't appear in list +// EXPECT_EQ(diag_mode, diagmodes_list.end()); + +// // List includes 0x01 +// diag_mode = std::find(diagmodes_list.begin(), diagmodes_list.end(), "0x01"); +// EXPECT_EQ(diag_mode, diagmodes_list.begin()); + +// // List includes 0x03 +// std::vector<std::string>::iterator element_mode = diagmodes_list.begin(); +// element_mode++; +// element_mode++; +// diag_mode = std::find(diagmodes_list.begin(), diagmodes_list.end(), " 0x03"); +// EXPECT_EQ(diag_mode, element_mode); +//} + +//#ifdef ENABLE_SECURITY +//TEST_F(ProfileTest, CheckIntContainerInSecurityData) { +// // Set new config file +// Profile::instance()->config_file_name("smartDeviceLink_test.ini"); +// EXPECT_EQ("smartDeviceLink_test.ini", +// Profile::instance()->config_file_name()); + +// std::vector<int> force_unprotected_list = +// profile::Profile::instance()->ReadIntContainer( +// "Security Manager", "ForceUnprotectedService", NULL); + +// std::vector<int> force_protected_list = +// profile::Profile::instance()->ReadIntContainer( +// "Security Manager", "ForceProtectedService", NULL); + +// std::vector<int>::iterator res_unprotect = std::find(force_unprotected_list.begin(), force_unprotected_list.end(), 0x07); +// std::vector<int>::iterator res_protect = std::find(force_protected_list.begin(), force_protected_list.end(), 0x07); +// // This element doesn't appear in both lists +// EXPECT_EQ(res_unprotect, force_unprotected_list.end() ); +// EXPECT_EQ(res_protect, force_protected_list.end() ); + +// // Both lists include 0 +// res_unprotect = std::find(force_unprotected_list.begin(), force_unprotected_list.end(), 0); +// res_protect = std::find(force_protected_list.begin(), force_protected_list.end(), 0); +// EXPECT_EQ(res_unprotect, force_unprotected_list.begin() ); +// EXPECT_EQ(res_protect, force_protected_list.begin() ); +//} +//#endif + +} // namespace profile +} // namespace components +} // namespace test diff --git a/src/components/config_profile/test/smartDeviceLink.ini b/src/components/config_profile/test/smartDeviceLink.ini new file mode 100644 index 0000000000..41dabaa530 --- /dev/null +++ b/src/components/config_profile/test/smartDeviceLink.ini @@ -0,0 +1,185 @@ + ; The INI-file consists of different chapters. +; Each chapter begins with the line containing +; the name in square brackets. Syntax: +; [chapter] +; The chapters consists of a set of items with a +; assinged value. The syntax is: +; item=value +; All white spaces an second encounters of chapters +; or items will be ignored. +; Remarks start with semicolon or star as first character. +; It is alowed for names of chapters and items to +; contain semicolon and star. Possible syntax is: +; [ chapter ] ;Remark +; item = value ;Remark + +[HMI] +LaunchHMI = true +ServerAddress = 127.0.0.1 +ServerPort = 8087 +VideoStreamingPort = 5050 +AudioStreamingPort = 5080 + +[MAIN] +; Contains .json/.ini files +AppConfigFolder = +; Contains output files, e.g. .wav +AppStorageFolder = storage +; Contains resourses, e.g. audio8bit.wav +AppResourceFolder = +; Standard min stack size +; in Ubuntu : PTHREAD_STACK_MIN = 16384 +; in QNX : PTHREAD_STACK_MIN = 256 +;The value of a variable ThreadStackSize used only if its realy needed, other way stack size will be PTHREAD_STACK_MIN +; +ThreadStackSize = 20480 +MixingAudioSupported = true +HMICapabilities = hmi_capabilities.json +MaxCmdID = 2000000000 +; Default request timeout in milliseconds +DefaultTimeout = 10000 + +AppDirectoryQuota = 104857600 +; Allowed requests amount in HMI level NONE during time scale. +; If value is 0 check will be skipped +AppHMILevelNoneTimeScaleMaxRequests = 100 +AppHMILevelNoneRequestsTimeScale = 10 +; Allowed requests amount during time scale. +; If value is 0 check will be skipped +AppTimeScaleMaxRequests = 1000 +AppRequestsTimeScale = 10 +; Allowed pending requests amount. If value is 0 check will be skipped +PendingRequestsAmount = 5000 +HeartBeatTimeout = 7 +SupportedDiagModes = 0x01, 0x02, 0x03, 0x05, 0x06, 0x07, 0x09, 0x0A, 0x18, 0x19, 0x22, 0x3E +SystemFilesPath = /tmp/fs/mp/images/ivsu_cache +UseLastState = true +TimeTestingPort = 8090 +ReadDIDRequest = 5, 1 +GetVehicleDataRequest = 5, 1 + +[MEDIA MANAGER] +; where 3 is a number of retries and 1 is a timeout in seconds for request frequency +StartStreamRetry = 3, 1 +EnableRedecoding = false +VideoStreamConsumer = socket +AudioStreamConsumer = socket +;VideoStreamConsumer = file +;AudioStreamConsumer = file +;VideoStreamConsumer = pipe +;AudioStreamConsumer = pipe +;Temp solution: if you change NamedPipePath also change path to pipe in src/components/qt_hmi/qml_model_qtXX/views/SDLNavi.qml +;Named pipe path will be constructed using AppStorageFolder + name +NamedVideoPipePath = video_stream_pipe +NamedAudioPipePath = audio_stream_pipe +;File path will be constructed using AppStorageFolder + name +VideoStreamFile = video_stream_file +AudioStreamFile = audio_stream_file +; Recording file source (used for audio pass thru emulation only) +RecordingFileSource = audio.8bit.wav +; Recording file for audio pass thru +RecordingFileName = audio.wav + +; HelpPromt and TimeOutPrompt is a vector of strings separated by comma +[GLOBAL PROPERTIES] + +; Delimiter, which will be appended to each TTS chunck, e.g. helpPrompt/timeoutPrompt +TTSDelimiter = , +; Default prompt items, separated by comma +HelpPromt = Please speak one of the following commands,Please say a command +; Default prompt items, separated by comma +TimeOutPromt = Please speak one of the following commands,Please say a command +HelpTitle = Available Vr Commands List +; In case mobile app didn't send global properties default global properties will be sent after this timeout +; max value TTSGlobalPropertiesTimeout 64K +TTSGlobalPropertiesTimeout = 20 + +[FILESYSTEM RESTRICTIONS] +; Max allowed number of PutFile requests for one application in NONE +PutFileRequest = 5 +; Max allowed number of DeleteFile requests for one application in NONE +DeleteFileRequest = 5 +; Max allowed number of ListFiles requests for one application in NONE +ListFilesRequest = 5 + +[VR COMMANDS] +HelpCommand = Help + +[AppInfo] +; The path for applications info storage. +AppInfoStorage = app_info.dat + +[Security Manager] +Protocol = TLSv1.2 +; Certificate and key path to pem file +CertificatePath = mycert.pem +KeyPath = mykey.pem +; SSL mode could be SERVER or CLIENT +SSLMode = CLIENT +; Could be ALL ciphers or list of chosen +;CipherList = AES256-GCM-SHA384 +CipherList = ALL +; Verify Mobile app certificate (could be used in both SSLMode Server and Client) +VerifyPeer = false +; If VerifyPeer is enable - terminate handshake if mobile app did not return a certificate +FialOnNoCert = false +; If VerifyPeer is enable - do not ask for a mobile app certificate again in case of a renegotiation +VerifyClientOnce = false +; Force protected services (could be id's from 0x01 to 0xFF) +;ForceProtectedService = 0x0A, 0x0B +ForceProtectedService = Non +; Force unprotected services +;ForceUnprotectedService = 0x07 +ForceUnprotectedService = Non + +[Policy] +EnablePolicy = true +PreloadedPT = sdl_preloaded_pt.json +PathToSnapshot = sdl_snapshot.json +; Number of attempts to open policy DB +AttemptsToOpenPolicyDB = 5 +; Timeout between attempts during opening DB in milliseconds +OpenAttemptTimeoutMs = 500 + +[TransportManager] +TCPAdapterPort = 12345 +MMEDatabase = /dev/qdb/mediaservice_db +EventMQ = /dev/mqueue/ToSDLCoreUSBAdapter +AckMQ = /dev/mqueue/FromSDLCoreUSBAdapter + +[IAP] +LegacyProtocol = com.ford.sync.prot[0-29] +HubProtocol = com.smartdevicelink.prot0 +PoolProtocol = com.smartdevicelink.prot[1-29] +IAPSystemConfig = /fs/mp/etc/mm/ipod.cfg +IAP2SystemConfig = /fs/mp/etc/mm/iap2.cfg +IAP2HubConnectAttempts = 3 + +[ProtocolHandler] +; Packet with payload bigger than next value will be marked as a malformed +; 1488 = 1500 - 12 = TCP MTU - header size +MaximumPayloadSize = 1488 +; Application shall send less #FrequencyCount messages per #FrequencyTime mSecs +; Frequency check could be disable by setting FrequencyTime to Zero +FrequencyCount = 1000 +FrequencyTime = 1000 + +[ApplicationManager] +ApplicationListUpdateTimeout = 2 +; Max allowed threads for handling mobile requests. Currently max allowed is 2 +ThreadPoolSize = 1 + +[Resumption] + +# Timeout in seconds for resumption Application HMILevel +# and resolving conflicts in case if multiple applications initiate resumption +ApplicationResumingTimeout = 3 + +# Timeout in seconds for pereodical saving resumption persisten data +AppSavePersistentDataTimeout = 10 #seconds + +# Timeout in seconds to store hmi_level for media app before ign_off +ResumptionDelayBeforeIgn = 30; + +# Timeout in seconds to restore hmi_level for media app after sdl run +ResumptionDelayAfterIgn = 30; diff --git a/src/components/config_profile/test/smartDeviceLink_invalid_boolean.ini b/src/components/config_profile/test/smartDeviceLink_invalid_boolean.ini new file mode 100644 index 0000000000..560fb5117a --- /dev/null +++ b/src/components/config_profile/test/smartDeviceLink_invalid_boolean.ini @@ -0,0 +1,185 @@ + ; The INI-file consists of different chapters. +; Each chapter begins with the line containing +; the name in square brackets. Syntax: +; [chapter] +; The chapters consists of a set of items with a +; assinged value. The syntax is: +; item=value +; All white spaces an second encounters of chapters +; or items will be ignored. +; Remarks start with semicolon or star as first character. +; It is alowed for names of chapters and items to +; contain semicolon and star. Possible syntax is: +; [ chapter ] ;Remark +; item = value ;Remark + +[HMI] +LaunchHMI = True +ServerAddress = 127.0.0.1 +ServerPort = 8087 +VideoStreamingPort = 5050 +AudioStreamingPort = 5080 + +[MAIN] +; Contains .json/.ini files +AppConfigFolder = +; Contains output files, e.g. .wav +AppStorageFolder = storage +; Contains resourses, e.g. audio8bit.wav +AppResourceFolder = +; Standard min stack size +; in Ubuntu : PTHREAD_STACK_MIN = 16384 +; in QNX : PTHREAD_STACK_MIN = 256 +;The value of a variable ThreadStackSize used only if its realy needed, other way stack size will be PTHREAD_STACK_MIN +; +ThreadStackSize = 20480 +MixingAudioSupported = true +HMICapabilities = hmi_capabilities.json +MaxCmdID = 2000000000 +; Default request timeout in milliseconds +DefaultTimeout = 10000 + +AppDirectoryQuota = 104857600 +; Allowed requests amount in HMI level NONE during time scale. +; If value is 0 check will be skipped +AppHMILevelNoneTimeScaleMaxRequests = 100 +AppHMILevelNoneRequestsTimeScale = 10 +; Allowed requests amount during time scale. +; If value is 0 check will be skipped +AppTimeScaleMaxRequests = 1000 +AppRequestsTimeScale = 10 +; Allowed pending requests amount. If value is 0 check will be skipped +PendingRequestsAmount = 5000 +HeartBeatTimeout = 7 +SupportedDiagModes = 0x01, 0x02, 0x03, 0x05, 0x06, 0x07, 0x09, 0x0A, 0x18, 0x19, 0x22, 0x3E +SystemFilesPath = /tmp/fs/mp/images/ivsu_cache +UseLastState = true +TimeTestingPort = 8090 +ReadDIDRequest = 5, 1 +GetVehicleDataRequest = 5, 1 + +[MEDIA MANAGER] +; where 3 is a number of retries and 1 is a timeout in seconds for request frequency +StartStreamRetry = 3, 1 +EnableRedecoding = FALSE +VideoStreamConsumer = socket +AudioStreamConsumer = socket +;VideoStreamConsumer = file +;AudioStreamConsumer = file +;VideoStreamConsumer = pipe +;AudioStreamConsumer = pipe +;Temp solution: if you change NamedPipePath also change path to pipe in src/components/qt_hmi/qml_model_qtXX/views/SDLNavi.qml +;Named pipe path will be constructed using AppStorageFolder + name +NamedVideoPipePath = video_stream_pipe +NamedAudioPipePath = audio_stream_pipe +;File path will be constructed using AppStorageFolder + name +VideoStreamFile = video_stream_file +AudioStreamFile = audio_stream_file +; Recording file source (used for audio pass thru emulation only) +RecordingFileSource = audio.8bit.wav +; Recording file for audio pass thru +RecordingFileName = audio.wav + +; HelpPromt and TimeOutPrompt is a vector of strings separated by comma +[GLOBAL PROPERTIES] + +; Delimiter, which will be appended to each TTS chunck, e.g. helpPrompt/timeoutPrompt +TTSDelimiter = , +; Default prompt items, separated by comma +HelpPromt = Please speak one of the following commands,Please say a command +; Default prompt items, separated by comma +TimeOutPromt = Please speak one of the following commands,Please say a command +HelpTitle = Available Vr Commands List +; In case mobile app didn't send global properties default global properties will be sent after this timeout +; max value TTSGlobalPropertiesTimeout 64K +TTSGlobalPropertiesTimeout = 20 + +[FILESYSTEM RESTRICTIONS] +; Max allowed number of PutFile requests for one application in NONE +PutFileRequest = 5 +; Max allowed number of DeleteFile requests for one application in NONE +DeleteFileRequest = 5 +; Max allowed number of ListFiles requests for one application in NONE +ListFilesRequest = 5 + +[VR COMMANDS] +HelpCommand = Help + +[AppInfo] +; The path for applications info storage. +AppInfoStorage = app_info.dat + +[Security Manager] +Protocol = TLSv1.2 +; Certificate and key path to pem file +CertificatePath = mycert.pem +KeyPath = mykey.pem +; SSL mode could be SERVER or CLIENT +SSLMode = CLIENT +; Could be ALL ciphers or list of chosen +;CipherList = AES256-GCM-SHA384 +CipherList = ALL +; Verify Mobile app certificate (could be used in both SSLMode Server and Client) +VerifyPeer = false +; If VerifyPeer is enable - terminate handshake if mobile app did not return a certificate +FialOnNoCert = false +; If VerifyPeer is enable - do not ask for a mobile app certificate again in case of a renegotiation +VerifyClientOnce = false +; Force protected services (could be id's from 0x01 to 0xFF) +;ForceProtectedService = 0x0A, 0x0B +ForceProtectedService = Non +; Force unprotected services +;ForceUnprotectedService = 0x07 +ForceUnprotectedService = Non + +[Policy] +EnablePolicy = TRUE +PreloadedPT = sdl_preloaded_pt.json +PathToSnapshot = sdl_snapshot.json +; Number of attempts to open policy DB +AttemptsToOpenPolicyDB = 5 +; Timeout between attempts during opening DB in milliseconds +OpenAttemptTimeoutMs = 500 + +[TransportManager] +TCPAdapterPort = 12345 +MMEDatabase = /dev/qdb/mediaservice_db +EventMQ = /dev/mqueue/ToSDLCoreUSBAdapter +AckMQ = /dev/mqueue/FromSDLCoreUSBAdapter + +[IAP] +LegacyProtocol = com.ford.sync.prot[0-29] +HubProtocol = com.smartdevicelink.prot0 +PoolProtocol = com.smartdevicelink.prot[1-29] +IAPSystemConfig = /fs/mp/etc/mm/ipod.cfg +IAP2SystemConfig = /fs/mp/etc/mm/iap2.cfg +IAP2HubConnectAttempts = 3 + +[ProtocolHandler] +; Packet with payload bigger than next value will be marked as a malformed +; 1488 = 1500 - 12 = TCP MTU - header size +MaximumPayloadSize = 1488 +; Application shall send less #FrequencyCount messages per #FrequencyTime mSecs +; Frequency check could be disable by setting FrequencyTime to Zero +FrequencyCount = 1000 +FrequencyTime = 1000 + +[ApplicationManager] +ApplicationListUpdateTimeout = 2 +; Max allowed threads for handling mobile requests. Currently max allowed is 2 +ThreadPoolSize = 1 + +[Resumption] + +# Timeout in seconds for resumption Application HMILevel +# and resolving conflicts in case if multiple applications initiate resumption +ApplicationResumingTimeout = 3 + +# Timeout in seconds for pereodical saving resumption persisten data +AppSavePersistentDataTimeout = 10 #seconds + +# Timeout in seconds to store hmi_level for media app before ign_off +ResumptionDelayBeforeIgn = 30; + +# Timeout in seconds to restore hmi_level for media app after sdl run +ResumptionDelayAfterIgn = 30; diff --git a/src/components/config_profile/test/smartDeviceLink_invalid_int.ini b/src/components/config_profile/test/smartDeviceLink_invalid_int.ini new file mode 100644 index 0000000000..76bcc5a0f0 --- /dev/null +++ b/src/components/config_profile/test/smartDeviceLink_invalid_int.ini @@ -0,0 +1,187 @@ + ; The INI-file consists of different chapters. +; Each chapter begins with the line containing +; the name in square brackets. Syntax: +; [chapter] +; The chapters consists of a set of items with a +; assinged value. The syntax is: +; item=value +; All white spaces an second encounters of chapters +; or items will be ignored. +; Remarks start with semicolon or star as first character. +; It is alowed for names of chapters and items to +; contain semicolon and star. Possible syntax is: +; [ chapter ] ;Remark +; item = value ;Remark + +[HMI] +LaunchHMI = true +ServerAddress = 127.0.0.1 +ServerPort = -1 +VideoStreamingPort = 5050 +AudioStreamingPort = 5080 + +[MAIN] +; Contains .json/.ini files +AppConfigFolder = +; Contains output files, e.g. .wav +AppStorageFolder = storage +; Contains resourses, e.g. audio8bit.wav +AppResourceFolder = +; Standard min stack size +; in Ubuntu : PTHREAD_STACK_MIN = 16384 +; in QNX : PTHREAD_STACK_MIN = 256 +;The value of a variable ThreadStackSize used only if its realy needed, other way stack size will be PTHREAD_STACK_MIN +; +ThreadStackSize = 0 +MixingAudioSupported = true +HMICapabilities = hmi_capabilities.json +MaxCmdID = 20000000000 +; Default request timeout in milliseconds +DefaultTimeout = 10000 + +AppDirectoryQuota = 104857600 +; Allowed requests amount in HMI level NONE during time scale. +; If value is 0 check will be skipped +AppHMILevelNoneTimeScaleMaxRequests = 100 +AppHMILevelNoneRequestsTimeScale = 10 +; Allowed requests amount during time scale. +; If value is 0 check will be skipped +AppTimeScaleMaxRequests = 1000 +AppRequestsTimeScale = 10 +; Allowed pending requests amount. If value is 0 check will be skipped +PendingRequestsAmount = 5000 +; word instead of number +HeartBeatTimeout = seven +SupportedDiagModes = 0x01, 0x02, 0x03, 0x05, 0x06, 0x07, 0x09, 0x0A, 0x18, 0x19, 0x22, 0x3E +SystemFilesPath = /tmp/fs/mp/images/ivsu_cache +UseLastState = true +TimeTestingPort = 8090 +ReadDIDRequest = 5, 1 +GetVehicleDataRequest = 5, 1 + +[MEDIA MANAGER] +; where 3 is a number of retries and 1 is a timeout in seconds for request frequency +StartStreamRetry = 3, 1 +EnableRedecoding = false +VideoStreamConsumer = socket +AudioStreamConsumer = socket +;VideoStreamConsumer = file +;AudioStreamConsumer = file +;VideoStreamConsumer = pipe +;AudioStreamConsumer = pipe +;Temp solution: if you change NamedPipePath also change path to pipe in src/components/qt_hmi/qml_model_qtXX/views/SDLNavi.qml +;Named pipe path will be constructed using AppStorageFolder + name +NamedVideoPipePath = video_stream_pipe +NamedAudioPipePath = audio_stream_pipe +;File path will be constructed using AppStorageFolder + name +VideoStreamFile = video_stream_file +AudioStreamFile = audio_stream_file +; Recording file source (used for audio pass thru emulation only) +RecordingFileSource = audio.8bit.wav +; Recording file for audio pass thru +RecordingFileName = audio.wav + +; HelpPromt and TimeOutPrompt is a vector of strings separated by comma +[GLOBAL PROPERTIES] + +; Delimiter, which will be appended to each TTS chunck, e.g. helpPrompt/timeoutPrompt +TTSDelimiter = , +; Default prompt items, separated by comma +HelpPromt = Please speak one of the following commands,Please say a command +; Default prompt items, separated by comma +TimeOutPromt = Please speak one of the following commands,Please say a command +HelpTitle = Available Vr Commands List +; In case mobile app didn't send global properties default global properties will be sent after this timeout +; max value TTSGlobalPropertiesTimeout 64K +TTSGlobalPropertiesTimeout = 20 + +[FILESYSTEM RESTRICTIONS] +; Max allowed number of PutFile requests for one application in NONE +PutFileRequest = 5 +; Max allowed number of DeleteFile requests for one application in NONE +DeleteFileRequest = 5 +; Max allowed number of ListFiles requests for one application in NONE +;--------------- should be int +ListFilesRequest = 5,1 + +[VR COMMANDS] +HelpCommand = Help + +[AppInfo] +; The path for applications info storage. +AppInfoStorage = app_info.dat + +[Security Manager] +Protocol = TLSv1.2 +; Certificate and key path to pem file +CertificatePath = mycert.pem +KeyPath = mykey.pem +; SSL mode could be SERVER or CLIENT +SSLMode = CLIENT +; Could be ALL ciphers or list of chosen +;CipherList = AES256-GCM-SHA384 +CipherList = ALL +; Verify Mobile app certificate (could be used in both SSLMode Server and Client) +VerifyPeer = false +; If VerifyPeer is enable - terminate handshake if mobile app did not return a certificate +FialOnNoCert = false +; If VerifyPeer is enable - do not ask for a mobile app certificate again in case of a renegotiation +VerifyClientOnce = false +; Force protected services (could be id's from 0x01 to 0xFF) +;ForceProtectedService = 0x0A, 0x0B +ForceProtectedService = Non +; Force unprotected services +;ForceUnprotectedService = 0x07 +ForceUnprotectedService = Non + +[Policy] +EnablePolicy = true +PreloadedPT = sdl_preloaded_pt.json +PathToSnapshot = sdl_snapshot.json +; Number of attempts to open policy DB +AttemptsToOpenPolicyDB = 5 +; Timeout between attempts during opening DB in milliseconds +OpenAttemptTimeoutMs = 500 + +[TransportManager] +TCPAdapterPort = 12345 +MMEDatabase = /dev/qdb/mediaservice_db +EventMQ = /dev/mqueue/ToSDLCoreUSBAdapter +AckMQ = /dev/mqueue/FromSDLCoreUSBAdapter + +[IAP] +LegacyProtocol = com.ford.sync.prot[0-29] +HubProtocol = com.smartdevicelink.prot0 +PoolProtocol = com.smartdevicelink.prot[1-29] +IAPSystemConfig = /fs/mp/etc/mm/ipod.cfg +IAP2SystemConfig = /fs/mp/etc/mm/iap2.cfg +IAP2HubConnectAttempts = 3 + +[ProtocolHandler] +; Packet with payload bigger than next value will be marked as a malformed +; 1488 = 1500 - 12 = TCP MTU - header size +MaximumPayloadSize = 1488 +; Application shall send less #FrequencyCount messages per #FrequencyTime mSecs +; Frequency check could be disable by setting FrequencyTime to Zero +FrequencyCount = 1000 +FrequencyTime = 1000 + +[ApplicationManager] +ApplicationListUpdateTimeout = 2 +; Max allowed threads for handling mobile requests. Currently max allowed is 2 +ThreadPoolSize = 1 + +[Resumption] + +# Timeout in seconds for resumption Application HMILevel +# and resolving conflicts in case if multiple applications initiate resumption +ApplicationResumingTimeout = 3 + +# Timeout in seconds for pereodical saving resumption persisten data +AppSavePersistentDataTimeout = 10 #seconds + +# Timeout in seconds to store hmi_level for media app before ign_off +ResumptionDelayBeforeIgn = 30; + +# Timeout in seconds to restore hmi_level for media app after sdl run +ResumptionDelayAfterIgn = 30; diff --git a/src/components/config_profile/test/smartDeviceLink_invalid_pairs.ini b/src/components/config_profile/test/smartDeviceLink_invalid_pairs.ini new file mode 100644 index 0000000000..1507b2a84c --- /dev/null +++ b/src/components/config_profile/test/smartDeviceLink_invalid_pairs.ini @@ -0,0 +1,187 @@ + ; The INI-file consists of different chapters. +; Each chapter begins with the line containing +; the name in square brackets. Syntax: +; [chapter] +; The chapters consists of a set of items with a +; assinged value. The syntax is: +; item=value +; All white spaces an second encounters of chapters +; or items will be ignored. +; Remarks start with semicolon or star as first character. +; It is alowed for names of chapters and items to +; contain semicolon and star. Possible syntax is: +; [ chapter ] ;Remark +; item = value ;Remark + +[HMI] +LaunchHMI = true +ServerAddress = 127.0.0.1 +ServerPort = 8087 +VideoStreamingPort = 5050 +AudioStreamingPort = 5080 + +[MAIN] +; Contains .json/.ini files +AppConfigFolder = +; Contains output files, e.g. .wav +AppStorageFolder = storage +; Contains resourses, e.g. audio8bit.wav +AppResourceFolder = +; Standard min stack size +; in Ubuntu : PTHREAD_STACK_MIN = 16384 +; in QNX : PTHREAD_STACK_MIN = 256 +;The value of a variable ThreadStackSize used only if its realy needed, other way stack size will be PTHREAD_STACK_MIN +; +ThreadStackSize = 20480 +MixingAudioSupported = true +HMICapabilities = hmi_capabilities.json +MaxCmdID = 2000000000 +; Default request timeout in milliseconds +DefaultTimeout = 10000 + +AppDirectoryQuota = 104857600 +; Allowed requests amount in HMI level NONE during time scale. +; If value is 0 check will be skipped +AppHMILevelNoneTimeScaleMaxRequests = 100 +AppHMILevelNoneRequestsTimeScale = 10 +; Allowed requests amount during time scale. +; If value is 0 check will be skipped +AppTimeScaleMaxRequests = 1000 +AppRequestsTimeScale = 10 +; Allowed pending requests amount. If value is 0 check will be skipped +PendingRequestsAmount = 5000 +HeartBeatTimeout = 7 +SupportedDiagModes = 0x01, 0x02, 0x03, 0x05, 0x06, 0x07, 0x09, 0x0A, 0x18, 0x19, 0x22, 0x3E +SystemFilesPath = /tmp/fs/mp/images/ivsu_cache +UseLastState = true +TimeTestingPort = 8090 +;---------------------- +ReadDIDRequest = +GetVehicleDataRequest = , + +[MEDIA MANAGER] +; where 3 is a number of retries and 1 is a timeout in seconds for request frequency +;------------------------ should be pair +StartStreamRetry = 9 +EnableRedecoding = false +VideoStreamConsumer = socket +AudioStreamConsumer = socket +;VideoStreamConsumer = file +;AudioStreamConsumer = file +;VideoStreamConsumer = pipe +;AudioStreamConsumer = pipe +;Temp solution: if you change NamedPipePath also change path to pipe in src/components/qt_hmi/qml_model_qtXX/views/SDLNavi.qml +;Named pipe path will be constructed using AppStorageFolder + name +NamedVideoPipePath = video_stream_pipe +NamedAudioPipePath = audio_stream_pipe +;File path will be constructed using AppStorageFolder + name +VideoStreamFile = video_stream_file +AudioStreamFile = audio_stream_file +; Recording file source (used for audio pass thru emulation only) +RecordingFileSource = audio.8bit.wav +; Recording file for audio pass thru +RecordingFileName = audio.wav + +; HelpPromt and TimeOutPrompt is a vector of strings separated by comma +[GLOBAL PROPERTIES] + +; Delimiter, which will be appended to each TTS chunck, e.g. helpPrompt/timeoutPrompt +TTSDelimiter = , +; Default prompt items, separated by comma +HelpPromt = Please speak one of the following commands,Please say a command +; Default prompt items, separated by comma +TimeOutPromt = Please speak one of the following commands,Please say a command +HelpTitle = Available Vr Commands List +; In case mobile app didn't send global properties default global properties will be sent after this timeout +; max value TTSGlobalPropertiesTimeout 64K +TTSGlobalPropertiesTimeout = 20 + +[FILESYSTEM RESTRICTIONS] +; Max allowed number of PutFile requests for one application in NONE +PutFileRequest = 5 +; Max allowed number of DeleteFile requests for one application in NONE +DeleteFileRequest = 5 +; Max allowed number of ListFiles requests for one application in NONE +ListFilesRequest = 5 + +[VR COMMANDS] +HelpCommand = Help + +[AppInfo] +; The path for applications info storage. +AppInfoStorage = app_info.dat + +[Security Manager] +Protocol = TLSv1.2 +; Certificate and key path to pem file +CertificatePath = mycert.pem +KeyPath = mykey.pem +; SSL mode could be SERVER or CLIENT +SSLMode = CLIENT +; Could be ALL ciphers or list of chosen +;CipherList = AES256-GCM-SHA384 +CipherList = ALL +; Verify Mobile app certificate (could be used in both SSLMode Server and Client) +VerifyPeer = false +; If VerifyPeer is enable - terminate handshake if mobile app did not return a certificate +FialOnNoCert = false +; If VerifyPeer is enable - do not ask for a mobile app certificate again in case of a renegotiation +VerifyClientOnce = false +; Force protected services (could be id's from 0x01 to 0xFF) +;ForceProtectedService = 0x0A, 0x0B +ForceProtectedService = Non +; Force unprotected services +;ForceUnprotectedService = 0x07 +ForceUnprotectedService = Non + +[Policy] +EnablePolicy = true +PreloadedPT = sdl_preloaded_pt.json +PathToSnapshot = sdl_snapshot.json +; Number of attempts to open policy DB +AttemptsToOpenPolicyDB = 5 +; Timeout between attempts during opening DB in milliseconds +OpenAttemptTimeoutMs = 500 + +[TransportManager] +TCPAdapterPort = 12345 +MMEDatabase = /dev/qdb/mediaservice_db +EventMQ = /dev/mqueue/ToSDLCoreUSBAdapter +AckMQ = /dev/mqueue/FromSDLCoreUSBAdapter + +[IAP] +LegacyProtocol = com.ford.sync.prot[0-29] +HubProtocol = com.smartdevicelink.prot0 +PoolProtocol = com.smartdevicelink.prot[1-29] +IAPSystemConfig = /fs/mp/etc/mm/ipod.cfg +IAP2SystemConfig = /fs/mp/etc/mm/iap2.cfg +IAP2HubConnectAttempts = 3 + +[ProtocolHandler] +; Packet with payload bigger than next value will be marked as a malformed +; 1488 = 1500 - 12 = TCP MTU - header size +MaximumPayloadSize = 1488 +; Application shall send less #FrequencyCount messages per #FrequencyTime mSecs +; Frequency check could be disable by setting FrequencyTime to Zero +FrequencyCount = 1000 +FrequencyTime = 1000 + +[ApplicationManager] +ApplicationListUpdateTimeout = 2 +; Max allowed threads for handling mobile requests. Currently max allowed is 2 +ThreadPoolSize = 1 + +[Resumption] + +# Timeout in seconds for resumption Application HMILevel +# and resolving conflicts in case if multiple applications initiate resumption +ApplicationResumingTimeout = 3 + +# Timeout in seconds for pereodical saving resumption persisten data +AppSavePersistentDataTimeout = 10 #seconds + +# Timeout in seconds to store hmi_level for media app before ign_off +ResumptionDelayBeforeIgn = 30; + +# Timeout in seconds to restore hmi_level for media app after sdl run +ResumptionDelayAfterIgn = 30; diff --git a/src/components/config_profile/test/smartDeviceLink_invalid_string.ini b/src/components/config_profile/test/smartDeviceLink_invalid_string.ini new file mode 100644 index 0000000000..6669b580c5 --- /dev/null +++ b/src/components/config_profile/test/smartDeviceLink_invalid_string.ini @@ -0,0 +1,190 @@ + ; The INI-file consists of different chapters. +; Each chapter begins with the line containing +; the name in square brackets. Syntax: +; [chapter] +; The chapters consists of a set of items with a +; assinged value. The syntax is: +; item=value +; All white spaces an second encounters of chapters +; or items will be ignored. +; Remarks start with semicolon or star as first character. +; It is alowed for names of chapters and items to +; contain semicolon and star. Possible syntax is: +; [ chapter ] ;Remark +; item = value ;Remark + +[HMI] +LaunchHMI = true +ServerAddress = 127.0.0.1 + слово +ServerPort = 8087 +VideoStreamingPort = 5050 +AudioStreamingPort = 5080 + +[MAIN] +; Contains .json/.ini files +; forbidden name for directory +AppConfigFolder = /// +; Contains output files, e.g. .wav +; +AppStorageFolder = " " +; Contains resourses, e.g. audio8bit.wav +;----- +AppResourceFolder = new folder/ +; Standard min stack size +; in Ubuntu : PTHREAD_STACK_MIN = 16384 +; in QNX : PTHREAD_STACK_MIN = 256 +;The value of a variable ThreadStackSize used only if its realy needed, other way stack size will be PTHREAD_STACK_MIN +; +ThreadStackSize = 20480 +MixingAudioSupported = true +HMICapabilities = hmi_capabilities.json +MaxCmdID = 2000000000 +; Default request timeout in milliseconds +DefaultTimeout = 10000 + +AppDirectoryQuota = 104857600 +; Allowed requests amount in HMI level NONE during time scale. +; If value is 0 check will be skipped +AppHMILevelNoneTimeScaleMaxRequests = 100 +AppHMILevelNoneRequestsTimeScale = 10 +; Allowed requests amount during time scale. +; If value is 0 check will be skipped +AppTimeScaleMaxRequests = 1000 +AppRequestsTimeScale = 10 +; Allowed pending requests amount. If value is 0 check will be skipped +PendingRequestsAmount = 5000 +HeartBeatTimeout = 7 +SupportedDiagModes = 0x01, 0x02, 0x03, 0x05, 0x06, 0x07, 0x09, 0x0A, 0x18, 0x19, 0x22, 0x3E +SystemFilesPath = /tmp/fs/mp/images/ivsu_cache +UseLastState = true +TimeTestingPort = 8090 +ReadDIDRequest = 5, 1 +;Check wrong pair value +GetVehicleDataRequest = A, 0 + +[MEDIA MANAGER] +; where 3 is a number of retries and 1 is a timeout in seconds for request frequency +StartStreamRetry = 3, 1 +EnableRedecoding = false +VideoStreamConsumer = socket +AudioStreamConsumer = socket +;VideoStreamConsumer = file +;AudioStreamConsumer = file +;VideoStreamConsumer = pipe +;AudioStreamConsumer = pipe +;Temp solution: if you change NamedPipePath also change path to pipe in src/components/qt_hmi/qml_model_qtXX/views/SDLNavi.qml +;Named pipe path will be constructed using AppStorageFolder + name +NamedVideoPipePath = video_stream_pipe +NamedAudioPipePath = audio_stream_pipe +;File path will be constructed using AppStorageFolder + name +VideoStreamFile = video_stream_file +AudioStreamFile = audio_stream_file +; Recording file source (used for audio pass thru emulation only) +RecordingFileSource = 00012\\345/678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012\\345/678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012\\345/678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012\\345/678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012\\345/678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a +; Recording file for audio pass thru +RecordingFileName = 0/0/0/1/2345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890abc!def@ghi + +; HelpPromt and TimeOutPrompt is a vector of strings separated by comma +[GLOBAL PROPERTIES] + +; Delimiter, which will be appended to each TTS chunck, e.g. helpPrompt/timeoutPrompt +; ---------- words instead of coma +TTSDelimiter = coma and point +; Default prompt items, separated by comma +HelpPromt = Please speak one of the following commands,Please say a command +; Default prompt items, separated by comma +TimeOutPromt = Please speak one of the following commands,Please say a command +HelpTitle = 0/0/0/1/2345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890abc!def@ghi +; In case mobile app didn't send global properties default global properties will be sent after this timeout +; max value TTSGlobalPropertiesTimeout 64K +TTSGlobalPropertiesTimeout = 20 + +[FILESYSTEM RESTRICTIONS] +; Max allowed number of PutFile requests for one application in NONE +PutFileRequest = 5 +; Max allowed number of DeleteFile requests for one application in NONE +DeleteFileRequest = 5 +; Max allowed number of ListFiles requests for one application in NONE +ListFilesRequest = 5 + +[VR COMMANDS] +HelpCommand = Help + +[AppInfo] +; The path for applications info storage. +AppInfoStorage = app_info.dat + +[Security Manager] +Protocol = TLSv1.2 +; Certificate and key path to pem file +CertificatePath = mycert.pem +KeyPath = mykey.pem +; SSL mode could be SERVER or CLIENT +SSLMode = CLIENT +; Could be ALL ciphers or list of chosen +;CipherList = AES256-GCM-SHA384 +CipherList = ALL +; Verify Mobile app certificate (could be used in both SSLMode Server and Client) +VerifyPeer = false +; If VerifyPeer is enable - terminate handshake if mobile app did not return a certificate +FialOnNoCert = false +; If VerifyPeer is enable - do not ask for a mobile app certificate again in case of a renegotiation +VerifyClientOnce = false +; Force protected services (could be id's from 0x01 to 0xFF) +;ForceProtectedService = 0x0A, 0x0B +ForceProtectedService = Non +; Force unprotected services +;ForceUnprotectedService = 0x07 +ForceUnprotectedService = Non + +[Policy] +EnablePolicy = true +PreloadedPT = sdl_preloaded_pt.json +PathToSnapshot = sdl_snapshot.json +; Number of attempts to open policy DB +AttemptsToOpenPolicyDB = 5 +; Timeout between attempts during opening DB in milliseconds +OpenAttemptTimeoutMs = 500 + +[TransportManager] +TCPAdapterPort = 12345 +MMEDatabase = /dev/qdb/mediaservice_db +EventMQ = /dev/mqueue/ToSDLCoreUSBAdapter +AckMQ = /dev/mqueue/FromSDLCoreUSBAdapter + +[IAP] +LegacyProtocol = com.ford.sync.prot[0-29] +HubProtocol = com.smartdevicelink.prot0 +PoolProtocol = com.smartdevicelink.prot[1-29] +IAPSystemConfig = /fs/mp/etc/mm/ipod.cfg +IAP2SystemConfig = /fs/mp/etc/mm/iap2.cfg +IAP2HubConnectAttempts = 3 + +[ProtocolHandler] +; Packet with payload bigger than next value will be marked as a malformed +; 1488 = 1500 - 12 = TCP MTU - header size +MaximumPayloadSize = 1488 +; Application shall send less #FrequencyCount messages per #FrequencyTime mSecs +; Frequency check could be disable by setting FrequencyTime to Zero +FrequencyCount = 1000 +FrequencyTime = 1000 + +[ApplicationManager] +ApplicationListUpdateTimeout = 2 +; Max allowed threads for handling mobile requests. Currently max allowed is 2 +ThreadPoolSize = 1 + +[Resumption] + +# Timeout in seconds for resumption Application HMILevel +# and resolving conflicts in case if multiple applications initiate resumption +ApplicationResumingTimeout = 3 + +# Timeout in seconds for pereodical saving resumption persisten data +AppSavePersistentDataTimeout = 10 #seconds + +# Timeout in seconds to store hmi_level for media app before ign_off +ResumptionDelayBeforeIgn = 30; + +# Timeout in seconds to restore hmi_level for media app after sdl run +ResumptionDelayAfterIgn = 30; diff --git a/src/components/config_profile/test/smartDeviceLink_test.ini b/src/components/config_profile/test/smartDeviceLink_test.ini new file mode 100644 index 0000000000..6e2943b569 --- /dev/null +++ b/src/components/config_profile/test/smartDeviceLink_test.ini @@ -0,0 +1,192 @@ + ; The INI-file consists of different chapters. +; Each chapter begins with the line containing +; the name in square brackets. Syntax: +; [chapter] +; The chapters consists of a set of items with a +; assinged value. The syntax is: +; item=value +; All white spaces an second encounters of chapters +; or items will be ignored. +; Remarks start with semicolon or star as first character. +; It is alowed for names of chapters and items to +; contain semicolon and star. Possible syntax is: +; [ chapter ] ;Remark +; item = value ;Remark + +[HMI] +;-------------------- +LaunchHMI = false +ServerAddress = 127.0.0.1 +ServerPort = 8088 +ServerPort = 8087 +VideoStreamingPort = 5050 +AudioStreamingPort = 5080 + +[MAIN] +; Contains .json/.ini files +AppConfigFolder = +; Contains output files, e.g. .wav +AppStorageFolder = storage +; Contains resourses, e.g. audio8bit.wav +AppResourceFolder = +; Standard min stack size +; in Ubuntu : PTHREAD_STACK_MIN = 16384 +; in QNX : PTHREAD_STACK_MIN = 256 +;The value of a variable ThreadStackSize used only if its realy needed, other way stack size will be PTHREAD_STACK_MIN +; +ThreadStackSize = 21000 +MixingAudioSupported = false +HMICapabilities = hmi_capabilities.json +;----------------------- +MaxCmdID = 20000000000 +; Default request timeout in milliseconds +;----------------------- +DefaultTimeout = + +AppDirectoryQuota = 104857600 +; Allowed requests amount in HMI level NONE during time scale. +; If value is 0 check will be skipped +AppHMILevelNoneTimeScaleMaxRequests = 100 +AppHMILevelNoneRequestsTimeScale = 10 +; Allowed requests amount during time scale. +; If value is 0 check will be skipped +AppTimeScaleMaxRequests = 1000 +AppRequestsTimeScale = 10 +; Allowed pending requests amount. If value is 0 check will be skipped +PendingRequestsAmount = 5000 +HeartBeatTimeout = 7 +SupportedDiagModes = 0x01, 0x02, 0x03, 0x05, 0x06, 0x07, 0x09, 0x0A, 0x18, 0x19, 0x22, 0x3E +SystemFilesPath = /tmp/fs/mp/images/ivsu_cache +UseLastState = true +TimeTestingPort = 8090 +ReadDIDRequest = 5, 1 +GetVehicleDataRequest = 5, 1 + +[MEDIA MANAGER] +; where 3 is a number of retries and 1 is a timeout in seconds for request frequency +StartStreamRetry = 3, 1 +EnableRedecoding = true +VideoStreamConsumer = socket +AudioStreamConsumer = socket +;VideoStreamConsumer = file +;AudioStreamConsumer = file +;VideoStreamConsumer = pipe +;AudioStreamConsumer = pipe +;Temp solution: if you change NamedPipePath also change path to pipe in src/components/qt_hmi/qml_model_qtXX/views/SDLNavi.qml +;Named pipe path will be constructed using AppStorageFolder + name +NamedVideoPipePath = video_stream_pipe +NamedAudioPipePath = audio_stream_pipe +;File path will be constructed using AppStorageFolder + name +VideoStreamFile = video_stream_file +AudioStreamFile = audio_stream_file +; Recording file source (used for audio pass thru emulation only) +RecordingFileSource = audio.8bit.wav +; Recording file for audio pass thru +RecordingFileName = video.wav +RecordingFileName = audio.wav + +; HelpPromt and TimeOutPrompt is a vector of strings separated by comma +[GLOBAL PROPERTIES] + +; Delimiter, which will be appended to each TTS chunck, e.g. helpPrompt/timeoutPrompt +TTSDelimiter = , +; Default prompt items, separated by comma +HelpPromt = Please speak one of the following commands,Please say a command +; Default prompt items, separated by comma +TimeOutPromt = Please say a command +TimeOutPromt = Please speak one of the following commands,Please say a command +HelpTitle = Available Vr Commands List +; In case mobile app didn't send global properties default global properties will be sent after this timeout +; max value TTSGlobalPropertiesTimeout 64K +TTSGlobalPropertiesTimeout = 20 + +[FILESYSTEM RESTRICTIONS] +; Max allowed number of PutFile requests for one application in NONE +PutFileRequest = 5 +; Max allowed number of DeleteFile requests for one application in NONE +DeleteFileRequest = 5 +; Max allowed number of ListFiles requests for one application in NONE +ListFilesRequest = 5 + +[VR COMMANDS] +HelpCommand = Help + +[AppInfo] +; The path for applications info storage. +AppInfoStorage = app_info.dat + +[Security Manager] +Protocol = TLSv1.2 +; Certificate and key path to pem file +CertificatePath = mycert.pem +KeyPath = mykey.pem +; SSL mode could be SERVER or CLIENT +SSLMode = CLIENT +; Could be ALL ciphers or list of chosen +;CipherList = AES256-GCM-SHA384 +CipherList = ALL +; Verify Mobile app certificate (could be used in both SSLMode Server and Client) +VerifyPeer = false +; If VerifyPeer is enable - terminate handshake if mobile app did not return a certificate +FialOnNoCert = false +; If VerifyPeer is enable - do not ask for a mobile app certificate again in case of a renegotiation +VerifyClientOnce = false +; Force protected services (could be id's from 0x01 to 0xFF) +;ForceProtectedService = 0x0A, 0x0B +ForceProtectedService = Non +; Force unprotected services +;ForceUnprotectedService = 0x07 +ForceUnprotectedService = Non + +[Policy] +;----------------------------- +EnablePolicy = false +PreloadedPT = sdl_preloaded_pt.json +PathToSnapshot = sdl_snapshot.json +; Number of attempts to open policy DB +AttemptsToOpenPolicyDB = 5 +; Timeout between attempts during opening DB in milliseconds +OpenAttemptTimeoutMs = 500 + +[TransportManager] +TCPAdapterPort = 12345 +MMEDatabase = /dev/qdb/mediaservice_db +EventMQ = /dev/mqueue/ToSDLCoreUSBAdapter +AckMQ = /dev/mqueue/FromSDLCoreUSBAdapter + +[IAP] +LegacyProtocol = com.ford.sync.prot[0-29] +HubProtocol = com.smartdevicelink.prot0 +PoolProtocol = com.smartdevicelink.prot[1-29] +IAPSystemConfig = /fs/mp/etc/mm/ipod.cfg +IAP2SystemConfig = /fs/mp/etc/mm/iap2.cfg +IAP2HubConnectAttempts = 3 + +[ProtocolHandler] +; Packet with payload bigger than next value will be marked as a malformed +; 1488 = 1500 - 12 = TCP MTU - header size +MaximumPayloadSize = 1488 +; Application shall send less #FrequencyCount messages per #FrequencyTime mSecs +; Frequency check could be disable by setting FrequencyTime to Zero +FrequencyCount = 1000 +FrequencyTime = 1000 + +[ApplicationManager] +ApplicationListUpdateTimeout = 2 +; Max allowed threads for handling mobile requests. Currently max allowed is 2 +ThreadPoolSize = 1 + +[Resumption] + +# Timeout in seconds for resumption Application HMILevel +# and resolving conflicts in case if multiple applications initiate resumption +ApplicationResumingTimeout = 3 + +# Timeout in seconds for pereodical saving resumption persisten data +AppSavePersistentDataTimeout = 10 #seconds + +# Timeout in seconds to store hmi_level for media app before ign_off +ResumptionDelayBeforeIgn = 30; + +# Timeout in seconds to restore hmi_level for media app after sdl run +ResumptionDelayAfterIgn = 30; diff --git a/src/components/connection_handler/test/CMakeLists.txt b/src/components/connection_handler/test/CMakeLists.txt index f98c03391d..8e454ccf9e 100644 --- a/src/components/connection_handler/test/CMakeLists.txt +++ b/src/components/connection_handler/test/CMakeLists.txt @@ -36,13 +36,19 @@ include_directories( ${GMOCK_INCLUDE_DIRECTORY} ${COMPONENTS_DIR}/connection_handler/include ${COMPONENTS_DIR}/security_manager/test/include + ${COMPONENTS_DIR}/protocol_handler/test/include ${COMPONENTS_DIR}/security_manager/include + ${COMPONENTS_DIR}/application_manager/include + ${COMPONENTS_DIR}/connection_handler/test/include + ${COMPONENTS_DIR}/transport_manager/test/include ) set(LIBRARIES gmock connectionHandler ConfigProfile + ProtocolHandler + TransportManager ) set(SOURCES 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 59dbe3bb7e..94e4c816fa 100644 --- a/src/components/connection_handler/test/connection_handler_impl_test.cc +++ b/src/components/connection_handler/test/connection_handler_impl_test.cc @@ -38,6 +38,9 @@ #include "config_profile/profile.h" // TODO(EZamakhov): move security test #include "security_manager_mock.h" +#include "protocol_handler_mock.h" +#include "connection_handler_observer_mock.h" +#include "transport_manager_mock.h" namespace test { namespace components { @@ -46,52 +49,66 @@ namespace connection_handle_test { using namespace ::connection_handler; using ::protocol_handler::ServiceType; using namespace ::protocol_handler; +using ::testing::_; +using ::testing::InSequence; // For service types and PROTECTION_ON/OFF class ConnectionHandlerTest : public ::testing::Test { protected: void SetUp() OVERRIDE { connection_handler_ = ConnectionHandlerImpl::instance(); - uid = 1u; - connection_key = connection_handler_->KeyFromPair(0, 0u); + uid_ = 1u; + connection_key_ = connection_handler_->KeyFromPair(0, 0u); } void TearDown() OVERRIDE { ConnectionHandlerImpl::destroy(); } // Additional SetUp void AddTestDeviceConnection() { - const transport_manager::DeviceHandle device_handle = 0; - const transport_manager::DeviceInfo device_info(device_handle, - std::string("test_address"), - std::string("test_name"), - std::string("BTMAC")); + device_handle_ = 0; + + connection_type_ = "BTMAC"; + device_name_ = "test_name"; + mac_address_ = "test_address"; + + const transport_manager::DeviceInfo device_info(device_handle_, + mac_address_, + device_name_, + connection_type_); // Add Device and connection - connection_handler_->addDeviceConnection(device_info, uid); - connection_key = connection_handler_->KeyFromPair(uid, 0u); + connection_handler_->addDeviceConnection(device_info, uid_); + connection_key_ = connection_handler_->KeyFromPair(uid_, 0u); // Remove all specific services SetSpecificServices("", ""); } void AddTestSession() { - start_session_id = connection_handler_->OnSessionStartedCallback( - uid, 0, kRpc, PROTECTION_OFF, &out_hash_id); - EXPECT_NE(0u, start_session_id); - EXPECT_EQ(SessionHash(uid, start_session_id), out_hash_id); - connection_key = connection_handler_->KeyFromPair(uid, start_session_id); - CheckSessionExists(uid, start_session_id); + start_session_id_ = connection_handler_->OnSessionStartedCallback( + uid_, 0, kRpc, PROTECTION_OFF, &out_hash_id_); + EXPECT_NE(0u, start_session_id_); + EXPECT_EQ(SessionHash(uid_, start_session_id_), out_hash_id_); + connection_key_ = connection_handler_->KeyFromPair(uid_, start_session_id_); + CheckSessionExists(uid_, start_session_id_); } uint32_t SessionHash(const uint32_t connection, const uint32_t session) { return connection_handler_->KeyFromPair(connection, session); } + void AddTestService(ServiceType service_type) { + EXPECT_NE(0u, start_session_id_); + EXPECT_EQ(SessionHash(uid_, start_session_id_), out_hash_id_); + connection_key_ = connection_handler_->KeyFromPair(uid_, start_session_id_); + CheckSessionExists(uid_, start_session_id_); + uint32_t session_id = connection_handler_->OnSessionStartedCallback( + uid_, start_session_id_, service_type, PROTECTION_OFF, 0); + EXPECT_EQ(session_id, start_session_id_); + } // Additional SetUp - void SetSpecificServices(const std::string& protect, - const std::string& not_protect) { + void SetSpecificServices(const std::string& protect, const std::string& not_protect) { const char* config_file = "config.ini"; std::ofstream file_config(config_file); ASSERT_TRUE(file_config.is_open()); const std::string non("NON"); - file_config - << "[Security Manager]" << std::endl + file_config << "[Security Manager]" << std::endl << "; Force protected services (could be id's from 0x01 to 0xFF)" << std::endl << "ForceProtectedService = " << (protect.empty() ? non : protect) << std::endl @@ -105,8 +122,7 @@ class ConnectionHandlerTest : public ::testing::Test { // If session_id is NULL - check that there is no sessions in connection void CheckSessionExists(const int connectionId, const int session_id) { // Check all tree to find Session and check own protected value - const ConnectionList& connection_list = connection_handler_ - ->getConnectionList(); + const ConnectionList& connection_list = connection_handler_->getConnectionList(); ASSERT_FALSE(connection_list.empty()); ConnectionList::const_iterator conn_it = connection_list.find(connectionId); ASSERT_NE(conn_it, connection_list.end()); @@ -123,10 +139,8 @@ class ConnectionHandlerTest : public ::testing::Test { const ServiceList& service_list = session.service_list; ASSERT_FALSE(service_list.empty()); // Check RPC and bulk services in session - ASSERT_NE(service_list.end(), - std::find(service_list.begin(), service_list.end(), kRpc)); - ASSERT_NE(service_list.end(), - std::find(service_list.begin(), service_list.end(), kBulk)); + ASSERT_NE(service_list.end(), std::find(service_list.begin(), service_list.end(), kRpc)); + ASSERT_NE(service_list.end(), std::find(service_list.begin(), service_list.end(), kBulk)); } } @@ -135,8 +149,7 @@ class ConnectionHandlerTest : public ::testing::Test { const ::protocol_handler::ServiceType serviceId, const bool exists) { // Check all trees to find Service and check own protected value - const ConnectionList& connection_list = connection_handler_ - ->getConnectionList(); + const ConnectionList& connection_list = connection_handler_->getConnectionList(); ASSERT_FALSE(connection_list.empty()); ConnectionList::const_iterator conn_it = connection_list.find(connectionId); ASSERT_NE(conn_it, connection_list.end()); @@ -149,9 +162,7 @@ class ConnectionHandlerTest : public ::testing::Test { const Session& session = sess_it->second; const ServiceList& service_list = session.service_list; ASSERT_FALSE(service_list.empty()); - ServiceList::const_iterator serv_it = std::find(service_list.begin(), - service_list.end(), - serviceId); + ServiceList::const_iterator serv_it = std::find(service_list.begin(), service_list.end(), serviceId); if (exists) { ASSERT_NE(serv_it, service_list.end()); } else { @@ -164,8 +175,7 @@ class ConnectionHandlerTest : public ::testing::Test { const ::security_manager::SSLContext* ssl_context, const bool is_protected) { // Check all tree to find Service and check own protected value - const ConnectionList& connection_list = connection_handler_ - ->getConnectionList(); + const ConnectionList& connection_list = connection_handler_->getConnectionList(); ASSERT_FALSE(connection_list.empty()); ConnectionList::const_iterator conn_it = connection_list.find(connectionId); ASSERT_NE(conn_it, connection_list.end()); @@ -181,9 +191,7 @@ class ConnectionHandlerTest : public ::testing::Test { #endif // ENABLE_SECURITY const ServiceList& service_list = session.service_list; ASSERT_FALSE(service_list.empty()); - ServiceList::const_iterator serv_it = std::find(service_list.begin(), - service_list.end(), - serviceId); + ServiceList::const_iterator serv_it = std::find(service_list.begin(), service_list.end(), serviceId); ASSERT_NE(serv_it, service_list.end()); const Service& service = *serv_it; @@ -191,31 +199,51 @@ class ConnectionHandlerTest : public ::testing::Test { #ifdef ENABLE_SECURITY if (is_protected) { // Emulate success protection - check enable service flag - const uint32_t connection_key = connection_handler_->KeyFromPair( + const uint32_t connection_key_ = connection_handler_->KeyFromPair( connectionId, session_id); - connection_handler_->SetProtectionFlag(connection_key, serviceId); + connection_handler_->SetProtectionFlag(connection_key_, serviceId); } #endif // ENABLE_SECURITY } + void ChangeProtocol(const int connectionId, const int session_id, const uint8_t protocol_version) { + ConnectionList connection_list = connection_handler_->getConnectionList(); + + ConnectionList::const_iterator conn_it = (connection_handler_->getConnectionList()).find(connectionId); + ASSERT_NE(conn_it, connection_list.end()); + Connection * connection = conn_it->second; + ASSERT_TRUE(connection != NULL); + connection->UpdateProtocolVersionSession(session_id, protocol_version); + uint8_t check_protocol_version; + EXPECT_TRUE(connection->ProtocolVersion(session_id, check_protocol_version)); + EXPECT_EQ(check_protocol_version,protocol_version); + + } + ConnectionHandlerImpl* connection_handler_; - transport_manager::ConnectionUID uid; - uint32_t connection_key; - uint32_t start_session_id; - uint32_t out_hash_id; + transport_manager::DeviceHandle device_handle_; + transport_manager::ConnectionUID uid_; + uint32_t connection_key_; + uint32_t start_session_id_; + uint32_t out_hash_id_; + + std::string connection_type_; + std::string device_name_; + std::string mac_address_; + }; TEST_F(ConnectionHandlerTest, StartSession_NoConnection) { // Null sessionId for start new session const uint8_t sessionID = 0; // Start new session with RPC service - const uint32_t result_fail = connection_handler_->OnSessionStartedCallback( - uid, sessionID, kRpc, PROTECTION_ON, &out_hash_id); + const uint32_t result_fail = connection_handler_->OnSessionStartedCallback(uid_, sessionID, kRpc, PROTECTION_ON, &out_hash_id_); // Unknown connection error is '0' EXPECT_EQ(0u, result_fail); - EXPECT_EQ(protocol_handler::HASH_ID_WRONG, out_hash_id); + EXPECT_EQ(protocol_handler::HASH_ID_WRONG, out_hash_id_); ASSERT_TRUE(connection_handler_->getConnectionList().empty()); } + TEST_F(ConnectionHandlerTest, StartSession) { // Add virtual device and connection AddTestDeviceConnection(); @@ -376,17 +404,28 @@ TEST_F(ConnectionHandlerTest,OnFindNewApplicationsRequestWithoutSession) { TEST_F(ConnectionHandlerTest, OnMalformedMessageCallback) { AddTestDeviceConnection(); AddTestSession(); + AddTestService(kAudio); + AddTestService(kMobileNav); connection_handler_test::ConnectionHandlerObserverMock mock_connection_handler_observer; connection_handler_->set_connection_handler_observer(&mock_connection_handler_observer); + InSequence seq; + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kMobileNav, kMalformed)).Times(1); + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kAudio, kMalformed)).Times(1); EXPECT_CALL(mock_connection_handler_observer, - OnServiceEndedCallback(connection_key_,_, kMalformed)).Times(2); + OnServiceEndedCallback(connection_key_,kBulk, kMalformed)).Times(1); + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kRpc, kMalformed)).Times(1); connection_handler_->OnMalformedMessageCallback(uid_); } TEST_F(ConnectionHandlerTest, OnApplicationFloodCallBack) { AddTestDeviceConnection(); AddTestSession(); + AddTestService(kAudio); + AddTestService(kMobileNav); connection_handler_test::ConnectionHandlerObserverMock mock_connection_handler_observer; connection_handler_->set_connection_handler_observer(&mock_connection_handler_observer); @@ -394,8 +433,16 @@ TEST_F(ConnectionHandlerTest, OnApplicationFloodCallBack) { connection_handler_->set_protocol_handler(&mock_protocol_handler); EXPECT_CALL(mock_protocol_handler, SendEndSession(uid_,start_session_id_)); + + InSequence seq; + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kMobileNav, kCommon)).Times(1); + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kAudio, kCommon)).Times(1); EXPECT_CALL(mock_connection_handler_observer, - OnServiceEndedCallback(connection_key_,_, kCommon)).Times(2); + OnServiceEndedCallback(connection_key_,kBulk, kCommon)).Times(1); + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kRpc, kCommon)).Times(1); connection_handler_->OnApplicationFloodCallBack(uid_); } @@ -442,7 +489,8 @@ TEST_F(ConnectionHandlerTest, CloseRevokedConnection) { TEST_F(ConnectionHandlerTest, CloseSessionWithCommonReason) { AddTestDeviceConnection(); AddTestSession(); - + AddTestService(kAudio); + AddTestService(kMobileNav); connection_handler_test::ConnectionHandlerObserverMock mock_connection_handler_observer; connection_handler_->set_connection_handler_observer(&mock_connection_handler_observer); @@ -450,16 +498,24 @@ TEST_F(ConnectionHandlerTest, CloseSessionWithCommonReason) { connection_handler_->set_protocol_handler(&mock_protocol_handler); EXPECT_CALL(mock_protocol_handler, SendEndSession(uid_,start_session_id_)); - EXPECT_CALL(mock_connection_handler_observer, - OnServiceEndedCallback(connection_key_,_, kCommon)).Times(2); + InSequence seq; + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kMobileNav, kCommon)).Times(1); + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kAudio, kCommon)).Times(1); + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kBulk, kCommon)).Times(1); + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kRpc, kCommon)).Times(1); connection_handler_->CloseSession(connection_key_, kCommon); } TEST_F(ConnectionHandlerTest, CloseSessionWithFloodReason) { AddTestDeviceConnection(); AddTestSession(); - + AddTestService(kAudio); + AddTestService(kMobileNav); connection_handler_test::ConnectionHandlerObserverMock mock_connection_handler_observer; connection_handler_->set_connection_handler_observer(&mock_connection_handler_observer); @@ -467,16 +523,24 @@ TEST_F(ConnectionHandlerTest, CloseSessionWithFloodReason) { connection_handler_->set_protocol_handler(&mock_protocol_handler); EXPECT_CALL(mock_protocol_handler, SendEndSession(uid_,start_session_id_)); - EXPECT_CALL(mock_connection_handler_observer, - OnServiceEndedCallback(connection_key_,_, kFlood)).Times(2); + InSequence seq; + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kMobileNav, kFlood)).Times(1); + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kAudio, kFlood)).Times(1); + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kBulk, kFlood)).Times(1); + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kRpc, kFlood)).Times(1); connection_handler_->CloseSession(connection_key_, kFlood); } TEST_F(ConnectionHandlerTest, CloseSessionWithMalformedMessage) { AddTestDeviceConnection(); AddTestSession(); - + AddTestService(kAudio); + AddTestService(kMobileNav); connection_handler_test::ConnectionHandlerObserverMock mock_connection_handler_observer; connection_handler_->set_connection_handler_observer(&mock_connection_handler_observer); @@ -484,16 +548,24 @@ TEST_F(ConnectionHandlerTest, CloseSessionWithMalformedMessage) { connection_handler_->set_protocol_handler(&mock_protocol_handler); EXPECT_CALL(mock_protocol_handler, SendEndSession(uid_,start_session_id_)).Times(0); - EXPECT_CALL(mock_connection_handler_observer, - OnServiceEndedCallback(connection_key_,_, kMalformed)).Times(2); + InSequence seq; + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kMobileNav, kMalformed)).Times(1); + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kAudio, kMalformed)).Times(1); + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kBulk, kMalformed)).Times(1); + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kRpc, kMalformed)).Times(1); connection_handler_->CloseSession(connection_key_, kMalformed); } TEST_F(ConnectionHandlerTest, CloseConnectionSessionsWithMalformedMessage) { AddTestDeviceConnection(); AddTestSession(); - + AddTestService(kAudio); + AddTestService(kMobileNav); connection_handler_test::ConnectionHandlerObserverMock mock_connection_handler_observer; connection_handler_->set_connection_handler_observer(&mock_connection_handler_observer); @@ -501,16 +573,24 @@ TEST_F(ConnectionHandlerTest, CloseConnectionSessionsWithMalformedMessage) { connection_handler_->set_protocol_handler(&mock_protocol_handler); EXPECT_CALL(mock_protocol_handler, SendEndSession(uid_,start_session_id_)).Times(0); - EXPECT_CALL(mock_connection_handler_observer, - OnServiceEndedCallback(connection_key_,_, kMalformed)).Times(2); + InSequence seq; + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kMobileNav, kMalformed)).Times(1); + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kAudio, kMalformed)).Times(1); + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kBulk, kMalformed)).Times(1); + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kRpc, kMalformed)).Times(1); connection_handler_->CloseConnectionSessions(uid_, kMalformed); } TEST_F(ConnectionHandlerTest, CloseConnectionSessionsWithCommonReason) { AddTestDeviceConnection(); AddTestSession(); - + AddTestService(kAudio); + AddTestService(kMobileNav); connection_handler_test::ConnectionHandlerObserverMock mock_connection_handler_observer; connection_handler_->set_connection_handler_observer(&mock_connection_handler_observer); @@ -518,9 +598,16 @@ TEST_F(ConnectionHandlerTest, CloseConnectionSessionsWithCommonReason) { connection_handler_->set_protocol_handler(&mock_protocol_handler); EXPECT_CALL(mock_protocol_handler, SendEndSession(uid_,start_session_id_)); - EXPECT_CALL(mock_connection_handler_observer, - OnServiceEndedCallback(connection_key_,_, kCommon)).Times(2); + InSequence seq; + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kMobileNav, kCommon)).Times(1); + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kAudio, kCommon)).Times(1); + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kBulk, kCommon)).Times(1); + EXPECT_CALL(mock_connection_handler_observer, + OnServiceEndedCallback(connection_key_,kRpc, kCommon)).Times(1); connection_handler_->CloseConnectionSessions(uid_, kCommon); } @@ -531,35 +618,35 @@ TEST_F(ConnectionHandlerTest, StartService_withServices) { // Start Audio service const uint32_t start_audio = connection_handler_->OnSessionStartedCallback( - uid, start_session_id, kAudio, PROTECTION_OFF, &out_hash_id); - EXPECT_EQ(start_session_id, start_audio); - CheckServiceExists(uid, start_session_id, kAudio, true); - EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id); + uid_, start_session_id_, kAudio, PROTECTION_OFF, &out_hash_id_); + EXPECT_EQ(start_session_id_, start_audio); + CheckServiceExists(uid_, start_session_id_, kAudio, true); + EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id_); // Start Audio service const uint32_t start_video = connection_handler_->OnSessionStartedCallback( - uid, start_session_id, kMobileNav, PROTECTION_OFF, &out_hash_id); - EXPECT_EQ(start_session_id, start_video); - CheckServiceExists(uid, start_session_id, kMobileNav, true); - EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id); + uid_, start_session_id_, kMobileNav, PROTECTION_OFF, &out_hash_id_); + EXPECT_EQ(start_session_id_, start_video); + CheckServiceExists(uid_, start_session_id_, kMobileNav, true); + EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id_); } TEST_F(ConnectionHandlerTest, ServiceStop_UnExistSession) { AddTestDeviceConnection(); - const uint32_t end_session_result = connection_handler_ - ->OnSessionEndedCallback(uid, 0u, 0u, kAudio); + const uint32_t end_session_result = connection_handler_->OnSessionEndedCallback( + uid_, 0u, 0u, kAudio); EXPECT_EQ(0u, end_session_result); - CheckSessionExists(uid, 0); + CheckSessionExists(uid_, 0); } TEST_F(ConnectionHandlerTest, ServiceStop_UnExistService) { AddTestDeviceConnection(); AddTestSession(); - const uint32_t end_session_result = connection_handler_ - ->OnSessionEndedCallback(uid, start_session_id, 0u, kAudio); + const uint32_t end_session_result = connection_handler_->OnSessionEndedCallback( + uid_, start_session_id_, 0u, kAudio); EXPECT_EQ(0u, end_session_result); - CheckServiceExists(uid, start_session_id, kAudio, false); + CheckServiceExists(uid_, start_session_id_, kAudio, false); } TEST_F(ConnectionHandlerTest, ServiceStop) { @@ -569,14 +656,14 @@ TEST_F(ConnectionHandlerTest, ServiceStop) { for (uint32_t some_hash_id = 0; some_hash_id < 0xFF; ++some_hash_id) { // Start audio service const uint32_t start_audio = connection_handler_->OnSessionStartedCallback( - uid, start_session_id, kAudio, PROTECTION_OFF, &out_hash_id); - EXPECT_EQ(start_session_id, start_audio); - EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id); - - const uint32_t end_session_result = connection_handler_ - ->OnSessionEndedCallback(uid, start_session_id, some_hash_id, kAudio); - EXPECT_EQ(connection_key, end_session_result); - CheckServiceExists(uid, start_session_id, kAudio, false); + uid_, start_session_id_, kAudio, PROTECTION_OFF, &out_hash_id_); + EXPECT_EQ(start_session_id_, start_audio); + EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id_); + + const uint32_t end_session_result = connection_handler_->OnSessionEndedCallback( + uid_, start_session_id_, some_hash_id, kAudio); + EXPECT_EQ(connection_key_, end_session_result); + CheckServiceExists(uid_, start_session_id_, kAudio, false); } } @@ -585,18 +672,18 @@ TEST_F(ConnectionHandlerTest, SessionStop_CheckHash) { for (uint32_t session = 0; session < 0xFF; ++session) { AddTestSession(); - const uint32_t hash = connection_key; + const uint32_t hash = connection_key_; const uint32_t wrong_hash = hash + 1; - const uint32_t end_audio_wrong_hash = connection_handler_ - ->OnSessionEndedCallback(uid, start_session_id, wrong_hash, kRpc); + const uint32_t end_audio_wrong_hash = connection_handler_->OnSessionEndedCallback( + uid_, start_session_id_, wrong_hash, kRpc); EXPECT_EQ(0u, end_audio_wrong_hash); - CheckSessionExists(uid, start_session_id); + CheckSessionExists(uid_, start_session_id_); const uint32_t end_audio = connection_handler_->OnSessionEndedCallback( - uid, start_session_id, hash, kRpc); - EXPECT_EQ(connection_key, end_audio); - CheckSessionExists(uid, 0); + uid_, start_session_id_, hash, kRpc); + EXPECT_EQ(connection_key_, end_audio); + CheckSessionExists(uid_, 0); } } @@ -608,15 +695,15 @@ TEST_F(ConnectionHandlerTest, SessionStop_CheckSpecificHash) { const uint32_t wrong_hash = protocol_handler::HASH_ID_WRONG; const uint32_t hash = protocol_handler::HASH_ID_NOT_SUPPORTED; - const uint32_t end_audio_wrong_hash = connection_handler_ - ->OnSessionEndedCallback(uid, start_session_id, wrong_hash, kRpc); + const uint32_t end_audio_wrong_hash = connection_handler_->OnSessionEndedCallback( + uid_, start_session_id_, wrong_hash, kRpc); EXPECT_EQ(0u, end_audio_wrong_hash); - CheckSessionExists(uid, start_session_id); + CheckSessionExists(uid_, start_session_id_); const uint32_t end_audio = connection_handler_->OnSessionEndedCallback( - uid, start_session_id, hash, kRpc); - EXPECT_EQ(connection_key, end_audio); - CheckSessionExists(uid, 0); + uid_, start_session_id_, hash, kRpc); + EXPECT_EQ(connection_key_, end_audio); + CheckSessionExists(uid_, 0); } } @@ -626,28 +713,24 @@ TEST_F(ConnectionHandlerTest, SessionStarted_StartSession_SecureSpecific_Unprote // Forbid start kRPC without encryption SetSpecificServices("0x07", ""); // Start new session with RPC service - const uint32_t session_id_fail = - connection_handler_->OnSessionStartedCallback(uid, 0, kRpc, - PROTECTION_OFF, - &out_hash_id); + const uint32_t session_id_fail = connection_handler_->OnSessionStartedCallback( + uid_, 0, kRpc, PROTECTION_OFF, &out_hash_id_); #ifdef ENABLE_SECURITY EXPECT_EQ(0u, session_id_fail); - EXPECT_EQ(protocol_handler::HASH_ID_WRONG, out_hash_id); + EXPECT_EQ(protocol_handler::HASH_ID_WRONG, out_hash_id_); #else EXPECT_EQ(1u, session_id_fail); - EXPECT_EQ(SessionHash(uid, session_id_fail), out_hash_id); + EXPECT_EQ(SessionHash(uid_, session_id_fail), out_hash_id_); #endif // ENABLE_SECURITY // Allow start kRPC without encryption SetSpecificServices("0x00, Non", ""); // Start new session with RPC service const uint32_t session_id = connection_handler_->OnSessionStartedCallback( - uid, 0, kRpc, PROTECTION_OFF, &out_hash_id); + uid_, 0, kRpc, PROTECTION_OFF, &out_hash_id_); EXPECT_NE(0u, session_id); - CheckService(uid, session_id, kRpc, - NULL, - PROTECTION_OFF); - EXPECT_EQ(SessionHash(uid, session_id), out_hash_id); + CheckService(uid_, session_id, kRpc, NULL, PROTECTION_OFF); + EXPECT_EQ(SessionHash(uid_, session_id), out_hash_id_); } TEST_F(ConnectionHandlerTest, SessionStarted_StartSession_SecureSpecific_Protect) { @@ -656,9 +739,8 @@ TEST_F(ConnectionHandlerTest, SessionStarted_StartSession_SecureSpecific_Protect // Forbid start kRPC with encryption SetSpecificServices("", "0x06, 0x07, 0x08, Non"); // Start new session with RPC service - const uint32_t session_id_fail = - connection_handler_->OnSessionStartedCallback(uid, 0, kRpc, PROTECTION_ON, - NULL); + const uint32_t session_id_fail = connection_handler_->OnSessionStartedCallback( + uid_, 0, kRpc, PROTECTION_ON, NULL); #ifdef ENABLE_SECURITY EXPECT_EQ(0u, session_id_fail); #else @@ -669,14 +751,12 @@ TEST_F(ConnectionHandlerTest, SessionStarted_StartSession_SecureSpecific_Protect SetSpecificServices("", "0x00, 0x05, Non"); // Start new session with RPC service const uint32_t session_id = connection_handler_->OnSessionStartedCallback( - uid, 0, kRpc, PROTECTION_ON, &out_hash_id); + uid_, 0, kRpc, PROTECTION_ON, &out_hash_id_); EXPECT_NE(0u, session_id); - EXPECT_EQ(SessionHash(uid, session_id), out_hash_id); + EXPECT_EQ(SessionHash(uid_, session_id), out_hash_id_); // Protection steal FALSE because of APPlink Protocol implementation - CheckService(uid, session_id, kRpc, - NULL, - PROTECTION_OFF); + CheckService(uid_, session_id, kRpc, NULL, PROTECTION_OFF); } TEST_F(ConnectionHandlerTest, SessionStarted_StartService_SecureSpecific_Unprotect) { @@ -690,7 +770,7 @@ TEST_F(ConnectionHandlerTest, SessionStarted_StartService_SecureSpecific_Unprote SetSpecificServices("0x06, 0x0A, 0x08, Non", ""); // Start new session with Audio service const uint32_t session_id2 = connection_handler_->OnSessionStartedCallback( - uid, start_session_id, kAudio, PROTECTION_OFF, NULL); + uid_, start_session_id_, kAudio, PROTECTION_OFF, NULL); #ifdef ENABLE_SECURITY EXPECT_EQ(0u, session_id2); #else @@ -699,17 +779,17 @@ TEST_F(ConnectionHandlerTest, SessionStarted_StartService_SecureSpecific_Unprote // Allow start kAudio without encryption SetSpecificServices("0x06, 0x0B, 0x08, Non", ""); const uint32_t session_id3 = connection_handler_->OnSessionStartedCallback( - uid, start_session_id, kAudio, PROTECTION_OFF, &out_hash_id); + uid_, start_session_id_, kAudio, PROTECTION_OFF, &out_hash_id_); // Returned original session id #ifdef ENABLE_SECURITY - EXPECT_EQ(start_session_id, session_id3); - EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id); - CheckService(uid, session_id3, kRpc, - NULL, - PROTECTION_OFF); + EXPECT_EQ(start_session_id_, session_id3); + EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id_); + CheckService(uid_, session_id3, kRpc, + NULL, + PROTECTION_OFF); #else EXPECT_EQ(0u, session_id3); - EXPECT_EQ(protocol_handler::HASH_ID_WRONG, out_hash_id); + EXPECT_EQ(protocol_handler::HASH_ID_WRONG, out_hash_id_); #endif // ENABLE_SECURITY } @@ -722,9 +802,8 @@ TEST_F(ConnectionHandlerTest, SessionStarted_StartService_SecureSpecific_Protect // Forbid start kAudio with encryption SetSpecificServices("", "0x06, 0x0A, 0x08, Non"); // Start new session with Audio service - const uint32_t session_id_reject = connection_handler_ - ->OnSessionStartedCallback(uid, start_session_id, kAudio, PROTECTION_ON, - NULL); + const uint32_t session_id_reject = connection_handler_->OnSessionStartedCallback( + uid_, start_session_id_, kAudio, PROTECTION_ON, NULL); #ifdef ENABLE_SECURITY EXPECT_EQ(0u, session_id_reject); #else @@ -733,20 +812,18 @@ TEST_F(ConnectionHandlerTest, SessionStarted_StartService_SecureSpecific_Protect // Allow start kAudio with encryption SetSpecificServices("", "Non"); const uint32_t session_id3 = connection_handler_->OnSessionStartedCallback( - uid, start_session_id, kAudio, PROTECTION_ON, &out_hash_id); + uid_, start_session_id_, kAudio, PROTECTION_ON, &out_hash_id_); // Returned original session id #ifdef ENABLE_SECURITY - EXPECT_EQ(start_session_id, session_id3); - EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id); - CheckService(uid, session_id3, kAudio, - NULL, - PROTECTION_ON); + EXPECT_EQ(start_session_id_, session_id3); + EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id_); + CheckService(uid_, session_id3, kAudio, + NULL, + PROTECTION_ON); #else EXPECT_EQ(0u, session_id3); - EXPECT_EQ(protocol_handler::HASH_ID_WRONG, out_hash_id); - CheckService(uid, start_session_id, kAudio, - NULL, - PROTECTION_OFF); + EXPECT_EQ(protocol_handler::HASH_ID_WRONG, out_hash_id_); + CheckService(uid_, start_session_id_, kAudio, NULL, PROTECTION_OFF); #endif // ENABLE_SECURITY } @@ -756,47 +833,41 @@ TEST_F(ConnectionHandlerTest, SessionStarted_DealyProtect) { // Start RPC protection const uint32_t session_id_new = connection_handler_->OnSessionStartedCallback( - uid, start_session_id, kRpc, PROTECTION_ON, &out_hash_id); + uid_, start_session_id_, kRpc, PROTECTION_ON, &out_hash_id_); #ifdef ENABLE_SECURITY - EXPECT_EQ(start_session_id, session_id_new); + EXPECT_EQ(start_session_id_, session_id_new); // Post protection nedd no hash - EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id); - CheckService(uid, start_session_id, kRpc, - NULL, - PROTECTION_ON); + EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id_); + CheckService(uid_, start_session_id_, kRpc, + NULL, + PROTECTION_ON); #else EXPECT_EQ(0u, session_id_new); - // Post protection nedd no hash - EXPECT_EQ(protocol_handler::HASH_ID_WRONG, out_hash_id); - CheckService(uid, start_session_id, kRpc, - NULL, - PROTECTION_OFF); + // Post protection nedd no hash + EXPECT_EQ(protocol_handler::HASH_ID_WRONG, out_hash_id_); + CheckService(uid_, start_session_id_, kRpc, NULL, PROTECTION_OFF); #endif // ENABLE_SECURITY // Start Audio session without protection const uint32_t session_id2 = connection_handler_->OnSessionStartedCallback( - uid, start_session_id, kAudio, PROTECTION_OFF, &out_hash_id); - EXPECT_EQ(start_session_id, session_id2); - EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id); - CheckService(uid, start_session_id, kAudio, - NULL, - PROTECTION_OFF); + uid_, start_session_id_, kAudio, PROTECTION_OFF, &out_hash_id_); + EXPECT_EQ(start_session_id_, session_id2); + EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id_); + CheckService(uid_, start_session_id_, kAudio, NULL, PROTECTION_OFF); // Start Audio protection const uint32_t session_id3 = connection_handler_->OnSessionStartedCallback( - uid, start_session_id, kAudio, PROTECTION_ON, &out_hash_id); + uid_, start_session_id_, kAudio, PROTECTION_ON, &out_hash_id_); #ifdef ENABLE_SECURITY - EXPECT_EQ(start_session_id, session_id3); - EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id); - CheckService(uid, start_session_id, kAudio, - NULL, - PROTECTION_ON); + EXPECT_EQ(start_session_id_, session_id3); + EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id_); + CheckService(uid_, start_session_id_, kAudio, + NULL, + PROTECTION_ON); #else EXPECT_EQ(0u, session_id3); - EXPECT_EQ(protocol_handler::HASH_ID_WRONG, out_hash_id); - CheckService(uid, start_session_id, kAudio, - NULL, - PROTECTION_OFF); + EXPECT_EQ(protocol_handler::HASH_ID_WRONG, out_hash_id_); + CheckService(uid_, start_session_id_, kAudio, NULL, PROTECTION_OFF); #endif // ENABLE_SECURITY } @@ -805,169 +876,168 @@ TEST_F(ConnectionHandlerTest, SessionStarted_DealyProtectBulk) { AddTestSession(); const uint32_t session_id_new = connection_handler_->OnSessionStartedCallback( - uid, start_session_id, kBulk, PROTECTION_ON, NULL); + uid_, start_session_id_, kBulk, PROTECTION_ON, NULL); #ifdef ENABLE_SECURITY - EXPECT_EQ(start_session_id, session_id_new); - CheckService(uid, start_session_id, kRpc, - NULL, - PROTECTION_ON); + EXPECT_EQ(start_session_id_, session_id_new); + CheckService(uid_, start_session_id_, kRpc, + NULL, + PROTECTION_ON); #else EXPECT_EQ(0u, session_id_new); - CheckService(uid, start_session_id, kRpc, - NULL, - PROTECTION_OFF); + CheckService(uid_, start_session_id_, kRpc, NULL, PROTECTION_OFF); #endif // ENABLE_SECURITY } #ifdef ENABLE_SECURITY TEST_F(ConnectionHandlerTest, SetSSLContext_Null) { // No SSLContext on start up - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kControl), - reinterpret_cast<security_manager::SSLContext *>(NULL)); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl), + reinterpret_cast<security_manager::SSLContext *>(NULL)); EXPECT_EQ(::security_manager::SecurityManager::ERROR_INTERNAL, - connection_handler_->SetSSLContext(connection_key, NULL)); + connection_handler_->SetSSLContext(connection_key_, NULL)); // No SSLContext after error - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kControl), - reinterpret_cast<security_manager::SSLContext *>(NULL)); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl), + reinterpret_cast<security_manager::SSLContext *>(NULL)); AddTestDeviceConnection(); EXPECT_EQ(::security_manager::SecurityManager::ERROR_INTERNAL, - connection_handler_->SetSSLContext(connection_key, NULL)); + connection_handler_->SetSSLContext(connection_key_, NULL)); // No SSLContext after error - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kControl), - reinterpret_cast<security_manager::SSLContext *>(NULL)); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl), + reinterpret_cast<security_manager::SSLContext *>(NULL)); AddTestSession(); EXPECT_EQ(::security_manager::SecurityManager::ERROR_SUCCESS, - connection_handler_->SetSSLContext(connection_key, NULL)); + connection_handler_->SetSSLContext(connection_key_, NULL)); // NULL SSLContext after success - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kControl), - reinterpret_cast<security_manager::SSLContext *>(NULL)); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl), + reinterpret_cast<security_manager::SSLContext *>(NULL)); } TEST_F(ConnectionHandlerTest, SetSSLContext) { // No SSLContext on start up - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kControl), - reinterpret_cast<security_manager::SSLContext *>(NULL)); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl), + reinterpret_cast<security_manager::SSLContext *>(NULL)); testing::StrictMock<security_manager_test::SSLContextMock> mock_ssl_context; // Error on no connection EXPECT_EQ( - connection_handler_->SetSSLContext(connection_key, &mock_ssl_context), + connection_handler_->SetSSLContext(connection_key_, &mock_ssl_context), ::security_manager::SecurityManager::ERROR_INTERNAL); // No SSLContext after error - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kControl), - reinterpret_cast<security_manager::SSLContext *>(NULL)); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl), + reinterpret_cast<security_manager::SSLContext *>(NULL)); AddTestDeviceConnection(); // Error on no session EXPECT_EQ( - connection_handler_->SetSSLContext(connection_key, &mock_ssl_context), + connection_handler_->SetSSLContext(connection_key_, &mock_ssl_context), ::security_manager::SecurityManager::ERROR_INTERNAL); // No SSLContext after error - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kControl), - reinterpret_cast<security_manager::SSLContext *>(NULL)); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl), + reinterpret_cast<security_manager::SSLContext *>(NULL)); AddTestSession(); // Success EXPECT_EQ( - connection_handler_->SetSSLContext(connection_key, &mock_ssl_context), + connection_handler_->SetSSLContext(connection_key_, &mock_ssl_context), ::security_manager::SecurityManager::ERROR_SUCCESS); // SSLContext set on Success - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kControl), - &mock_ssl_context); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl), + &mock_ssl_context); // Null SSLContext for unprotected services - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kRpc), - reinterpret_cast<security_manager::SSLContext *>(NULL)); - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kBulk), - reinterpret_cast<security_manager::SSLContext *>(NULL)); - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kAudio), - reinterpret_cast<security_manager::SSLContext *>(NULL)); - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kMobileNav), - reinterpret_cast<security_manager::SSLContext *>(NULL)); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kRpc), + reinterpret_cast<security_manager::SSLContext *>(NULL)); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kBulk), + reinterpret_cast<security_manager::SSLContext *>(NULL)); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kAudio), + reinterpret_cast<security_manager::SSLContext *>(NULL)); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kMobileNav), + reinterpret_cast<security_manager::SSLContext *>(NULL)); } TEST_F(ConnectionHandlerTest, GetSSLContext_ByProtectedService) { // No SSLContext on start up - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kControl), - reinterpret_cast<security_manager::SSLContext *>(NULL)); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl), + reinterpret_cast<security_manager::SSLContext *>(NULL)); testing::StrictMock<security_manager_test::SSLContextMock> mock_ssl_context; AddTestDeviceConnection(); AddTestSession(); EXPECT_EQ( - connection_handler_->SetSSLContext(connection_key, &mock_ssl_context), + connection_handler_->SetSSLContext(connection_key_, &mock_ssl_context), ::security_manager::SecurityManager::ERROR_SUCCESS); // kControl service mean - return for all connection - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kControl), - &mock_ssl_context); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl), + &mock_ssl_context); // kAudio is not exists yet - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kAudio), - reinterpret_cast<security_manager::SSLContext *>(NULL)); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kAudio), + reinterpret_cast<security_manager::SSLContext *>(NULL)); // Open kAudio service const uint32_t session_id = connection_handler_->OnSessionStartedCallback( - uid, start_session_id, kAudio, PROTECTION_ON, NULL); - EXPECT_EQ(session_id, start_session_id); - CheckService(uid, session_id, kAudio, &mock_ssl_context, PROTECTION_ON); + uid_, start_session_id_, kAudio, PROTECTION_ON, NULL); + EXPECT_EQ(session_id, start_session_id_); + CheckService(uid_, session_id, kAudio, &mock_ssl_context, PROTECTION_ON); // kAudio is not exists yet - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kAudio), - &mock_ssl_context); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kAudio), + &mock_ssl_context); } -TEST_F(ConnectionHandlerTest, GetSSLContext_ByDealyProtecteRPC) { +TEST_F(ConnectionHandlerTest, GetSSLContext_ByDealyProtectedRPC) { testing::StrictMock<security_manager_test::SSLContextMock> mock_ssl_context; AddTestDeviceConnection(); AddTestSession(); EXPECT_EQ( - connection_handler_->SetSSLContext(connection_key, &mock_ssl_context), + connection_handler_->SetSSLContext(connection_key_, &mock_ssl_context), ::security_manager::SecurityManager::ERROR_SUCCESS); - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kControl), - &mock_ssl_context); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl), + &mock_ssl_context); // kRpc is not protected - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kRpc), - reinterpret_cast<security_manager::SSLContext *>(NULL)); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kRpc), + reinterpret_cast<security_manager::SSLContext *>(NULL)); // Protect kRpc (Bulk will be protect also) const uint32_t session_id = connection_handler_->OnSessionStartedCallback( - uid, start_session_id, kRpc, PROTECTION_ON, NULL); - EXPECT_EQ(start_session_id, session_id); - CheckService(uid, session_id, kRpc, &mock_ssl_context, PROTECTION_ON); + uid_, start_session_id_, kRpc, PROTECTION_ON, NULL); + EXPECT_EQ(start_session_id_, session_id); + CheckService(uid_, session_id, kRpc, &mock_ssl_context, PROTECTION_ON); // kRpc is protected - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kRpc), - &mock_ssl_context); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kRpc), + &mock_ssl_context); // kBulk is protected - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kBulk), - &mock_ssl_context); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kBulk), + &mock_ssl_context); } -TEST_F(ConnectionHandlerTest, GetSSLContext_ByDealyProtecteBulk) { +TEST_F(ConnectionHandlerTest, GetSSLContext_ByDealyProtectedBulk) { testing::StrictMock<security_manager_test::SSLContextMock> mock_ssl_context; AddTestDeviceConnection(); AddTestSession(); EXPECT_EQ( - connection_handler_->SetSSLContext(connection_key, &mock_ssl_context), + connection_handler_->SetSSLContext(connection_key_, &mock_ssl_context), ::security_manager::SecurityManager::ERROR_SUCCESS); - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kControl), - &mock_ssl_context); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl), + &mock_ssl_context); // kRpc is not protected - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kRpc), - reinterpret_cast<security_manager::SSLContext *>(NULL)); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kRpc), + reinterpret_cast<security_manager::SSLContext *>(NULL)); // Protect Bulk (kRpc will be protected also) const uint32_t session_id = connection_handler_->OnSessionStartedCallback( - uid, start_session_id, kBulk, PROTECTION_ON, NULL); - EXPECT_EQ(start_session_id, session_id); - CheckService(uid, session_id, kRpc, &mock_ssl_context, PROTECTION_ON); + uid_, start_session_id_, kBulk, PROTECTION_ON, NULL); + EXPECT_EQ(start_session_id_, session_id); + CheckService(uid_, session_id, kRpc, &mock_ssl_context, PROTECTION_ON); // kRpc is protected - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kRpc), - &mock_ssl_context); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kRpc), + &mock_ssl_context); // kBulk is protected - EXPECT_EQ(connection_handler_->GetSSLContext(connection_key, kBulk), - &mock_ssl_context); + EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kBulk), + &mock_ssl_context); } #endif // ENABLE_SECURITY + } // namespace connection_handle_test } // namespace components } // namespace test diff --git a/src/components/connection_handler/test/connection_test.cc b/src/components/connection_handler/test/connection_test.cc index 9462f039c9..a1e9307ce3 100644 --- a/src/components/connection_handler/test/connection_test.cc +++ b/src/components/connection_handler/test/connection_test.cc @@ -37,6 +37,7 @@ #include "connection_handler/connection_handler_impl.h" #include "protocol/service_type.h" #include "utils/shared_ptr.h" +#include "security_manager_mock.h" #define EXPECT_RETURN_TRUE true #define EXPECT_RETURN_FALSE false @@ -46,17 +47,18 @@ namespace test { namespace components { namespace connection_handle { - using namespace ::connection_handler; - using namespace ::protocol_handler; +using namespace ::connection_handler; +using namespace ::protocol_handler; -class ConnectionTest: public ::testing::Test { +class ConnectionTest : public ::testing::Test { protected: void SetUp() OVERRIDE { connection_handler_ = ConnectionHandlerImpl::instance(); const ConnectionHandle connectionHandle = 0; const DeviceHandle device_handle = 0; - connection_.reset(new Connection(connectionHandle, device_handle, - connection_handler_, 10000)); + connection_.reset( + new Connection(connectionHandle, device_handle, connection_handler_, + 10000)); } void TearDown() OVERRIDE { @@ -70,16 +72,17 @@ class ConnectionTest: public ::testing::Test { EXPECT_FALSE(sessionMap.empty()); const ServiceList serviceList = sessionMap.begin()->second.service_list; EXPECT_FALSE(serviceList.empty()); - const ServiceList::const_iterator it = - std::find(serviceList.begin(), serviceList.end(), protocol_handler::kRpc); + const ServiceList::const_iterator it = std::find(serviceList.begin(), + serviceList.end(), + protocol_handler::kRpc); EXPECT_NE(it, serviceList.end()); } void AddNewService(const protocol_handler::ServiceType service_type, - const bool protection, - const bool expect_add_new_service_call_result, - const bool expect_exist_service) { - const bool result = connection_-> - AddNewService(session_id, service_type, protection); + const bool protection, + const bool expect_add_new_service_call_result, + const bool expect_exist_service) { + const bool result = connection_->AddNewService(session_id, service_type, + protection); EXPECT_EQ(result, expect_add_new_service_call_result); #ifdef ENABLE_SECURITY @@ -91,8 +94,9 @@ class ConnectionTest: public ::testing::Test { EXPECT_FALSE(session_map.empty()); const ServiceList newServiceList = session_map.begin()->second.service_list; EXPECT_FALSE(newServiceList.empty()); - const ServiceList::const_iterator it = - std::find(newServiceList.begin(), newServiceList.end(), service_type); + const ServiceList::const_iterator it = std::find(newServiceList.begin(), + newServiceList.end(), + service_type); const bool found_result = it != newServiceList.end(); EXPECT_EQ(expect_exist_service, found_result); #ifdef ENABLE_SECURITY @@ -106,16 +110,17 @@ class ConnectionTest: public ::testing::Test { void RemoveService(const protocol_handler::ServiceType service_type, const bool expect_remove_service_result, const bool expect_exist_service) { - const bool result = connection_-> - RemoveService(session_id, service_type); + const bool result = connection_->RemoveService(session_id, service_type); EXPECT_EQ(result, expect_remove_service_result); const SessionMap newSessionMap = connection_->session_map(); EXPECT_FALSE(newSessionMap.empty()); - const ServiceList newServiceList = newSessionMap.begin()->second.service_list; + const ServiceList newServiceList = newSessionMap.begin()->second + .service_list; EXPECT_FALSE(newServiceList.empty()); - const ServiceList::const_iterator it = - std::find(newServiceList.begin(), newServiceList.end(), service_type); + const ServiceList::const_iterator it = std::find(newServiceList.begin(), + newServiceList.end(), + service_type); const bool found_result = it != newServiceList.end(); EXPECT_EQ(expect_exist_service, found_result); } @@ -125,50 +130,89 @@ class ConnectionTest: public ::testing::Test { uint32_t session_id; }; + +TEST_F(ConnectionTest, Session_TryGetProtocolVersionWithoutSession) { + uint8_t protocol_version; + EXPECT_FALSE(connection_->ProtocolVersion(session_id, protocol_version)); +} + +TEST_F(ConnectionTest, Session_GetDefaultProtocolVersion) { + StartSession(); + uint8_t protocol_version; + EXPECT_TRUE(connection_->ProtocolVersion(session_id, protocol_version)); + EXPECT_EQ(protocol_version, ::protocol_handler::PROTOCOL_VERSION_2); +} +TEST_F(ConnectionTest, Session_UpdateProtocolVersion) { + StartSession(); + uint8_t protocol_version = ::protocol_handler::PROTOCOL_VERSION_3; + connection_->UpdateProtocolVersionSession(session_id, protocol_version); + EXPECT_TRUE(connection_->ProtocolVersion(session_id, protocol_version)); + EXPECT_EQ(protocol_version, ::protocol_handler::PROTOCOL_VERSION_3); +} + +TEST_F(ConnectionTest, HeartBeat_NotSupported) { + // Arrange + StartSession(); + uint8_t protocol_version; + EXPECT_TRUE(connection_->ProtocolVersion(session_id, protocol_version)); + EXPECT_EQ(protocol_version, ::protocol_handler::PROTOCOL_VERSION_2); + + // Assert + EXPECT_FALSE(connection_->SupportHeartBeat(session_id)); +} + +TEST_F(ConnectionTest, DISABLED_HeartBeat_Supported) { + // Arrange + StartSession(); + + // Check if protocol version is 3 + uint8_t protocol_version = ::protocol_handler::PROTOCOL_VERSION_3; + connection_->UpdateProtocolVersionSession(session_id, protocol_version); + EXPECT_EQ(protocol_version, ::protocol_handler::PROTOCOL_VERSION_3); + + // Assert + EXPECT_TRUE(connection_->SupportHeartBeat(session_id)); +} + // Try to add service without session TEST_F(ConnectionTest, Session_AddNewServiceWithoutSession) { - EXPECT_EQ(connection_-> - AddNewService(session_id, protocol_handler::kAudio, true), - EXPECT_RETURN_FALSE); - EXPECT_EQ(connection_-> - AddNewService(session_id, protocol_handler::kAudio, false), - EXPECT_RETURN_FALSE); - EXPECT_EQ(connection_-> - AddNewService(session_id, protocol_handler::kMobileNav, true), - EXPECT_RETURN_FALSE); - EXPECT_EQ(connection_-> - AddNewService(session_id, protocol_handler::kMobileNav, false), - EXPECT_RETURN_FALSE); + EXPECT_EQ( + connection_->AddNewService(session_id, protocol_handler::kAudio, true), + EXPECT_RETURN_FALSE); + EXPECT_EQ( + connection_->AddNewService(session_id, protocol_handler::kAudio, false), + EXPECT_RETURN_FALSE); + EXPECT_EQ( + connection_->AddNewService(session_id, protocol_handler::kMobileNav, true), + EXPECT_RETURN_FALSE); + EXPECT_EQ( + connection_->AddNewService(session_id, protocol_handler::kMobileNav, false), + EXPECT_RETURN_FALSE); } // Try to remove service without session TEST_F(ConnectionTest, Session_RemoveServiceWithoutSession) { - EXPECT_EQ(connection_-> - RemoveService(session_id, protocol_handler::kAudio), - EXPECT_RETURN_FALSE); - EXPECT_EQ(connection_-> - RemoveService(session_id, protocol_handler::kMobileNav), + EXPECT_EQ(connection_->RemoveService(session_id, protocol_handler::kAudio), EXPECT_RETURN_FALSE); + EXPECT_EQ( + connection_->RemoveService(session_id, protocol_handler::kMobileNav), + EXPECT_RETURN_FALSE); } // Try to remove RPC TEST_F(ConnectionTest, Session_RemoveRPCBulk) { StartSession(); - EXPECT_EQ(connection_-> - RemoveService(session_id, protocol_handler::kRpc), + EXPECT_EQ(connection_->RemoveService(session_id, protocol_handler::kRpc), EXPECT_RETURN_FALSE); - EXPECT_EQ(connection_-> - RemoveService(session_id, protocol_handler::kBulk), + EXPECT_EQ(connection_->RemoveService(session_id, protocol_handler::kBulk), EXPECT_RETURN_FALSE); } // Control Service could not be started anyway TEST_F(ConnectionTest, Session_AddControlService) { StartSession(); - AddNewService(protocol_handler::kControl, PROTECTION_OFF, - EXPECT_RETURN_FALSE, + AddNewService(protocol_handler::kControl, PROTECTION_OFF, EXPECT_RETURN_FALSE, EXPECT_SERVICE_NOT_EXISTS); - AddNewService(protocol_handler::kControl, PROTECTION_ON, - EXPECT_RETURN_FALSE, + AddNewService(protocol_handler::kControl, PROTECTION_ON, EXPECT_RETURN_FALSE, EXPECT_SERVICE_NOT_EXISTS); } @@ -177,89 +221,107 @@ TEST_F(ConnectionTest, Session_AddInvalidService) { StartSession(); AddNewService(protocol_handler::kInvalidServiceType, PROTECTION_OFF, - EXPECT_RETURN_FALSE, - EXPECT_SERVICE_NOT_EXISTS); + EXPECT_RETURN_FALSE, EXPECT_SERVICE_NOT_EXISTS); AddNewService(protocol_handler::kInvalidServiceType, PROTECTION_ON, - EXPECT_RETURN_FALSE, - EXPECT_SERVICE_NOT_EXISTS); + EXPECT_RETURN_FALSE, EXPECT_SERVICE_NOT_EXISTS); } // RPC and Bulk Services could be only delay protected TEST_F(ConnectionTest, Session_AddRPCBulkServices) { StartSession(); AddNewService(protocol_handler::kRpc, PROTECTION_OFF, - EXPECT_RETURN_FALSE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS); // Bulk shall not be added and shall be PROTECTION_OFF AddNewService(protocol_handler::kBulk, PROTECTION_OFF, - EXPECT_RETURN_FALSE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS); #ifdef ENABLE_SECURITY AddNewService(protocol_handler::kRpc, PROTECTION_ON, - EXPECT_RETURN_TRUE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_TRUE, + EXPECT_SERVICE_EXISTS); #else AddNewService(protocol_handler::kRpc, PROTECTION_ON, - EXPECT_RETURN_FALSE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS); #endif // ENABLE_SECURITY // Bulk shall not be added and shall be PROTECTION_ON AddNewService(protocol_handler::kBulk, PROTECTION_ON, - EXPECT_RETURN_FALSE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS); } TEST_F(ConnectionTest, Session_AddAllOtherService_Unprotected) { StartSession(); AddNewService(protocol_handler::kAudio, PROTECTION_OFF, - EXPECT_RETURN_TRUE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS); AddNewService(protocol_handler::kMobileNav, PROTECTION_OFF, - EXPECT_RETURN_TRUE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS); } TEST_F(ConnectionTest, Session_AddAllOtherService_Protected) { StartSession(); AddNewService(protocol_handler::kAudio, PROTECTION_ON, - EXPECT_RETURN_TRUE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS); AddNewService(protocol_handler::kMobileNav, PROTECTION_ON, - EXPECT_RETURN_TRUE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS); +} + +TEST_F(ConnectionTest, FindAddedService) { + StartSession(); + + // Arrange + SessionMap currentSessionMap = connection_->session_map(); + Service * sessionWithService = currentSessionMap.find(session_id)->second + .FindService(protocol_handler::kAudio); + EXPECT_EQ(NULL, sessionWithService); + + // Act + AddNewService(protocol_handler::kAudio, PROTECTION_OFF, + EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS); + + currentSessionMap = connection_->session_map(); + + // Expect that service is existing + sessionWithService = currentSessionMap.find(session_id)->second.FindService( + protocol_handler::kAudio); + EXPECT_TRUE(sessionWithService != NULL); +} + +TEST_F(ConnectionTest, Session_RemoveAddedService) { + StartSession(); + AddNewService(protocol_handler::kAudio, PROTECTION_OFF, + EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS); + + EXPECT_EQ(connection_->RemoveService(session_id, protocol_handler::kAudio), + EXPECT_RETURN_TRUE); + + // Try delete nonexisting service + EXPECT_EQ(connection_->RemoveService(session_id, protocol_handler::kAudio), + EXPECT_RETURN_FALSE); } TEST_F(ConnectionTest, Session_AddAllOtherService_DelayProtected1) { StartSession(); AddNewService(protocol_handler::kAudio, PROTECTION_OFF, - EXPECT_RETURN_TRUE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS); AddNewService(protocol_handler::kMobileNav, PROTECTION_OFF, - EXPECT_RETURN_TRUE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS); #ifdef ENABLE_SECURITY AddNewService(protocol_handler::kAudio, PROTECTION_ON, - EXPECT_RETURN_TRUE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS); AddNewService(protocol_handler::kMobileNav, PROTECTION_ON, - EXPECT_RETURN_TRUE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS); #else AddNewService(protocol_handler::kAudio, PROTECTION_ON, - EXPECT_RETURN_FALSE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS); AddNewService(protocol_handler::kMobileNav, PROTECTION_ON, - EXPECT_RETURN_FALSE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS); #endif // ENABLE_SECURITY } @@ -268,32 +330,121 @@ TEST_F(ConnectionTest, Session_AddAllOtherService_DelayProtected2) { StartSession(); AddNewService(protocol_handler::kAudio, PROTECTION_OFF, - EXPECT_RETURN_TRUE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS); #ifdef ENABLE_SECURITY AddNewService(protocol_handler::kAudio, PROTECTION_ON, - EXPECT_RETURN_TRUE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_TRUE, + EXPECT_SERVICE_EXISTS); #else AddNewService(protocol_handler::kAudio, PROTECTION_ON, - EXPECT_RETURN_FALSE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS); #endif // ENABLE_SECURITY AddNewService(protocol_handler::kMobileNav, PROTECTION_OFF, - EXPECT_RETURN_TRUE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS); #ifdef ENABLE_SECURITY AddNewService(protocol_handler::kMobileNav, PROTECTION_ON, - EXPECT_RETURN_TRUE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS); #else AddNewService(protocol_handler::kMobileNav, PROTECTION_ON, - EXPECT_RETURN_FALSE, - EXPECT_SERVICE_EXISTS); + EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS); #endif // ENABLE_SECURITY } +TEST_F(ConnectionTest, RemoveSession) { + StartSession(); + EXPECT_EQ(session_id, connection_->RemoveSession(session_id)); + EXPECT_EQ(0u, connection_->RemoveSession(session_id)); +} + +#ifdef ENABLE_SECURITY + +TEST_F(ConnectionTest, SetSSLContextWithoutSession) { + //random value. Session was not started + uint8_t session_id = 10; + security_manager_test::SSLContextMock mock_ssl_context; + int setResult = connection_->SetSSLContext(session_id, &mock_ssl_context); + EXPECT_EQ(security_manager::SecurityManager::ERROR_INTERNAL,setResult); +} + +TEST_F(ConnectionTest, GetSSLContextWithoutSession) { + //random value. Session was not started + uint8_t session_id = 10; + + EXPECT_EQ(NULL,connection_->GetSSLContext(session_id,protocol_handler::kMobileNav)); +} + +TEST_F(ConnectionTest, SetGetSSLContext) { + StartSession(); + + EXPECT_EQ(NULL,connection_->GetSSLContext(session_id,protocol_handler::kMobileNav)); + AddNewService(protocol_handler::kMobileNav, PROTECTION_ON, + EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS); + + EXPECT_EQ(NULL,connection_->GetSSLContext(session_id,protocol_handler::kMobileNav)); + + security_manager_test::SSLContextMock mock_ssl_context; + //Set SSLContext + int setResult = connection_->SetSSLContext(session_id, &mock_ssl_context); + EXPECT_EQ(security_manager::SecurityManager::ERROR_SUCCESS,setResult); + + security_manager::SSLContext *result = connection_->GetSSLContext(session_id,protocol_handler::kMobileNav); + EXPECT_EQ(result,&mock_ssl_context); +} + +TEST_F(ConnectionTest, SetProtectionFlagForRPC) { + StartSession(); + // Arrange + SessionMap currentSessionMap = connection_->session_map(); + Service * service_rpc = currentSessionMap.find(session_id)->second + .FindService(protocol_handler::kRpc); + + EXPECT_FALSE(service_rpc->is_protected_); + + Service * service_bulk = currentSessionMap.find(session_id)->second + .FindService(protocol_handler::kBulk); + EXPECT_FALSE(service_bulk->is_protected_); + + // Expect that service protection is enabled + connection_->SetProtectionFlag(session_id, protocol_handler::kRpc); + + currentSessionMap = connection_->session_map(); + service_bulk = currentSessionMap.find(session_id)->second + .FindService(protocol_handler::kBulk); + EXPECT_TRUE(service_bulk->is_protected_); + + service_rpc = currentSessionMap.find(session_id)->second + .FindService(protocol_handler::kRpc); + EXPECT_TRUE(service_rpc->is_protected_); +} + + +TEST_F(ConnectionTest, SetProtectionFlagForBulk) { + StartSession(); + // Arrange + SessionMap currentSessionMap = connection_->session_map(); + Service * service_rpc = currentSessionMap.find(session_id)->second + .FindService(protocol_handler::kRpc); + + EXPECT_FALSE(service_rpc->is_protected_); + + Service * service_bulk = currentSessionMap.find(session_id)->second + .FindService(protocol_handler::kBulk); + EXPECT_FALSE(service_bulk->is_protected_); + + // Expect that service protection is enabled + connection_->SetProtectionFlag(session_id, protocol_handler::kBulk); + + currentSessionMap = connection_->session_map(); + service_bulk = currentSessionMap.find(session_id)->second.FindService(protocol_handler::kBulk); + EXPECT_TRUE(service_bulk->is_protected_); + + service_rpc = currentSessionMap.find(session_id)->second.FindService(protocol_handler::kRpc); + EXPECT_TRUE(service_rpc->is_protected_); +} + +#endif // ENABLE_SECURITY + } // namespace connection_handle } // namespace components } // namespace test diff --git a/src/components/connection_handler/test/device_test.cc b/src/components/connection_handler/test/device_test.cc new file mode 100644 index 0000000000..dc1a51faf1 --- /dev/null +++ b/src/components/connection_handler/test/device_test.cc @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2015, 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. + */ + +#include <gtest/gtest.h> +#include "encryption/hashing.h" +#include "connection_handler/device.h" + +namespace test { +namespace components { +namespace connection_handle { + +using namespace connection_handler; +TEST(ConnectionDevice, CompareDevicesWithDifferentMacAddresses) { + DeviceHandle device_handle = 0; + + std::string connection_type = "BTMAC"; + std::string device_name = "test_name"; + std::string mac_address = "test_address"; + + Device test_device(device_handle, device_name, mac_address, connection_type); + + EXPECT_EQ(device_handle, test_device.device_handle()); + EXPECT_EQ(device_name, test_device.user_friendly_name()); + EXPECT_NE(mac_address, test_device.mac_address()); + EXPECT_EQ(connection_type, test_device.connection_type()); + std::string hash_mac_address = test_device.mac_address(); + + std::string test_next_mac_address = "test_address_"; + Device next_test_device(device_handle, device_name, test_next_mac_address, connection_type); + EXPECT_NE(test_next_mac_address, next_test_device.mac_address()); + std::string hash_next_mac_address = next_test_device.mac_address(); + + EXPECT_NE(hash_mac_address, hash_next_mac_address); +} + +TEST(ConnectionDevice, MacAddressHash) { + DeviceHandle device_handle = 0; + std::string connection_type = "BTMAC"; + std::string device_name = "test_name"; + std::string mac_address = "test_address"; + + Device test_device(device_handle, device_name, mac_address, connection_type); + + std::string hashed_mac_address = encryption::MakeHash(mac_address); + EXPECT_EQ(hashed_mac_address, test_device.mac_address()); +} + +} // namespace connection_handle +} // namespace components +} // namespace test + 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 f4a1708de5..710977c643 100644 --- a/src/components/connection_handler/test/heart_beat_monitor_test.cc +++ b/src/components/connection_handler/test/heart_beat_monitor_test.cc @@ -31,6 +31,7 @@ */ #include <string> +#include <iostream> //#include <stdio.h> #include "gmock/gmock.h" #include "connection_handler/heartbeat_monitor.h" @@ -38,6 +39,12 @@ #include "connection_handler/connection_handler.h" #include "config_profile/profile.h" +namespace { +const int32_t MILLISECONDS_IN_SECOND = 1000; +const int32_t MICROSECONDS_IN_MILLISECONDS = 1000; +const int32_t MICROSECONDS_IN_SECOND = 1000 * 1000; +} + namespace test { namespace components { namespace connection_handler_test { @@ -62,6 +69,7 @@ class ConnectionHandlerMock : public connection_handler::ConnectionHandler { MOCK_METHOD2(GetDeviceID, bool(const std::string& mac_address, connection_handler::DeviceHandle* device_handle)); + MOCK_CONST_METHOD1(GetConnectedDevicesMAC, void(std::vector<std::string> &device_macs)); MOCK_METHOD2(CloseSession, void(uint32_t key, connection_handler::CloseSessionReason close_reason)); @@ -78,10 +86,14 @@ class ConnectionHandlerMock : public connection_handler::ConnectionHandler { void(connection_handler::ConnectionHandle connection_handle, uint8_t session_id)); MOCK_METHOD2(SetHeartBeatTimeout, void(uint32_t connection_key, - int32_t timeout)); + uint32_t timeout)); MOCK_METHOD2(BindProtocolVersionWithSession, void(uint32_t connection_key, uint8_t protocol_version)); + MOCK_METHOD4(GetDataOnSessionKey, + int32_t(uint32_t key, uint32_t* app_id, + std::list<int32_t>* sessions_list, + uint32_t* device_id)); }; class HeartBeatMonitorTest : public testing::Test { @@ -95,7 +107,7 @@ public: protected: testing::NiceMock<ConnectionHandlerMock> connection_handler_mock; connection_handler::Connection* conn; - int32_t kTimeout; + uint32_t kTimeout; static const connection_handler::ConnectionHandle kConnectionHandle = 0xABCDEF; virtual void SetUp() { @@ -122,7 +134,7 @@ TEST_F(HeartBeatMonitorTest, TimerNotStarted) { EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, _)).Times(0); conn->AddNewSession(); - sleep(kTimeout + 1); + usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND); } TEST_F(HeartBeatMonitorTest, TimerNotElapsed) { @@ -132,7 +144,7 @@ TEST_F(HeartBeatMonitorTest, TimerNotElapsed) { const uint32_t session = conn->AddNewSession(); conn->StartHeartBeat(session); - sleep(kTimeout - 1); + usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND); } TEST_F(HeartBeatMonitorTest, TimerElapsed) { @@ -144,7 +156,7 @@ TEST_F(HeartBeatMonitorTest, TimerElapsed) { EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, session)); conn->StartHeartBeat(session); - sleep(2 * kTimeout + 1); + usleep(2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND); } TEST_F(HeartBeatMonitorTest, KeptAlive) { @@ -154,13 +166,13 @@ TEST_F(HeartBeatMonitorTest, KeptAlive) { const uint32_t session = conn->AddNewSession(); conn->StartHeartBeat(session); - sleep(kTimeout - 1); + usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND); conn->KeepAlive(session); - sleep(kTimeout - 1); + usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND); conn->KeepAlive(session); - sleep(kTimeout - 1); + usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND); conn->KeepAlive(session); - sleep(kTimeout - 1); + usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND); } TEST_F(HeartBeatMonitorTest, NotKeptAlive) { @@ -172,13 +184,13 @@ TEST_F(HeartBeatMonitorTest, NotKeptAlive) { EXPECT_CALL(connection_handler_mock, CloseConnection(_)); conn->StartHeartBeat(session); - sleep(kTimeout - 1); + usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND); conn->KeepAlive(session); - sleep(kTimeout - 1); + usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND); conn->KeepAlive(session); - sleep(kTimeout - 1); + usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND); conn->KeepAlive(session); - sleep(2 * kTimeout + 1); + usleep(2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND); } TEST_F(HeartBeatMonitorTest, TwoSessionsElapsed) { @@ -195,7 +207,7 @@ TEST_F(HeartBeatMonitorTest, TwoSessionsElapsed) { conn->StartHeartBeat(kSession1); conn->StartHeartBeat(kSession2); - sleep(2 * kTimeout + 1); + usleep(2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND); } TEST_F(HeartBeatMonitorTest, IncreaseHeartBeatTimeout) { @@ -206,25 +218,26 @@ TEST_F(HeartBeatMonitorTest, IncreaseHeartBeatTimeout) { EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, _)).Times(0); - const int32_t kNewTimeout = kTimeout + 1; + 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 - sleep(kTimeout); + usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS); } TEST_F(HeartBeatMonitorTest, DecreaseHeartBeatTimeout) { const uint32_t kSession = conn->AddNewSession(); - EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, kSession)); + EXPECT_CALL(connection_handler_mock, CloseSession(_, kSession,_)) .WillOnce(RemoveSession(conn, kSession)); EXPECT_CALL(connection_handler_mock, CloseConnection(_)); + EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, kSession)); - const int32_t kNewTimeout = kTimeout - 1; + 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 - sleep(kTimeout*2); + usleep(kTimeout * 2 * MICROSECONDS_IN_MILLISECONDS); } } // namespace connection_handler_test diff --git a/src/components/connection_handler/test/include/connection_handler_observer_mock.h b/src/components/connection_handler/test/include/connection_handler_observer_mock.h new file mode 100644 index 0000000000..9a74375262 --- /dev/null +++ b/src/components/connection_handler/test/include/connection_handler_observer_mock.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2015, 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. + */ + +#ifndef SRC_COMPONENTS_CONNECTION_HANDLER_TEST_INCLUDE_CONNECTION_HANDLER_OBSERVER_MOCK_H_ +#define SRC_COMPONENTS_CONNECTION_HANDLER_TEST_INCLUDE_CONNECTION_HANDLER_OBSERVER_MOCK_H_ + +#include <gmock/gmock.h> +#include <string> +#include "connection_handler/connection_handler_observer.h" + +namespace test { +namespace components { +namespace connection_handler_test { + +/* + * MOCK implementation of ::connection_handler::ConnectionHandlerObserver interface + */ +class ConnectionHandlerObserverMock : public ::connection_handler::ConnectionHandlerObserver { + public: + MOCK_METHOD1(OnDeviceListUpdated, + void(const connection_handler::DeviceMap &device_list)); + MOCK_METHOD0(OnFindNewApplicationsRequest,void()); + MOCK_METHOD1(RemoveDevice, + void(const connection_handler::DeviceHandle &device_handle)); + MOCK_METHOD3(OnServiceStartedCallback, + bool(const connection_handler::DeviceHandle &device_handle, + const int32_t &session_key, + const protocol_handler::ServiceType &type)); + MOCK_METHOD3(OnServiceEndedCallback, + void(const int32_t &session_key, + const protocol_handler::ServiceType &type, + const connection_handler::CloseSessionReason& close_reason)); + MOCK_CONST_METHOD1(GetHandshakeContext, + security_manager::SSLContext::HandshakeContext( + uint32_t key)); + +}; +} // namespace connection_handler_test +} // namespace components +} // namespace test +#endif //SRC_COMPONENTS_CONNECTION_HANDLER_TEST_INCLUDE_CONNECTION_HANDLER_OBSERVER_MOCK_H_ diff --git a/src/components/connection_handler/test/smartDeviceLink.ini b/src/components/connection_handler/test/smartDeviceLink.ini index 0e79edf3ac..109003eb5f 100644 --- a/src/components/connection_handler/test/smartDeviceLink.ini +++ b/src/components/connection_handler/test/smartDeviceLink.ini @@ -58,7 +58,7 @@ AppTimeScaleMaxRequests = 1000 AppRequestsTimeScale = 10 ; Allowed pending requests amount. If value is 0 check will be skipped PendingRequestsAmount = 5000 -HeartBeatTimeout = 7 +HeartBeatTimeout = 7000 SupportedDiagModes = 0x01, 0x02, 0x03, 0x05, 0x06, 0x07, 0x09, 0x0A, 0x18, 0x19, 0x22, 0x3E SystemFilesPath = /tmp/fs/mp/images/ivsu_cache UseLastState = true diff --git a/src/components/formatters/test/CFormatterJsonBase_test.cc b/src/components/formatters/test/CFormatterJsonBase_test.cc new file mode 100644 index 0000000000..9efbfdcf77 --- /dev/null +++ b/src/components/formatters/test/CFormatterJsonBase_test.cc @@ -0,0 +1,337 @@ +/* + * Copyright (c) 2015, 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. + */ + +#include <string> +#include <algorithm> +#include "json/value.h" +#include "gtest/gtest.h" +#include "json/reader.h" +#include "formatters/CFormatterJsonBase.hpp" +#include "formatters/generic_json_formatter.h" + +namespace test { +namespace components { +namespace formatters { + +using namespace NsSmartDeviceLink::NsSmartObjects; +using namespace NsSmartDeviceLink::NsJSONHandler::Formatters; + +TEST(CFormatterJsonBaseTest, JSonStringValueToSmartObj_ExpectSuccessful) { + // Arrange value + std::string string_val("test_string"); + Json::Value json_value(string_val); // Json value from string + SmartObject object; + // Convert json to smart object + CFormatterJsonBase::jsonValueToObj(json_value, object); + // Check conversion was successful + EXPECT_EQ(string_val, object.asString()); +} + +TEST(CFormatterJsonBaseTest, JSonDoubleValueToSmartObj_ExpectSuccessful) { + // Arrange value + double dval = 3.512; + Json::Value json_value(dval); // Json value from double + SmartObject object; + // Convert json to smart object + CFormatterJsonBase::jsonValueToObj(json_value, object); + // Check conversion was successful + EXPECT_DOUBLE_EQ(dval, object.asDouble()); +} + +TEST(CFormatterJsonBaseTest, JSonMinIntValueToSmartObj_ExpectSuccessful) { + // Arrange value + Json::Int ival = Json::Value::minInt; + Json::Value json_value(ival); // Json value from possible minimum signed int + SmartObject object; + // Convert json to smart object + CFormatterJsonBase::jsonValueToObj(json_value, object); + // Check conversion was successful + EXPECT_EQ(ival, object.asInt()); +} + +TEST(CFormatterJsonBaseTest, JSonNullIntValueToSmartObj_ExpectSuccessful) { + // Arrange value + Json::Int ival = Json::nullValue; + Json::Value json_value(ival); // Json value from null int value + SmartObject object; + // Convert json to smart object + CFormatterJsonBase::jsonValueToObj(json_value, object); + // Check conversion was successful + EXPECT_EQ(ival, object.asInt()); +} + +TEST(CFormatterJsonBaseTest, JSonSignedMaxIntValueToSmartObj_ExpectSuccessful) { + // Arrange value + Json::Int ival = Json::Value::maxInt; + Json::Value json_value(ival); // Json value from maximum possible signed int + SmartObject object; + // Convert json to smart object + CFormatterJsonBase::jsonValueToObj(json_value, object); + // Check conversion was successful + EXPECT_EQ(ival, object.asInt()); +} + +TEST(CFormatterJsonBaseTest, DISABLED_JSonUnsignedMaxIntValueToSmartObj_ExpectSuccessful) { + // Arrange value + Json::UInt ui_val = Json::Value::maxUInt; + Json::Value json_value(ui_val); // Json value from maximum possible unsigned int + SmartObject object; + // Convert json to smart object + CFormatterJsonBase::jsonValueToObj(json_value, object); + // Check conversion was successful + EXPECT_EQ(ui_val, object.asUInt()); +} + +TEST(CFormatterJsonBaseTest, JSonSignedMaxInt64ValueToSmartObj_ExpectFailed) { + // Arrange value + Json::Int64 ival = Json::Value::maxInt64; + Json::Value json_value(ival); // Json value from maximum possible signed int + SmartObject object; + // Convert json to smart object + CFormatterJsonBase::jsonValueToObj(json_value, object); + // Check conversion was not successful as there is no such conversion + EXPECT_EQ(invalid_int64_value, object.asInt64()); +} + +TEST(CFormatterJsonBaseTest, JSonBoolValueToSmartObj_ExpectSuccessful) { + // Arrange value + bool bval1 = true; + bool bval2 = false; + Json::Value json_value1(bval1); // Json value from bool + Json::Value json_value2(bval2); // Json value from bool + SmartObject object1; + SmartObject object2; + // Convert json to smart object + CFormatterJsonBase::jsonValueToObj(json_value1, object1); + CFormatterJsonBase::jsonValueToObj(json_value2, object2); + // Check conversion was successful + EXPECT_TRUE(object1.asBool()); + EXPECT_FALSE(object2.asBool()); +} + +TEST(CFormatterJsonBaseTest, JSonCStringValueToSmartObj_ExpectSuccessful) { + // Arrange value + const char* cstr_val = "cstring_test"; + Json::Value json_value(cstr_val); // Json value from const char* + SmartObject object; + // Convert json to smart object + CFormatterJsonBase::jsonValueToObj(json_value, object); + // Check conversion was successful + EXPECT_STREQ(cstr_val, object.asCharArray()); +} + +TEST(CFormatterJsonBaseTest, JSonArrayValueToSmartObj_ExpectSuccessful) { + // Arrange value + const char* json_array = "[\"test1\", \"test2\", \"test3\"]"; // Array in json format + Json::Value json_value; // Json value from array. Will be initialized later + SmartObject object; + Json::Reader reader; // Json reader - Needed for correct parsing + // Parse array to json value + ASSERT_TRUE(reader.parse(json_array, json_value)); + // Convert json array to SmartObject + CFormatterJsonBase::jsonValueToObj(json_value, object); + // Check conversion was successful + EXPECT_TRUE(json_value.isArray()); + EXPECT_EQ(3u, object.asArray()->size()); + SmartArray *ptr = NULL; // Smart Array pointer; + EXPECT_NE(ptr, object.asArray()); +} + +TEST(CFormatterJsonBaseTest, JSonObjectValueToSmartObj_ExpectSuccessful) { + // Arrange value + const char* json_object = + "{ \"json_test_object\": [\"test1\", \"test2\", \"test3\"], \"json_test_object2\": [\"test11\", \"test12\", \"test13\" ]}"; // Json object + Json::Value json_value; // Json value from object. Will be initialized later + SmartObject object; + Json::Reader reader; // Json reader - Needed for correct parsing + ASSERT_TRUE(reader.parse(json_object, json_value)); // If parsing not successful - no sense to continue + CFormatterJsonBase::jsonValueToObj(json_value, object); + // Check conversion was successful + EXPECT_TRUE(json_value.isObject()); + EXPECT_TRUE(json_value.type() == Json::objectValue); + // Get keys collection from Smart Object + std::set<std::string> keys = object.enumerate(); + std::set<std::string>::iterator it1 = keys.begin(); + // Get members names(keys) from Json object + Json::Value::Members mems = json_value.getMemberNames(); + std::vector<std::string>::iterator it; + // Compare sizes + EXPECT_EQ(mems.size(), keys.size()); + // Sort mems + std::sort(mems.begin(), mems.end()); + // Full data compare + for (it = mems.begin(); it != mems.end(); ++it) { + EXPECT_EQ(*it, *it1); + ++it1; + } + ASSERT(it == mems.end() && it1 == keys.end()); +} + +TEST(CFormatterJsonBaseTest, StringSmartObjectToJSon_ExpectSuccessful) { + // Arrange value + std::string string_val("test_string"); + SmartObject object(string_val); + Json::Value json_value; // Json value from string + // Convert smart object to json + CFormatterJsonBase::objToJsonValue(object, json_value); + // Check conversion was successful + EXPECT_EQ(string_val, json_value.asString()); +} + +TEST(CFormatterJsonBaseTest, DoubleSmartObjectToJSon_ExpectSuccessful) { + // Arrange value + double dval = 3.512; + Json::Value json_value; // Json value from double + SmartObject object(dval); + // Convert json to smart object + CFormatterJsonBase::objToJsonValue(object, json_value); + // Check conversion was successful + EXPECT_DOUBLE_EQ(dval, json_value.asDouble()); +} + +TEST(CFormatterJsonBaseTest, ZeroIntSmartObjectToJSon_ExpectSuccessful) { + // Arrange value + Json::Int ival = Json::nullValue; + Json::Value json_value; // Json value from zero int + SmartObject object(ival); + // Convert json to smart object + CFormatterJsonBase::objToJsonValue(object, json_value); + // Check conversion was successful + EXPECT_EQ(ival, json_value.asInt()); +} + +TEST(CFormatterJsonBaseTest, MinIntSmartObjectToJSon_ExpectSuccessful) { + // Arrange value + Json::Int ival = Json::Value::minInt; + Json::Value json_value; // Json value from mimimum possible signed int + SmartObject object(ival); + // Convert json to smart object + CFormatterJsonBase::objToJsonValue(object, json_value); + // Check conversion was successful + EXPECT_EQ(ival, json_value.asInt()); +} + +TEST(CFormatterJsonBaseTest, DISABLED_UnsignedMaxIntSmartObjectToJSon_ExpectSuccessful) { + // Arrange value + Json::UInt ui_val = Json::Value::maxUInt; + Json::Value json_value; // Json value from maximum unsigned int + SmartObject object(ui_val); + // Convert json to smart object + CFormatterJsonBase::objToJsonValue(object, json_value); + // Check conversion was successful + EXPECT_EQ(ui_val, json_value.asUInt()); +} + +TEST(CFormatterJsonBaseTest, BoolSmartObjectToJSon_ExpectSuccessful) { + // Arrange value + bool bval1 = true; + bool bval2 = false; + Json::Value json_value1; // Json value from bool + Json::Value json_value2; // Json value from bool + SmartObject object1(bval1); + SmartObject object2(bval2); + // Convert json to smart object + CFormatterJsonBase::objToJsonValue(object1, json_value1); + CFormatterJsonBase::objToJsonValue(object2, json_value2); + // Check conversion was successful + EXPECT_TRUE(json_value1.asBool()); + EXPECT_FALSE(json_value2.asBool()); +} + +TEST(CFormatterJsonBaseTest, CStringSmartObjectToJSon_ExpectSuccessful) { + // Arrange value + const char* cstr_val = "cstring_test"; + Json::Value json_value; // Json value from const char* + SmartObject object(cstr_val); + // Convert json to smart object + CFormatterJsonBase::objToJsonValue(object, json_value); + // Check conversion was successful + EXPECT_STREQ(cstr_val, json_value.asCString()); +} + +TEST(CFormatterJsonBaseTest, ArraySmartObjectToJSon_ExpectSuccessful) { + // Arrange value + const char* json_array = "[\"test1\", \"test2\", \"test3\"]"; // Array in json format + Json::Value json_value; // Json value from array. Will be initialized later + Json::Value result; // Json value from array. Will be initialized later + SmartObject object; + Json::Reader reader; // Json reader - Needed for correct parsing + // Parse array to json value + ASSERT_TRUE(reader.parse(json_array, json_value)); // Convert json array to SmartObject + // Convert json array to SmartObject + CFormatterJsonBase::jsonValueToObj(json_value, object); + // Convert SmartObject to JSon + CFormatterJsonBase::objToJsonValue(object, result); + // Check conversion was successful + EXPECT_TRUE(result.isArray()); + EXPECT_EQ(3u, result.size()); +} + +TEST(CFormatterJsonBaseTest, JSonObjectValueToObj_ExpectSuccessful) { + // Arrange value + const char* json_object = + "{ \"json_test_object\": [\"test1\", \"test2\", \"test3\"], \"json_test_object2\": [\"test11\", \"test12\", \"test13\" ]}"; // Json object + Json::Value json_value; // Json value from json object. Will be initialized later + Json::Value result; // Json value from Smart object. Will keep conversion result + SmartObject object; + Json::Reader reader; // Json reader - Needed for correct parsing + // Parse json object to correct json value + ASSERT_TRUE(reader.parse(json_object, json_value)); // If parsing not successful - no sense to continue + // Convert json array to SmartObject + CFormatterJsonBase::jsonValueToObj(json_value, object); + // Convert SmartObject to JSon + CFormatterJsonBase::objToJsonValue(object, result); + // Check conversion was successful + EXPECT_TRUE(result.isObject()); + EXPECT_TRUE(result.type() == Json::objectValue); + EXPECT_TRUE(result == json_value); + // Get keys collection from Smart Object + std::set<std::string> keys = object.enumerate(); + std::set<std::string>::iterator it1 = keys.begin(); + // Get members names(keys) from Json object + Json::Value::Members mems = result.getMemberNames(); + std::vector<std::string>::iterator it; + // Compare sizes + EXPECT_EQ(mems.size(), keys.size()); + // Sort mems + std::sort(mems.begin(), mems.end()); + // Full data compare + for (it = mems.begin(); it != mems.end(); ++it) { + EXPECT_EQ(*it, *it1); + ++it1; + } + ASSERT(it == mems.end() && it1 == keys.end()); +} + +} // namespace formatters +} // namespace components +} // namespace test diff --git a/src/components/formatters/test/CMakeLists.txt b/src/components/formatters/test/CMakeLists.txt index cbe9a2190e..b9966c8670 100644 --- a/src/components/formatters/test/CMakeLists.txt +++ b/src/components/formatters/test/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2014, Ford Motor Company +# Copyright (c) 2015, Ford Motor Company # All rights reserved. # # Redistribution and use in source and binary forms, with or without @@ -35,19 +35,33 @@ include_directories( ${GMOCK_INCLUDE_DIRECTORY} ${COMPONENTS_DIR}/smart_objects/include ${COMPONENTS_DIR}/formatters/include + ${COMPONENTS_DIR}/formatters/test/include + ${CMAKE_BINARY_DIR}/src/components/interfaces + ${CMAKE_SOURCE_DIR}/src/3rd_party-static/jsoncpp/include ) set(LIBRARIES - gmock - SmartObjects - formatters - jsoncpp + gmock + HMI_API + MOBILE_API + SmartObjects + formatters + jsoncpp ) set(SOURCES -${COMPONENTS_DIR}/formatters/test/generic_json_formatter_test.cc + ${COMPONENTS_DIR}/formatters/test/src/SmartFactoryTestHelper.cc + ${COMPONENTS_DIR}/formatters/test/CSmartFactory_test.cc + ${COMPONENTS_DIR}/formatters/test/CFormatterJsonBase_test.cc + ${COMPONENTS_DIR}/formatters/test/generic_json_formatter_test.cc + ${COMPONENTS_DIR}/formatters/test/formatter_json_rpc_test.cc + ${COMPONENTS_DIR}/formatters/test/src/create_smartSchema.cc + ${COMPONENTS_DIR}/formatters/test/cFormatterJsonSDLRPCv1_test.cc + ${COMPONENTS_DIR}/formatters/test/cFormatterJsonSDLRPCv2_test.cc + ${COMPONENTS_DIR}/formatters/test/src/meta_formatter_test_helper.cc + ${COMPONENTS_DIR}/formatters/test/meta_formatter_test.cc ) -create_test("generic_json_formatter_test" "${SOURCES}" "${LIBRARIES}") +create_test("formatters_test" "${SOURCES}" "${LIBRARIES}") endif() diff --git a/src/components/formatters/test/CSmartFactory_test.cc b/src/components/formatters/test/CSmartFactory_test.cc new file mode 100644 index 0000000000..39cf67b3fd --- /dev/null +++ b/src/components/formatters/test/CSmartFactory_test.cc @@ -0,0 +1,397 @@ +/* + * Copyright (c) 2015, 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. + */ + +#include "SmartFactoryTestHelper.h" +#include "formatters/CSmartFactory.hpp" +#include "gtest/gtest.h" + +namespace test { +namespace components { +namespace formatters { + +TEST(CSmartFactoryTest, CreateSmartSchemaKey_ExpectCreated) { + SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType> test_key( + FunctionIdTest::Function1, MessageTypeTest::notification); + EXPECT_EQ(test_key.functionId, FunctionIdTest::Function1); + EXPECT_EQ(test_key.messageType, MessageTypeTest::notification); +} + +TEST(CSmartFactoryTest, CreateSmartFactory_ExpectCreated) { + CSmartFactoryTest test_factory; + EXPECT_EQ(9u, test_factory.function_schemes().size()); + EXPECT_EQ(2u, test_factory.structs_schemes().size()); +} + +TEST(CSmartFactoryTest, CreateSmartObjWithSchema1_ExpectCreatedObjectToCorrespondSmSchema1) { + CSmartFactoryTest test_factory; + // Create SmartObject with attached SmartChmema + SmartObject obj = test_factory.CreateSmartObject(FunctionIdTest::Function1, + MessageTypeTest::request); + EXPECT_TRUE(SmartType::SmartType_Map == obj.getType()); + // Adding necessary fields + obj[S_PARAMS][S_FUNCTION_ID] = FunctionIdTest::Function1; + obj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request; + obj[S_PARAMS][S_CORRELATION_ID] = 444; + obj[S_PARAMS][S_PROTOCOL_VERSION] = 1; + obj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map); + std::set<std::string> keys = obj.enumerate(); + EXPECT_EQ(2u, keys.size()); + EXPECT_EQ(Errors::eType::OK, obj.validate()); + EXPECT_TRUE(obj.isValid()); +} + +TEST(CSmartFactoryTest, CreateSmartObjWithNotExistedSchema_ExpectCreatedObjectNotValid) { + CSmartFactoryTest test_factory; + // Create SmartObject with attached SmartChmema + SmartObject obj = test_factory.CreateSmartObject( + FunctionIdTest::Function1, MessageTypeTest::INVALID_ENUM); + EXPECT_FALSE(SmartType::SmartType_Map == obj.getType()); + EXPECT_TRUE(SmartType::SmartType_Null == obj.getType()); + EXPECT_EQ(Errors::eType::OK, obj.validate()); + EXPECT_TRUE(obj.isValid()); +} + +TEST(CSmartFactoryTest, CreateSmartObjectWithSchema1_MissedOneField_ExpectCreatedNotCorrespondSmartSchema) { + CSmartFactoryTest test_factory; + // Create SmartObject with attached SmartChmema + SmartObject obj = test_factory.CreateSmartObject(FunctionIdTest::Function1, + MessageTypeTest::request); + EXPECT_TRUE(SmartType::SmartType_Map == obj.getType()); + // Adding necessary fields but one field is missed + obj[S_PARAMS][S_FUNCTION_ID] = FunctionIdTest::Function1; + obj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request; + obj[S_PARAMS][S_PROTOCOL_VERSION] = 1; + obj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map); + std::set<std::string> keys = obj.enumerate(); + EXPECT_EQ(2u, keys.size()); + EXPECT_EQ(Errors::eType::MISSING_MANDATORY_PARAMETER, obj.validate()); + EXPECT_FALSE(obj.isValid()); +} + +TEST(CSmartFactoryTest, CreateSmartObjectWithSchema1_AddOutOfRangeValue_ExpectCreatedNotCorrespondSmartSchema) { + CSmartFactoryTest test_factory; + // Create SmartObject with attached SmartChmema + SmartObject obj = test_factory.CreateSmartObject(FunctionIdTest::Function1, + MessageTypeTest::request); + EXPECT_TRUE(SmartType::SmartType_Map == obj.getType()); + // Adding necessary fields but one field is missed + obj[S_PARAMS][S_FUNCTION_ID] = FunctionIdTest::Function1; + obj[S_PARAMS][S_MESSAGE_TYPE] = 5; + obj[S_PARAMS][S_PROTOCOL_VERSION] = 1; + obj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + obj[S_PARAMS][S_CORRELATION_ID] = 444; + obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map); + std::set<std::string> keys = obj.enumerate(); + EXPECT_EQ(2u, keys.size()); + EXPECT_EQ(Errors::eType::OUT_OF_RANGE, obj.validate()); + EXPECT_FALSE(obj.isValid()); +} + +TEST(CSmartFactoryTest, CreateSmartObjectWithSchema1_AddInvalidValue_ExpectCreatedNotCorrespondSmartSchema) { + CSmartFactoryTest test_factory; + // Create SmartObject with attached SmartChmema + SmartObject obj = test_factory.CreateSmartObject(FunctionIdTest::Function1, + MessageTypeTest::request); + EXPECT_TRUE(SmartType::SmartType_Map == obj.getType()); + // Adding necessary fields but one field is missed + obj[S_PARAMS][S_FUNCTION_ID] = FunctionIdTest::Function1; + obj[S_PARAMS][S_MESSAGE_TYPE] = "return"; + obj[S_PARAMS][S_PROTOCOL_VERSION] = 1; + obj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + obj[S_PARAMS][S_CORRELATION_ID] = 444; + obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map); + std::set<std::string> keys = obj.enumerate(); + EXPECT_EQ(2u, keys.size()); + EXPECT_EQ(Errors::eType::INVALID_VALUE, obj.validate()); + EXPECT_FALSE(obj.isValid()); +} + +TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema1_ExpectCreatedObjectCorrespondsSmSchema1) { + CSmartFactoryTest test_factory; + // Create empty SmartObject without any schema + SmartObject obj; + // Adding fields necessary for schema to attach + obj[S_PARAMS][S_FUNCTION_ID] = FunctionIdTest::Function1; + obj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request; + // Attach schema to object + EXPECT_TRUE(test_factory.attachSchema(obj)); + EXPECT_TRUE(SmartType::SmartType_Map == obj.getType()); + // Adding necessary fileds to correspond schema + obj[S_PARAMS][S_CORRELATION_ID] = 444; + obj[S_PARAMS][S_PROTOCOL_VERSION] = 1; + obj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map); + std::set<std::string> keys = obj.enumerate(); + EXPECT_EQ(2u, keys.size()); + EXPECT_EQ(Errors::eType::OK, obj.validate()); + EXPECT_TRUE(obj.isValid()); +} + +TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema1_MissOneField_ExpectCreatedObjectNotCorrespondsSmSchema1) { + CSmartFactoryTest test_factory; + // Create empty SmartObject without any schema + SmartObject obj; + // Adding fields necessary for schema to attach + obj[S_PARAMS][S_FUNCTION_ID] = FunctionIdTest::Function1; + obj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request; + // Attach schema to object + EXPECT_TRUE(test_factory.attachSchema(obj)); + EXPECT_TRUE(SmartType::SmartType_Map == obj.getType()); + // Adding necessary fileds to correspond schema but 1 field is missing + obj[S_PARAMS][S_PROTOCOL_VERSION] = 1; + obj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map); + std::set<std::string> keys = obj.enumerate(); + EXPECT_EQ(2u, keys.size()); + EXPECT_EQ(Errors::eType::MISSING_MANDATORY_PARAMETER, obj.validate()); + EXPECT_FALSE(obj.isValid()); +} + +TEST(CSmartFactoryTest, CreateSmartObj_AttachNotExistedSchema_ExpectSmSchemaNotAttached) { + CSmartFactoryTest test_factory; + // Create empty SmartObject without any schema + SmartObject obj; + // Adding fields necessary for schema to attach but one value is invalid + obj[S_PARAMS][S_FUNCTION_ID] = FunctionIdTest::Function1; + obj[S_PARAMS][S_MESSAGE_TYPE] = 10; + // Attach schema to object + EXPECT_FALSE(test_factory.attachSchema(obj)); + EXPECT_TRUE(SmartType::SmartType_Map == obj.getType()); +} + +TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema1_AddInvalidValue_ExpectCreatedObjectNotCorrespondsSmSchema1) { + CSmartFactoryTest test_factory; + // Create empty SmartObject without any schema + SmartObject obj; + // Adding fields necessary for schema to attach + obj[S_PARAMS][S_FUNCTION_ID] = FunctionIdTest::Function1; + obj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request; + // Attach schema to object + EXPECT_TRUE(test_factory.attachSchema(obj)); + EXPECT_TRUE(SmartType::SmartType_Map == obj.getType()); + // Adding necessary fileds to correspond schema but 1 field is missing + obj[S_PARAMS][S_PROTOCOL_VERSION] = "string"; + obj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + obj[S_PARAMS][S_CORRELATION_ID] = 444; + obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map); + std::set<std::string> keys = obj.enumerate(); + EXPECT_EQ(2u, keys.size()); + EXPECT_EQ(Errors::eType::INVALID_VALUE, obj.validate()); + EXPECT_FALSE(obj.isValid()); +} + +TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema1_ExpectCreatedObjectCorrespondsSmSchema) { + CSmartFactoryTest test_factory; + // Create empty SmartObject without any schema + SmartObject obj; + // Attach schema to object + EXPECT_TRUE(test_factory.AttachSchema(StructIdentifiersTest::Common_1, obj)); + obj["text"] = "test"; + obj["position"] = 200; + std::set<std::string> keys = obj.enumerate(); + EXPECT_EQ(2u, keys.size()); + EXPECT_EQ(Errors::eType::OK, obj.validate()); + EXPECT_TRUE(obj.isValid()); +} + +TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema1_OneMandatoryFieldMissed_ExpectCreatedObjectNotCorrespondsSmSchema) { + CSmartFactoryTest test_factory; + // Create empty SmartObject without any schema + SmartObject obj; + // Attach schema to object + EXPECT_TRUE(test_factory.AttachSchema(StructIdentifiersTest::Common_1, obj)); + obj["text"] = "test"; + std::set<std::string> keys = obj.enumerate(); + EXPECT_EQ(1u, keys.size()); + EXPECT_EQ(Errors::eType::MISSING_MANDATORY_PARAMETER, obj.validate()); + EXPECT_FALSE(obj.isValid()); +} + +TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema2_ExpectCreatedObjectCorrespondsSmSchema) { + CSmartFactoryTest test_factory; + // Create empty SmartObject without any schema + SmartObject obj; + // Attach schema to object + EXPECT_TRUE(test_factory.AttachSchema(StructIdentifiersTest::Common_2, obj)); + obj["text"] = "test1"; + obj["position"] = 200; + std::set<std::string> keys = obj.enumerate(); + EXPECT_EQ(2u, keys.size()); + EXPECT_EQ(Errors::eType::OK, obj.validate()); + EXPECT_TRUE(obj.isValid()); +} + +TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema_ExpectCreatedObjectCorrespondsSmSchema) { + CSmartFactoryTest test_factory; + // Create empty SmartObject without any schema + SmartObject obj; + // Attach schema to object + EXPECT_TRUE(test_factory.AttachSchema(StructIdentifiersTest::Common_1, obj)); + obj["text"] = "test"; + obj["position"] = 200; + obj["image"]["text"] = "test2"; + obj["image"]["position"] = 100; + EXPECT_EQ(Errors::eType::OK, obj["image"].validate()); + std::set<std::string> keys = obj.enumerate(); + EXPECT_EQ(3u, keys.size()); + EXPECT_EQ(Errors::eType::OK, obj.validate()); + EXPECT_TRUE(obj.isValid()); +} + +TEST(CSmartFactoryTest, CreateSmartObj_WithSchemaFromStructId_ExpectCreatedObjectCorrespondsSmSchema) { + CSmartFactoryTest test_factory; + // Create empty SmartObject with schema correspopnding StructId + SmartObject obj = test_factory.CreateSmartObject( + StructIdentifiersTest::Common_1); + // Add fields + obj["text"] = "test"; + obj["position"] = 200; + obj["image"]["text"] = "test2"; + obj["image"]["position"] = 100; + // Check object "image" + EXPECT_EQ(Errors::eType::OK, obj["image"].validate()); + std::set<std::string> keys = obj.enumerate(); + EXPECT_EQ(3u, keys.size()); + // Check global object + EXPECT_EQ(Errors::eType::OK, obj.validate()); + EXPECT_TRUE(obj.isValid()); +} + +TEST(CSmartFactoryTest, CreateSmartObj_WithSchemaFromStructId_MissedOneField_ExpectCreatedObjectNotCorrespondsSmSchema) { + CSmartFactoryTest test_factory; + // Create empty SmartObject with schema correspopnding StructId + SmartObject obj = test_factory.CreateSmartObject( + StructIdentifiersTest::Common_1); + // Add fields. One missed. + obj["text"] = "test"; + obj["image"]["text"] = "test2"; + obj["image"]["position"] = 100; + // Check object "image" + EXPECT_EQ(Errors::eType::OK, obj["image"].validate()); + std::set<std::string> keys = obj.enumerate(); + EXPECT_EQ(2u, keys.size()); + // Check global object + EXPECT_EQ(Errors::eType::MISSING_MANDATORY_PARAMETER, obj.validate()); + EXPECT_FALSE(obj.isValid()); +} + +TEST(CSmartFactoryTest, CreateSmartObj_WithSchemaFromStructId2_ExpectCreatedObjectCorrespondsSmSchema) { + CSmartFactoryTest test_factory; + // Create empty SmartObject with schema correspopnding StructId + SmartObject obj = test_factory.CreateSmartObject( + StructIdentifiersTest::Common_2); + // Add fields + obj["text"] = "test"; + obj["position"] = 200; + obj["image"]["text"] = "test2"; + obj["image"]["position"] = 100; + // Check object "image" + EXPECT_EQ(Errors::eType::OK, obj["image"].validate()); + std::set<std::string> keys = obj.enumerate(); + EXPECT_EQ(3u, keys.size()); + // Check global object + EXPECT_EQ(Errors::eType::OK, obj.validate()); + EXPECT_TRUE(obj.isValid()); +} + +TEST(CSmartFactoryTest, CreateSmartObj_WithSchemaFromStructId2_MissedOneField_ExpectCreatedObjectNotCorrespondsSmSchema) { + CSmartFactoryTest test_factory; + // Create empty SmartObject with schema correspopnding StructId + SmartObject obj = test_factory.CreateSmartObject( + StructIdentifiersTest::Common_2); + // Add fields. One missed. + obj["text"] = "test"; + obj["image"]["text"] = "test2"; + std::set<std::string> keys = obj.enumerate(); + EXPECT_EQ(2u, keys.size()); + // Check global object + EXPECT_EQ(Errors::eType::MISSING_MANDATORY_PARAMETER, obj.validate()); + EXPECT_FALSE(obj.isValid()); +} + +TEST(CSmartFactoryTest, CreateSmartObj_WithSchemaFromStructId2_InvalidValueAdded_ExpectCreatedObjectNotCorrespondsSmSchema) { + CSmartFactoryTest test_factory; + // Create empty SmartObject with schema correspopnding StructId + SmartObject obj = test_factory.CreateSmartObject( + StructIdentifiersTest::Common_2); + // Add fields. One missed. + obj["text"] = 111; + obj["position"] = 200; + obj["image"]["text"] = "test2"; + std::set<std::string> keys = obj.enumerate(); + EXPECT_EQ(3u, keys.size()); + // Check global object + EXPECT_EQ(Errors::eType::INVALID_VALUE, obj.validate()); + EXPECT_FALSE(obj.isValid()); +} + +TEST(CSmartFactoryTest, GetSchemaWithSmartFactory_ExpectReceivedSchema) { + CSmartFactoryTest test_factory; + CSmartSchema schema; + EXPECT_TRUE( + test_factory.GetSchema(FunctionIdTest::Function1, + MessageTypeTest::request, schema)); +} + +TEST(CSmartFactoryTest, GetNotExistedSchemaWithSmartFactory_ExpectNotReceivedSchema) { + CSmartFactoryTest test_factory; + CSmartSchema schema; + EXPECT_FALSE( + test_factory.GetSchema(FunctionIdTest::Function1, + MessageTypeTest::INVALID_ENUM, schema)); +} + +TEST(CSmartFactoryTest, GetSchemaWithSmartFactoryWithStructId1_ExpectReceivedSchema) { + CSmartFactoryTest test_factory; + CSmartSchema schema; + EXPECT_TRUE(test_factory.GetSchema(StructIdentifiersTest::Common_1, schema)); +} + +TEST(CSmartFactoryTest, GetSchemaWithSmartFactoryWithStructId2_ExpectReceivedSchema) { + CSmartFactoryTest test_factory; + CSmartSchema schema; + EXPECT_TRUE(test_factory.GetSchema(StructIdentifiersTest::Common_2, schema)); +} + +TEST(CSmartFactoryTest, GetNotExistedSchemaWithSmartFactoryWithStructId_ExpectNotReceivedSchema) { + CSmartFactoryTest test_factory; + CSmartSchema schema; + EXPECT_FALSE( + test_factory.GetSchema(StructIdentifiersTest::INVALID_ENUM, schema)); +} + +} // namespace formatters +} // namespace components +} // namespace test + diff --git a/src/components/formatters/test/cFormatterJsonSDLRPCv1_test.cc b/src/components/formatters/test/cFormatterJsonSDLRPCv1_test.cc new file mode 100644 index 0000000000..55b7f886fd --- /dev/null +++ b/src/components/formatters/test/cFormatterJsonSDLRPCv1_test.cc @@ -0,0 +1,502 @@ +/* + * Copyright (c) 2015, 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. + */ + +#include "gtest/gtest.h" + +#include "formatters/CFormatterJsonSDLRPCv1.hpp" +#include "create_smartSchema.h" + +namespace test { +namespace components { +namespace formatters { + +TEST(CFormatterJsonSDLRPCv1Test, EmptySmartObjectToString) { + SmartObject srcObj; + + EXPECT_EQ(Errors::eType::OK, srcObj.validate()); + + std::string jsonString; + bool result = CFormatterJsonSDLRPCv1::toString(srcObj, jsonString); + + EXPECT_TRUE(result); + + std::string expectOutputJsonString = + "{\n \ + \"\" : {\n\ + \"name\" : \"\",\n\ + \"parameters\" : \"\"\n\ + }\n\ +}\n"; + + EXPECT_EQ(expectOutputJsonString, jsonString); +} + +TEST(CFormatterJsonSDLRPCv1Test, SmObjWithRequestWithoutMsgNotValid_ToString) { + SmartObject srcObj; + CSmartSchema schema = initObjectSchema(); + srcObj.setSchema(schema); + + srcObj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request; + srcObj[S_PARAMS][S_FUNCTION_ID] = FunctionIDTest::RegisterAppInterface; + srcObj[S_PARAMS][S_CORRELATION_ID] = 13; + srcObj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + srcObj[S_PARAMS][S_PROTOCOL_VERSION] = 1; + + EXPECT_EQ(Errors::eType::MISSING_MANDATORY_PARAMETER, srcObj.validate()); + + std::string jsonString; + bool result = CFormatterJsonSDLRPCv1::toString(srcObj, jsonString); + EXPECT_TRUE(result); + + std::string expectOutputJsonString = + "{\n \ + \"request\" : {\n\ + \"correlationID\" : 13,\n\ + \"name\" : \"RegisterAppInterface\",\n\ + \"parameters\" : \"\"\n\ + }\n\ +}\n"; + + EXPECT_EQ(expectOutputJsonString, jsonString); +} + +TEST(CFormatterJsonSDLRPCv1Test, SmObjWithRequestWithEmptyMsgWithTestSchemaToString) { + SmartObject srcObj; + CSmartSchema schema = initObjectSchema(); + srcObj.setSchema(schema); + + srcObj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request; + srcObj[S_PARAMS][S_FUNCTION_ID] = FunctionIDTest::RegisterAppInterface; + srcObj[S_PARAMS][S_CORRELATION_ID] = 13; + srcObj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + srcObj[S_PARAMS][S_PROTOCOL_VERSION] = 1; + srcObj[S_MSG_PARAMS][""] = ""; + + EXPECT_EQ(Errors::eType::OK, srcObj.validate()); + + std::string jsonString; + + bool result = CFormatterJsonSDLRPCv1::toString(srcObj, jsonString); + + EXPECT_TRUE(result); + + std::string expectOutputJsonString = + "{\n \ + \"request\" : {\n\ + \"correlationID\" : 13,\n\ + \"name\" : \"RegisterAppInterface\",\n\ + \"parameters\" : {}\n\ + }\n\ +}\n"; + + EXPECT_EQ(expectOutputJsonString, jsonString); +} + +TEST(CFormatterJsonSDLRPCv1Test, SmObjWithRequestWithNonemptyMsgWithTestSchemaToString) { + SmartObject srcObj; + CSmartSchema schema = initObjectSchema(); + srcObj.setSchema(schema); + + srcObj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request; + srcObj[S_PARAMS][S_FUNCTION_ID] = FunctionIDTest::RegisterAppInterface; + srcObj[S_PARAMS][S_CORRELATION_ID] = 13; + srcObj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + srcObj[S_PARAMS][S_PROTOCOL_VERSION] = 1; + srcObj[S_MSG_PARAMS]["info"] = "value"; + + std::string jsonString; + + bool result = CFormatterJsonSDLRPCv1::toString(srcObj, jsonString); + + EXPECT_TRUE(result); + + std::string expectOutputJsonString = + "{\n \ + \"request\" : {\n\ + \"correlationID\" : 13,\n\ + \"name\" : \"RegisterAppInterface\",\n\ + \"parameters\" : {\n\ + \"info\" : \"value\"\n\ + }\n\ + }\n\ +}\n"; + + EXPECT_EQ(expectOutputJsonString, jsonString); +} + +TEST(CFormatterJsonSDLRPCv1Test, SmObjWithRequestWithNonemptyMsgToString) { + SmartObject srcObj; + + srcObj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request; + srcObj[S_PARAMS][S_FUNCTION_ID] = 5; + srcObj[S_PARAMS][S_CORRELATION_ID] = 13; + srcObj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + srcObj[S_PARAMS][S_PROTOCOL_VERSION] = 1; + srcObj[S_MSG_PARAMS]["vrSynonyms"][0] = "Synonym 1"; + + std::string jsonString; + + bool result = CFormatterJsonSDLRPCv1::toString(srcObj, jsonString); + + EXPECT_TRUE(result); + + std::string expectOutputJsonString = + "{\n \ + \"0\" : {\n\ + \"correlationID\" : 13,\n\ + \"name\" : \"5\",\n\ + \"parameters\" : {\n\ + \"vrSynonyms\" : [ \"Synonym 1\" ]\n\ + }\n\ + }\n\ +}\n"; + EXPECT_EQ(expectOutputJsonString, jsonString); +} + +TEST(CFormatterJsonSDLRPCv1Test, SmObjWithResponseWithoutSchemaToString) { + SmartObject srcObj; + + srcObj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::response; + srcObj[S_PARAMS][S_FUNCTION_ID] = 5; + srcObj[S_PARAMS][S_CORRELATION_ID] = 13; + srcObj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + srcObj[S_PARAMS][S_PROTOCOL_VERSION] = 1; + srcObj[S_MSG_PARAMS]["success"] = true; + srcObj[S_MSG_PARAMS]["resultCode"] = 0; + + std::string jsonString; + + bool result = CFormatterJsonSDLRPCv1::toString(srcObj, jsonString); + + EXPECT_TRUE(result); + + std::string expectOutputJsonString = + "{\n \ + \"1\" : {\n\ + \"correlationID\" : 13,\n\ + \"name\" : \"5\",\n\ + \"parameters\" : {\n\ + \"resultCode\" : 0,\n\ + \"success\" : true\n\ + }\n\ + }\n\ +}\n"; + EXPECT_EQ(expectOutputJsonString, jsonString); +} + +TEST(CFormatterJsonSDLRPCv1Test, SmObjWithNotificationToString) { + SmartObject srcObj; + CSmartSchema schema = initObjectSchema(); + srcObj.setSchema(schema); + + srcObj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::notification; + srcObj[S_PARAMS][S_FUNCTION_ID] = FunctionIDTest::SetGlobalProperties; + srcObj[S_PARAMS][S_CORRELATION_ID] = 13; + srcObj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + srcObj[S_PARAMS][S_PROTOCOL_VERSION] = 1; + srcObj[S_MSG_PARAMS][""] = ""; + std::string jsonString; + + bool result = CFormatterJsonSDLRPCv1::toString(srcObj, jsonString); + + EXPECT_TRUE(result); + + std::string expectOutputJsonString = + "{\n \ + \"notification\" : {\n\ + \"correlationID\" : 13,\n\ + \"name\" : \"SetGlobalProperties\",\n\ + \"parameters\" : {}\n\ + }\n\ +}\n"; + + EXPECT_EQ(expectOutputJsonString, jsonString); +} + +TEST(CFormatterJsonSDLRPCv1Test, SmObjWithResponseToString) { + SmartObject srcObj; + + CSmartSchema schema = initObjectSchema(); + srcObj.setSchema(schema); + + srcObj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::response; + srcObj[S_PARAMS][S_FUNCTION_ID] = FunctionIDTest::RegisterAppInterface; + srcObj[S_PARAMS][S_CORRELATION_ID] = 13; + srcObj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + srcObj[S_PARAMS][S_PROTOCOL_VERSION] = 1; + + srcObj[S_MSG_PARAMS]["success"] = true; + srcObj[S_MSG_PARAMS]["resultCode"] = TestType::SUCCESS; + + std::string jsonString; + + bool result = CFormatterJsonSDLRPCv1::toString(srcObj, jsonString); + + EXPECT_TRUE(result); + + std::string expectOutputJsonString = + "{\n \ + \"response\" : {\n\ + \"correlationID\" : 13,\n\ + \"name\" : \"RegisterAppInterface\",\n\ + \"parameters\" : {\n\ + \"resultCode\" : \"SUCCESS\",\n\ + \"success\" : true\n\ + }\n\ + }\n\ +}\n"; + + EXPECT_EQ(expectOutputJsonString, jsonString); +} + +TEST(CFormatterJsonSDLRPCv1Test, SmObjWithResponseWithoutSchemaWithoutParamsToString) { + SmartObject srcObj; + srcObj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::response; + std::string jsonString; + + bool result = CFormatterJsonSDLRPCv1::toString(srcObj, jsonString); + + EXPECT_TRUE(result); + + std::string expectOutputJsonString = + "{\n \ + \"1\" : {\n\ + \"name\" : \"\",\n\ + \"parameters\" : \"\"\n\ + }\n\ +}\n"; + + EXPECT_EQ(expectOutputJsonString, jsonString); +} + +TEST(CFormatterJsonSDLRPCv1Test, StringRequestToSmObj) { + std::string inputJsonString = + "\ + {\ + \"request\": {\ + \"correlationID\": 5,\ + \"name\" : \"RegisterAppInterface\",\n\ + \"parameters\": {\ + \"syncMsgVersion\" : {\ + \"majorVersion\" : 2,\ + \"minorVersion\" : 10\ + },\ + \"appName\": \"some app name\",\ + \"ttsName\": [{\ + \"text\": \"ABC\",\ + \"type\": \"TEXT\"\ + }],\ + \"vrSynonyms\": [\"Synonym 1\", \"Synonym 2\"]\ + }\ + }\ + }"; + + SmartObject obj; + + CSmartSchema schema = initObjectSchema(); + obj.setSchema(schema); + + bool result = CFormatterJsonSDLRPCv1::fromString<FunctionIDTest::eType, + MessageTypeTest::eType>(inputJsonString, obj); + + EXPECT_EQ(CFormatterJsonSDLRPCv1::kSuccess, result); + EXPECT_EQ(Errors::eType::OK, obj.validate()); + EXPECT_EQ(obj[S_PARAMS][S_MESSAGE_TYPE], MessageTypeTest::request); + EXPECT_EQ(obj[S_PARAMS][S_FUNCTION_ID], FunctionIDTest::RegisterAppInterface); + EXPECT_EQ(obj[S_PARAMS][S_CORRELATION_ID], 5); + EXPECT_EQ(obj[S_PARAMS][S_PROTOCOL_TYPE], 0); + EXPECT_EQ(obj[S_PARAMS][S_PROTOCOL_VERSION], 1); + EXPECT_EQ(obj[S_MSG_PARAMS]["appName"], "some app name"); + + EXPECT_EQ(obj[S_MSG_PARAMS]["syncMsgVersion"]["majorVersion"], 2); + EXPECT_EQ(obj[S_MSG_PARAMS]["syncMsgVersion"]["minorVersion"], 10); + EXPECT_EQ(obj[S_MSG_PARAMS]["ttsName"][0]["text"], "ABC"); + EXPECT_EQ(obj[S_MSG_PARAMS]["ttsName"][0]["type"], "TEXT"); + EXPECT_EQ(obj[S_MSG_PARAMS]["vrSynonyms"][0], "Synonym 1"); + EXPECT_EQ(obj[S_MSG_PARAMS]["vrSynonyms"][1], "Synonym 2"); +} + +TEST(CFormatterJsonSDLRPCv1Test, StringRequestWithoutNameToSmartObject) { + std::string inputJsonString = + "\ + {\ + \"request\": {\ + \"correlationID\": 5,\ + \"parameters\": {\ + \"syncMsgVersion\" : {\ + \"majorVersion\" : 2,\ + \"minorVersion\" : 10\ + },\ + \"appName\": \"some app name\",\ + \"ttsName\": [{\ + \"text\": \"ABC\",\ + \"type\": \"TEXT\"\ + }],\ + \"vrSynonyms\": [\"Synonym 1\", \"Synonym 2\"]\ + }\ + }\ + }"; + + SmartObject obj; + + bool result = CFormatterJsonSDLRPCv1::fromString<FunctionIDTest::eType, + MessageTypeTest::eType>(inputJsonString, obj); + + EXPECT_EQ(CFormatterJsonSDLRPCv1::kParsingError, result); + + EXPECT_EQ(obj[S_PARAMS][S_MESSAGE_TYPE], MessageTypeTest::request); + EXPECT_EQ(obj[S_PARAMS][S_FUNCTION_ID], "-1"); + EXPECT_EQ(obj[S_PARAMS][S_CORRELATION_ID], 5); + EXPECT_EQ(obj[S_MSG_PARAMS]["appName"], "some app name"); + + EXPECT_EQ(obj[S_MSG_PARAMS]["syncMsgVersion"]["majorVersion"], 2); + EXPECT_EQ(obj[S_MSG_PARAMS]["syncMsgVersion"]["minorVersion"], 10); + EXPECT_EQ(obj[S_MSG_PARAMS]["ttsName"][0]["text"], "ABC"); + EXPECT_EQ(obj[S_MSG_PARAMS]["ttsName"][0]["type"], "TEXT"); + EXPECT_EQ(obj[S_MSG_PARAMS]["vrSynonyms"][0], "Synonym 1"); + EXPECT_EQ(obj[S_MSG_PARAMS]["vrSynonyms"][1], "Synonym 2"); +} + +TEST(CFormatterJsonSDLRPCv1Test, StringRequestWithIncorrectCorIDToSmartObject) { + std::string inputJsonString = + "\ + {\ + \"request\": {\ + \"correlationID\": \"5\",\ + \"parameters\": {\ + \"syncMsgVersion\" : {\ + \"majorVersion\" : 2,\ + \"minorVersion\" : 10\ + },\ + \"appName\": \"some app name\",\ + \"ttsName\": [{\ + \"text\": \"ABC\",\ + \"type\": \"TEXT\"\ + }],\ + \"vrSynonyms\": [\"Synonym 1\", \"Synonym 2\"]\ + }\ + }\ + }"; + + SmartObject obj; + + bool result = CFormatterJsonSDLRPCv1::fromString<FunctionIDTest::eType, + MessageTypeTest::eType>(inputJsonString, obj); + EXPECT_EQ(CFormatterJsonSDLRPCv1::kParsingError, result); + + EXPECT_EQ(obj[S_PARAMS][S_MESSAGE_TYPE], MessageTypeTest::request); + EXPECT_EQ(obj[S_PARAMS][S_FUNCTION_ID], "-1"); + EXPECT_EQ(obj[S_MSG_PARAMS]["appName"], "some app name"); + EXPECT_EQ(obj[S_MSG_PARAMS]["syncMsgVersion"]["majorVersion"], 2); + EXPECT_EQ(obj[S_MSG_PARAMS]["ttsName"][0]["text"], "ABC"); + EXPECT_EQ(obj[S_MSG_PARAMS]["vrSynonyms"][0], "Synonym 1"); +} + +TEST(CFormatterJsonSDLRPCv1Test, StringResponceToSmartObject) { + std::string inputJsonString = + "{\n \ + \"response\" : {\n\ + \"correlationID\" : 13,\n\ + \"name\" : \"RegisterAppInterface\",\n\ + \"parameters\" : {\n\ + \"resultCode\" : \"SUCCESS\",\n\ + \"success\" : true\n\ + }\n\ + }\n\ +}\n"; + + SmartObject obj; + + CSmartSchema schema = initObjectSchema(); + obj.setSchema(schema); + + bool result = CFormatterJsonSDLRPCv1::fromString<FunctionIDTest::eType, + MessageTypeTest::eType>(inputJsonString, obj); + EXPECT_EQ(CFormatterJsonSDLRPCv1::kSuccess, result); + EXPECT_EQ(obj[S_PARAMS][S_MESSAGE_TYPE], MessageTypeTest::response); + EXPECT_EQ(obj[S_PARAMS][S_FUNCTION_ID], 0); + EXPECT_EQ(obj[S_PARAMS][S_CORRELATION_ID], 13); + EXPECT_EQ(obj[S_PARAMS][S_PROTOCOL_TYPE], 0); + EXPECT_EQ(obj[S_PARAMS][S_PROTOCOL_VERSION], 1); + EXPECT_EQ(obj[S_MSG_PARAMS]["resultCode"], "SUCCESS"); + EXPECT_EQ(obj[S_MSG_PARAMS]["success"], true); +} + +TEST(CFormatterJsonSDLRPCv1Test, StringNotificationToSmartObject) { + std::string inputJsonString = + "{\n \ + \"notification\" : {\n\ + \"correlationID\" : 13,\n\ + \"name\" : \"SetGlobalProperties\",\n\ + \"parameters\" : {}\n\ + }\n\ +}\n"; + + SmartObject obj; + + CSmartSchema schema = initObjectSchema(); + obj.setSchema(schema); + + bool result = CFormatterJsonSDLRPCv1::fromString<FunctionIDTest::eType, + MessageTypeTest::eType>(inputJsonString, obj); + EXPECT_EQ(CFormatterJsonSDLRPCv1::kSuccess, result); + EXPECT_EQ(Errors::eType::OK, obj.validate()); + EXPECT_EQ(obj[S_PARAMS][S_MESSAGE_TYPE], MessageTypeTest::notification); + EXPECT_EQ(obj[S_PARAMS][S_FUNCTION_ID], FunctionIDTest::SetGlobalProperties); + EXPECT_EQ(obj[S_PARAMS][S_CORRELATION_ID], 13); + EXPECT_EQ(obj[S_PARAMS][S_PROTOCOL_TYPE], 0); + EXPECT_EQ(obj[S_PARAMS][S_PROTOCOL_VERSION], 1); +} + +TEST(CFormatterJsonSDLRPCv1Test, MetaFormatToString) { + SmartObject srcObj; + + srcObj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request; + srcObj[S_PARAMS][S_FUNCTION_ID] = FunctionIDTest::RegisterAppInterface; + srcObj[S_PARAMS][S_CORRELATION_ID] = 13; + srcObj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + srcObj[S_PARAMS][S_PROTOCOL_VERSION] = 1; + srcObj[S_MSG_PARAMS]["info"] = "value"; + + std::string jsonString; + + CSmartSchema schema = initObjectSchema(); + srcObj.setSchema(schema); + + meta_formatter_error_code::tMetaFormatterErrorCode result = + CFormatterJsonSDLRPCv1::MetaFormatToString(srcObj, schema, jsonString); + EXPECT_EQ(meta_formatter_error_code::kErrorOk, result); +} + +} // namespace formatters +} // namespace components +} // namespace test diff --git a/src/components/formatters/test/cFormatterJsonSDLRPCv2_test.cc b/src/components/formatters/test/cFormatterJsonSDLRPCv2_test.cc new file mode 100644 index 0000000000..814cff4ab7 --- /dev/null +++ b/src/components/formatters/test/cFormatterJsonSDLRPCv2_test.cc @@ -0,0 +1,392 @@ +/* + * Copyright (c) 2015, 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. + */ + +#include "gtest/gtest.h" +#include "create_smartSchema.h" +#include "formatters/CFormatterJsonSDLRPCv2.hpp" + +namespace test { +namespace components { +namespace formatters { + +TEST(CFormatterJsonSDLRPCv2Test, EmptySmartObjectToString) { + SmartObject srcObj; + + EXPECT_EQ(Errors::eType::OK, srcObj.validate()); + + std::string jsonString; + bool result = CFormatterJsonSDLRPCv2::toString(srcObj, jsonString); + + EXPECT_TRUE(result); + + std::string expectOutputJsonString = "\"\"\n"; + + EXPECT_EQ(expectOutputJsonString, jsonString); +} + +TEST(CFormatterJsonSDLRPCv2Test, SmObjWithRequestWithoutMsgNotValid_ToString) { + SmartObject srcObj; + CSmartSchema schema = initObjectSchema(); + srcObj.setSchema(schema); + + srcObj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request; + srcObj[S_PARAMS][S_FUNCTION_ID] = FunctionIDTest::RegisterAppInterface; + srcObj[S_PARAMS][S_CORRELATION_ID] = 13; + srcObj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + srcObj[S_PARAMS][S_PROTOCOL_VERSION] = 2; + + EXPECT_EQ(Errors::eType::MISSING_MANDATORY_PARAMETER, srcObj.validate()); + + std::string jsonString; + bool result = CFormatterJsonSDLRPCv2::toString(srcObj, jsonString); + EXPECT_TRUE(result); + + std::string expectOutputJsonString = "\"\"\n"; + + EXPECT_EQ(expectOutputJsonString, jsonString); +} + +TEST(CFormatterJsonSDLRPCv2Test, SmObjWithRequestWithEmptyMsgWithTestSchemaToString) { + SmartObject srcObj; + CSmartSchema schema = initObjectSchema(); + srcObj.setSchema(schema); + + srcObj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request; + srcObj[S_PARAMS][S_FUNCTION_ID] = FunctionIDTest::RegisterAppInterface; + srcObj[S_PARAMS][S_CORRELATION_ID] = 13; + srcObj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + srcObj[S_PARAMS][S_PROTOCOL_VERSION] = 2; + srcObj[S_MSG_PARAMS][""] = ""; + + EXPECT_EQ(Errors::eType::OK, srcObj.validate()); + + std::string jsonString; + + bool result = CFormatterJsonSDLRPCv2::toString(srcObj, jsonString); + + EXPECT_TRUE(result); + + std::string expectOutputJsonString = "{}\n"; + + EXPECT_EQ(expectOutputJsonString, jsonString); +} + +TEST(CFormatterJsonSDLRPCv2Test, SmObjWithRequestWithNonemptyMsgWithTestSchemaToString) { + SmartObject srcObj; + CSmartSchema schema = initObjectSchema(); + srcObj.setSchema(schema); + + srcObj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request; + srcObj[S_PARAMS][S_FUNCTION_ID] = FunctionIDTest::RegisterAppInterface; + srcObj[S_PARAMS][S_CORRELATION_ID] = 13; + srcObj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + srcObj[S_PARAMS][S_PROTOCOL_VERSION] = 2; + srcObj[S_MSG_PARAMS]["info"] = "value"; + + std::string jsonString; + + bool result = CFormatterJsonSDLRPCv2::toString(srcObj, jsonString); + + EXPECT_TRUE(result); + + std::string expectOutputJsonString = "{\n \"info\" : \"value\"\n}\n"; + + EXPECT_EQ(expectOutputJsonString, jsonString); +} + +TEST(CFormatterJsonSDLRPCv2Test, SmObjWithRequestWithNonemptyMsgToString) { + SmartObject srcObj; + + srcObj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request; + srcObj[S_PARAMS][S_FUNCTION_ID] = 5; + srcObj[S_PARAMS][S_CORRELATION_ID] = 13; + srcObj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + srcObj[S_PARAMS][S_PROTOCOL_VERSION] = 2; + srcObj[S_MSG_PARAMS]["vrSynonyms"][0] = "Synonym 1"; + + std::string jsonString; + + bool result = CFormatterJsonSDLRPCv2::toString(srcObj, jsonString); + + EXPECT_TRUE(result); + + std::string expectOutputJsonString = + "{\n \"vrSynonyms\" : [ \"Synonym 1\" ]\n}\n"; + EXPECT_EQ(expectOutputJsonString, jsonString); +} + +TEST(CFormatterJsonSDLRPCv2Test, SmObjWithResponseWithoutSchemaToString) { + SmartObject srcObj; + + srcObj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::response; + srcObj[S_PARAMS][S_FUNCTION_ID] = 5; + srcObj[S_PARAMS][S_CORRELATION_ID] = 13; + srcObj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + srcObj[S_PARAMS][S_PROTOCOL_VERSION] = 2; + srcObj[S_MSG_PARAMS]["success"] = true; + srcObj[S_MSG_PARAMS]["resultCode"] = 0; + + std::string jsonString; + + bool result = CFormatterJsonSDLRPCv2::toString(srcObj, jsonString); + + EXPECT_TRUE(result); + + std::string expectOutputJsonString = + "{\n \"resultCode\" : 0,\n \"success\" : true\n}\n"; + EXPECT_EQ(expectOutputJsonString, jsonString); +} + +TEST(CFormatterJsonSDLRPCv2Test, SmObjWithNotificationToString) { + SmartObject srcObj; + CSmartSchema schema = initObjectSchema(); + srcObj.setSchema(schema); + + srcObj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::notification; + srcObj[S_PARAMS][S_FUNCTION_ID] = FunctionIDTest::SetGlobalProperties; + srcObj[S_PARAMS][S_CORRELATION_ID] = 13; + srcObj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + srcObj[S_PARAMS][S_PROTOCOL_VERSION] = 2; + srcObj[S_MSG_PARAMS]["info"] = "info_notification"; + std::string jsonString; + + bool result = CFormatterJsonSDLRPCv2::toString(srcObj, jsonString); + + EXPECT_TRUE(result); + + std::string expectOutputJsonString = + "{\n \"info\" : \"info_notification\"\n}\n"; + + EXPECT_EQ(expectOutputJsonString, jsonString); +} + +TEST(CFormatterJsonSDLRPCv2Test, SmObjWithResponseToString) { + SmartObject srcObj; + + CSmartSchema schema = initObjectSchema(); + srcObj.setSchema(schema); + + srcObj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::response; + srcObj[S_PARAMS][S_FUNCTION_ID] = FunctionIDTest::RegisterAppInterface; + srcObj[S_PARAMS][S_CORRELATION_ID] = 13; + srcObj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + srcObj[S_PARAMS][S_PROTOCOL_VERSION] = 2; + + srcObj[S_MSG_PARAMS]["success"] = true; + srcObj[S_MSG_PARAMS]["resultCode"] = TestType::SUCCESS; + + std::string jsonString; + + bool result = CFormatterJsonSDLRPCv2::toString(srcObj, jsonString); + + EXPECT_TRUE(result); + + std::string expectOutputJsonString = + "{\n \"resultCode\" : \"SUCCESS\",\n \"success\" : true\n}\n"; + + EXPECT_EQ(expectOutputJsonString, jsonString); +} + +TEST(CFormatterJsonSDLRPCv2Test, SmObjWithResponseWithoutSchemaWithoutParamsToString) { + SmartObject srcObj; + srcObj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::response; + std::string jsonString; + + bool result = CFormatterJsonSDLRPCv2::toString(srcObj, jsonString); + + EXPECT_TRUE(result); + + std::string expectOutputJsonString = "\"\"\n"; + + EXPECT_EQ(expectOutputJsonString, jsonString); +} + +TEST(CFormatterJsonSDLRPCv2Test, StringRequestWithoutCorIdToSmObj) { + std::string inputJsonString = + "\ + {\ + \"syncMsgVersion\" : {\ + \"majorVersion\" : 2,\ + \"minorVersion\" : 10\ + },\ + \"appName\": \"some app name\",\ + \"ttsName\": [{\ + \"text\": \"ABC\",\ + \"type\": \"TEXT\"\ + }],\ + \"vrSynonyms\": [\"Synonym 1\", \"Synonym 2\"]\ + }\n"; + + SmartObject obj; + + CSmartSchema schema = initObjectSchema(); + obj.setSchema(schema); + + bool result = CFormatterJsonSDLRPCv2::fromString<FunctionIDTest::eType, + MessageTypeTest::eType>(inputJsonString, obj, + FunctionIDTest::RegisterAppInterface, + MessageTypeTest::request); + + EXPECT_EQ(true, result); + EXPECT_EQ(Errors::eType::MISSING_MANDATORY_PARAMETER, obj.validate()); + EXPECT_EQ(obj[S_PARAMS][S_MESSAGE_TYPE], MessageTypeTest::request); + EXPECT_EQ(obj[S_PARAMS][S_FUNCTION_ID], FunctionIDTest::RegisterAppInterface); + EXPECT_EQ(obj[S_PARAMS][S_PROTOCOL_TYPE], 0); + EXPECT_EQ(obj[S_PARAMS][S_PROTOCOL_VERSION], 2); + EXPECT_EQ(obj[S_MSG_PARAMS]["appName"], "some app name"); + + EXPECT_EQ(obj[S_MSG_PARAMS]["syncMsgVersion"]["majorVersion"], 2); + EXPECT_EQ(obj[S_MSG_PARAMS]["syncMsgVersion"]["minorVersion"], 10); + EXPECT_EQ(obj[S_MSG_PARAMS]["ttsName"][0]["text"], "ABC"); + EXPECT_EQ(obj[S_MSG_PARAMS]["ttsName"][0]["type"], "TEXT"); + EXPECT_EQ(obj[S_MSG_PARAMS]["vrSynonyms"][0], "Synonym 1"); + EXPECT_EQ(obj[S_MSG_PARAMS]["vrSynonyms"][1], "Synonym 2"); +} + +TEST(CFormatterJsonSDLRPCv2Test, StringRequestWithCorIdToSmObj) { + std::string inputJsonString = + "\ + {\ + \"syncMsgVersion\" : {\ + \"majorVersion\" : 2,\ + \"minorVersion\" : 10\ + },\ + \"appName\": \"some app name\",\ + \"ttsName\": [{\ + \"text\": \"ABC\",\ + \"type\": \"TEXT\"\ + }],\ + \"vrSynonyms\": [\"Synonym 1\", \"Synonym 2\"]\ + }\n"; + + SmartObject obj; + + CSmartSchema schema = initObjectSchema(); + obj.setSchema(schema); + int32_t corId = 10; + bool result = CFormatterJsonSDLRPCv2::fromString<FunctionIDTest::eType, + MessageTypeTest::eType>(inputJsonString, obj, + FunctionIDTest::RegisterAppInterface, + MessageTypeTest::request, corId); + + EXPECT_EQ(true, result); + EXPECT_EQ(Errors::eType::OK, obj.validate()); + EXPECT_EQ(obj[S_PARAMS][S_MESSAGE_TYPE], MessageTypeTest::request); + EXPECT_EQ(obj[S_PARAMS][S_FUNCTION_ID], FunctionIDTest::RegisterAppInterface); + EXPECT_EQ(obj[S_PARAMS][S_CORRELATION_ID], corId); + EXPECT_EQ(obj[S_PARAMS][S_PROTOCOL_TYPE], 0); + EXPECT_EQ(obj[S_PARAMS][S_PROTOCOL_VERSION], 2); + EXPECT_EQ(obj[S_MSG_PARAMS]["appName"], "some app name"); + + EXPECT_EQ(obj[S_MSG_PARAMS]["syncMsgVersion"]["majorVersion"], 2); + EXPECT_EQ(obj[S_MSG_PARAMS]["syncMsgVersion"]["minorVersion"], 10); + EXPECT_EQ(obj[S_MSG_PARAMS]["ttsName"][0]["text"], "ABC"); + EXPECT_EQ(obj[S_MSG_PARAMS]["ttsName"][0]["type"], "TEXT"); + EXPECT_EQ(obj[S_MSG_PARAMS]["vrSynonyms"][0], "Synonym 1"); + EXPECT_EQ(obj[S_MSG_PARAMS]["vrSynonyms"][1], "Synonym 2"); +} + +TEST(CFormatterJsonSDLRPCv2Test, StringResponceWithCorIdToSmartObject) { + std::string inputJsonString = + "{\n \ + \"resultCode\" : \"SUCCESS\",\n\ + \"success\" : true\n\ + }\n"; + + SmartObject obj; + + CSmartSchema schema = initObjectSchema(); + obj.setSchema(schema); + int32_t corId = 10; + bool result = CFormatterJsonSDLRPCv2::fromString<FunctionIDTest::eType, + MessageTypeTest::eType>(inputJsonString, obj, + FunctionIDTest::RegisterAppInterface, + MessageTypeTest::response, corId); + EXPECT_EQ(true, result); + + EXPECT_EQ(obj[S_PARAMS][S_MESSAGE_TYPE], MessageTypeTest::response); + EXPECT_EQ(obj[S_PARAMS][S_FUNCTION_ID], 0); + EXPECT_EQ(obj[S_PARAMS][S_CORRELATION_ID], corId); + EXPECT_EQ(obj[S_PARAMS][S_PROTOCOL_TYPE], 0); + EXPECT_EQ(obj[S_PARAMS][S_PROTOCOL_VERSION], 2); + EXPECT_EQ(obj[S_MSG_PARAMS]["resultCode"], "SUCCESS"); + EXPECT_EQ(obj[S_MSG_PARAMS]["success"], true); +} + +TEST(CFormatterJsonSDLRPCv2Test, StringNotificationToSmartObject) { + std::string inputJsonString = + "{\ + \"info\" : \"info_notification\"\ + }\n"; + + SmartObject obj; + + CSmartSchema schema = initObjectSchema(); + obj.setSchema(schema); + int32_t corId = 10; + bool result = CFormatterJsonSDLRPCv2::fromString<FunctionIDTest::eType, + MessageTypeTest::eType>(inputJsonString, obj, + FunctionIDTest::SetGlobalProperties, + MessageTypeTest::notification, corId); + EXPECT_EQ(true, result); + EXPECT_EQ(Errors::eType::OK, obj.validate()); + EXPECT_EQ(obj[S_PARAMS][S_MESSAGE_TYPE], MessageTypeTest::notification); + EXPECT_EQ(obj[S_PARAMS][S_FUNCTION_ID], FunctionIDTest::SetGlobalProperties); + EXPECT_EQ(obj[S_PARAMS][S_CORRELATION_ID], corId); + EXPECT_EQ(obj[S_PARAMS][S_PROTOCOL_TYPE], 0); + EXPECT_EQ(obj[S_PARAMS][S_PROTOCOL_VERSION], 2); + EXPECT_EQ(obj[S_MSG_PARAMS]["info"], "info_notification"); +} + +TEST(CFormatterJsonSDLRPCv2Test, MetaFormatToString) { + SmartObject srcObj; + + srcObj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request; + srcObj[S_PARAMS][S_FUNCTION_ID] = FunctionIDTest::RegisterAppInterface; + srcObj[S_PARAMS][S_CORRELATION_ID] = 13; + srcObj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + srcObj[S_PARAMS][S_PROTOCOL_VERSION] = 2; + srcObj[S_MSG_PARAMS]["info"] = "value"; + + std::string jsonString; + + CSmartSchema schema = initObjectSchema(); + srcObj.setSchema(schema); + + meta_formatter_error_code::tMetaFormatterErrorCode result = + CFormatterJsonSDLRPCv2::MetaFormatToString(srcObj, schema, jsonString); + EXPECT_EQ(meta_formatter_error_code::kErrorOk, result); +} + +} // namespace formatters +} // namespace components +} // namespace test diff --git a/src/components/formatters/test/formatter_json_rpc_test.cc b/src/components/formatters/test/formatter_json_rpc_test.cc new file mode 100644 index 0000000000..24bdc2fa3f --- /dev/null +++ b/src/components/formatters/test/formatter_json_rpc_test.cc @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2015, 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. + */ + +#include <algorithm> +#include "gtest/gtest.h" +#include "formatters/formatter_json_rpc.h" +#include "formatters/CSmartFactory.hpp" +#include "HMI_API_schema.h" +#include "MOBILE_API_schema.h" + +namespace test { +namespace components { +namespace formatters { + +using namespace NsSmartDeviceLink::NsSmartObjects; +using namespace NsSmartDeviceLink::NsJSONHandler::Formatters; +using namespace NsSmartDeviceLink::NsJSONHandler::strings; + +TEST(FormatterJsonRPCTest, CorrectRPCv1_request_SmartObjectToString_EXPECT_SUCCESS) { + // Create SmartObject + SmartObject obj; + obj[S_PARAMS][S_FUNCTION_ID] = hmi_apis::FunctionID::VR_IsReady; + obj[S_PARAMS][S_MESSAGE_TYPE] = hmi_apis::messageType::request; + obj[S_PARAMS][S_PROTOCOL_VERSION] = 2; + obj[S_PARAMS][S_PROTOCOL_TYPE] = 1; + obj[S_PARAMS][S_CORRELATION_ID] = 4444; + obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map); + // Attach Schema + hmi_apis::HMI_API factory; + EXPECT_TRUE(factory.attachSchema(obj)); + + std::string result; + // Convert SmrtObject to Json string + EXPECT_TRUE(FormatterJsonRpc::ToString(obj, result)); + EXPECT_EQ( + std::string( + "{\n \"id\" : 4444,\n \"jsonrpc\" : \"2.0\",\n \"method\" : \"VR.IsReady\"\n}\n"), + result); +} + +TEST(FormatterJsonRPCTest, CorrectRPCv2_request_SmartObjectToString_EXPECT_SUCCESS) { + // Create SmartObject + SmartObject obj; + obj[S_PARAMS][S_FUNCTION_ID] = mobile_apis::FunctionID::AddCommandID; + obj[S_PARAMS][S_MESSAGE_TYPE] = mobile_apis::messageType::request; + obj[S_PARAMS][S_CORRELATION_ID] = 4444; + obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map); + // Attach Schema + mobile_apis::MOBILE_API factory; + EXPECT_TRUE(factory.attachSchema(obj)); + + std::string result; + // Convert SmrtObject to Json string + EXPECT_TRUE(FormatterJsonRpc::ToString(obj, result)); + EXPECT_EQ( + std::string( + "{\n \"id\" : 4444,\n \"jsonrpc\" : \"2.0\",\n \"method\" : \"AddCommandID\"\n}\n"), + result); +} + +TEST(FormatterJsonRPCTest, CorrectRPCv1_notification_SmartObjectToString_EXPECT_SUCCESS) { + // Create SmartObject + SmartObject obj; + std::string result; + obj[S_PARAMS][S_FUNCTION_ID] = hmi_apis::FunctionID::Buttons_OnButtonPress; + obj[S_PARAMS][S_MESSAGE_TYPE] = hmi_apis::messageType::notification; + obj[S_PARAMS][S_PROTOCOL_VERSION] = 2; + obj[S_PARAMS][S_PROTOCOL_TYPE] = 1; + obj[S_PARAMS][S_CORRELATION_ID] = 4222; + obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map); + // Attach Schema + hmi_apis::HMI_API factory; + EXPECT_TRUE(factory.attachSchema(obj)); + // Convert SmrtObject to Json string + EXPECT_TRUE(FormatterJsonRpc::ToString(obj, result)); + EXPECT_EQ( + std::string( + "{\n \"jsonrpc\" : \"2.0\",\n \"method\" : \"Buttons.OnButtonPress\",\n \"params\" : {}\n}\n"), + result); +} + +TEST(FormatterJsonRPCTest, InvalidRPC_SmartObjectToString_EXPECT_FALSE) { + // Create SmartObject + SmartObject obj; + std::string result; + obj[S_PARAMS][S_FUNCTION_ID] = + hmi_apis::FunctionID::BasicCommunication_OnReady; + obj[S_PARAMS][S_MESSAGE_TYPE] = hmi_apis::messageType::response; + obj[S_PARAMS][S_PROTOCOL_VERSION] = 2; + obj[S_PARAMS][S_PROTOCOL_TYPE] = 1; + obj[S_PARAMS][S_CORRELATION_ID] = 4222; + obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map); + // Attach Schema + hmi_apis::HMI_API factory; + EXPECT_FALSE(factory.attachSchema(obj)); + // Convert SmrtObject to Json string + EXPECT_FALSE(FormatterJsonRpc::ToString(obj, result)); + // Expect result with default value. No correct conversion was done + EXPECT_EQ(std::string("{\n \"jsonrpc\" : \"2.0\"\n}\n"), result); +} + +TEST(FormatterJsonRPCTest, FromStringNotificationToSmartObj_ExpectSuccess) { + // Source Json string + const std::string json_string( + "{\n \"jsonrpc\" : \"2.0\",\n \"method\" : \"BasicCommunication.OnReady\",\n \"params\" : {}\n}\n"); + // Smart Object to keep result + SmartObject obj; + // Convert json string to smart object + EXPECT_EQ( + 0, + (FormatterJsonRpc::FromString<hmi_apis::FunctionID::eType, + hmi_apis::messageType::eType>(json_string, obj))); + // Get keys collection from Smart Object + std::set<std::string> keys = obj["params"].enumerate(); + EXPECT_EQ(4u, keys.size()); +} + +TEST(FormatterJsonRPCTest, FromStringToSmartObjInvalidFormat_ExpectFalse) { + // Source Json string + const std::string json_string( + "{\n \"method\" : \"BasicCommunication.OnReady\",\n \"params\" : {}\n}\n"); + // Smart Object to keep result + SmartObject obj; + // Convert json string to smart object + EXPECT_EQ( + 2, + (FormatterJsonRpc::FromString<hmi_apis::FunctionID::eType, + hmi_apis::messageType::eType>(json_string, obj))); + // Get keys collection from Smart Object + std::set<std::string> keys = obj["params"].enumerate(); + EXPECT_EQ(4u, keys.size()); +} + +TEST(FormatterJsonRPCTest, FromStringRequestToSmartObj_ExpectSuccess) { + // Source Json string + const std::string json_string( + "{\n \"id\" : 4444,\n \"jsonrpc\" : \"2.0\",\n \"method\" : \"VR.IsReady\"\n}\n"); + // Smart Object to keep result + SmartObject obj; + // Convert json string to smart object + EXPECT_EQ( + 0, + (FormatterJsonRpc::FromString<hmi_apis::FunctionID::eType, + hmi_apis::messageType::eType>(json_string, obj))); + // Get keys collection from Smart Object + std::set<std::string> keys = obj["params"].enumerate(); + std::set<std::string>::iterator it1 = keys.begin(); + EXPECT_EQ(5u, keys.size()); +} + +TEST(FormatterJsonRPCTest, FromStringResponseToSmartObj_ExpectSuccess) { + // Source Json string + const std::string json_string( + "{\n \"id\" : 4444,\n \"jsonrpc\" : \"2.0\",\n \"method\" : \"VR.IsReady\"\n}\n"); + // Smart Object to keep result + SmartObject obj; + // Convert json string to smart object + EXPECT_EQ( + 0, + (FormatterJsonRpc::FromString<hmi_apis::FunctionID::eType, + hmi_apis::messageType::eType>(json_string, obj))); + // Get keys collection from Smart Object + std::set<std::string> keys = obj["params"].enumerate(); + std::set<std::string>::iterator it1 = keys.begin(); + EXPECT_EQ(5u, keys.size()); +} + +} // namespace formatters +} // namespace components +} // namespace test diff --git a/src/components/formatters/test/include/SmartFactoryTestHelper.h b/src/components/formatters/test/include/SmartFactoryTestHelper.h new file mode 100644 index 0000000000..ca7021b844 --- /dev/null +++ b/src/components/formatters/test/include/SmartFactoryTestHelper.h @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2015, 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. + */ + +#ifndef SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_SMARTFACTORYTESTHELPER_H_ +#define SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_SMARTFACTORYTESTHELPER_H_ + +#include <map> +#include <set> + +#include "formatters/CSmartFactory.hpp" +#include "HMI_API_schema.h" +#include "smart_objects/always_true_schema_item.h" +#include "smart_objects/always_false_schema_item.h" +#include "smart_objects/array_schema_item.h" +#include "smart_objects/bool_schema_item.h" +#include "smart_objects/object_schema_item.h" +#include "smart_objects/string_schema_item.h" +#include "smart_objects/enum_schema_item.h" +#include "smart_objects/number_schema_item.h" +#include "smart_objects/schema_item_parameter.h" + +namespace test { +namespace components { +namespace formatters { + +using namespace NsSmartDeviceLink::NsSmartObjects; +using namespace NsSmartDeviceLink::NsJSONHandler; +using namespace NsSmartDeviceLink::NsJSONHandler::strings; +using namespace hmi_apis; + +namespace TestType { +enum eType { + INVALID_ENUM = -1, + APPLICATION_NOT_REGISTERED = 0, + SUCCESS, + TOO_MANY_PENDING_REQUESTS, + REJECTED, + INVALID_DATA, + OUT_OF_MEMORY, + ABORTED, + USER_DISALLOWED, + GENERIC_ERROR, + DISALLOWED +}; +} // namespace TestType + +namespace FunctionIdTest { +enum eType { + INVALID_ENUM = -1, + Function1, + Function2, + Function3 +}; +} // namespace FunctionIdTest + +namespace MessageTypeTest { +enum eType { + INVALID_ENUM = -1, + request, + response, + notification, + error_response +}; +} // namespace MessageTypeTest + +namespace StructIdentifiersTest { +enum eType { + INVALID_ENUM = -1, + Common_1, + Common_2, + Common_3 +}; +} // namespace StructIdentifiersTest + +class CSmartFactoryTest : public CSmartFactory<FunctionIdTest::eType, + MessageTypeTest::eType, StructIdentifiersTest::eType> { + public: + CSmartFactoryTest(); + std::map<SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>, + CSmartSchema> function_schemes() { + return functions_schemes_; + } + std::map<StructIdentifiersTest::eType, CSmartSchema> structs_schemes() { + return structs_schemes_; + } + protected: + typedef std::map<const StructIdentifiersTest::eType, + utils::SharedPtr<ISchemaItem> > TStructsSchemaItems; + + static utils::SharedPtr<ISchemaItem> ProvideObjectSchemaItemForStruct( + TStructsSchemaItems &struct_schema_items, + const StructIdentifiersTest::eType struct_id); + + void InitStructSchemes(TStructsSchemaItems &struct_schema_items); + + void InitFunctionSchemes( + const TStructsSchemaItems &struct_schema_items, + const std::set<FunctionIdTest::eType> &function_id_items, + const std::set<MessageTypeTest::eType> &message_type_items); + + static CSmartSchema InitFunction_Function1_request( + const std::set<FunctionIdTest::eType> &function_id_items, + const std::set<MessageTypeTest::eType> &message_type_items); + + static CSmartSchema InitFunction_Function1_response( + const TStructsSchemaItems &struct_schema_items, + const std::set<FunctionIdTest::eType> &function_id_items, + const std::set<MessageTypeTest::eType> &message_type_items); + + static CSmartSchema InitFunction_Function2_request( + const std::set<FunctionIdTest::eType> &function_id_items, + const std::set<MessageTypeTest::eType> &message_type_items); + + static CSmartSchema InitFunction_Function2_response( + const TStructsSchemaItems &struct_schema_items, + const std::set<FunctionIdTest::eType> &function_id_items, + const std::set<MessageTypeTest::eType> &message_type_items); + + static CSmartSchema InitFunction_Function3_request( + const std::set<FunctionIdTest::eType> &function_id_items, + const std::set<MessageTypeTest::eType> &message_type_items); + + static CSmartSchema InitFunction_Function3_response( + const TStructsSchemaItems &struct_schema_items, + const std::set<FunctionIdTest::eType> &function_id_items, + const std::set<MessageTypeTest::eType> &message_type_items); + + static utils::SharedPtr<ISchemaItem> InitStructSchemaItem_Common_1( + TStructsSchemaItems &struct_schema_items); + + static utils::SharedPtr<ISchemaItem> InitStructSchemaItem_Common_2(); +}; + +} // namespace formatters +} // namespace components +} // namespace test + +#endif // SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_SMARTFACTORYTESTHELPER_H_ diff --git a/src/components/formatters/test/include/create_smartSchema.h b/src/components/formatters/test/include/create_smartSchema.h new file mode 100644 index 0000000000..c3bc2651e5 --- /dev/null +++ b/src/components/formatters/test/include/create_smartSchema.h @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2015, 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. + */ + +#ifndef SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_CREATESMARTSCHEMA_H_ +#define SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_CREATESMARTSCHEMA_H_ + +#include "formatters/CFormatterJsonSDLRPCv1.hpp" +#include "SmartFactoryTestHelper.h" + +namespace test { +namespace components { +namespace formatters { + +using namespace NsSmartDeviceLink::NsJSONHandler::strings; +using namespace NsSmartDeviceLink::NsJSONHandler::Formatters; +using namespace NsSmartDeviceLink::NsSmartObjects; + +namespace FunctionIDTest { +enum eType { + INVALID_ENUM = -1, + RegisterAppInterface, + UnregisterAppInterface, + SetGlobalProperties, +}; +} + +namespace Language { +enum eType { + INVALID_ENUM = -1, + EN_EU, + RU_RU +}; +} +namespace AppTypeTest { +enum eType { + INVALID_ENUM = -1, + SYSTEM, + MEDIA +}; +} +namespace SpeechCapabilities { +enum eType { + INVALID_ENUM = -1, + SC_TEXT, +}; +} + +namespace StructIdentifiers { +enum eType { + INVALID_ENUM = -1, + Struct1, + Struct2 +}; +} + +CSmartSchema initObjectSchema(); +CSmartSchema initSchemaForMetaFormatter(); + +} // namespace formatters +} // namespace components +} // namespace test + +#endif // SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_CREATESMARTSCHEMA_H_ diff --git a/src/components/formatters/test/include/meta_formatter_test_helper.h b/src/components/formatters/test/include/meta_formatter_test_helper.h new file mode 100644 index 0000000000..e2be3beb64 --- /dev/null +++ b/src/components/formatters/test/include/meta_formatter_test_helper.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2015, 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. + */ + +#ifndef SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_METAFORMATTERTESTHELPER_H_ +#define SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_METAFORMATTERTESTHELPER_H_ + +#include "gtest/gtest.h" + +#include "smart_objects/smart_object.h" +#include "formatters/CFormatterJsonSDLRPCv1.hpp" +#include "formatters/CSmartFactory.hpp" +#include "create_smartSchema.h" + +namespace test { +namespace components { +namespace formatters { + +class CMetaFormatterTestHelper : public ::testing::Test { + protected: + + virtual void SetUp(); + + virtual void TearDown(); + + void AnyObjectToJsonString( + const NsSmartDeviceLink::NsSmartObjects::SmartObject& obj, + std::string& result_string); + + void FillObjectIdenticalToSchema( + NsSmartDeviceLink::NsSmartObjects::SmartObject& obj); + + void FillObjectIdenticalToSchemaWithoutNoMandatoriesParams( + NsSmartDeviceLink::NsSmartObjects::SmartObject& obj); + + void CompareObjects( + const NsSmartDeviceLink::NsSmartObjects::SmartObject& first, + const NsSmartDeviceLink::NsSmartObjects::SmartObject& second); + + void FillObjectWithDefaultValues( + NsSmartDeviceLink::NsSmartObjects::SmartObject& obj); + + void FillObjectWithoutSomeMandatoryFields( + NsSmartDeviceLink::NsSmartObjects::SmartObject& obj); + + // Members + std::set<FunctionIDTest::eType> function_id_items_; + std::set<MessageTypeTest::eType> message_type_items_; +}; + +} // namespace formatters +} // namespace components +} // namespace test + +#endif // SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_METAFORMATTERTESTHELPER_H_ diff --git a/src/components/formatters/test/meta_formatter_test.cc b/src/components/formatters/test/meta_formatter_test.cc new file mode 100644 index 0000000000..17c2506ac6 --- /dev/null +++ b/src/components/formatters/test/meta_formatter_test.cc @@ -0,0 +1,351 @@ +/* + * Copyright (c) 2015, 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. + */ + +#include "gtest/gtest.h" +#include "formatters/meta_formatter.h" +#include "meta_formatter_test_helper.h" + +namespace test { +namespace components { +namespace formatters { + +TEST_F(CMetaFormatterTestHelper, inputObjectIdenticalToSchemaWithAndWithoutMandatoryParams) { + Json::Value value; + Json::Reader reader; + CSmartFactory<FunctionIDTest::eType, MessageTypeTest::eType, + StructIdentifiers::eType> factory_; + + SmartObject object1 = factory_.CreateSmartObject( + FunctionIDTest::RegisterAppInterface, MessageTypeTest::request); + + SmartObject object2 = factory_.CreateSmartObject( + FunctionIDTest::RegisterAppInterface, MessageTypeTest::request); + + SmartObject result_object1; + SmartObject result_object2; + // Get schema + CSmartSchema schema; + schema = initSchemaForMetaFormatter(); + + FillObjectIdenticalToSchema(object1); + FillObjectIdenticalToSchemaWithoutNoMandatoriesParams(object2); + bool creationresult; + creationresult = CMetaFormatter::CreateObjectByPattern(object1, schema, + result_object1); + EXPECT_TRUE(creationresult); + creationresult = CMetaFormatter::CreateObjectByPattern(object2, schema, + result_object2); + EXPECT_TRUE(creationresult); + + // Uncomment code to print objects in console +// std::string formatted_string; +// CFormatterJsonSDLRPCv1::toString(object1, formatted_string); +// printf("object1 %s\n", formatted_string.c_str()); +// +// CFormatterJsonSDLRPCv1::toString(result_object1, formatted_string); +// printf("result_object1 %s\n", formatted_string.c_str()); +// +// CFormatterJsonSDLRPCv1::toString(object2, formatted_string); +// printf("object2 %s\n", formatted_string.c_str()); +// +// CFormatterJsonSDLRPCv1::toString(result_object2, formatted_string); +// printf("result_object2 %s\n", formatted_string.c_str()); + + CompareObjects(object1, result_object1); + CompareObjects(object2, result_object2); + + // Enums must be unapplied (converted to string) in order to be compared against strings + result_object1.getSchema().unapplySchema(result_object1); + EXPECT_EQ("request", result_object1[S_PARAMS][S_MESSAGE_TYPE].asString()); + EXPECT_EQ("RegisterAppInterface", + result_object1[S_PARAMS][S_FUNCTION_ID].asString()); + + result_object2.getSchema().unapplySchema(result_object2); + EXPECT_EQ("request", result_object2[S_PARAMS][S_MESSAGE_TYPE].asString()); + EXPECT_EQ("RegisterAppInterface", + result_object2[S_PARAMS][S_FUNCTION_ID].asString()); +} + +TEST_F(CMetaFormatterTestHelper, NormalSchemaWithEmptyObject) { + SmartObject object; + SmartObject result_object; + SmartObject expected_object; + + // Get schema + CSmartSchema schema = initSchemaForMetaFormatter(); + bool create_object_result = CMetaFormatter::CreateObjectByPattern( + object, schema, result_object); + EXPECT_TRUE(create_object_result); + + FillObjectWithDefaultValues(expected_object); + + CompareObjects(expected_object, result_object); + +// Uncomment code to print objects in console +// std::string str; +// AnyObjectToJsonString(result_object, str); +// printf("result_object(default) %s", str.c_str()); +// AnyObjectToJsonString(expected_object, str); +// printf("expected_object %s", str.c_str()); + + +} + +TEST_F(CMetaFormatterTestHelper, NormalSchemaWithObjectWithoutSomeMandatoryFields) { + SmartObject object; + SmartObject result_object; + + // Get schema + CSmartSchema schema = initSchemaForMetaFormatter(); + FillObjectWithoutSomeMandatoryFields(object); + + CMetaFormatter::CreateObjectByPattern(object, schema, result_object); + + CompareObjects(object, result_object); + EXPECT_EQ(0, result_object[S_PARAMS][S_CORRELATION_ID].asInt()); + EXPECT_EQ( + 0, result_object[S_MSG_PARAMS]["syncMsgVersion"]["majorVersion"].asInt()); + EXPECT_EQ( + 0, result_object[S_MSG_PARAMS]["syncMsgVersion"]["minorVersion"].asInt()); + +// Uncomment code to print object in console +// std::string str; +// AnyObjectToJsonString(result_object, str); +// printf("result_object %s", str.c_str()); + +} + +TEST_F(CMetaFormatterTestHelper, ObjectWithEmptyMap) { + std::map<std::string, CObjectSchemaItem::SMember> schemaMembersMap; + CSmartSchema map_schema = CSmartSchema( + CObjectSchemaItem::create(schemaMembersMap)); + + SmartObject object; + SmartObject result_object_empty_map; + + SmartObject object_empty_map = SmartObject(SmartType_Map); + CMetaFormatter::CreateObjectByPattern(object_empty_map, map_schema, + result_object_empty_map); + EXPECT_EQ(SmartType_Map, result_object_empty_map.getType())<< "smartObject is not map type"; + EXPECT_EQ(0u, result_object_empty_map.length())<< "non empty map"; + + CMetaFormatter::CreateObjectByPattern(object, map_schema, + result_object_empty_map); + EXPECT_EQ(SmartType_Map, result_object_empty_map.getType())<< "smartObject is not map type"; + EXPECT_EQ(0u, result_object_empty_map.length())<< "non empty map"; + + object["field1"] = 0; + object["field2"] = SmartObject(); + CMetaFormatter::CreateObjectByPattern(object, map_schema, + result_object_empty_map); + EXPECT_EQ(SmartType_Map, result_object_empty_map.getType())<< "smartObject is not map type"; + EXPECT_EQ(0u, result_object_empty_map.length())<< "non empty map"; + + // Fill object with any values. Result must be the same + FillObjectIdenticalToSchema(object); + CMetaFormatter::CreateObjectByPattern(object, map_schema, + result_object_empty_map); + EXPECT_EQ(SmartType_Map, result_object_empty_map.getType())<< "smartObject is not map type"; + EXPECT_EQ(0u, result_object_empty_map.length())<< "non empty map"; + + // Fill object with any values. Result must be the same + FillObjectIdenticalToSchemaWithoutNoMandatoriesParams(object); + CMetaFormatter::CreateObjectByPattern(object, map_schema, + result_object_empty_map); + EXPECT_EQ(SmartType_Map, result_object_empty_map.getType())<< "smartObject is not map type"; + EXPECT_EQ(0u, result_object_empty_map.length())<< "non empty map"; + +// Uncomment code to print object in console +// std::string str; +// AnyObjectToJsonString(result_object_empty_map, str); +// printf("result_object(empty map) %s", str.c_str()); + +} + +TEST_F(CMetaFormatterTestHelper, ObjectWithEmptyArray) { + SmartObject object; + + SmartObject result_object_empty_array; + CSmartSchema array_schema = CSmartSchema(CArraySchemaItem::create()); + + SmartObject object_empty_aray = SmartObject(SmartType_Array); + + CMetaFormatter::CreateObjectByPattern(object_empty_aray, array_schema, + result_object_empty_array); + EXPECT_EQ(SmartType_Array, result_object_empty_array.getType())<< "smartObject is not array type"; + EXPECT_EQ(0u, result_object_empty_array.length())<< "non empty array"; + + CMetaFormatter::CreateObjectByPattern(object, array_schema, + result_object_empty_array); + EXPECT_EQ(SmartType_Array, result_object_empty_array.getType())<< "smartObject is not array type"; + EXPECT_EQ(0u, result_object_empty_array.length())<< "non empty array"; + + // Fill object with any values. Result must be the same + FillObjectIdenticalToSchema(object); + CMetaFormatter::CreateObjectByPattern(object, array_schema, + result_object_empty_array); + EXPECT_EQ(SmartType_Array, result_object_empty_array.getType())<< "smartObject is not array type"; + EXPECT_EQ(0u, result_object_empty_array.length())<< "non empty array"; + + // Fill object with any values. Result must be the same + FillObjectWithoutSomeMandatoryFields(object); + CMetaFormatter::CreateObjectByPattern(object, array_schema, + result_object_empty_array); + EXPECT_EQ(SmartType_Array, result_object_empty_array.getType())<< "smartObject is not array type"; + EXPECT_EQ(0u, result_object_empty_array.length())<< "non empty array"; + +// Uncomment code to print object in console +// std::string str; +// AnyObjectToJsonString(result_object_empty_array, str); +// printf("result_object(empty array) %s", str.c_str()); + +} + +TEST_F(CMetaFormatterTestHelper, ObjectWithEmptyArrayAndEmptyMapWithOtherParameters) { + // Arrange + SmartObject result_object; + SmartObject object; + + std::map<std::string, CObjectSchemaItem::SMember> paramsMembersMap; + + paramsMembersMap[S_FUNCTION_ID] = CObjectSchemaItem::SMember( + TEnumSchemaItem<FunctionIDTest::eType>::create(function_id_items_), true); + + paramsMembersMap[S_MESSAGE_TYPE] = CObjectSchemaItem::SMember( + TEnumSchemaItem<MessageTypeTest::eType>::create(message_type_items_), + true); + + paramsMembersMap[S_CORRELATION_ID] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(0), + TSchemaItemParameter<int>(100), + TSchemaItemParameter<int>(55)), + true); + + paramsMembersMap[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(1), + TSchemaItemParameter<int>(2)), + false); + paramsMembersMap[S_PROTOCOL_TYPE] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), false); + + std::map<std::string, CObjectSchemaItem::SMember> schemaMembersMap; + + schemaMembersMap["mandatory_emptyMap1"] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create( + std::map<std::string, CObjectSchemaItem::SMember>()), + true); + + schemaMembersMap["mandatory_emptyMap2"] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create( + std::map<std::string, CObjectSchemaItem::SMember>()), + true); + + schemaMembersMap["mandatory_emptyAray"] = CObjectSchemaItem::SMember( + CArraySchemaItem::create(TNumberSchemaItem<int>::create()), true); + + schemaMembersMap["non_mandatory_Array"] = CObjectSchemaItem::SMember( + CArraySchemaItem::create(TNumberSchemaItem<int>::create(), + TSchemaItemParameter<size_t>(1), + TSchemaItemParameter<size_t>(2)), + false); + + schemaMembersMap["mandatory_string"] = CObjectSchemaItem::SMember( + CStringSchemaItem::create(TSchemaItemParameter<size_t>(0), + TSchemaItemParameter<size_t>(500), + TSchemaItemParameter<std::string>("defValue")), + true); + + schemaMembersMap["non_mandatory_string"] = CObjectSchemaItem::SMember( + CStringSchemaItem::create( + TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(500), + TSchemaItemParameter<std::string>("ignoredDefValue")), + false); + + std::map<std::string, CObjectSchemaItem::SMember> rootMembersMap; + rootMembersMap[S_MSG_PARAMS] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create(schemaMembersMap), true); + rootMembersMap[S_PARAMS] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create(paramsMembersMap), true); + + CSmartSchema schema = CSmartSchema(CObjectSchemaItem::create(rootMembersMap)); + + // Set object value + object[S_PARAMS][S_FUNCTION_ID] = 500; + object[S_PARAMS][S_PROTOCOL_VERSION] = 11; + object[S_PARAMS]["new_field"] = "100500 string"; + + object[S_MSG_PARAMS]["mandatory_emptyMap1"]["field1"] = 123; + object[S_MSG_PARAMS]["mandatory_emptyMap1"]["field2"][0] = 100; + object[S_MSG_PARAMS]["mandatory_emptyMap1"]["field2"][1] = 200; + object[S_MSG_PARAMS]["non_mandatory_Array"][0] = 100; + object[S_MSG_PARAMS]["non_mandatory_Array"][1] = 200; + object[S_MSG_PARAMS]["non_mandatory_Array"][2] = 300; + object[S_MSG_PARAMS]["non_mandatory_string"] = "some string"; + + CMetaFormatter::CreateObjectByPattern(object, schema, result_object); + +// Uncomment code to print object in console +// std::string str; +// AnyObjectToJsonString(object, str); +// printf("object %s", str.c_str()); +// AnyObjectToJsonString(result_object, str); +// printf("result_object %s", str.c_str()); + + + // Assert + EXPECT_EQ(500, result_object[S_PARAMS][S_FUNCTION_ID].asInt()); + EXPECT_EQ(-1, result_object[S_PARAMS][S_MESSAGE_TYPE].asInt()); + EXPECT_EQ(55, result_object[S_PARAMS][S_CORRELATION_ID].asInt()); + EXPECT_EQ(11u, result_object[S_PARAMS][S_PROTOCOL_VERSION].asUInt()); + + EXPECT_EQ(SmartType_Map, + result_object[S_MSG_PARAMS]["mandatory_emptyMap1"].getType()); + EXPECT_EQ(0u, result_object[S_MSG_PARAMS]["mandatory_emptyMap1"].length()); + EXPECT_EQ(SmartType_Map, + result_object[S_MSG_PARAMS]["mandatory_emptyMap2"].getType()); + EXPECT_EQ(0u, result_object[S_MSG_PARAMS]["mandatory_emptyMap2"].length()); + EXPECT_EQ(SmartType_Array, + result_object[S_MSG_PARAMS]["mandatory_emptyAray"].getType()); + EXPECT_EQ(0u, result_object[S_MSG_PARAMS]["mandatory_emptyAray"].length()); + EXPECT_EQ(100, result_object[S_MSG_PARAMS]["non_mandatory_Array"][0].asInt()); + EXPECT_EQ(200, result_object[S_MSG_PARAMS]["non_mandatory_Array"][1].asInt()); + EXPECT_EQ(300u, + result_object[S_MSG_PARAMS]["non_mandatory_Array"][2].asUInt()); + EXPECT_EQ(std::string("defValue"), + result_object[S_MSG_PARAMS]["mandatory_string"].asString()); + EXPECT_EQ(std::string("some string"), + result_object[S_MSG_PARAMS]["non_mandatory_string"].asString()); +} + +} // namespace formatters +} // namespace components +} // namespace test diff --git a/src/components/formatters/test/src/SmartFactoryTestHelper.cc b/src/components/formatters/test/src/SmartFactoryTestHelper.cc new file mode 100644 index 0000000000..8f601afc29 --- /dev/null +++ b/src/components/formatters/test/src/SmartFactoryTestHelper.cc @@ -0,0 +1,501 @@ +/* + * Copyright (c) 2015, 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. + */ + +#include "SmartFactoryTestHelper.h" + +using namespace test::components::formatters; + +template<> +const EnumConversionHelper<TestType::eType>::EnumToCStringMap EnumConversionHelper< + test::components::formatters::TestType::eType>::enum_to_cstring_map_ = + EnumConversionHelper<test::components::formatters::TestType::eType>::InitEnumToCStringMap(); + +template<> +const EnumConversionHelper<TestType::eType>::CStringToEnumMap EnumConversionHelper< + test::components::formatters::TestType::eType>::cstring_to_enum_map_ = + EnumConversionHelper<test::components::formatters::TestType::eType>::InitCStringToEnumMap(); + +template<> +const char* const EnumConversionHelper<TestType::eType>::cstring_values_[] = { + "APPLICATION_NOT_REGISTERED", "SUCCESS", "TOO_MANY_PENDING_REQUESTS", + "REJECTED", "INVALID_DATA", "OUT_OF_MEMORY", "ABORTED", "USER_DISALLOWED", + "GENERIC_ERROR", "DISALLOWED" }; + +template<> +const TestType::eType EnumConversionHelper<TestType::eType>::enum_values_[] = { + test::components::formatters::TestType::APPLICATION_NOT_REGISTERED, + test::components::formatters::TestType::SUCCESS, + test::components::formatters::TestType::TOO_MANY_PENDING_REQUESTS, + test::components::formatters::TestType::REJECTED, + test::components::formatters::TestType::INVALID_DATA, + test::components::formatters::TestType::OUT_OF_MEMORY, + test::components::formatters::TestType::ABORTED, + test::components::formatters::TestType::USER_DISALLOWED, + test::components::formatters::TestType::GENERIC_ERROR, + test::components::formatters::TestType::DISALLOWED }; + +template<> +const EnumConversionHelper<FunctionIdTest::eType>::EnumToCStringMap EnumConversionHelper< + test::components::formatters::FunctionIdTest::eType>::enum_to_cstring_map_ = + EnumConversionHelper<test::components::formatters::FunctionIdTest::eType>::InitEnumToCStringMap(); + +template<> +const EnumConversionHelper<FunctionIdTest::eType>::CStringToEnumMap EnumConversionHelper< + test::components::formatters::FunctionIdTest::eType>::cstring_to_enum_map_ = + EnumConversionHelper<test::components::formatters::FunctionIdTest::eType>::InitCStringToEnumMap(); + +template<> +const char* const EnumConversionHelper<FunctionIdTest::eType>::cstring_values_[] = + { "Function1", "Function2", "Function3" }; + +template<> +const FunctionIdTest::eType EnumConversionHelper<FunctionIdTest::eType>::enum_values_[] = + { test::components::formatters::FunctionIdTest::Function1, + test::components::formatters::FunctionIdTest::Function2, + test::components::formatters::FunctionIdTest::Function3 }; + +template<> +const EnumConversionHelper<MessageTypeTest::eType>::EnumToCStringMap EnumConversionHelper< + test::components::formatters::MessageTypeTest::eType>::enum_to_cstring_map_ = + EnumConversionHelper<test::components::formatters::MessageTypeTest::eType>::InitEnumToCStringMap(); + +template<> +const EnumConversionHelper<MessageTypeTest::eType>::CStringToEnumMap EnumConversionHelper< + test::components::formatters::MessageTypeTest::eType>::cstring_to_enum_map_ = + EnumConversionHelper<test::components::formatters::MessageTypeTest::eType>::InitCStringToEnumMap(); + +template<> +const char* const EnumConversionHelper<MessageTypeTest::eType>::cstring_values_[] = + { "request", "response", "notification" }; + +template<> +const MessageTypeTest::eType EnumConversionHelper<MessageTypeTest::eType>::enum_values_[] = + { test::components::formatters::MessageTypeTest::request, + test::components::formatters::MessageTypeTest::response, + test::components::formatters::MessageTypeTest::notification }; + +CSmartFactoryTest::CSmartFactoryTest() + : CSmartFactory<FunctionIdTest::eType, MessageTypeTest::eType, + StructIdentifiersTest::eType>() { + TStructsSchemaItems struct_schema_items; + InitStructSchemes(struct_schema_items); + std::set<FunctionIdTest::eType> function_id_items; + function_id_items.insert(FunctionIdTest::Function1); + function_id_items.insert(FunctionIdTest::Function2); + function_id_items.insert(FunctionIdTest::Function3); + + std::set<MessageTypeTest::eType> message_type_items; + message_type_items.insert(MessageTypeTest::request); + message_type_items.insert(MessageTypeTest::response); + message_type_items.insert(MessageTypeTest::notification); + message_type_items.insert(MessageTypeTest::error_response); + InitFunctionSchemes(struct_schema_items, function_id_items, + message_type_items); +} + +void CSmartFactoryTest::InitStructSchemes( + TStructsSchemaItems &struct_schema_items) { + utils::SharedPtr<ISchemaItem> struct_schema_item_Common_1 = + InitStructSchemaItem_Common_1(struct_schema_items); + struct_schema_items.insert( + std::make_pair(StructIdentifiersTest::Common_1, + struct_schema_item_Common_1)); + structs_schemes_.insert( + std::make_pair(StructIdentifiersTest::Common_1, + CSmartSchema(struct_schema_item_Common_1))); + + utils::SharedPtr<ISchemaItem> struct_schema_item_Common_2 = + InitStructSchemaItem_Common_2(); + struct_schema_items.insert( + std::make_pair(StructIdentifiersTest::Common_2, + struct_schema_item_Common_2)); + structs_schemes_.insert( + std::make_pair(StructIdentifiersTest::Common_2, + CSmartSchema(struct_schema_item_Common_2))); +} + +void CSmartFactoryTest::InitFunctionSchemes( + const TStructsSchemaItems &struct_schema_items, + const std::set<FunctionIdTest::eType> &function_id_items, + const std::set<MessageTypeTest::eType> &message_type_items) { + CObjectSchemaItem::Members params_members; + params_members[S_FUNCTION_ID] = CObjectSchemaItem::SMember( + TEnumSchemaItem<FunctionIdTest::eType>::create(function_id_items), true); + params_members[S_MESSAGE_TYPE] = CObjectSchemaItem::SMember( + TEnumSchemaItem<MessageTypeTest::eType>::create(message_type_items), + true); + params_members[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + params_members[S_PROTOCOL_TYPE] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + params_members[S_CORRELATION_ID] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + params_members[kCode] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + params_members[kMessage] = CObjectSchemaItem::SMember( + CStringSchemaItem::create(), true); + + CObjectSchemaItem::Members root_members_map; + root_members_map[NsSmartDeviceLink::NsJSONHandler::strings::S_PARAMS] = + CObjectSchemaItem::SMember(CObjectSchemaItem::create(params_members), + true); + + CSmartSchema error_response_schema( + CObjectSchemaItem::create(root_members_map)); + + functions_schemes_.insert( + std::make_pair( + SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>( + FunctionIdTest::Function1, MessageTypeTest::error_response), + error_response_schema)); + functions_schemes_.insert( + std::make_pair( + SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>( + FunctionIdTest::Function1, MessageTypeTest::request), + InitFunction_Function1_request(function_id_items, + message_type_items))); + functions_schemes_.insert( + std::make_pair( + SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>( + FunctionIdTest::Function1, MessageTypeTest::response), + InitFunction_Function1_response(struct_schema_items, + function_id_items, + message_type_items))); + + functions_schemes_.insert( + std::make_pair( + SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>( + FunctionIdTest::Function2, MessageTypeTest::error_response), + error_response_schema)); + functions_schemes_.insert( + std::make_pair( + SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>( + FunctionIdTest::Function2, MessageTypeTest::request), + InitFunction_Function2_request(function_id_items, + message_type_items))); + functions_schemes_.insert( + std::make_pair( + SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>( + FunctionIdTest::Function2, MessageTypeTest::response), + InitFunction_Function2_response(struct_schema_items, + function_id_items, + message_type_items))); + + functions_schemes_.insert( + std::make_pair( + SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>( + FunctionIdTest::Function3, MessageTypeTest::error_response), + error_response_schema)); + functions_schemes_.insert( + std::make_pair( + SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>( + FunctionIdTest::Function3, MessageTypeTest::request), + InitFunction_Function3_request(function_id_items, + message_type_items))); + functions_schemes_.insert( + std::make_pair( + SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>( + FunctionIdTest::Function3, MessageTypeTest::response), + InitFunction_Function3_response(struct_schema_items, + function_id_items, + message_type_items))); +} + +CSmartSchema CSmartFactoryTest::InitFunction_Function1_request( + const std::set<FunctionIdTest::eType> &function_id_items, + const std::set<MessageTypeTest::eType> &message_type_items) { + + CObjectSchemaItem::Members schema_members; + CObjectSchemaItem::Members params_members; + + params_members[S_FUNCTION_ID] = CObjectSchemaItem::SMember( + TEnumSchemaItem<FunctionIdTest::eType>::create(function_id_items), true); + params_members[S_MESSAGE_TYPE] = CObjectSchemaItem::SMember( + TEnumSchemaItem<MessageTypeTest::eType>::create(message_type_items), + true); + params_members[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + params_members[S_PROTOCOL_TYPE] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + params_members[S_CORRELATION_ID] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + + CObjectSchemaItem::Members root_members_map; + root_members_map[S_MSG_PARAMS] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create(schema_members), true); + root_members_map[S_PARAMS] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create(params_members), true); + + return CSmartSchema(CObjectSchemaItem::create(root_members_map)); +} + +CSmartSchema CSmartFactoryTest::InitFunction_Function1_response( + const TStructsSchemaItems &struct_schema_items, + const std::set<FunctionIdTest::eType> &function_id_items, + const std::set<MessageTypeTest::eType> &message_type_items) { + // Function parameter available. + utils::SharedPtr<ISchemaItem> available_SchemaItem = CBoolSchemaItem::create( + TSchemaItemParameter<bool>()); + + CObjectSchemaItem::Members schema_members; + + schema_members["available"] = CObjectSchemaItem::SMember(available_SchemaItem, + true); + + CObjectSchemaItem::Members params_members; + params_members[S_FUNCTION_ID] = CObjectSchemaItem::SMember( + TEnumSchemaItem<FunctionIdTest::eType>::create(function_id_items), true); + params_members[S_MESSAGE_TYPE] = CObjectSchemaItem::SMember( + TEnumSchemaItem<MessageTypeTest::eType>::create(message_type_items), + true); + params_members[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + params_members[S_PROTOCOL_TYPE] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + params_members[S_CORRELATION_ID] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + params_members[kCode] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + + CObjectSchemaItem::Members root_members_map; + root_members_map[S_MSG_PARAMS] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create(schema_members), true); + root_members_map[S_PARAMS] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create(params_members), true); + + return CSmartSchema(CObjectSchemaItem::create(root_members_map)); +} + +CSmartSchema CSmartFactoryTest::InitFunction_Function2_request( + const std::set<FunctionIdTest::eType> &function_id_items, + const std::set<MessageTypeTest::eType> &message_type_items) { + CObjectSchemaItem::Members schema_members; + + CObjectSchemaItem::Members params_members; + params_members[S_FUNCTION_ID] = CObjectSchemaItem::SMember( + TEnumSchemaItem<FunctionIdTest::eType>::create(function_id_items), true); + params_members[S_MESSAGE_TYPE] = CObjectSchemaItem::SMember( + TEnumSchemaItem<MessageTypeTest::eType>::create(message_type_items), + true); + params_members[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + params_members[S_PROTOCOL_TYPE] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + params_members[S_CORRELATION_ID] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + + CObjectSchemaItem::Members root_members_map; + root_members_map[S_MSG_PARAMS] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create(schema_members), true); + root_members_map[S_PARAMS] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create(params_members), true); + + return CSmartSchema(CObjectSchemaItem::create(root_members_map)); +} + +CSmartSchema CSmartFactoryTest::InitFunction_Function2_response( + const TStructsSchemaItems &struct_schema_items, + const std::set<FunctionIdTest::eType> &function_id_items, + const std::set<MessageTypeTest::eType> &message_type_items) { + // Function parameter available. + utils::SharedPtr<ISchemaItem> available_SchemaItem = CBoolSchemaItem::create( + TSchemaItemParameter<bool>()); + + CObjectSchemaItem::Members schema_members; + + schema_members["available"] = CObjectSchemaItem::SMember(available_SchemaItem, + true); + + CObjectSchemaItem::Members params_members; + params_members[S_FUNCTION_ID] = CObjectSchemaItem::SMember( + TEnumSchemaItem<FunctionIdTest::eType>::create(function_id_items), true); + params_members[S_MESSAGE_TYPE] = CObjectSchemaItem::SMember( + TEnumSchemaItem<MessageTypeTest::eType>::create(message_type_items), + true); + params_members[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + params_members[S_PROTOCOL_TYPE] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + params_members[S_CORRELATION_ID] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + params_members[kCode] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + + CObjectSchemaItem::Members root_members_map; + root_members_map[S_MSG_PARAMS] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create(schema_members), true); + root_members_map[S_PARAMS] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create(params_members), true); + + return CSmartSchema(CObjectSchemaItem::create(root_members_map)); +} + +CSmartSchema CSmartFactoryTest::InitFunction_Function3_request( + const std::set<FunctionIdTest::eType> &function_id_items, + const std::set<MessageTypeTest::eType> &message_type_items) { + CObjectSchemaItem::Members schema_members; + + CObjectSchemaItem::Members params_members; + params_members[S_FUNCTION_ID] = CObjectSchemaItem::SMember( + TEnumSchemaItem<FunctionIdTest::eType>::create(function_id_items), true); + params_members[S_MESSAGE_TYPE] = CObjectSchemaItem::SMember( + TEnumSchemaItem<MessageTypeTest::eType>::create(message_type_items), + true); + params_members[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + params_members[S_PROTOCOL_TYPE] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + params_members[S_CORRELATION_ID] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + + CObjectSchemaItem::Members root_members_map; + root_members_map[S_MSG_PARAMS] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create(schema_members), true); + root_members_map[S_PARAMS] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create(params_members), true); + + return CSmartSchema(CObjectSchemaItem::create(root_members_map)); +} + +CSmartSchema CSmartFactoryTest::InitFunction_Function3_response( + const TStructsSchemaItems &struct_schema_items, + const std::set<FunctionIdTest::eType> &function_id_items, + const std::set<MessageTypeTest::eType> &message_type_items) { + // Function parameter available. + // + // Must be true if VR is present and ready to communicate with SDL. + utils::SharedPtr<ISchemaItem> available_SchemaItem = CBoolSchemaItem::create( + TSchemaItemParameter<bool>()); + + CObjectSchemaItem::Members schema_members; + + schema_members["available"] = CObjectSchemaItem::SMember(available_SchemaItem, + true); + + CObjectSchemaItem::Members params_members; + params_members[S_FUNCTION_ID] = CObjectSchemaItem::SMember( + TEnumSchemaItem<FunctionIdTest::eType>::create(function_id_items), true); + params_members[S_MESSAGE_TYPE] = CObjectSchemaItem::SMember( + TEnumSchemaItem<MessageTypeTest::eType>::create(message_type_items), + true); + params_members[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + params_members[S_PROTOCOL_TYPE] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + params_members[S_CORRELATION_ID] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + params_members[kCode] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + + CObjectSchemaItem::Members root_members_map; + root_members_map[S_MSG_PARAMS] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create(schema_members), true); + root_members_map[S_PARAMS] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create(params_members), true); + + return CSmartSchema(CObjectSchemaItem::create(root_members_map)); +} + +utils::SharedPtr<ISchemaItem> CSmartFactoryTest::InitStructSchemaItem_Common_1( + TStructsSchemaItems &struct_schema_items) { + // Struct member text. + // + // Text to display + utils::SharedPtr<ISchemaItem> text_SchemaItem = CStringSchemaItem::create( + TSchemaItemParameter<size_t>(1), TSchemaItemParameter<size_t>(500), + TSchemaItemParameter<std::string>()); + + // Struct member image. + // + // Image struct + utils::SharedPtr<ISchemaItem> image_SchemaItem = + ProvideObjectSchemaItemForStruct(struct_schema_items, + StructIdentifiersTest::Common_2); + + // Struct member position. + // + // Position to display item + utils::SharedPtr<ISchemaItem> position_SchemaItem = + TNumberSchemaItem<int32_t>::create(TSchemaItemParameter<int32_t>(1), + TSchemaItemParameter<int32_t>(500), + TSchemaItemParameter<int32_t>()); + CObjectSchemaItem::Members struct_members; + struct_members["image"] = CObjectSchemaItem::SMember(image_SchemaItem, false); + + CObjectSchemaItem::Members schema_members; + + schema_members["text"] = CObjectSchemaItem::SMember(text_SchemaItem, true); + schema_members["position"] = CObjectSchemaItem::SMember(position_SchemaItem, + true); + + CObjectSchemaItem::Members root_members_map; + root_members_map[""] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create(struct_members), true); + root_members_map[""] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create(schema_members), true); + return CObjectSchemaItem::create(schema_members); +} + +utils::SharedPtr<ISchemaItem> CSmartFactoryTest::InitStructSchemaItem_Common_2() { + // Struct member text. + // + // Text to display + utils::SharedPtr<ISchemaItem> text_SchemaItem = CStringSchemaItem::create( + TSchemaItemParameter<size_t>(1), TSchemaItemParameter<size_t>(500), + TSchemaItemParameter<std::string>()); + // Struct member position. + // + // Position to display item + utils::SharedPtr<ISchemaItem> position_SchemaItem = + TNumberSchemaItem<int32_t>::create(TSchemaItemParameter<int32_t>(1), + TSchemaItemParameter<int32_t>(500), + TSchemaItemParameter<int32_t>()); + + CObjectSchemaItem::Members schema_members; + schema_members["text"] = CObjectSchemaItem::SMember(text_SchemaItem, true); + schema_members["position"] = CObjectSchemaItem::SMember(position_SchemaItem, + true); + + return CObjectSchemaItem::create(schema_members); +} + +utils::SharedPtr<ISchemaItem> CSmartFactoryTest::ProvideObjectSchemaItemForStruct( + TStructsSchemaItems &struct_schema_items, + const StructIdentifiersTest::eType struct_id) { + const TStructsSchemaItems::const_iterator it = struct_schema_items.find( + struct_id); + if (it != struct_schema_items.end()) { + return it->second; + } + return NsSmartDeviceLink::NsSmartObjects::CAlwaysFalseSchemaItem::create(); +} + diff --git a/src/components/formatters/test/src/create_smartSchema.cc b/src/components/formatters/test/src/create_smartSchema.cc new file mode 100644 index 0000000000..9d44567dcd --- /dev/null +++ b/src/components/formatters/test/src/create_smartSchema.cc @@ -0,0 +1,379 @@ +/* + * Copyright (c) 2015, 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. + */ + +#include "create_smartSchema.h" +namespace test { +namespace components { +namespace formatters { + +using namespace NsSmartDeviceLink::NsJSONHandler::strings; +using namespace NsSmartDeviceLink::NsJSONHandler::Formatters; +using namespace NsSmartDeviceLink::NsSmartObjects; + +template<> +const EnumConversionHelper<FunctionIDTest::eType>::EnumToCStringMap EnumConversionHelper< + test::components::formatters::FunctionIDTest::eType>::enum_to_cstring_map_ = + EnumConversionHelper<test::components::formatters::FunctionIDTest::eType>::InitEnumToCStringMap(); + +template<> +const EnumConversionHelper<FunctionIDTest::eType>::CStringToEnumMap EnumConversionHelper< + test::components::formatters::FunctionIDTest::eType>::cstring_to_enum_map_ = + EnumConversionHelper<test::components::formatters::FunctionIDTest::eType>::InitCStringToEnumMap(); + +template<> +const char* const EnumConversionHelper<FunctionIDTest::eType>::cstring_values_[] = + { "RegisterAppInterface", "UnregisterAppInterface", "SetGlobalProperties" }; + +template<> +const FunctionIDTest::eType EnumConversionHelper<FunctionIDTest::eType>::enum_values_[] = + { test::components::formatters::FunctionIDTest::RegisterAppInterface, + test::components::formatters::FunctionIDTest::UnregisterAppInterface, + test::components::formatters::FunctionIDTest::SetGlobalProperties }; + +template<> +const EnumConversionHelper<Language::eType>::EnumToCStringMap EnumConversionHelper< + test::components::formatters::Language::eType>::enum_to_cstring_map_ = + EnumConversionHelper<test::components::formatters::Language::eType>::InitEnumToCStringMap(); + +template<> +const EnumConversionHelper<Language::eType>::CStringToEnumMap EnumConversionHelper< + test::components::formatters::Language::eType>::cstring_to_enum_map_ = + EnumConversionHelper<test::components::formatters::Language::eType>::InitCStringToEnumMap(); + +template<> +const char* const EnumConversionHelper<Language::eType>::cstring_values_[] = + { "EN_EU", "RU_RU"}; + +template<> +const Language::eType EnumConversionHelper<Language::eType>::enum_values_[] = + { test::components::formatters::Language::EN_EU, + test::components::formatters::Language::RU_RU}; + +template<> +const EnumConversionHelper<SpeechCapabilities::eType>::EnumToCStringMap EnumConversionHelper< + test::components::formatters::SpeechCapabilities::eType>::enum_to_cstring_map_ = + EnumConversionHelper<test::components::formatters::SpeechCapabilities::eType>::InitEnumToCStringMap(); + +template<> +const EnumConversionHelper<SpeechCapabilities::eType>::CStringToEnumMap EnumConversionHelper< + test::components::formatters::SpeechCapabilities::eType>::cstring_to_enum_map_ = + EnumConversionHelper<test::components::formatters::SpeechCapabilities::eType>::InitCStringToEnumMap(); + +template<> +const char* const EnumConversionHelper<SpeechCapabilities::eType>::cstring_values_[] = + { "SC_TEXT"}; + +template<> +const SpeechCapabilities::eType EnumConversionHelper<SpeechCapabilities::eType>::enum_values_[] = + { test::components::formatters::SpeechCapabilities::SC_TEXT}; + +template<> +const EnumConversionHelper<AppTypeTest::eType>::EnumToCStringMap EnumConversionHelper< + test::components::formatters::AppTypeTest::eType>::enum_to_cstring_map_ = + EnumConversionHelper<test::components::formatters::AppTypeTest::eType>::InitEnumToCStringMap(); + +template<> +const EnumConversionHelper<AppTypeTest::eType>::CStringToEnumMap EnumConversionHelper< + test::components::formatters::AppTypeTest::eType>::cstring_to_enum_map_ = + EnumConversionHelper<test::components::formatters::AppTypeTest::eType>::InitCStringToEnumMap(); + +template<> +const char* const EnumConversionHelper<AppTypeTest::eType>::cstring_values_[] = + { "SYSTEM", "MEDIA"}; + +template<> +const AppTypeTest::eType EnumConversionHelper<AppTypeTest::eType>::enum_values_[] = + { test::components::formatters::AppTypeTest::SYSTEM, + test::components::formatters::AppTypeTest::MEDIA, + }; + +CSmartSchema initObjectSchema() { + std::set<TestType::eType> resultCode_allowedEnumSubsetValues; + resultCode_allowedEnumSubsetValues.insert( + TestType::APPLICATION_NOT_REGISTERED); + resultCode_allowedEnumSubsetValues.insert(TestType::SUCCESS); + resultCode_allowedEnumSubsetValues.insert( + TestType::TOO_MANY_PENDING_REQUESTS); + resultCode_allowedEnumSubsetValues.insert(TestType::REJECTED); + resultCode_allowedEnumSubsetValues.insert(TestType::INVALID_DATA); + resultCode_allowedEnumSubsetValues.insert(TestType::OUT_OF_MEMORY); + resultCode_allowedEnumSubsetValues.insert(TestType::ABORTED); + resultCode_allowedEnumSubsetValues.insert(TestType::USER_DISALLOWED); + resultCode_allowedEnumSubsetValues.insert(TestType::GENERIC_ERROR); + resultCode_allowedEnumSubsetValues.insert(TestType::DISALLOWED); + + // Possible functions in this test scheme + std::set<FunctionIDTest::eType> functionId_allowedEnumSubsetValues; + functionId_allowedEnumSubsetValues.insert( + FunctionIDTest::RegisterAppInterface); + functionId_allowedEnumSubsetValues.insert( + FunctionIDTest::UnregisterAppInterface); + functionId_allowedEnumSubsetValues.insert( + FunctionIDTest::SetGlobalProperties); + + // Possible message types + std::set<MessageTypeTest::eType> messageType_allowedEnumSubsetValues; + messageType_allowedEnumSubsetValues.insert(MessageTypeTest::request); + messageType_allowedEnumSubsetValues.insert(MessageTypeTest::response); + messageType_allowedEnumSubsetValues.insert(MessageTypeTest::notification); + + // Create result item + ISchemaItemPtr success_SchemaItem = CBoolSchemaItem::create( + TSchemaItemParameter<bool>()); + ISchemaItemPtr resultCode_SchemaItem = + TEnumSchemaItem<TestType::eType>::create( + resultCode_allowedEnumSubsetValues, + TSchemaItemParameter<TestType::eType>()); + + // Create info value with min 0 length and max 1000 + ISchemaItemPtr info_SchemaItem = CStringSchemaItem::create( + TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000), + TSchemaItemParameter<std::string>()); + + ISchemaItemPtr tryAgainTime_SchemaItem = TNumberSchemaItem<int>::create( + TSchemaItemParameter<int>(0), TSchemaItemParameter<int>(2000000000), + TSchemaItemParameter<int>()); + + // Map of parameters + std::map<std::string, CObjectSchemaItem::SMember> schemaMembersMap; + + schemaMembersMap["success"] = CObjectSchemaItem::SMember(success_SchemaItem, + false); + schemaMembersMap["resultCode"] = CObjectSchemaItem::SMember( + resultCode_SchemaItem, false); + schemaMembersMap["info"] = CObjectSchemaItem::SMember(info_SchemaItem, false); + schemaMembersMap["tryAgainTime"] = CObjectSchemaItem::SMember( + tryAgainTime_SchemaItem, false); + + std::map<std::string, CObjectSchemaItem::SMember> paramsMembersMap; + paramsMembersMap[S_FUNCTION_ID] = CObjectSchemaItem::SMember( + TEnumSchemaItem<FunctionIDTest::eType>::create( + functionId_allowedEnumSubsetValues), + true); + paramsMembersMap[S_MESSAGE_TYPE] = CObjectSchemaItem::SMember( + TEnumSchemaItem<MessageTypeTest::eType>::create( + messageType_allowedEnumSubsetValues), + true); + paramsMembersMap[S_CORRELATION_ID] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + paramsMembersMap[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(1), + TSchemaItemParameter<int>(2)), + true); + paramsMembersMap[S_PROTOCOL_TYPE] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + + std::map<std::string, CObjectSchemaItem::SMember> rootMembersMap; + rootMembersMap[S_MSG_PARAMS] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create(schemaMembersMap), true); + rootMembersMap[S_PARAMS] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create(paramsMembersMap), true); + return CSmartSchema(CObjectSchemaItem::create(rootMembersMap)); +}; + + +CSmartSchema initSchemaForMetaFormatter() { + std::set<TestType::eType> resultCode_allowedEnumSubsetValues; + resultCode_allowedEnumSubsetValues.insert( + TestType::APPLICATION_NOT_REGISTERED); + resultCode_allowedEnumSubsetValues.insert(TestType::SUCCESS); + resultCode_allowedEnumSubsetValues.insert( + TestType::TOO_MANY_PENDING_REQUESTS); + resultCode_allowedEnumSubsetValues.insert(TestType::REJECTED); + resultCode_allowedEnumSubsetValues.insert(TestType::INVALID_DATA); + resultCode_allowedEnumSubsetValues.insert(TestType::OUT_OF_MEMORY); + resultCode_allowedEnumSubsetValues.insert(TestType::ABORTED); + resultCode_allowedEnumSubsetValues.insert(TestType::USER_DISALLOWED); + resultCode_allowedEnumSubsetValues.insert(TestType::GENERIC_ERROR); + resultCode_allowedEnumSubsetValues.insert(TestType::DISALLOWED); + + // Possible functions in this test scheme + std::set<FunctionIDTest::eType> functionId_allowedEnumSubsetValues; + functionId_allowedEnumSubsetValues.insert( + FunctionIDTest::RegisterAppInterface); + functionId_allowedEnumSubsetValues.insert( + FunctionIDTest::UnregisterAppInterface); + functionId_allowedEnumSubsetValues.insert( + FunctionIDTest::SetGlobalProperties); + + std::set<Language::eType> languageDesired_allowedEnumSubsetValues; + languageDesired_allowedEnumSubsetValues.insert(Language::RU_RU); + languageDesired_allowedEnumSubsetValues.insert(Language::EN_EU); + + + std::set<AppTypeTest::eType> appType_allowedEnumSubsetValues; + appType_allowedEnumSubsetValues.insert(AppTypeTest::SYSTEM); + appType_allowedEnumSubsetValues.insert(AppTypeTest::MEDIA); + + std::set<SpeechCapabilities::eType> speechCapabilities_allowedEnumSubsetValues; + speechCapabilities_allowedEnumSubsetValues.insert(SpeechCapabilities::SC_TEXT); + + // Possible message types + std::set<MessageTypeTest::eType> messageType_allowedEnumSubsetValues; + messageType_allowedEnumSubsetValues.insert(MessageTypeTest::request); + messageType_allowedEnumSubsetValues.insert(MessageTypeTest::response); + messageType_allowedEnumSubsetValues.insert(MessageTypeTest::notification); + + // Create param items + ISchemaItemPtr appID_SchemaItem = CStringSchemaItem::create( + TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000), + TSchemaItemParameter<std::string>()); + ISchemaItemPtr appName_SchemaItem = CStringSchemaItem::create( + TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000), + TSchemaItemParameter<std::string>()); + ISchemaItemPtr isMediaApplication_SchemaItem = CBoolSchemaItem::create( + TSchemaItemParameter<bool>()); + ISchemaItemPtr ngnMediaScreenAppName_SchemaItem = CStringSchemaItem::create( + TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000), + TSchemaItemParameter<std::string>()); + + ISchemaItemPtr ttsNameItem_SchemaItem = CStringSchemaItem::create( + TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000), + TSchemaItemParameter<std::string>()); + + ISchemaItemPtr ttstype_SchemaItem = + TEnumSchemaItem<SpeechCapabilities::eType>::create( + speechCapabilities_allowedEnumSubsetValues, + TSchemaItemParameter<SpeechCapabilities::eType>()); + + std::map<std::string, CObjectSchemaItem::SMember> ttsMap; + ttsMap["text"]=CObjectSchemaItem::SMember(ttsNameItem_SchemaItem, + false); + ttsMap["type"]=CObjectSchemaItem::SMember(ttstype_SchemaItem, + false);; + + ISchemaItemPtr hmiDisplayLanguageDesired_SchemaItem = + TEnumSchemaItem<Language::eType>::create( + languageDesired_allowedEnumSubsetValues, + TSchemaItemParameter<Language::eType>()); + + ISchemaItemPtr languageDesired_SchemaItem = + TEnumSchemaItem<Language::eType>::create( + languageDesired_allowedEnumSubsetValues, + TSchemaItemParameter<Language::eType>()); + + ISchemaItemPtr vrElementSchemaItem = CStringSchemaItem::create( + TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000), + TSchemaItemParameter<std::string>()); + + ISchemaItemPtr appTypeElementSchemaItem = + TEnumSchemaItem<AppTypeTest::eType>::create( + appType_allowedEnumSubsetValues, + TSchemaItemParameter<AppTypeTest::eType>()); + + ISchemaItemPtr ttsElementSchemaItem = CObjectSchemaItem::create(ttsMap); + + ISchemaItemPtr ttsName_SchemaItem = + CArraySchemaItem::create(ttsElementSchemaItem, + TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000)); + + ISchemaItemPtr vrSynonyms_SchemaItem = + CArraySchemaItem::create(vrElementSchemaItem, + TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000)); + + ISchemaItemPtr appType_SchemaItem = + CArraySchemaItem::create(appTypeElementSchemaItem, + TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000)); + + + ISchemaItemPtr majorVersion_SchemaItem = TNumberSchemaItem<int>::create(); + ISchemaItemPtr minorVersion_SchemaItem = TNumberSchemaItem<int>::create(); + + ISchemaItemPtr syncMsg_SchemaItem =CStringSchemaItem::create( + TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000), + TSchemaItemParameter<std::string>()); + + ISchemaItemPtr syncMsgVersion_SchemaItem = + CArraySchemaItem::create(syncMsg_SchemaItem, + TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000)); + + // Creation map for syncMsgVersion + std::map<std::string, CObjectSchemaItem::SMember> schemaSyncMsgVersionMap; + schemaSyncMsgVersionMap["majorVersion"]=CObjectSchemaItem::SMember(majorVersion_SchemaItem, + false); + schemaSyncMsgVersionMap["minorVersion"]=CObjectSchemaItem::SMember(minorVersion_SchemaItem, + false);; + + // Map of parameters + std::map<std::string, CObjectSchemaItem::SMember> schemaMembersMap; + + schemaMembersMap["appID"] = CObjectSchemaItem::SMember(appID_SchemaItem, + false); + schemaMembersMap["appName"] = CObjectSchemaItem::SMember(appName_SchemaItem, + false); + schemaMembersMap["appType"] = CObjectSchemaItem::SMember(appType_SchemaItem, + false); + schemaMembersMap["hmiDisplayLanguageDesired"] = CObjectSchemaItem::SMember(hmiDisplayLanguageDesired_SchemaItem, + false); + schemaMembersMap["isMediaApplication"] = CObjectSchemaItem::SMember(isMediaApplication_SchemaItem, + false); + schemaMembersMap["languageDesired"] = CObjectSchemaItem::SMember(languageDesired_SchemaItem, + false); + schemaMembersMap["ngnMediaScreenAppName"] = CObjectSchemaItem::SMember(ngnMediaScreenAppName_SchemaItem, + false); + schemaMembersMap["syncMsgVersion"] = CObjectSchemaItem::SMember(CObjectSchemaItem::create(schemaSyncMsgVersionMap), + false); + schemaMembersMap["ttsName"] = CObjectSchemaItem::SMember(ttsName_SchemaItem, + false); + schemaMembersMap["vrSynonyms"] = CObjectSchemaItem::SMember(vrSynonyms_SchemaItem, false); + + std::map<std::string, CObjectSchemaItem::SMember> paramsMembersMap; + paramsMembersMap[S_FUNCTION_ID] = CObjectSchemaItem::SMember( + TEnumSchemaItem<FunctionIDTest::eType>::create( + functionId_allowedEnumSubsetValues), + true); + paramsMembersMap[S_MESSAGE_TYPE] = CObjectSchemaItem::SMember( + TEnumSchemaItem<MessageTypeTest::eType>::create( + messageType_allowedEnumSubsetValues), + true); + paramsMembersMap[S_CORRELATION_ID] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + paramsMembersMap[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(1), + TSchemaItemParameter<int>(2)), + true); + paramsMembersMap[S_PROTOCOL_TYPE] = CObjectSchemaItem::SMember( + TNumberSchemaItem<int>::create(), true); + + std::map<std::string, CObjectSchemaItem::SMember> rootMembersMap; + rootMembersMap[S_MSG_PARAMS] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create(schemaMembersMap), true); + rootMembersMap[S_PARAMS] = CObjectSchemaItem::SMember( + CObjectSchemaItem::create(paramsMembersMap), true); + return CSmartSchema(CObjectSchemaItem::create(rootMembersMap)); +}; + + + +} // namespace formatters +} // namespace components +} // namespace test diff --git a/src/components/formatters/test/src/meta_formatter_test_helper.cc b/src/components/formatters/test/src/meta_formatter_test_helper.cc new file mode 100644 index 0000000000..3445d948bb --- /dev/null +++ b/src/components/formatters/test/src/meta_formatter_test_helper.cc @@ -0,0 +1,222 @@ +/* + * Copyright (c) 2015, 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. + */ +#include "gtest/gtest.h" +#include "meta_formatter_test_helper.h" + +namespace test { +namespace components { +namespace formatters { + +using namespace NsSmartDeviceLink::NsJSONHandler::strings; +using namespace NsSmartDeviceLink::NsJSONHandler::Formatters; + +void CMetaFormatterTestHelper::SetUp() { + function_id_items_.insert(FunctionIDTest::RegisterAppInterface); + function_id_items_.insert(FunctionIDTest::UnregisterAppInterface); + function_id_items_.insert(FunctionIDTest::SetGlobalProperties); + + message_type_items_.insert(MessageTypeTest::request); + message_type_items_.insert(MessageTypeTest::response); + message_type_items_.insert(MessageTypeTest::notification); +} + +void CMetaFormatterTestHelper::TearDown() { + function_id_items_.clear(); + message_type_items_.clear(); +} + +//----------------------------------------------------------- + +void CMetaFormatterTestHelper::AnyObjectToJsonString( + const SmartObject& obj, std::string& result_string) { + + Json::Value params(Json::objectValue); + + SmartObject formattedObj(obj); + + CFormatterJsonBase::objToJsonValue(formattedObj, params); + + result_string = params.toStyledString(); +} + +//----------------------------------------------------------- + +void CMetaFormatterTestHelper::FillObjectIdenticalToSchema(SmartObject& obj) { + + obj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request; + obj[S_PARAMS][S_FUNCTION_ID] = FunctionIDTest::RegisterAppInterface; + obj[S_PARAMS][S_CORRELATION_ID] = 12; + obj[S_PARAMS][S_PROTOCOL_VERSION] = 1; + obj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + + obj[S_MSG_PARAMS]["syncMsgVersion"]["majorVersion"] = 2; + obj[S_MSG_PARAMS]["syncMsgVersion"]["minorVersion"] = 10; + obj[S_MSG_PARAMS]["appName"] = "APP NAME"; + obj[S_MSG_PARAMS]["ttsName"][0]["text"] = "ABC"; + obj[S_MSG_PARAMS]["ttsName"][0]["type"] = SpeechCapabilities::SC_TEXT; + obj[S_MSG_PARAMS]["ngnMediaScreenAppName"] = "SCREEN NAME"; + obj[S_MSG_PARAMS]["vrSynonyms"][0] = "Synonym1"; + obj[S_MSG_PARAMS]["vrSynonyms"][1] = "Synonym2"; + obj[S_MSG_PARAMS]["isMediaApplication"] = true; + obj[S_MSG_PARAMS]["languageDesired"] = Language::EN_EU; + obj[S_MSG_PARAMS]["hmiDisplayLanguageDesired"] = Language::RU_RU; + obj[S_MSG_PARAMS]["appType"][0] = AppTypeTest::SYSTEM; + obj[S_MSG_PARAMS]["appType"][1] = AppTypeTest::MEDIA; + obj[S_MSG_PARAMS]["appID"] = "APP ID"; +} + +//----------------------------------------------------------- +void CMetaFormatterTestHelper::FillObjectIdenticalToSchemaWithoutNoMandatoriesParams( + SmartObject& obj) { + obj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request; + obj[S_PARAMS][S_FUNCTION_ID] = FunctionIDTest::RegisterAppInterface; + obj[S_PARAMS][S_CORRELATION_ID] = 12; + obj[S_PARAMS][S_PROTOCOL_VERSION] = 1; + obj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + + obj[S_MSG_PARAMS]["syncMsgVersion"]["majorVersion"] = 2; + obj[S_MSG_PARAMS]["syncMsgVersion"]["minorVersion"] = 10; + obj[S_MSG_PARAMS]["appName"] = "APP NAME"; + obj[S_MSG_PARAMS]["ngnMediaScreenAppName"] = "SCREEN NAME"; + obj[S_MSG_PARAMS]["isMediaApplication"] = true; + obj[S_MSG_PARAMS]["languageDesired"] = Language::EN_EU; + obj[S_MSG_PARAMS]["hmiDisplayLanguageDesired"] = Language::RU_RU; + obj[S_MSG_PARAMS]["appID"] = "APP ID"; + + // Commented not mandatory params for check creation object without them +// obj[S_MSG_PARAMS]["ttsName"][0]["text"] = "ABC"; +// obj[S_MSG_PARAMS]["ttsName"][0]["type"] = +// SpeechCapabilities::SC_TEXT; + +// obj[S_MSG_PARAMS]["vrSynonyms"][0] = "Synonym1"; +// obj[S_MSG_PARAMS]["vrSynonyms"][1] = "Synonym2"; + +// obj[S_MSG_PARAMS]["appType"][0] = AppTypeTest::SYSTEM; // not mandatory +// obj[S_MSG_PARAMS]["appType"][1] = AppTypeTest::MEDIA; + +} + +void CMetaFormatterTestHelper::FillObjectWithoutSomeMandatoryFields( + SmartObject& obj) { + obj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request; + obj[S_PARAMS][S_FUNCTION_ID] = FunctionIDTest::RegisterAppInterface; + + obj[S_PARAMS][S_PROTOCOL_VERSION] = 1; + obj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + +// Commented mandatory params for check creation object without them +// obj[S_PARAMS][S_CORRELATION_ID] = 12; +// obj[S_MSG_PARAMS]["syncMsgVersion"]["majorVersion"] = 2; +// obj[S_MSG_PARAMS]["syncMsgVersion"]["minorVersion"] = 10; + + obj[S_MSG_PARAMS]["appName"] = "APP NAME"; + obj[S_MSG_PARAMS]["ttsName"][0]["text"] = "ABC"; + obj[S_MSG_PARAMS]["ttsName"][0]["type"] = SpeechCapabilities::SC_TEXT; + obj[S_MSG_PARAMS]["ngnMediaScreenAppName"] = "SCREEN NAME"; + obj[S_MSG_PARAMS]["vrSynonyms"][0] = "Synonym1"; + obj[S_MSG_PARAMS]["vrSynonyms"][1] = "Synonym2"; + obj[S_MSG_PARAMS]["isMediaApplication"] = true; + obj[S_MSG_PARAMS]["languageDesired"] = Language::EN_EU; + obj[S_MSG_PARAMS]["hmiDisplayLanguageDesired"] = Language::RU_RU; + obj[S_MSG_PARAMS]["appType"][0] = AppTypeTest::SYSTEM; + obj[S_MSG_PARAMS]["appType"][1] = AppTypeTest::MEDIA; + obj[S_MSG_PARAMS]["appID"] = "APP ID"; +} + +//----------------------------------------------------------- + +void CMetaFormatterTestHelper::CompareObjects(const SmartObject& first, + const SmartObject& second) { + + if (SmartType_Array == first.getType()) { + ASSERT_EQ(SmartType_Array, second.getType()); + for (size_t i = 0; i < first.length(); i++) { + CompareObjects(first.getElement(i), second.getElement(i)); + } + } else if (SmartType_Map == first.getType()) { + ASSERT_EQ(SmartType_Map, second.getType()); + std::set < std::string > keys = first.enumerate(); + + for (std::set<std::string>::const_iterator key = keys.begin(); + key != keys.end(); key++) { + CompareObjects(first.getElement(*key), second.getElement(*key)); + } + } else if (SmartType_Boolean == first.getType()) { + ASSERT_EQ(first.asBool(), second.asBool()); + } else if (SmartType_Integer == first.getType()) { + ASSERT_EQ(first.asInt(), second.asInt()); + } else if (SmartType_Double == first.getType()) { + ASSERT_EQ(first.asDouble(), second.asDouble()); + } else if (SmartType_String == first.getType()) { + ASSERT_EQ(first.asString(), second.asString()); + } else if (SmartType_Null == first.getType()) { + ASSERT_EQ(SmartType_Null, second.getType()); + } else { + FAIL()<< "Unknown SmartObject type: " << first.getType(); + } +} + +//----------------------------------------------------------- + +void CMetaFormatterTestHelper::FillObjectWithDefaultValues(SmartObject& obj) { + + obj[S_PARAMS][S_MESSAGE_TYPE] = -1; + obj[S_PARAMS][S_FUNCTION_ID] = -1; + obj[S_PARAMS][S_CORRELATION_ID] = 0; + obj[S_PARAMS][S_PROTOCOL_VERSION] = 0; + obj[S_PARAMS][S_PROTOCOL_TYPE] = 0; + + obj[S_MSG_PARAMS]["syncMsgVersion"]["majorVersion"] = 0; + obj[S_MSG_PARAMS]["syncMsgVersion"]["minorVersion"] = 0; + obj[S_MSG_PARAMS]["appName"] = ""; + obj[S_MSG_PARAMS]["ngnMediaScreenAppName"] = ""; + obj[S_MSG_PARAMS]["isMediaApplication"] = false; + obj[S_MSG_PARAMS]["languageDesired"] = -1; + obj[S_MSG_PARAMS]["hmiDisplayLanguageDesired"] = -1; + obj[S_MSG_PARAMS]["appID"] = ""; + +// Commented params for check creation object with only default values +// obj[S_MSG_PARAMS]["ttsName"][0]["text"] = "ABC"; +// obj[S_MSG_PARAMS]["ttsName"][0]["type"] = +// SpeechCapabilities::SC_TEXT; + +// obj[S_MSG_PARAMS]["vrSynonyms"][0] = "Synonym1"; +// obj[S_MSG_PARAMS]["vrSynonyms"][1] = "Synonym2"; + +// obj[S_MSG_PARAMS]["appType"][0] = AppTypeTest::SYSTEM; +// obj[S_MSG_PARAMS]["appType"][1] = AppTypeTest::MEDIA; + +} + +} // namespace formatters +} // namespace components +} // namespace test diff --git a/src/components/policy/src/policy/src/cache_manager.cc b/src/components/policy/src/policy/src/cache_manager.cc index 9c536e0f37..ba84727388 100644 --- a/src/components/policy/src/policy/src/cache_manager.cc +++ b/src/components/policy/src/policy/src/cache_manager.cc @@ -810,6 +810,7 @@ bool policy::CacheManager::IsNumberService(const std::string& input, utils::SharedPtr<policy_table::Table> CacheManager::GenerateSnapshot() { CACHE_MANAGER_CHECK(snapshot_); + sync_primitives::AutoLock lock(cache_lock_); snapshot_ = new policy_table::Table(); snapshot_->policy_table = pt_->policy_table; CheckSnapshotInitialization(); diff --git a/src/components/policy/test/CMakeLists.txt b/src/components/policy/test/CMakeLists.txt index 46fafb85c6..00622875b6 100644 --- a/src/components/policy/test/CMakeLists.txt +++ b/src/components/policy/test/CMakeLists.txt @@ -57,10 +57,6 @@ set(testSources ) list (APPEND testSources - # sql_pt_ext_representation_test.cc -) - -list (APPEND testSources sql_pt_representation_test.cc ) diff --git a/src/components/protocol_handler/test/incoming_data_handler_test.cc b/src/components/protocol_handler/test/incoming_data_handler_test.cc index dd30620733..f3c87f9293 100644 --- a/src/components/protocol_handler/test/incoming_data_handler_test.cc +++ b/src/components/protocol_handler/test/incoming_data_handler_test.cc @@ -250,7 +250,7 @@ TEST_F(IncomingDataHandlerTest, MalformedPacket_Version) { } // ServiceType shall be equal 0x0 (Control), 0x07 (RPC), 0x0A (PCM), 0x0B (Video), 0x0F (Bulk) -TEST_F(IncomingDataHandlerTest, MalformedPacket_ServiceType) { +TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_ServiceType) { FrameList malformed_packets; std::vector<uint8_t> malformed_serv_types; for (uint8_t service_type = kControl + 1; service_type < kRpc; ++service_type) { @@ -290,7 +290,7 @@ TEST_F(IncomingDataHandlerTest, MalformedPacket_ServiceType) { } // Frame type shall be 0x00 (Control), 0x01 (Single), 0x02 (First), 0x03 (Consecutive) -TEST_F(IncomingDataHandlerTest, MalformedPacket_FrameType) { +TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_FrameType) { FrameList malformed_packets; std::vector<uint8_t> malformed_frame_types; for (uint8_t frame_type = FRAME_TYPE_CONSECUTIVE + 1; @@ -325,7 +325,7 @@ TEST_F(IncomingDataHandlerTest, MalformedPacket_FrameType) { } // For Control frames Frame info value shall be from 0x00 to 0x06 or 0xFE(Data Ack), 0xFF(HB Ack) -TEST_F(IncomingDataHandlerTest, MalformedPacket_ControlFrame) { +TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_ControlFrame) { FrameList malformed_packets; std::vector<uint8_t> malformed_frame_data; for (uint8_t frame_type = FRAME_DATA_END_SERVICE_NACK + 1; @@ -360,7 +360,7 @@ TEST_F(IncomingDataHandlerTest, MalformedPacket_ControlFrame) { } // For Single and First frames Frame info value shall be equal 0x00 -TEST_F(IncomingDataHandlerTest, MalformedPacket_SingleFrame) { +TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_SingleFrame) { FrameList malformed_packets; std::vector<uint8_t> malformed_frame_data; for (uint8_t frame_type = FRAME_DATA_SINGLE + 1; @@ -396,7 +396,7 @@ TEST_F(IncomingDataHandlerTest, MalformedPacket_SingleFrame) { } // For Single and First frames Frame info value shall be equal 0x00 -TEST_F(IncomingDataHandlerTest, MalformedPacket_FirstFrame) { +TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_FirstFrame) { FrameList malformed_packets; std::vector<uint8_t> malformed_frame_data; for (uint8_t frame_type = FRAME_DATA_FIRST + 1; diff --git a/src/components/security_manager/test/include/security_manager_mock.h b/src/components/security_manager/test/include/security_manager_mock.h index 886b022c37..fbd50d2cc4 100644 --- a/src/components/security_manager/test/include/security_manager_mock.h +++ b/src/components/security_manager/test/include/security_manager_mock.h @@ -40,6 +40,7 @@ #include "security_manager/security_manager.h" #include "security_manager/ssl_context.h" #include "security_manager/security_query.h" +#include "security_manager/crypto_manager.h" namespace test { namespace components { @@ -51,29 +52,23 @@ namespace security_manager_test { class SecurityManagerMock : public ::security_manager::SecurityManager { public: MOCK_METHOD1(set_session_observer, - void(::protocol_handler::SessionObserver *)); + void(::protocol_handler::SessionObserver*)); MOCK_METHOD1(set_protocol_handler, - void(::protocol_handler::ProtocolHandler *)); - MOCK_METHOD1(set_crypto_manager, - void(::security_manager::CryptoManager *)); - MOCK_METHOD4(SendInternalError, - void(const uint32_t , - const uint8_t &, - const std::string &, - const uint32_t)); + void(::protocol_handler::ProtocolHandler*)); + MOCK_METHOD1(set_crypto_manager, void(::security_manager::CryptoManager*)); + MOCK_METHOD4(SendInternalError, void(const uint32_t, const uint8_t&, + const std::string&, const uint32_t)); MOCK_METHOD1(CreateSSLContext, - ::security_manager::SSLContext * (const uint32_t &)); - MOCK_METHOD1(StartHandshake, - void(uint32_t)); - MOCK_METHOD1(AddListener, - void(::security_manager::SecurityManagerListener *)); + ::security_manager::SSLContext*(const uint32_t&)); + MOCK_METHOD1(StartHandshake, void(uint32_t)); + MOCK_METHOD1(AddListener, void(::security_manager::SecurityManagerListener*)); MOCK_METHOD1(RemoveListener, - void(::security_manager::SecurityManagerListener *)); + void(::security_manager::SecurityManagerListener*)); // protocol_handler::ProtocolObserver part MOCK_METHOD1(OnMessageReceived, - void(const ::protocol_handler::RawMessagePtr)); + void(const ::protocol_handler::RawMessagePtr)); MOCK_METHOD1(OnMobileMessageSent, - void(const ::protocol_handler::RawMessagePtr)); + void(const ::protocol_handler::RawMessagePtr)); }; /* @@ -82,74 +77,60 @@ class SecurityManagerMock : public ::security_manager::SecurityManager { class SessionObserverMock : public protocol_handler::SessionObserver { public: MOCK_METHOD2(SetSSLContext, - int (const uint32_t& key, - security_manager::SSLContext* context)); + int(const uint32_t& key, security_manager::SSLContext* context)); MOCK_METHOD2(GetSSLContext, - security_manager::SSLContext* ( - const uint32_t& key, - const protocol_handler::ServiceType& service_type)); + security_manager::SSLContext*( + const uint32_t& key, + const protocol_handler::ServiceType& service_type)); MOCK_METHOD2(SetProtectionFlag, - void( - const uint32_t& key, - const protocol_handler::ServiceType& service_type)); - MOCK_METHOD5(OnSessionStartedCallback, + void(const uint32_t& key, + const protocol_handler::ServiceType& service_type)); + MOCK_METHOD5( + OnSessionStartedCallback, - uint32_t( - const transport_manager::ConnectionUID &connection_handle, - const uint8_t session_id, - const ::protocol_handler::ServiceType &service_type, - const bool is_protected, uint32_t* hash_id)); + uint32_t(const transport_manager::ConnectionUID& connection_handle, + const uint8_t session_id, + const ::protocol_handler::ServiceType& service_type, + const bool is_protected, uint32_t* hash_id)); - MOCK_METHOD4(OnSessionEndedCallback, - uint32_t( - const transport_manager::ConnectionUID& connection_handle, - const uint8_t sessionId, - const uint32_t& hashCode, - const protocol_handler::ServiceType& service_type)); + MOCK_METHOD4( + OnSessionEndedCallback, + uint32_t(const transport_manager::ConnectionUID& connection_handle, + const uint8_t sessionId, const uint32_t& hashCode, + const protocol_handler::ServiceType& service_type)); - MOCK_METHOD1(OnApplicationFloodCallBack, - void(const uint32_t&)); + MOCK_METHOD1(OnApplicationFloodCallBack, void(const uint32_t&)); - MOCK_METHOD1(OnMalformedMessageCallback, - void(const uint32_t&)); + MOCK_METHOD1(OnMalformedMessageCallback, void(const uint32_t&)); MOCK_METHOD2(KeyFromPair, - uint32_t( - transport_manager::ConnectionUID connection_handle, - uint8_t sessionId)); + uint32_t(transport_manager::ConnectionUID connection_handle, + uint8_t sessionId)); MOCK_METHOD3(PairFromKey, - void( - uint32_t key, - transport_manager::ConnectionUID* connection_handle, - uint8_t* sessionId)); + void(uint32_t key, + transport_manager::ConnectionUID* connection_handle, + uint8_t* sessionId)); MOCK_METHOD4(GetDataOnSessionKey, - int32_t(uint32_t key, - uint32_t* app_id, - std::list<int32_t>* sessions_list, - uint32_t* device_id)); + int32_t(uint32_t key, uint32_t* app_id, + std::list<int32_t>* sessions_list, uint32_t* device_id)); MOCK_METHOD4(GetDataOnDeviceID, - int32_t( - uint32_t device_handle, - std::string* device_name, - std::list<uint32_t>* applications_list, - std::string* mac_address)); + int32_t(uint32_t device_handle, std::string* device_name, + std::list<uint32_t>* applications_list, + std::string* mac_address)); MOCK_METHOD5(GetDataOnDeviceID, - int32_t( - uint32_t device_handle, - std::string *device_name, - std::list<uint32_t> *applications_list, - std::string *mac_address, - std::string *connection_type)); + int32_t(uint32_t device_handle, std::string* device_name, + std::list<uint32_t>* applications_list, + std::string* mac_address, std::string* connection_type)); MOCK_METHOD2(IsHeartBeatSupported, - bool( transport_manager::ConnectionUID connection_handle, - uint8_t session_id)); + bool(transport_manager::ConnectionUID connection_handle, + uint8_t session_id)); MOCK_METHOD3(ProtocolVersionUsed, - bool(uint32_t connection_id, uint8_t session_id, - uint8_t& protocol_version)); + bool(uint32_t connection_id, uint8_t session_id, + uint8_t& protocol_version)); }; /* * MOCK implementation of protocol_handler::ProtocolObserver interface @@ -157,73 +138,62 @@ class SessionObserverMock : public protocol_handler::SessionObserver { class ProtocoloObserverMock : public protocol_handler::ProtocolHandler { public: MOCK_METHOD2(SendMessageToMobileApp, - void(const protocol_handler::RawMessagePtr message, - bool final_message)); + void(const protocol_handler::RawMessagePtr message, + bool final_message)); MOCK_METHOD1(AddProtocolObserver, - void(protocol_handler::ProtocolObserver* observer)); + void(protocol_handler::ProtocolObserver* observer)); MOCK_METHOD1(RemoveProtocolObserver, - void(protocol_handler::ProtocolObserver* observer)); + void(protocol_handler::ProtocolObserver* observer)); MOCK_METHOD2(SendFramesNumber, - void(uint32_t connection_key, int32_t number_of_frames)); - MOCK_METHOD2(SendHeartBeat, - void(int32_t connection_id, uint8_t session_id)); - MOCK_METHOD2(SendEndSession, - void(int32_t connection_id, uint8_t session_id)); + void(uint32_t connection_key, int32_t number_of_frames)); + MOCK_METHOD2(SendHeartBeat, void(int32_t connection_id, uint8_t session_id)); + MOCK_METHOD2(SendEndSession, void(int32_t connection_id, uint8_t session_id)); }; /* * MOCK implementation of security_manager::SSLContext interface */ class CryptoManagerMock : public security_manager::CryptoManager { public: - MOCK_METHOD6(Init, - bool (security_manager::Mode mode, - security_manager::Protocol protocol, - const std::string& cert_filename, - const std::string& key_filename, - const std::string& ciphers_list, - bool verify_peer)); - MOCK_METHOD0(Finish, - void ()); - MOCK_METHOD0(CreateSSLContext, - security_manager::SSLContext* ()); - MOCK_METHOD1(ReleaseSSLContext, - void(security_manager::SSLContext*)); - MOCK_CONST_METHOD0(LastError, - std::string()); + MOCK_METHOD6(Init, bool(security_manager::Mode mode, + security_manager::Protocol protocol, + const std::string& cert_filename, + const std::string& key_filename, + const std::string& ciphers_list, bool verify_peer)); + MOCK_METHOD0(Finish, void()); + MOCK_METHOD0(CreateSSLContext, security_manager::SSLContext*()); + MOCK_METHOD1(ReleaseSSLContext, void(security_manager::SSLContext*)); + MOCK_CONST_METHOD0(LastError, std::string()); }; /* * MOCK implementation of security_manager::SSLContext interface */ class SSLContextMock : public security_manager::SSLContext { public: - MOCK_CONST_METHOD0(mode, int ()); - MOCK_METHOD2(StartHandshake, - security_manager::SSLContext::HandshakeResult ( - const uint8_t** const, size_t*)); - MOCK_METHOD4(DoHandshakeStep, - security_manager::SSLContext::HandshakeResult ( - const uint8_t* const, size_t, - const uint8_t** const, size_t*)); - MOCK_METHOD4(Encrypt, - bool (const uint8_t* const, size_t, - const uint8_t** const, size_t*)); - MOCK_METHOD4(Decrypt, - bool (const uint8_t* const, size_t, - const uint8_t** const, size_t*)); - MOCK_CONST_METHOD1(get_max_block_size, size_t (size_t)); + MOCK_CONST_METHOD0(mode, int()); + MOCK_METHOD2(StartHandshake, security_manager::SSLContext::HandshakeResult( + const uint8_t** const, size_t*)); + MOCK_METHOD4(DoHandshakeStep, security_manager::SSLContext::HandshakeResult( + const uint8_t* const, size_t, + const uint8_t** const, size_t*)); + MOCK_METHOD4(Encrypt, bool(const uint8_t* const, size_t, + const uint8_t** const, size_t*)); + MOCK_METHOD4(Decrypt, bool(const uint8_t* const, size_t, + const uint8_t** const, size_t*)); + MOCK_CONST_METHOD1(get_max_block_size, size_t(size_t)); MOCK_CONST_METHOD0(IsInitCompleted, bool()); MOCK_CONST_METHOD0(IsHandshakePending, bool()); - MOCK_CONST_METHOD0(LastError, - std::string()); + MOCK_CONST_METHOD0(LastError, std::string()); + MOCK_METHOD0(ResetConnection, void()); + MOCK_METHOD1( + SetHandshakeContext, + void(const security_manager::SSLContext::HandshakeContext& hsh_ctx)); }; /* * MOCK implementation of security_manager::SecurityManagerListener */ class SMListenerMock : public security_manager::SecurityManagerListener { public: - MOCK_METHOD2(OnHandshakeDone, - bool(uint32_t connection_key, - bool success)); + MOCK_METHOD2(OnHandshakeDone, bool(uint32_t connection_key, bool success)); }; /* @@ -231,14 +201,14 @@ class SMListenerMock : public security_manager::SecurityManagerListener { * Check binary data of RawMessages */ MATCHER_P2(RawMessageEq, exp_data, exp_data_size, - std::string(negation ? "is not" : "is") + " RawMessages "){ + std::string(negation ? "is not" : "is") + " RawMessages ") { const size_t arg_data_size = arg->data_size(); if (arg_data_size != exp_data_size) { *result_listener << "Got " << arg_data_size << " bytes " - << " expected " << exp_data_size << " bytes"; + << " expected " << exp_data_size << " bytes"; return false; } - const uint8_t *arg_data = arg->data(); + const uint8_t* arg_data = arg->data(); for (int i = 0; i < arg_data_size; ++i) { if (arg_data[i] != exp_data[i]) { *result_listener << "Fail in " << i << " byte"; @@ -253,59 +223,56 @@ MATCHER_P2(RawMessageEq, exp_data, exp_data_size, * Check error id */ MATCHER_P(InternalErrorWithErrId, expectedErrorId, - std::string(negation ? "is not" : "is") - + " InternalError with selected error" ){ - const size_t header_size = sizeof(security_manager::SecurityQuery::QueryHeader); + std::string(negation ? "is not" : "is") + + " InternalError with selected error") { + const size_t header_size = + sizeof(security_manager::SecurityQuery::QueryHeader); if (arg->data_size() <= header_size) { *result_listener << "Size " << arg->data_size() - << " bytes less or equal sizeof(QueryHeader)=" - << header_size; + << " bytes less or equal sizeof(QueryHeader)=" + << header_size; return false; } - const uint8_t *data = arg->data(); + const uint8_t* data = arg->data(); const uint8_t query_type = data[0]; if (security_manager::SecurityQuery::NOTIFICATION != query_type) { - *result_listener << "RawMessage is not notification, type=0x" - << std::hex << static_cast<int>(query_type); + *result_listener << "RawMessage is not notification, type=0x" << std::hex + << static_cast<int>(query_type); return false; } // Read Big-Endian number - const uint32_t query_id = data[1] << 16 | - data[2] << 8 | - data[3]; + const uint32_t query_id = data[1] << 16 | data[2] << 8 | data[3]; if (security_manager::SecurityQuery::SEND_INTERNAL_ERROR != query_id) { - *result_listener << "Notification is not InternalError, id=0x" - << std::hex << query_id; + *result_listener << "Notification is not InternalError, id=0x" << std::hex + << query_id; return false; } - const uint32_t json_size = data[8] << 24 | - data[9] << 16 | - data[10] << 8 | - data[11]; + const uint32_t json_size = + data[8] << 24 | data[9] << 16 | data[10] << 8 | data[11]; if (header_size + json_size >= arg->data_size()) { *result_listener << "InternalError contains only JSON data."; return false; } // Read err_id as bin data number const uint8_t* err_id = - reinterpret_cast<const uint8_t*>(data + header_size + json_size); + reinterpret_cast<const uint8_t*>(data + header_size + json_size); if (expectedErrorId != *err_id) { *result_listener << "InternalError id " << static_cast<int>(*err_id) - << " and not equal error " << expectedErrorId; + << " and not equal error " << expectedErrorId; return false; } return true; } -} // namespace security_manager_test -} // namespace components -} // namespace test -/* - * Matcher for checking QueryHeader equal in GTests - */ +} // namespace security_manager_test +} // namespace components +} // namespace test + /* + * Matcher for checking QueryHeader equal in GTests + */ ::testing::AssertionResult QueryHeader_EQ( - const char* m_expr, const char* n_expr, - const ::security_manager::SecurityQuery::QueryHeader& q1, - const ::security_manager::SecurityQuery::QueryHeader& q2); + const char* m_expr, const char* n_expr, + const ::security_manager::SecurityQuery::QueryHeader& q1, + const ::security_manager::SecurityQuery::QueryHeader& q2); #endif // TEST_COMPONENTS_SECURITY_MANAGER_INCLUDE_SECURITY_MANAGER_SECURITY_MANAGER_MOCK_H_ diff --git a/src/components/utils/include/utils/singleton.h b/src/components/utils/include/utils/singleton.h index 41face4f2f..fff7294d1c 100644 --- a/src/components/utils/include/utils/singleton.h +++ b/src/components/utils/include/utils/singleton.h @@ -111,18 +111,24 @@ class Singleton { static T** instance_pointer(); static Deleter* deleter(); + + static sync_primitives::Lock lock_; }; + +template<typename T, class Deleter> +sync_primitives::Lock Singleton<T, Deleter>::lock_; + + template<typename T, class Deleter> T* Singleton<T, Deleter>::instance() { - static sync_primitives::Lock lock; T* local_instance; atomic_pointer_assign(local_instance, *instance_pointer()); memory_barrier(); if (!local_instance) { - lock.Acquire(); + lock_.Acquire(); local_instance = *instance_pointer(); if (!local_instance) { local_instance = new T(); @@ -130,7 +136,7 @@ T* Singleton<T, Deleter>::instance() { atomic_pointer_assign(*instance_pointer(), local_instance); deleter()->grab(local_instance); } - lock.Release(); + lock_.Release(); } return local_instance; @@ -138,14 +144,13 @@ T* Singleton<T, Deleter>::instance() { template<typename T, class Deleter> void Singleton<T, Deleter>::destroy() { - static sync_primitives::Lock lock; T* local_instance; atomic_pointer_assign(local_instance, *instance_pointer()); memory_barrier(); if (local_instance) { - lock.Acquire(); + lock_.Acquire(); local_instance = *instance_pointer(); if (local_instance) { atomic_pointer_assign(*instance_pointer(), 0); @@ -153,7 +158,7 @@ void Singleton<T, Deleter>::destroy() { delete local_instance; deleter()->grab(0); } - lock.Release(); + lock_.Release(); } } diff --git a/src/components/utils/test/CMakeLists.txt b/src/components/utils/test/CMakeLists.txt index 74c5b331ef..2462a0b87a 100644 --- a/src/components/utils/test/CMakeLists.txt +++ b/src/components/utils/test/CMakeLists.txt @@ -43,12 +43,12 @@ include_directories ( set(testSources messagemeter_test.cc file_system_test.cc - date_time_test.cc + #date_time_test.cc system_test.cc signals_linux_test.cc thread_validator_test.cc conditional_variable_test.cc - message_queue_test.cc + #message_queue_test.cc resource_usage_test.cc bitstream_test.cc prioritized_queue_test.cc @@ -57,7 +57,7 @@ set(testSources singleton_test.cc #posix_thread_test.cc stl_utils_test.cc - timer_thread_test.cc + #timer_thread_test.cc rwlock_posix_test.cc async_runner_test.cc shared_ptr_test.cc diff --git a/src/components/utils/test/auto_trace_test.cc b/src/components/utils/test/auto_trace_test.cc index df7d91dac8..a53f4aa1e0 100644 --- a/src/components/utils/test/auto_trace_test.cc +++ b/src/components/utils/test/auto_trace_test.cc @@ -85,7 +85,7 @@ void DeinitLogger() { DEINIT_LOGGER(); } -//TODO(VVeremjova) Logger does not write debug information in file +//TODO(VVeremjova) APPLINK-12832 Logger does not write debug information in file TEST(AutoTraceTest, DISABLED_Basic) { const std::string testlog = "Test trace is working!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"; |