diff --git a/ACL/include/ACL/AVSConnectionManager.h b/ACL/include/ACL/AVSConnectionManager.h index 95ce71cc74..22bb22d7ca 100644 --- a/ACL/include/ACL/AVSConnectionManager.h +++ b/ACL/include/ACL/AVSConnectionManager.h @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2016-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -71,7 +72,9 @@ class AVSConnectionManager , public avsCommon::sdkInterfaces::MessageSenderInterface , public avsCommon::sdkInterfaces::AVSEndpointAssignerInterface , public MessageRouterObserverInterface - , public avsCommon::utils::RequiresShutdown { + , public avsCommon::sdkInterfaces::InternetConnectionObserverInterface + , public avsCommon::utils::RequiresShutdown + , public std::enable_shared_from_this { public: /** * A factory function that creates an AVSConnectionManager object. @@ -91,7 +94,9 @@ class AVSConnectionManager connectionStatusObservers = std::unordered_set>(), std::unordered_set> messageObservers = - std::unordered_set>()); + std::unordered_set>(), + std::shared_ptr internetConnectionMonitor = + nullptr); /// @name AVSConnectionManagerInterface method overrides. /// @{ @@ -112,6 +117,11 @@ class AVSConnectionManager */ void setAVSEndpoint(const std::string& avsEndpoint) override; + /// @name InternetConnectionObserverInterface method overrides. + /// @{ + void onConnectionStatusChanged(bool connected) override; + /// @} + private: /** * AVSConnectionManager constructor. @@ -127,7 +137,9 @@ class AVSConnectionManager connectionStatusObservers = std::unordered_set>(), std::unordered_set> messageObserver = - std::unordered_set>()); + std::unordered_set>(), + std::shared_ptr internetConnectionMonitor = + nullptr); void doShutdown() override; @@ -137,8 +149,11 @@ class AVSConnectionManager void receive(const std::string& contextId, const std::string& message) override; + /// Mutex to serialize access to @c m_isEnabled + std::mutex m_isEnabledMutex; + /// Internal state to indicate if the Connection object is enabled for making an AVS connection. - std::atomic m_isEnabled; + bool m_isEnabled; /// Client-provided message listener, which will receive all messages sent from AVS. std::unordered_set> m_messageObservers; @@ -148,6 +163,9 @@ class AVSConnectionManager /// Internal object that manages the actual connection to AVS. std::shared_ptr m_messageRouter; + + /// Object providing notification of gaining and losing internet connectivity. + std::shared_ptr m_internetConnectionMonitor; }; } // namespace acl diff --git a/ACL/src/AVSConnectionManager.cpp b/ACL/src/AVSConnectionManager.cpp index 08ac42229d..ee14c568a8 100644 --- a/ACL/src/AVSConnectionManager.cpp +++ b/ACL/src/AVSConnectionManager.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -39,7 +39,8 @@ std::shared_ptr AVSConnectionManager::create( std::shared_ptr messageRouter, bool isEnabled, std::unordered_set> connectionStatusObservers, - std::unordered_set> messageObservers) { + std::unordered_set> messageObservers, + std::shared_ptr internetConnectionMonitor) { if (!avsCommon::avs::initialization::AlexaClientSDKInit::isInitialized()) { ACSDK_ERROR(LX("createFailed").d("reason", "uninitialziedAlexaClientSdk").d("return", "nullptr")); return nullptr; @@ -64,8 +65,8 @@ std::shared_ptr AVSConnectionManager::create( } } - auto connectionManager = std::shared_ptr( - new AVSConnectionManager(messageRouter, connectionStatusObservers, messageObservers)); + auto connectionManager = std::shared_ptr(new AVSConnectionManager( + messageRouter, connectionStatusObservers, messageObservers, internetConnectionMonitor)); messageRouter->setObserver(connectionManager); @@ -73,21 +74,32 @@ std::shared_ptr AVSConnectionManager::create( connectionManager->enable(); } + if (internetConnectionMonitor) { + ACSDK_DEBUG5(LX(__func__).m("Subscribing to InternetConnectionMonitor Callbacks")); + internetConnectionMonitor->addInternetConnectionObserver(connectionManager); + } + return connectionManager; } AVSConnectionManager::AVSConnectionManager( std::shared_ptr messageRouter, std::unordered_set> connectionStatusObservers, - std::unordered_set> messageObservers) : + std::unordered_set> messageObservers, + std::shared_ptr internetConnectionMonitor) : AbstractAVSConnectionManager{connectionStatusObservers}, RequiresShutdown{"AVSConnectionManager"}, m_isEnabled{false}, m_messageObservers{messageObservers}, - m_messageRouter{messageRouter} { + m_messageRouter{messageRouter}, + m_internetConnectionMonitor{internetConnectionMonitor} { } void AVSConnectionManager::doShutdown() { + if (m_internetConnectionMonitor) { + m_internetConnectionMonitor->removeInternetConnectionObserver(shared_from_this()); + } + disable(); clearObservers(); { @@ -98,20 +110,27 @@ void AVSConnectionManager::doShutdown() { } void AVSConnectionManager::enable() { + std::lock_guard lock(m_isEnabledMutex); + ACSDK_DEBUG5(LX(__func__)); m_isEnabled = true; m_messageRouter->enable(); } void AVSConnectionManager::disable() { + std::lock_guard lock(m_isEnabledMutex); + ACSDK_DEBUG5(LX(__func__)); m_isEnabled = false; m_messageRouter->disable(); } bool AVSConnectionManager::isEnabled() { + std::lock_guard lock(m_isEnabledMutex); return m_isEnabled; } void AVSConnectionManager::reconnect() { + std::lock_guard lock(m_isEnabledMutex); + ACSDK_DEBUG5(LX(__func__).d("isEnabled", m_isEnabled)); if (m_isEnabled) { m_messageRouter->disable(); m_messageRouter->enable(); @@ -129,6 +148,12 @@ bool AVSConnectionManager::isConnected() const { void AVSConnectionManager::setAVSEndpoint(const std::string& avsEndpoint) { m_messageRouter->setAVSEndpoint(avsEndpoint); } +void AVSConnectionManager::onConnectionStatusChanged(bool connected) { + ACSDK_DEBUG5(LX(__func__).d("connected", connected)); + if (!connected) { + reconnect(); + } +} void AVSConnectionManager::addMessageObserver( std::shared_ptr observer) { diff --git a/ACL/src/Transport/HTTP2TransportFactory.cpp b/ACL/src/Transport/HTTP2TransportFactory.cpp index 530494f2bd..7402338bd2 100644 --- a/ACL/src/Transport/HTTP2TransportFactory.cpp +++ b/ACL/src/Transport/HTTP2TransportFactory.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -32,7 +32,7 @@ static const std::string ACL_CONFIG_KEY = "acl"; /// Key for the 'endpoint' value under the @c ACL_CONFIG_KEY configuration node. static const std::string ENDPOINT_KEY = "endpoint"; /// Default @c AVS endpoint to connect to. -static const std::string DEFAULT_AVS_ENDPOINT = "https://avs-alexa-na.amazon.com"; +static const std::string DEFAULT_AVS_ENDPOINT = "https://alexa.na.gateway.devices.a2z.com"; std::shared_ptr HTTP2TransportFactory::createTransport( std::shared_ptr authDelegate, diff --git a/ACL/src/Transport/MessageRouter.cpp b/ACL/src/Transport/MessageRouter.cpp index fffbd99108..05eee03547 100644 --- a/ACL/src/Transport/MessageRouter.cpp +++ b/ACL/src/Transport/MessageRouter.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2016-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -62,13 +62,22 @@ MessageRouterInterface::ConnectionStatus MessageRouter::getConnectionStatus() { void MessageRouter::enable() { std::lock_guard lock{m_connectionMutex}; - m_isEnabled = true; - if (!m_activeTransport || !m_activeTransport->isConnected()) { - setConnectionStatusLocked( - ConnectionStatusObserverInterface::Status::PENDING, - ConnectionStatusObserverInterface::ChangedReason::ACL_CLIENT_REQUEST); - createActiveTransportLocked(); + + if (m_isEnabled) { + ACSDK_DEBUG0(LX(__func__).m("already enabled")); + return; + } + + if (m_activeTransport != nullptr) { + ACSDK_ERROR(LX("enableFailed").d("reason", "activeTransportNotNull")); + return; } + + m_isEnabled = true; + setConnectionStatusLocked( + ConnectionStatusObserverInterface::Status::PENDING, + ConnectionStatusObserverInterface::ChangedReason::ACL_CLIENT_REQUEST); + createActiveTransportLocked(); } void MessageRouter::doShutdown() { @@ -113,11 +122,24 @@ void MessageRouter::setAVSEndpoint(const std::string& avsEndpoint) { void MessageRouter::onConnected(std::shared_ptr transport) { std::unique_lock lock{m_connectionMutex}; - if (m_isEnabled) { - setConnectionStatusLocked( - ConnectionStatusObserverInterface::Status::CONNECTED, - ConnectionStatusObserverInterface::ChangedReason::ACL_CLIENT_REQUEST); + + /* + * Transport shutdown might be asynchronous,so the following scenarios are valid, + * but we shouldn't update the connection status. + */ + if (!m_isEnabled) { + ACSDK_DEBUG0(LX("onConnectedWhenDisabled")); + return; } + + if (transport != m_activeTransport) { + ACSDK_DEBUG0(LX("onInactiveTransportConnected")); + return; + } + + setConnectionStatusLocked( + ConnectionStatusObserverInterface::Status::CONNECTED, + ConnectionStatusObserverInterface::ChangedReason::ACL_CLIENT_REQUEST); } void MessageRouter::onDisconnected( diff --git a/ACL/test/AVSConnectionManagerTest.cpp b/ACL/test/AVSConnectionManagerTest.cpp index 3c0bb90041..6a4ba6b0aa 100644 --- a/ACL/test/AVSConnectionManagerTest.cpp +++ b/ACL/test/AVSConnectionManagerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -15,9 +15,11 @@ /// @file AVSConnectionManagerTest.cpp -#include #include +#include + #include +#include #include "ACL/AVSConnectionManager.h" namespace alexaClientSDK { @@ -27,6 +29,7 @@ namespace test { using namespace ::testing; using namespace alexaClientSDK::avsCommon::avs::initialization; using namespace alexaClientSDK::avsCommon::sdkInterfaces; +using namespace avsCommon::utils::network::test; /// This class allows us to test MessageObserver interaction class MockMessageObserver : public MessageObserverInterface { @@ -75,6 +78,7 @@ class AVSConnectionManagerTest : public ::testing::Test { std::shared_ptr m_messageRouter; std::shared_ptr m_observer; std::shared_ptr m_messageObserver; + std::shared_ptr m_mockConnectionMonitor; }; void AVSConnectionManagerTest::SetUp() { @@ -82,11 +86,15 @@ void AVSConnectionManagerTest::SetUp() { m_messageRouter = std::make_shared(); m_observer = std::make_shared(); m_messageObserver = std::make_shared(); + m_mockConnectionMonitor = std::make_shared(); m_avsConnectionManager = AVSConnectionManager::create( m_messageRouter, true, std::unordered_set>(), - std::unordered_set>()); + std::unordered_set>(), + m_mockConnectionMonitor); + + EXPECT_THAT(m_avsConnectionManager, NotNull()); } void AVSConnectionManagerTest::TearDown() { @@ -96,19 +104,27 @@ void AVSConnectionManagerTest::TearDown() { /** * Test @c create with valid messageRouter, ConnectionStatusObserver, MessageObservers */ -TEST_F(AVSConnectionManagerTest, createTest) { +TEST_F(AVSConnectionManagerTest, test_create) { EXPECT_CALL(*m_messageRouter, setObserver(_)).Times(1); EXPECT_CALL(*m_messageRouter, enable()).Times(1); ASSERT_NE(nullptr, m_avsConnectionManager->create(m_messageRouter, true, {m_observer}, {m_messageObserver})); } /** - * Test @c create with different combinations of messageRouter, ConnectionStatusObserver, MessageObservers + * Test @c create with different combinations of messageRouter, ConnectionStatusObserver, MessageObservers, + * InternetConnectionMonitor. */ -TEST_F(AVSConnectionManagerTest, createWithNullMessageRouterAndObservers) { +TEST_F(AVSConnectionManagerTest, test_createWithNullMessageRouterAndObservers) { ASSERT_EQ(nullptr, m_avsConnectionManager->create(nullptr, true, {m_observer}, {m_messageObserver})); ASSERT_EQ(nullptr, m_avsConnectionManager->create(m_messageRouter, true, {nullptr}, {m_messageObserver})); ASSERT_EQ(nullptr, m_avsConnectionManager->create(m_messageRouter, true, {m_observer}, {nullptr})); + ASSERT_NE( + nullptr, m_avsConnectionManager->create(m_messageRouter, true, {m_observer}, {m_messageObserver}, nullptr)); + ASSERT_NE( + nullptr, + m_avsConnectionManager->create( + m_messageRouter, true, {m_observer}, {m_messageObserver}, m_mockConnectionMonitor)); + std::shared_ptr validConnectionStatusObserver; validConnectionStatusObserver = std::make_shared(); ASSERT_EQ( @@ -147,7 +163,7 @@ TEST_F(AVSConnectionManagerTest, createWithNullMessageRouterAndObservers) { /** * Test addConnectionStatusObserver with a @c nullptr observer, expecting no errors. */ -TEST_F(AVSConnectionManagerTest, addConnectionStatusObserverNull) { +TEST_F(AVSConnectionManagerTest, test_addConnectionStatusObserverNull) { EXPECT_CALL(*m_messageRouter, getConnectionStatus()).Times(0); m_avsConnectionManager->addConnectionStatusObserver(nullptr); } @@ -155,7 +171,7 @@ TEST_F(AVSConnectionManagerTest, addConnectionStatusObserverNull) { /** * Test with addConnectionStatusObserver with MockConnectionStatusObserver. */ -TEST_F(AVSConnectionManagerTest, addConnectionStatusObserverValid) { +TEST_F(AVSConnectionManagerTest, test_addConnectionStatusObserverValid) { EXPECT_CALL(*m_observer, onConnectionStatusChanged(_, _)).Times(1); m_avsConnectionManager->addConnectionStatusObserver(m_observer); } @@ -163,28 +179,28 @@ TEST_F(AVSConnectionManagerTest, addConnectionStatusObserverValid) { /** * Test removeConnectionStatusObserver with a @c nullptr observer, expecting no errors. */ -TEST_F(AVSConnectionManagerTest, removeConnectionStatusObserverNull) { +TEST_F(AVSConnectionManagerTest, test_removeConnectionStatusObserverNull) { m_avsConnectionManager->removeConnectionStatusObserver(nullptr); } /** * Test addMessageObserver with a @c nullptr observer, expecting no errors. */ -TEST_F(AVSConnectionManagerTest, addMessageObserverNull) { +TEST_F(AVSConnectionManagerTest, test_addMessageObserverNull) { m_avsConnectionManager->addMessageObserver(nullptr); } /** * Test removeMessageObserver with a @c nullptr observer, expecting no errors. */ -TEST_F(AVSConnectionManagerTest, removeMessageObserverNull) { +TEST_F(AVSConnectionManagerTest, test_removeMessageObserverNull) { m_avsConnectionManager->removeMessageObserver(nullptr); } /** * Test enable and disable function of AVSConnectionManager */ -TEST_F(AVSConnectionManagerTest, enableAndDisableFunction) { +TEST_F(AVSConnectionManagerTest, test_enableAndDisableFunction) { EXPECT_CALL(*m_messageRouter, enable()).Times(1); m_avsConnectionManager->enable(); ASSERT_TRUE(m_avsConnectionManager->isEnabled()); @@ -196,7 +212,7 @@ TEST_F(AVSConnectionManagerTest, enableAndDisableFunction) { /** * Tests sendMessage with a @c nullptr request, expecting no errors. */ -TEST_F(AVSConnectionManagerTest, sendMessageRequestTest) { +TEST_F(AVSConnectionManagerTest, test_sendMessageRequest) { EXPECT_CALL(*m_messageRouter, sendMessage(_)).Times(1); m_avsConnectionManager->sendMessage(nullptr); EXPECT_CALL(*m_messageRouter, sendMessage(_)).Times(1); @@ -208,10 +224,83 @@ TEST_F(AVSConnectionManagerTest, sendMessageRequestTest) { /** * Test setAVSEndpoint and expect a call to messageRouter's setAVSEndpoint. */ -TEST_F(AVSConnectionManagerTest, setAVSEndpointTest) { +TEST_F(AVSConnectionManagerTest, test_setAVSEndpoint) { EXPECT_CALL(*m_messageRouter, setAVSEndpoint(_)).Times(1); m_avsConnectionManager->setAVSEndpoint("AVSEndpoint"); } + +/** + * Test that onConnectionStatusChanged(false) results in a reconnect attempt when enabled. + */ +TEST_F(AVSConnectionManagerTest, test_enabledOnConnectStatusChangedToFalse) { + // Create a new MessageRouter so we don't get residual calls to m_messageRouter from SetUp(). + auto messageRouter = std::make_shared(); + + { + InSequence dummy; + EXPECT_CALL(*messageRouter, enable()); + EXPECT_CALL(*messageRouter, disable()); + EXPECT_CALL(*messageRouter, enable()); + } + + m_avsConnectionManager = AVSConnectionManager::create( + messageRouter, + true, + std::unordered_set>(), + std::unordered_set>()); + m_avsConnectionManager->onConnectionStatusChanged(false); + // Explicitly reset so we control when destructor is called and can set expectations accordingly. + m_avsConnectionManager.reset(); +} + +/** + * Test that onConnectionStatusChanged(true) results in a no-op when enabled. + */ +TEST_F(AVSConnectionManagerTest, test_enabledOnConnectStatusChangedToTrue) { + // Create a new MessageRouter so we don't get residual calls to m_messageRouter from SetUp(). + auto messageRouter = std::make_shared(); + + { + InSequence dummy; + EXPECT_CALL(*messageRouter, enable()).Times(1); + EXPECT_CALL(*messageRouter, disable()).Times(0); + EXPECT_CALL(*messageRouter, enable()).Times(0); + } + + m_avsConnectionManager = AVSConnectionManager::create( + messageRouter, + true, + std::unordered_set>(), + std::unordered_set>()); + m_avsConnectionManager->onConnectionStatusChanged(true); + // Explicitly reset so we control when destructor is called and can set expectations accordingly. + m_avsConnectionManager.reset(); +} + +/** + * Test that onConnectionStatusChanged() results in no reconnect attempts when disabled. + */ +TEST_F(AVSConnectionManagerTest, test_disabledOnConnectStatusChanged) { + // Create a new MessageRouter so we don't get residual calls to m_messageRouter from SetUp(). + auto messageRouter = std::make_shared(); + + { + InSequence dummy; + EXPECT_CALL(*messageRouter, enable()).Times(0); + EXPECT_CALL(*messageRouter, disable()).Times(0); + } + + m_avsConnectionManager = AVSConnectionManager::create( + messageRouter, + false, + std::unordered_set>(), + std::unordered_set>()); + m_avsConnectionManager->onConnectionStatusChanged(true); + m_avsConnectionManager->onConnectionStatusChanged(false); + // Explicitly reset so we control when destructor is called and can set expectations accordingly. + m_avsConnectionManager.reset(); +} + } // namespace test } // namespace acl } // namespace alexaClientSDK diff --git a/ACL/test/CMakeLists.txt b/ACL/test/CMakeLists.txt index a907353ee5..29bc15b774 100644 --- a/ACL/test/CMakeLists.txt +++ b/ACL/test/CMakeLists.txt @@ -1,5 +1,9 @@ add_subdirectory("Transport") set(LIBRARIES ACL ${CMAKE_THREAD_LIBS_INIT} ACLTransportCommonTestLib) -set(INCLUDE_PATH ${AVSCommon_INCLUDE_DIRS} "${ACL_SOURCE_DIR}/include" "${AVSCommon_SOURCE_DIR}/AVS/test") +set(INCLUDE_PATH + ${AVSCommon_INCLUDE_DIRS} + "${ACL_SOURCE_DIR}/include" + "${AVSCommon_SOURCE_DIR}/AVS/test" + "${AVSCommon_SOURCE_DIR}/Utils/test") discover_unit_tests( "${INCLUDE_PATH}" "${LIBRARIES}") diff --git a/ACL/test/Transport/Common/MockHTTP2Connection.cpp b/ACL/test/Transport/Common/MockHTTP2Connection.cpp index 03351a5b90..4d134242e0 100644 --- a/ACL/test/Transport/Common/MockHTTP2Connection.cpp +++ b/ACL/test/Transport/Common/MockHTTP2Connection.cpp @@ -22,7 +22,7 @@ namespace http2 { namespace test { using namespace avsCommon::utils::http; - + MockHTTP2Connection::MockHTTP2Connection(std::string dURL, std::string pingURL) : m_downchannelURL{dURL}, m_pingURL{pingURL}, diff --git a/ACL/test/Transport/HTTP2TransportTest.cpp b/ACL/test/Transport/HTTP2TransportTest.cpp index ebd10b9cec..0f648f36a9 100644 --- a/ACL/test/Transport/HTTP2TransportTest.cpp +++ b/ACL/test/Transport/HTTP2TransportTest.cpp @@ -355,7 +355,7 @@ void HTTP2TransportTest::authorizeAndConnect() { /** * Test non-authorization on empty auth token. */ -TEST_F(HTTP2TransportTest, emptyAuthToken) { +TEST_F(HTTP2TransportTest, testSlow_emptyAuthToken) { // Send an empty Auth token. m_mockAuthDelegate->setAuthToken(""); @@ -378,7 +378,7 @@ TEST_F(HTTP2TransportTest, emptyAuthToken) { /** * Test waiting for AuthDelegateInterface. */ -TEST_F(HTTP2TransportTest, waitAuthDelegateInterface) { +TEST_F(HTTP2TransportTest, testSlow_waitAuthDelegateInterface) { setupHandlers(false, false); m_http2Transport->connect(); @@ -400,7 +400,7 @@ TEST_F(HTTP2TransportTest, waitAuthDelegateInterface) { /** * Test verifying the proper inclusion of bearer token in requests. */ -TEST_F(HTTP2TransportTest, bearerTokenInRequest) { +TEST_F(HTTP2TransportTest, test_bearerTokenInRequest) { setupHandlers(false, false); m_mockHttp2Connection->setWaitRequestHeader(HTTP_AUTHORIZATION_HEADER_BEARER); @@ -416,7 +416,7 @@ TEST_F(HTTP2TransportTest, bearerTokenInRequest) { /** * Test creation and triggering of post-connect object. */ -TEST_F(HTTP2TransportTest, triggerPostConnectObject) { +TEST_F(HTTP2TransportTest, test_triggerPostConnectObject) { setupHandlers(false, false); // Don't expect TransportObserverInterface::onConnected() will be called. @@ -442,7 +442,7 @@ TEST_F(HTTP2TransportTest, triggerPostConnectObject) { /** * Test delay of connection status until post-connect object created / notifies success. */ -TEST_F(HTTP2TransportTest, connectionStatusOnPostConnect) { +TEST_F(HTTP2TransportTest, test_connectionStatusOnPostConnect) { setupHandlers(true, true); // Call connect(). @@ -466,7 +466,7 @@ TEST_F(HTTP2TransportTest, connectionStatusOnPostConnect) { /** * Test retry upon failed downchannel connection. */ -TEST_F(HTTP2TransportTest, retryOnDownchannelConnectionFailure) { +TEST_F(HTTP2TransportTest, testSlow_retryOnDownchannelConnectionFailure) { setupHandlers(false, false); EXPECT_CALL(*m_mockTransportObserver, onConnected(_)).Times(0); @@ -489,7 +489,7 @@ TEST_F(HTTP2TransportTest, retryOnDownchannelConnectionFailure) { /** * Test sending of MessageRequest content. */ -TEST_F(HTTP2TransportTest, messageRequestContent) { +TEST_F(HTTP2TransportTest, test_messageRequestContent) { setupHandlers(false, false); // Call connect(). @@ -526,7 +526,7 @@ TEST_F(HTTP2TransportTest, messageRequestContent) { /** * Test sending of MessageRequest with attachment data. */ -TEST_F(HTTP2TransportTest, messageRequestWithAttachment) { +TEST_F(HTTP2TransportTest, test_messageRequestWithAttachment) { // Create an attachment reader. std::vector attachment(TEST_ATTACHMENT_MESSAGE.begin(), TEST_ATTACHMENT_MESSAGE.end()); std::shared_ptr attachmentReader = @@ -573,7 +573,7 @@ TEST_F(HTTP2TransportTest, messageRequestWithAttachment) { /** * Test pause of sending message when attachment buffer (SDS) empty but not closed. */ -TEST_F(HTTP2TransportTest, pauseSendWhenSDSEmpty) { +TEST_F(HTTP2TransportTest, test_pauseSendWhenSDSEmpty) { setupHandlers(false, false); // Call connect(). @@ -639,7 +639,7 @@ TEST_F(HTTP2TransportTest, pauseSendWhenSDSEmpty) { /** * Test queuing MessageRequests until a response code has been received for any outstanding MessageRequest */ -TEST_F(HTTP2TransportTest, messageRequestsQueuing) { +TEST_F(HTTP2TransportTest, testSlow_messageRequestsQueuing) { authorizeAndConnect(); // Send 5 messages. @@ -709,7 +709,7 @@ TEST_F(HTTP2TransportTest, messageRequestsQueuing) { * Test notification of onSendCompleted (check mapping of all cases and their mapping to * MessageRequestObserverInterface::Status). */ -TEST_F(HTTP2TransportTest, onSendCompletedNotification) { +TEST_F(HTTP2TransportTest, test_onSendCompletedNotification) { // Contains the mapping of HTTPResponseCode, HTTP2ResponseFinishedStatus and the expected // MessageRequestObserverInterface::Status. const std::vector> @@ -827,7 +827,7 @@ TEST_F(HTTP2TransportTest, onSendCompletedNotification) { /** * Test onExceptionReceived() notification for non 200 content. */ -TEST_F(HTTP2TransportTest, onExceptionReceivedNon200Content) { +TEST_F(HTTP2TransportTest, test_onExceptionReceivedNon200Content) { authorizeAndConnect(); // Send a message. @@ -851,7 +851,7 @@ TEST_F(HTTP2TransportTest, onExceptionReceivedNon200Content) { /** * Test MessageConsumerInterface receipt of directives on Downchannel and Event streams. */ -TEST_F(HTTP2TransportTest, messageConsumerReceiveDirective) { +TEST_F(HTTP2TransportTest, test_messageConsumerReceiveDirective) { PromiseFuturePair messagesAreConsumed; unsigned int consumedMessageCount = 0; std::vector messages; @@ -897,7 +897,7 @@ TEST_F(HTTP2TransportTest, messageConsumerReceiveDirective) { /** * Test broadcast onServerSideDisconnect() upon closure of successfully opened downchannel. */ -TEST_F(HTTP2TransportTest, onServerSideDisconnectOnDownchannelClosure) { +TEST_F(HTTP2TransportTest, test_onServerSideDisconnectOnDownchannelClosure) { authorizeAndConnect(); // Send a message. @@ -936,7 +936,7 @@ TEST_F(HTTP2TransportTest, onServerSideDisconnectOnDownchannelClosure) { /** * Test detection of MessageRequest timeout and trigger of ping request. */ -TEST_F(HTTP2TransportTest, messageRequestTimeoutPingRequest) { +TEST_F(HTTP2TransportTest, test_messageRequestTimeoutPingRequest) { authorizeAndConnect(); // Send a message. @@ -956,7 +956,7 @@ TEST_F(HTTP2TransportTest, messageRequestTimeoutPingRequest) { /** * Test detection of network inactivity and trigger of ping request and continued ping for continued inactivity. */ -TEST_F(HTTP2TransportTest, networkInactivityPingRequest) { +TEST_F(HTTP2TransportTest, testTimer_networkInactivityPingRequest) { // Short time to wait for inactivity before sending a ping. static const std::chrono::seconds testInactivityTimeout = SHORT_DELAY; // This test just checks that a second and third ping will be sen @@ -1006,7 +1006,7 @@ TEST_F(HTTP2TransportTest, networkInactivityPingRequest) { /** * Test connection tear down for ping timeout. */ -TEST_F(HTTP2TransportTest, tearDownPingTimeout) { +TEST_F(HTTP2TransportTest, testSlow_tearDownPingTimeout) { // Short time to wait for inactivity before sending a ping. const std::chrono::seconds testInactivityTimeout = SHORT_DELAY; @@ -1048,7 +1048,7 @@ TEST_F(HTTP2TransportTest, tearDownPingTimeout) { /** * Test connection tear down for ping failure. */ -TEST_F(HTTP2TransportTest, tearDownPingFailure) { +TEST_F(HTTP2TransportTest, testSlow_tearDownPingFailure) { // Short time to wait for inactivity before sending a ping. const std::chrono::seconds testInactivityTimeout = SHORT_DELAY; @@ -1091,7 +1091,7 @@ TEST_F(HTTP2TransportTest, tearDownPingFailure) { /** * Test limiting use of AVS streams to 10. */ -TEST_F(HTTP2TransportTest, avsStreamsLimit) { +TEST_F(HTTP2TransportTest, testSlow_avsStreamsLimit) { // Number of test messages to send for this test. This number is much larger than MAX_POST_STREAMS // to assure that this test exercises the case where more requests are outstanding than are allowed // to be sent at one time, forcing HTTP2Transport to queue the requests until some requests complete. diff --git a/ACL/test/Transport/MessageRouterTest.cpp b/ACL/test/Transport/MessageRouterTest.cpp index 2156633f28..0794b9a948 100644 --- a/ACL/test/Transport/MessageRouterTest.cpp +++ b/ACL/test/Transport/MessageRouterTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -23,26 +23,26 @@ namespace test { using namespace alexaClientSDK::avsCommon::sdkInterfaces; -TEST_F(MessageRouterTest, getConnectionStatusReturnsDisconnectedBeforeConnect) { +TEST_F(MessageRouterTest, test_getConnectionStatusReturnsDisconnectedBeforeConnect) { ASSERT_EQ(m_router->getConnectionStatus().first, ConnectionStatusObserverInterface::Status::DISCONNECTED); } -TEST_F(MessageRouterTest, getConnectionStatusReturnsPendingAfterConnectingStarts) { +TEST_F(MessageRouterTest, test_getConnectionStatusReturnsPendingAfterConnectingStarts) { setupStateToPending(); ASSERT_EQ(m_router->getConnectionStatus().first, ConnectionStatusObserverInterface::Status::PENDING); } -TEST_F(MessageRouterTest, getConnectionStatusReturnsConnectedAfterConnectionEstablished) { +TEST_F(MessageRouterTest, test_getConnectionStatusReturnsConnectedAfterConnectionEstablished) { setupStateToConnected(); ASSERT_EQ(m_router->getConnectionStatus().first, ConnectionStatusObserverInterface::Status::CONNECTED); } -TEST_F(MessageRouterTest, getConnectionStatusReturnsConnectedAfterDisconnected) { +TEST_F(MessageRouterTest, test_getConnectionStatusReturnsConnectedAfterDisconnected) { m_router->onDisconnected(m_mockTransport, ConnectionStatusObserverInterface::ChangedReason::ACL_DISABLED); ASSERT_EQ(m_router->getConnectionStatus().first, ConnectionStatusObserverInterface::Status::DISCONNECTED); } -TEST_F(MessageRouterTest, ensureTheMessageRouterObserverIsInformedOfConnectionPendingAfterConnect) { +TEST_F(MessageRouterTest, test_ensureTheMessageRouterObserverIsInformedOfConnectionPendingAfterConnect) { setupStateToPending(); // wait for the result to propagate by scheduling a task on the client executor @@ -55,7 +55,7 @@ TEST_F(MessageRouterTest, ensureTheMessageRouterObserverIsInformedOfConnectionPe ConnectionStatusObserverInterface::ChangedReason::ACL_CLIENT_REQUEST); } -TEST_F(MessageRouterTest, ensureTheMessageRouterObserverIsInformedOfNewConnection) { +TEST_F(MessageRouterTest, test_ensureTheMessageRouterObserverIsInformedOfNewConnection) { setupStateToConnected(); // wait for the result to propagate by scheduling a task on the client executor @@ -68,7 +68,7 @@ TEST_F(MessageRouterTest, ensureTheMessageRouterObserverIsInformedOfNewConnectio ConnectionStatusObserverInterface::ChangedReason::ACL_CLIENT_REQUEST); } -TEST_F(MessageRouterTest, ensureTheMessageRouterObserverIsInformedOfTransportDisconnection) { +TEST_F(MessageRouterTest, test_ensureTheMessageRouterObserverIsInformedOfTransportDisconnection) { setupStateToConnected(); auto reason = ConnectionStatusObserverInterface::ChangedReason::ACL_DISABLED; @@ -83,7 +83,7 @@ TEST_F(MessageRouterTest, ensureTheMessageRouterObserverIsInformedOfTransportDis ASSERT_EQ(m_mockMessageRouterObserver->getLatestConnectionChangedReason(), reason); } -TEST_F(MessageRouterTest, ensureTheMessageRouterObserverIsInformedOfRouterDisconnection) { +TEST_F(MessageRouterTest, test_ensureTheMessageRouterObserverIsInformedOfRouterDisconnection) { setupStateToConnected(); m_router->disable(); @@ -99,7 +99,7 @@ TEST_F(MessageRouterTest, ensureTheMessageRouterObserverIsInformedOfRouterDiscon ConnectionStatusObserverInterface::ChangedReason::ACL_CLIENT_REQUEST); } -TEST_F(MessageRouterTest, sendIsSuccessfulWhenConnected) { +TEST_F(MessageRouterTest, test_sendIsSuccessfulWhenConnected) { setupStateToConnected(); auto messageRequest = createMessageRequest(); @@ -113,7 +113,7 @@ TEST_F(MessageRouterTest, sendIsSuccessfulWhenConnected) { EXPECT_CALL(*m_mockTransport, disconnect()).Times(AnyNumber()); } -TEST_F(MessageRouterTest, sendFailsWhenDisconnected) { +TEST_F(MessageRouterTest, test_sendFailsWhenDisconnected) { auto messageRequest = createMessageRequest(); // Expect to have the message sent to the transport @@ -122,7 +122,7 @@ TEST_F(MessageRouterTest, sendFailsWhenDisconnected) { m_router->sendMessage(messageRequest); } -TEST_F(MessageRouterTest, sendFailsWhenPending) { +TEST_F(MessageRouterTest, test_sendFailsWhenPending) { // Ensure a transport exists initializeMockTransport(m_mockTransport.get()); m_router->enable(); @@ -136,7 +136,7 @@ TEST_F(MessageRouterTest, sendFailsWhenPending) { waitOnMessageRouter(SHORT_TIMEOUT_MS); } -TEST_F(MessageRouterTest, sendMessageDoesNotSendAfterDisconnected) { +TEST_F(MessageRouterTest, test_sendMessageDoesNotSendAfterDisconnected) { setupStateToConnected(); auto messageRequest = createMessageRequest(); @@ -150,7 +150,7 @@ TEST_F(MessageRouterTest, sendMessageDoesNotSendAfterDisconnected) { m_router->sendMessage(messageRequest); } -TEST_F(MessageRouterTest, disconnectDisconnectsConnectedTransports) { +TEST_F(MessageRouterTest, test_disconnectDisconnectsConnectedTransports) { setupStateToConnected(); EXPECT_CALL(*m_mockTransport, doShutdown()).Times(1); @@ -158,7 +158,7 @@ TEST_F(MessageRouterTest, disconnectDisconnectsConnectedTransports) { m_router->disable(); } -TEST_F(MessageRouterTest, serverSideDisconnectCreatesANewTransport) { +TEST_F(MessageRouterTest, test_serverSideDisconnectCreatesANewTransport) { /* * This test is difficult to setup in a nice way. The idea is to replace the original * transport with a new one, call onServerSideDisconnect to make it the new active @@ -214,7 +214,7 @@ TEST_F(MessageRouterTest, serverSideDisconnectCreatesANewTransport) { /** * This tests the calling of private method @c receive() for MessageRouterObserver from MessageRouter */ -TEST_F(MessageRouterTest, onReceiveTest) { +TEST_F(MessageRouterTest, test_onReceive) { m_mockMessageRouterObserver->reset(); m_router->consumeMessage(CONTEXT_ID, MESSAGE); waitOnMessageRouter(SHORT_TIMEOUT_MS); @@ -227,12 +227,40 @@ TEST_F(MessageRouterTest, onReceiveTest) { * This tests the calling of private method @c onConnectionStatusChanged() * for MessageRouterObserver from MessageRouter */ -TEST_F(MessageRouterTest, onConnectionStatusChangedTest) { +TEST_F(MessageRouterTest, test_onConnectionStatusChanged) { m_mockMessageRouterObserver->reset(); setupStateToConnected(); waitOnMessageRouter(SHORT_TIMEOUT_MS); ASSERT_TRUE(m_mockMessageRouterObserver->wasNotifiedOfStatusChange()); } + +/** + * Verify that when enable is called with active connection is pending + * we don't create a new connection. + */ +TEST_F(MessageRouterTest, test_enableTwiceOnPendingTransport) { + setupStateToPending(); + waitOnMessageRouter(SHORT_TIMEOUT_MS); + m_mockMessageRouterObserver->reset(); + + EXPECT_CALL(*m_mockTransport, connect()).Times(0); + + m_router->enable(); + + ASSERT_FALSE(m_mockMessageRouterObserver->wasNotifiedOfStatusChange()); +} + +/** + * Verify that if onConnected is called + * for inactive transport, we don't notify the observers and + * closing the connection. + */ +TEST_F(MessageRouterTest, test_onConnectedOnInactiveTransport) { + auto transport = std::make_shared(); + m_router->onConnected(transport); + ASSERT_FALSE(m_mockMessageRouterObserver->wasNotifiedOfStatusChange()); +} + } // namespace test } // namespace acl } // namespace alexaClientSDK diff --git a/ADSL/src/DirectiveProcessor.cpp b/ADSL/src/DirectiveProcessor.cpp index 41df44767c..d6f956ccd9 100644 --- a/ADSL/src/DirectiveProcessor.cpp +++ b/ADSL/src/DirectiveProcessor.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -293,8 +293,17 @@ std::deque::iterator DirectiveProcessor: (m_directivesBeingHandled[BlockingPolicy::Medium::VISUAL] != nullptr); for (auto it = m_handlingQueue.begin(); it != m_handlingQueue.end(); it++) { - auto currentUsingAudio = it->second.getMediums()[BlockingPolicy::Medium::AUDIO]; - auto currentUsingVisual = it->second.getMediums()[BlockingPolicy::Medium::VISUAL]; + auto policy = it->second; + bool currentUsingAudio = false; + bool currentUsingVisual = false; + + if (policy.getMediums()[BlockingPolicy::Medium::AUDIO]) { + currentUsingAudio = true; + } + + if (policy.getMediums()[BlockingPolicy::Medium::VISUAL]) { + currentUsingVisual = true; + } if ((currentUsingAudio && blockedMediums[BlockingPolicy::Medium::AUDIO]) || (currentUsingVisual && blockedMediums[BlockingPolicy::Medium::VISUAL])) { diff --git a/ADSL/test/DirectiveProcessorTest.cpp b/ADSL/test/DirectiveProcessorTest.cpp index 4cf12ea2cf..95b22d5b79 100644 --- a/ADSL/test/DirectiveProcessorTest.cpp +++ b/ADSL/test/DirectiveProcessorTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -195,7 +195,7 @@ void DirectiveProcessorTest::SetUp() { /** * Send a nullptr @c AVSDirective. Expect that it is ignored and a failure status (false) is returned. */ -TEST_F(DirectiveProcessorTest, testNullptrDirective) { +TEST_F(DirectiveProcessorTest, test_nullptrDirective) { ASSERT_FALSE(m_processor->onDirective(nullptr)); } @@ -205,7 +205,7 @@ TEST_F(DirectiveProcessorTest, testNullptrDirective) { * returns true (because the handler was registered) but that none of the handler methods are called * (because directives with the wrong @c dialogRequestID are dropped). */ -TEST_F(DirectiveProcessorTest, testWrongDialogRequestId) { +TEST_F(DirectiveProcessorTest, test_wrongDialogRequestId) { DirectiveHandlerConfiguration handler0Config; handler0Config[{NAMESPACE_AND_NAME_0_0}] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, false); std::shared_ptr handler0 = MockDirectiveHandler::create(handler0Config); @@ -225,7 +225,7 @@ TEST_F(DirectiveProcessorTest, testWrongDialogRequestId) { * Register an @c AUDIO_NON_BLOCKING @c DirectiveHandler. Send an @c AVSDirective that matches the registered handler. * Expect that @c preHandleDirective() and @c handleDirective() are called. */ -TEST_F(DirectiveProcessorTest, testSendNonBlocking) { +TEST_F(DirectiveProcessorTest, test_sendNonBlocking) { DirectiveHandlerConfiguration handler0Config; handler0Config[{NAMESPACE_AND_NAME_0_0}] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, false); std::shared_ptr handler0 = MockDirectiveHandler::create(handler0Config); @@ -247,7 +247,7 @@ TEST_F(DirectiveProcessorTest, testSendNonBlocking) { * Test sending a blocking and then a non-blocking directive. Expect that @c preHandleDirective() and * @c handleDirective() is called for each. */ -TEST_F(DirectiveProcessorTest, testSendBlockingThenNonBlocking) { +TEST_F(DirectiveProcessorTest, test_sendBlockingThenNonBlocking) { DirectiveHandlerConfiguration handler0Config; handler0Config[{NAMESPACE_AND_NAME_0_0}] = BlockingPolicy(BlockingPolicy::MEDIUMS_AUDIO_AND_VISUAL, true); std::shared_ptr handler0 = MockDirectiveHandler::create(handler0Config); @@ -284,7 +284,7 @@ TEST_F(DirectiveProcessorTest, testSendBlockingThenNonBlocking) { * has been called, set the @c dialogRequestId and send an @c AVSDirective for which the other handler was * registered. Expect that the last directive is handled as well. */ -TEST_F(DirectiveProcessorTest, testOnUnregisteredDirective) { +TEST_F(DirectiveProcessorTest, test_onUnregisteredDirective) { DirectiveHandlerConfiguration handler1Config; handler1Config[{NAMESPACE_AND_NAME_0_1}] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, false); std::shared_ptr handler1 = MockDirectiveHandler::create(handler1Config); @@ -326,7 +326,7 @@ TEST_F(DirectiveProcessorTest, testOnUnregisteredDirective) { * @c dialogRequestId(). Expect the first two @c AVSDirectives to be cancelled and expect the * final @c AVSDirective to be processed normally. */ -TEST_F(DirectiveProcessorTest, testSetDialogRequestIdCancelsOutstandingDirectives) { +TEST_F(DirectiveProcessorTest, test_setDialogRequestIdCancelsOutstandingDirectives) { DirectiveHandlerConfiguration longRunningHandlerConfig; longRunningHandlerConfig[{NAMESPACE_AND_NAME_0_0}] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, true); auto longRunningHandler = @@ -370,12 +370,12 @@ TEST_F(DirectiveProcessorTest, testSetDialogRequestIdCancelsOutstandingDirective ASSERT_TRUE(handler2->waitUntilCompleted()); } -TEST_F(DirectiveProcessorTest, testAddDirectiveWhileDisabled) { +TEST_F(DirectiveProcessorTest, test_addDirectiveWhileDisabled) { m_processor->disable(); ASSERT_FALSE(m_processor->onDirective(m_directive_0_0)); } -TEST_F(DirectiveProcessorTest, testAddDirectiveAfterReEnabled) { +TEST_F(DirectiveProcessorTest, test_addDirectiveAfterReEnabled) { m_processor->disable(); ASSERT_FALSE(m_processor->onDirective(m_directive_0_0)); @@ -387,7 +387,7 @@ TEST_F(DirectiveProcessorTest, testAddDirectiveAfterReEnabled) { * Verify that an @c AVSDirective using @c MEDIUMS_AUDIO_AND_VISUAL * is blocking @c MEDIUM_AUDIO but not blocking @c MEDIUMS_NONE. */ -TEST_F(DirectiveProcessorTest, testAudioAndVisualIsBlockingAudio) { +TEST_F(DirectiveProcessorTest, test_audioAndVisualIsBlockingAudio) { auto& audioAndVisualBlockingDirective = m_directive_0_0; DirectiveHandlerConfiguration audioAndVisualBlockingHandlerConfig; auto audioBlockingPolicy = BlockingPolicy(BlockingPolicy::MEDIUMS_AUDIO_AND_VISUAL, true); @@ -443,7 +443,7 @@ TEST_F(DirectiveProcessorTest, testAudioAndVisualIsBlockingAudio) { * Verify that a blocking @c AVSDirective is not blocking * a future @c AVSDirective on a different @c Medium. */ -TEST_F(DirectiveProcessorTest, testDifferentMediums) { +TEST_F(DirectiveProcessorTest, test_differentMediums) { auto& audioBlockingDirective = m_directive_0_0; DirectiveHandlerConfiguration audioBlockingHandlerConfig; audioBlockingHandlerConfig[{NAMESPACE_AND_NAME_0_0}] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, true); @@ -482,7 +482,7 @@ TEST_F(DirectiveProcessorTest, testDifferentMediums) { * When one of the blocking has been completed, only its @c Medium is * released. */ -TEST_F(DirectiveProcessorTest, testReleaseOneMedium) { +TEST_F(DirectiveProcessorTest, test_releaseOneMedium) { // 4 directives: blocking audio, blocking visual, using audio and using visual auto& audioBlockingDirective = m_directive_0_0; DirectiveHandlerConfiguration audioBlockingHandlerConfig; @@ -547,7 +547,7 @@ TEST_F(DirectiveProcessorTest, testReleaseOneMedium) { * Verify that a blocked directive with isBlocking=true on the queue is blocking * subsequent directives using the same @c Medium. */ -TEST_F(DirectiveProcessorTest, TestBlockingQueuedDirectivIsBlocking) { +TEST_F(DirectiveProcessorTest, test_blockingQueuedDirectivIsBlocking) { auto& audioBlockingDirective = m_directive_0_0; DirectiveHandlerConfiguration audioBlockingHandlerConfig; audioBlockingHandlerConfig[{NAMESPACE_AND_NAME_0_0}] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, true); @@ -633,7 +633,7 @@ TEST_F(DirectiveProcessorTest, TestBlockingQueuedDirectivIsBlocking) { * Verify that a blocked directive with isBlocking=false on the queue is NOT blocking * subsequent directives using the same @c Medium. */ -TEST_F(DirectiveProcessorTest, TestNonBlockingQueuedDirectivIsNotBlocking) { +TEST_F(DirectiveProcessorTest, test_nonBlockingQueuedDirectivIsNotBlocking) { auto& audioBlockingDirective = m_directive_0_0; DirectiveHandlerConfiguration audioBlockingHandlerConfig; audioBlockingHandlerConfig[{NAMESPACE_AND_NAME_0_0}] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, true); @@ -705,7 +705,7 @@ TEST_F(DirectiveProcessorTest, TestNonBlockingQueuedDirectivIsNotBlocking) { * directive. * TODO: ACSDK-2218: This test should be removed when the workaround is removed. */ -TEST_F(DirectiveProcessorTest, testNewDialogRequestHandling) { +TEST_F(DirectiveProcessorTest, test_newDialogRequestHandling) { auto directivePair = AVSDirective::create(NEW_DIALOG_REQUEST_DIRECTIVE_V0, nullptr, NO_CONTEXT); std::shared_ptr newDialogRequestDirective = std::move(directivePair.first); diff --git a/ADSL/test/DirectiveRouterTest.cpp b/ADSL/test/DirectiveRouterTest.cpp index ca7fbfa28a..b1dc0f4f55 100644 --- a/ADSL/test/DirectiveRouterTest.cpp +++ b/ADSL/test/DirectiveRouterTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -170,7 +170,7 @@ void DirectiveRouterTest::TearDown() { /** * Check that an un-registered @c AVDirective will not be routed. */ -TEST_F(DirectiveRouterTest, testUnroutedDirective) { +TEST_F(DirectiveRouterTest, test_unroutedDirective) { ASSERT_FALSE(m_router.handleDirectiveImmediately(m_directive_0_0)); } @@ -178,7 +178,7 @@ TEST_F(DirectiveRouterTest, testUnroutedDirective) { * Register an @c AVSDirective for routing. Exercise routing via @c handleDirectiveImmediately(). * Expect that the @c AVSDirective is routed. */ -TEST_F(DirectiveRouterTest, testSettingADirectiveHandler) { +TEST_F(DirectiveRouterTest, test_settingADirectiveHandler) { DirectiveHandlerConfiguration handler0Config; handler0Config[{NAMESPACE_AND_NAME_0_0}] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, false); std::shared_ptr handler0 = MockDirectiveHandler::create(handler0Config); @@ -197,7 +197,7 @@ TEST_F(DirectiveRouterTest, testSettingADirectiveHandler) { * Register @c AVSDirectives to be routed to different handlers. Exercise routing via @c preHandleDirective(). * Expect that the @c AVSDirectives make it to their registered handler. */ -TEST_F(DirectiveRouterTest, testRegisteringMultipeHandler) { +TEST_F(DirectiveRouterTest, test_registeringMultipeHandler) { DirectiveHandlerConfiguration handler0Config; auto audioNonBlockingPolicy = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, false); handler0Config[{NAMESPACE_AND_NAME_0_0}] = audioNonBlockingPolicy; @@ -271,7 +271,7 @@ TEST_F(DirectiveRouterTest, testRegisteringMultipeHandler) { * were last assigned to and that false and a @c BlockingPolicy of NONE is returned for the directive whose handler * was removed. */ -TEST_F(DirectiveRouterTest, testRemovingChangingAndNotChangingHandlers) { +TEST_F(DirectiveRouterTest, test_removingChangingAndNotChangingHandlers) { DirectiveHandlerConfiguration handler0Config; auto audioBlockingPolicy = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, true); auto audioNonBlockingPolicy = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, false); @@ -341,7 +341,7 @@ TEST_F(DirectiveRouterTest, testRemovingChangingAndNotChangingHandlers) { * mock handlers to return false from @c handleDirective(). Exercise routing via handleDirective(). Expect that * @c DirectiveRouter::handleDirective() returns @c false and BlockingPolicy::nonePolicy() to indicate failure. */ -TEST_F(DirectiveRouterTest, testResultOfHandleDirectiveFailure) { +TEST_F(DirectiveRouterTest, test_resultOfHandleDirectiveFailure) { DirectiveHandlerConfiguration handler0Config; handler0Config[{NAMESPACE_AND_NAME_0_0}] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, false); std::shared_ptr handler0 = MockDirectiveHandler::create(handler0Config); @@ -374,7 +374,7 @@ TEST_F(DirectiveRouterTest, testResultOfHandleDirectiveFailure) { * until a subsequent invocation of @c handleDirective() has started. Expect the blocked call to preHandleDirective() * to complete quickly. */ -TEST_F(DirectiveRouterTest, testHandlerMethodsCanRunConcurrently) { +TEST_F(DirectiveRouterTest, test_handlerMethodsCanRunConcurrently) { DirectiveHandlerConfiguration handler0Config; handler0Config[{NAMESPACE_AND_NAME_0_0}] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, true); std::shared_ptr handler0 = MockDirectiveHandler::create(handler0Config); diff --git a/ADSL/test/DirectiveSequencerTest.cpp b/ADSL/test/DirectiveSequencerTest.cpp index 6760d73676..95c903ea3d 100644 --- a/ADSL/test/DirectiveSequencerTest.cpp +++ b/ADSL/test/DirectiveSequencerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -184,7 +184,7 @@ void DirectiveSequencerTest::TearDown() { /** * Test DirectiveSequencer::create() with a nullptr @c ExceptionEncounteredSender. Expect create to fail. */ -TEST_F(DirectiveSequencerTest, testNullptrExceptionSender) { +TEST_F(DirectiveSequencerTest, test_nullptrExceptionSender) { ASSERT_TRUE(m_sequencer); auto sequencer = DirectiveSequencer::create(nullptr); ASSERT_FALSE(sequencer); @@ -193,14 +193,14 @@ TEST_F(DirectiveSequencerTest, testNullptrExceptionSender) { /** * Verify core DirectiveSequencerTest. Expect a new non-null instance of m_sequencer. */ -TEST_F(DirectiveSequencerTest, testCreateAndDoneTrigger) { +TEST_F(DirectiveSequencerTest, test_createAndDoneTrigger) { ASSERT_TRUE(m_sequencer); } /** * Exercise sending a @c nullptr to @c onDirective. Expect that false is returned. */ -TEST_F(DirectiveSequencerTest, testNullptrDirective) { +TEST_F(DirectiveSequencerTest, test_nullptrDirective) { ASSERT_FALSE(m_sequencer->onDirective(nullptr)); } @@ -208,7 +208,7 @@ TEST_F(DirectiveSequencerTest, testNullptrDirective) { * Exercise sending a @c AVSDirective for which no handler has been registered. Expect that * m_exceptionEncounteredSender will receive a request to send the ExceptionEncountered message. */ -TEST_F(DirectiveSequencerTest, testUnhandledDirective) { +TEST_F(DirectiveSequencerTest, test_unhandledDirective) { auto avsMessageHeader = std::make_shared(NAMESPACE_SPEAKER, NAME_SET_VOLUME, MESSAGE_ID_0); std::shared_ptr directive = AVSDirective::create( UNPARSED_DIRECTIVE, avsMessageHeader, PAYLOAD_TEST, m_attachmentManager, TEST_ATTACHMENT_CONTEXT_ID); @@ -220,7 +220,7 @@ TEST_F(DirectiveSequencerTest, testUnhandledDirective) { * Send a directive with an empty DialogRequestId. * Expect a call to handleDirectiveImmediately(). */ -TEST_F(DirectiveSequencerTest, testEmptyDialogRequestId) { +TEST_F(DirectiveSequencerTest, test_emptyDialogRequestId) { auto avsMessageHeader = std::make_shared(NAMESPACE_SPEAKER, NAME_SET_VOLUME, MESSAGE_ID_0); std::shared_ptr directive = AVSDirective::create( UNPARSED_DIRECTIVE, avsMessageHeader, PAYLOAD_TEST, m_attachmentManager, TEST_ATTACHMENT_CONTEXT_ID); @@ -240,7 +240,7 @@ TEST_F(DirectiveSequencerTest, testEmptyDialogRequestId) { * Send a directive with a DialogRequestId but with HANDLE_IMMEDIATELY policy in its handlier. * Expect a call to handleDirectiveImmediately(). */ -TEST_F(DirectiveSequencerTest, testHandleImmediatelyHandler) { +TEST_F(DirectiveSequencerTest, test_handleImmediatelyHandler) { auto avsMessageHeader = std::make_shared(NAMESPACE_TEST, NAME_HANDLE_IMMEDIATELY, MESSAGE_ID_0); std::shared_ptr directive = AVSDirective::create( UNPARSED_DIRECTIVE, avsMessageHeader, PAYLOAD_TEST, m_attachmentManager, TEST_ATTACHMENT_CONTEXT_ID); @@ -261,7 +261,7 @@ TEST_F(DirectiveSequencerTest, testHandleImmediatelyHandler) { * for each of the NamespaceAndName values. Expect that the directive with no mapping is not seen by a handler and * that the one that still has a handler is handled. */ -TEST_F(DirectiveSequencerTest, testRemovingAndChangingHandlers) { +TEST_F(DirectiveSequencerTest, test_removingAndChangingHandlers) { auto avsMessageHeader0 = std::make_shared(NAMESPACE_SPEAKER, NAME_SET_VOLUME, MESSAGE_ID_0); std::shared_ptr directive0 = AVSDirective::create( UNPARSED_DIRECTIVE, avsMessageHeader0, PAYLOAD_TEST, m_attachmentManager, TEST_ATTACHMENT_CONTEXT_ID); @@ -312,7 +312,7 @@ TEST_F(DirectiveSequencerTest, testRemovingAndChangingHandlers) { * @c preHandleDirective() and a call to @c handleDirective(). The @c AVSDirective is the cancelled, triggering * a call to cancelDirective() to close out the test. */ -TEST_F(DirectiveSequencerTest, testBlockingDirective) { +TEST_F(DirectiveSequencerTest, test_blockingDirective) { auto avsMessageHeader = std::make_shared(NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_0, DIALOG_REQUEST_ID_0); std::shared_ptr directive = AVSDirective::create( @@ -338,7 +338,7 @@ TEST_F(DirectiveSequencerTest, testBlockingDirective) { /** * Send a long running directive with an non-empty @c DialogRequestId and a BLOCKING policy. */ -TEST_F(DirectiveSequencerTest, testBlockingThenNonDialogDirective) { +TEST_F(DirectiveSequencerTest, test_blockingThenNonDialogDirective) { auto avsMessageHeader0 = std::make_shared(NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_0, DIALOG_REQUEST_ID_0); std::shared_ptr directive0 = AVSDirective::create( @@ -385,7 +385,7 @@ TEST_F(DirectiveSequencerTest, testBlockingThenNonDialogDirective) { * @c preHandleDirective(@cAVSDirective) a call to @c handleDirective(@c MessageId, @c DirectiveHandlingResult), * and a call to @c cancelDirective(@c MessageId). */ -TEST_F(DirectiveSequencerTest, testBargeIn) { +TEST_F(DirectiveSequencerTest, test_bargeIn) { auto avsMessageHeader = std::make_shared(NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_0, DIALOG_REQUEST_ID_0); std::shared_ptr directive = AVSDirective::create( @@ -415,7 +415,7 @@ TEST_F(DirectiveSequencerTest, testBargeIn) { * Along the way we set the DialogRequestId to the same value to verify that that setting it to the * current value does not cancel queued directives. */ -TEST_F(DirectiveSequencerTest, testBlockingThenNonBockingOnSameDialogId) { +TEST_F(DirectiveSequencerTest, testTimer_blockingThenNonBockingOnSameDialogId) { auto avsMessageHeader0 = std::make_shared(NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_0, DIALOG_REQUEST_ID_0); std::shared_ptr directive0 = AVSDirective::create( @@ -477,7 +477,7 @@ TEST_F(DirectiveSequencerTest, testBlockingThenNonBockingOnSameDialogId) { * the first two directives will be cancelled and the third one will be handled (and then cancelled at the * end by setting the dialogRequestId to close out the test). */ -TEST_F(DirectiveSequencerTest, testThatBargeInDropsSubsequentDirectives) { +TEST_F(DirectiveSequencerTest, test_thatBargeInDropsSubsequentDirectives) { auto avsMessageHeader0 = std::make_shared(NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_0, DIALOG_REQUEST_ID_0); std::shared_ptr directive0 = AVSDirective::create( @@ -540,7 +540,7 @@ TEST_F(DirectiveSequencerTest, testThatBargeInDropsSubsequentDirectives) { * Expect that the first @c AVSDirective will not be cancelled and that the second @c AVSDirective will be dropped * entirely. */ -TEST_F(DirectiveSequencerTest, testPreHandleDirectiveError) { +TEST_F(DirectiveSequencerTest, test_preHandleDirectiveError) { auto avsMessageHeader0 = std::make_shared(NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_0, DIALOG_REQUEST_ID_0); std::shared_ptr directive0 = AVSDirective::create( @@ -584,7 +584,7 @@ TEST_F(DirectiveSequencerTest, testPreHandleDirectiveError) { * Expect that the first @c AVSDirective will not be cancelled and that the second @c AVSDirective may be * dropped before @c preHandleDirective() is called, and that if not, it will be cancelled. */ -TEST_F(DirectiveSequencerTest, testHandleDirectiveError) { +TEST_F(DirectiveSequencerTest, test_handleDirectiveError) { auto avsMessageHeader0 = std::make_shared(NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_0, DIALOG_REQUEST_ID_0); std::shared_ptr directive0 = AVSDirective::create( @@ -635,7 +635,7 @@ TEST_F(DirectiveSequencerTest, testHandleDirectiveError) { * subsequent directives with the same dialogRequestId. Along the way, call @c addDirectiveHandler() while * inside cancelDirective() to verify that that operation is refused. */ -TEST_F(DirectiveSequencerTest, testAddDirectiveHandlersWhileHandlingDirectives) { +TEST_F(DirectiveSequencerTest, test_addDirectiveHandlersWhileHandlingDirectives) { auto avsMessageHeader0 = std::make_shared(NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_0, DIALOG_REQUEST_ID_0); std::shared_ptr directive0 = AVSDirective::create( @@ -731,7 +731,7 @@ TEST_F(DirectiveSequencerTest, testAddDirectiveHandlersWhileHandlingDirectives) * @c preHandleDirective(@c AVSDirective) and a call to @c handleDirective() for the @c AVSDirective that are not * @c HANDLE_IMMEDIATELY. And for the one with @c HANDLE_IMMEDIATELY, only @c handleDirectiveImmediately() is called. */ -TEST_F(DirectiveSequencerTest, testHandleBlockingThenImmediatelyThenNonBockingOnSameDialogId) { +TEST_F(DirectiveSequencerTest, test_handleBlockingThenImmediatelyThenNonBockingOnSameDialogId) { auto avsMessageHeader0 = std::make_shared(NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_0, DIALOG_REQUEST_ID_0); std::shared_ptr directive0 = AVSDirective::create( @@ -799,7 +799,7 @@ TEST_F(DirectiveSequencerTest, testHandleBlockingThenImmediatelyThenNonBockingOn /** * Check that the @ DirectiveSequencer does not handle directives when it is disabled */ -TEST_F(DirectiveSequencerTest, testAddDirectiveAfterDisabled) { +TEST_F(DirectiveSequencerTest, test_addDirectiveAfterDisabled) { auto avsMessageHeader = std::make_shared(NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_0, DIALOG_REQUEST_ID_0); std::shared_ptr directive = AVSDirective::create( @@ -826,7 +826,7 @@ TEST_F(DirectiveSequencerTest, testAddDirectiveAfterDisabled) { /** * Check that the @ DirectiveSequencer.disable() cancel directive being handled */ -TEST_F(DirectiveSequencerTest, testDisableCancelsDirective) { +TEST_F(DirectiveSequencerTest, test_disableCancelsDirective) { auto avsMessageHeader = std::make_shared(NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_0, DIALOG_REQUEST_ID_0); std::shared_ptr directive = AVSDirective::create( @@ -858,7 +858,7 @@ TEST_F(DirectiveSequencerTest, testDisableCancelsDirective) { /** * Check that the @ DirectiveSequencer can handle directives after being re-enabled */ -TEST_F(DirectiveSequencerTest, testAddDirectiveAfterReEnabled) { +TEST_F(DirectiveSequencerTest, test_addDirectiveAfterReEnabled) { auto avsMessageHeader0 = std::make_shared(NAMESPACE_AUDIO_PLAYER, NAME_PLAY, MESSAGE_ID_0, DIALOG_REQUEST_ID_0); std::shared_ptr directive0 = AVSDirective::create( diff --git a/ADSL/test/MessageInterpreterTest.cpp b/ADSL/test/MessageInterpreterTest.cpp index d61d9d6f70..0614ba370f 100644 --- a/ADSL/test/MessageInterpreterTest.cpp +++ b/ADSL/test/MessageInterpreterTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -208,7 +208,7 @@ class MessageIntepreterTest : public ::testing::Test { * Test when the content of message is invalid JSON format. The AVSDirective shouldn't be created and * and passed to directive sequencer. ExceptionEncounteredEvent should be sent to AVS. */ -TEST_F(MessageIntepreterTest, messageIsInValidJSON) { +TEST_F(MessageIntepreterTest, test_messageIsInValidJSON) { EXPECT_CALL(*m_mockExceptionEncounteredSender, sendExceptionEncountered(_, _, _)).Times(1); EXPECT_CALL(*m_mockDirectiveSequencer, onDirective(_)).Times(0); m_messageInterpreter->receive(TEST_ATTACHMENT_CONTEXT_ID, INVALID_JSON); @@ -218,7 +218,7 @@ TEST_F(MessageIntepreterTest, messageIsInValidJSON) { * Test when the message doesn't contain the directive key in JSON content. The AVSDirective shouldn't be created and * and passed to directive sequencer. ExceptionEncounteredEvent should be sent to AVS. */ -TEST_F(MessageIntepreterTest, messageHasInvalidDirectiveKey) { +TEST_F(MessageIntepreterTest, test_messageHasInvalidDirectiveKey) { EXPECT_CALL(*m_mockExceptionEncounteredSender, sendExceptionEncountered(_, _, _)).Times(1); EXPECT_CALL(*m_mockDirectiveSequencer, onDirective(_)).Times(0); m_messageInterpreter->receive(TEST_ATTACHMENT_CONTEXT_ID, DIRECTIVE_INVALID_DIRECTIVE_KEY); @@ -228,7 +228,7 @@ TEST_F(MessageIntepreterTest, messageHasInvalidDirectiveKey) { * Test when the message doesn't contain the header key in JSON content. The AVSDirective shouldn't be created and * and passed to directive sequencer. ExceptionEncounteredEvent should be sent to AVS. */ -TEST_F(MessageIntepreterTest, messageHasInvalidHeaderKey) { +TEST_F(MessageIntepreterTest, test_messageHasInvalidHeaderKey) { EXPECT_CALL(*m_mockExceptionEncounteredSender, sendExceptionEncountered(_, _, _)).Times(1); EXPECT_CALL(*m_mockDirectiveSequencer, onDirective(_)).Times(0); m_messageInterpreter->receive(TEST_ATTACHMENT_CONTEXT_ID, DIRECTIVE_INVALID_HEADER_KEY); @@ -238,7 +238,7 @@ TEST_F(MessageIntepreterTest, messageHasInvalidHeaderKey) { * Test when the message doesn't contain the namespace key in JSON content. The AVSDirective shouldn't be created and * and passed to directive sequencer. ExceptionEncounteredEvent should be sent to AVS. */ -TEST_F(MessageIntepreterTest, messageHasInvalidNamespaceKey) { +TEST_F(MessageIntepreterTest, test_messageHasInvalidNamespaceKey) { EXPECT_CALL(*m_mockExceptionEncounteredSender, sendExceptionEncountered(_, _, _)).Times(1); EXPECT_CALL(*m_mockDirectiveSequencer, onDirective(_)).Times(0); m_messageInterpreter->receive(TEST_ATTACHMENT_CONTEXT_ID, DIRECTIVE_INVALID_NAMESPACE_KEY); @@ -248,7 +248,7 @@ TEST_F(MessageIntepreterTest, messageHasInvalidNamespaceKey) { * Test when the message doesn't contain the name key in JSON content. The AVSDirective shouldn't be created and * and passed to directive sequencer. ExceptionEncounteredEvent should be sent to AVS. */ -TEST_F(MessageIntepreterTest, messageHasInvalidNameKey) { +TEST_F(MessageIntepreterTest, test_messageHasInvalidNameKey) { EXPECT_CALL(*m_mockExceptionEncounteredSender, sendExceptionEncountered(_, _, _)).Times(1); EXPECT_CALL(*m_mockDirectiveSequencer, onDirective(_)).Times(0); m_messageInterpreter->receive(TEST_ATTACHMENT_CONTEXT_ID, DIRECTIVE_INVALID_NAME_KEY); @@ -258,7 +258,7 @@ TEST_F(MessageIntepreterTest, messageHasInvalidNameKey) { * Test when the message doesn't contain the messageId key in JSON content. The AVSDirective shouldn't be created and * and passed to directive sequencer. ExceptionEncounteredEvent should be sent to AVS. */ -TEST_F(MessageIntepreterTest, messageHasInvalidMessageIdKey) { +TEST_F(MessageIntepreterTest, test_messageHasInvalidMessageIdKey) { EXPECT_CALL(*m_mockExceptionEncounteredSender, sendExceptionEncountered(_, _, _)).Times(1); EXPECT_CALL(*m_mockDirectiveSequencer, onDirective(_)).Times(0); m_messageInterpreter->receive(TEST_ATTACHMENT_CONTEXT_ID, DIRECTIVE_INVALID_MESSAGEID_KEY); @@ -268,7 +268,7 @@ TEST_F(MessageIntepreterTest, messageHasInvalidMessageIdKey) { * Test when the message doesn't contain the dialogRequestId key in JSON content. DialogRequestId is optional, so * AVSDirective should be created and passed to the directive sequencer. */ -TEST_F(MessageIntepreterTest, messageHasNoDialogRequestIdKey) { +TEST_F(MessageIntepreterTest, test_messageHasNoDialogRequestIdKey) { EXPECT_CALL(*m_mockExceptionEncounteredSender, sendExceptionEncountered(_, _, _)).Times(0); EXPECT_CALL(*m_mockDirectiveSequencer, onDirective(_)) .Times(1) @@ -286,7 +286,7 @@ TEST_F(MessageIntepreterTest, messageHasNoDialogRequestIdKey) { * Test when the message doesn't contain the payload key in JSON content. The AVSDirective shouldn't be created and * and passed to directive sequencer. ExceptionEncounteredEvent should be sent to AVS. */ -TEST_F(MessageIntepreterTest, messageHasNoPayloadKey) { +TEST_F(MessageIntepreterTest, test_messageHasNoPayloadKey) { EXPECT_CALL(*m_mockExceptionEncounteredSender, sendExceptionEncountered(_, _, _)).Times(1); EXPECT_CALL(*m_mockDirectiveSequencer, onDirective(_)).Times(0); m_messageInterpreter->receive(TEST_ATTACHMENT_CONTEXT_ID, DIRECTIVE_NO_PAYLOAD); @@ -296,7 +296,7 @@ TEST_F(MessageIntepreterTest, messageHasNoPayloadKey) { * Test when the message contains an invalid payload key in JSON content. The AVSDirective shouldn't be created and * and passed to directive sequencer. ExceptionEncounteredEvent should be sent to AVS. */ -TEST_F(MessageIntepreterTest, messageHasInvalidPayloadKey) { +TEST_F(MessageIntepreterTest, test_messageHasInvalidPayloadKey) { EXPECT_CALL(*m_mockExceptionEncounteredSender, sendExceptionEncountered(_, _, _)).Times(1); EXPECT_CALL(*m_mockDirectiveSequencer, onDirective(_)).Times(0); m_messageInterpreter->receive(TEST_ATTACHMENT_CONTEXT_ID, DIRECTIVE_INVALID_PAYLOAD_KEY); @@ -306,7 +306,7 @@ TEST_F(MessageIntepreterTest, messageHasInvalidPayloadKey) { * Test when the message is valid JSON content with all keys required in the header. An AVSDirective should be created * and passed to the directive sequencer. */ -TEST_F(MessageIntepreterTest, messageIsValidDirective) { +TEST_F(MessageIntepreterTest, test_messageIsValidDirective) { EXPECT_CALL(*m_mockExceptionEncounteredSender, sendExceptionEncountered(_, _, _)).Times(0); EXPECT_CALL(*m_mockDirectiveSequencer, onDirective(_)) .Times(1) diff --git a/AFML/include/AFML/FocusManager.h b/AFML/include/AFML/FocusManager.h index 6efe787bbb..4d0cdbfee0 100644 --- a/AFML/include/AFML/FocusManager.h +++ b/AFML/include/AFML/FocusManager.h @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ #ifndef ALEXA_CLIENT_SDK_AFML_INCLUDE_AFML_FOCUSMANAGER_H_ #define ALEXA_CLIENT_SDK_AFML_INCLUDE_AFML_FOCUSMANAGER_H_ +#include #include #include #include @@ -108,6 +109,8 @@ class FocusManager : public avsCommon::sdkInterfaces::FocusManagerInterface { void stopForegroundActivity() override; + void stopAllActivities() override; + void addObserver(const std::shared_ptr& observer) override; void removeObserver( @@ -128,6 +131,8 @@ class FocusManager : public avsCommon::sdkInterfaces::FocusManagerInterface { static const std::vector getDefaultVisualChannels(); private: + /// A Map for mapping a @c Channel to its owner. + using ChannelsToInterfaceNamesMap = std::map, std::string>; /** * Functor so that we can compare Channel objects via shared_ptr. */ @@ -193,6 +198,17 @@ class FocusManager : public avsCommon::sdkInterfaces::FocusManagerInterface { std::shared_ptr foregroundChannel, std::string foregroundChannelInterface); + /** + * Stops all channels specified in @c channelsOwnersMap. + * A channel will get stopped if it's currently owned by the interface mapped to the channel + * in @c channelsOwnersMap. + * This function provides the full implementation which the public method will + * call. + * + * @param channelsOwnersMap Mapping of channel to owning interfaces + */ + void stopAllActivitiesHelper(const ChannelsToInterfaceNamesMap& channelsOwnersMap); + /** * Finds the channel from the given channel name. * diff --git a/AFML/src/FocusManager.cpp b/AFML/src/FocusManager.cpp index e633e7f97c..4b42532760 100644 --- a/AFML/src/FocusManager.cpp +++ b/AFML/src/FocusManager.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -108,6 +108,26 @@ void FocusManager::stopForegroundActivity() { }); } +void FocusManager::stopAllActivities() { + ACSDK_DEBUG5(LX(__func__)); + + if (m_activeChannels.empty()) { + ACSDK_DEBUG5(LX(__func__).m("no active channels")); + return; + } + + ChannelsToInterfaceNamesMap channelOwnersCapture; + std::unique_lock lock(m_mutex); + + for (const auto& channel : m_activeChannels) { + channelOwnersCapture.insert(std::pair, std::string>(channel, channel->getInterface())); + } + + lock.unlock(); + + m_executor.submitToFront([this, channelOwnersCapture]() { stopAllActivitiesHelper(channelOwnersCapture); }); +} + void FocusManager::addObserver(const std::shared_ptr& observer) { std::lock_guard lock(m_mutex); m_observers.insert(observer); @@ -205,6 +225,35 @@ void FocusManager::stopForegroundActivityHelper( notifyActivityTracker(); } +void FocusManager::stopAllActivitiesHelper(const ChannelsToInterfaceNamesMap& channelsOwnersMap) { + ACSDK_DEBUG3(LX(__func__)); + + std::set> channelsToClear; + + std::unique_lock lock(m_mutex); + + for (const auto& channelAndInterface : channelsOwnersMap) { + if (channelAndInterface.first->getInterface() == channelAndInterface.second) { + m_activeChannels.erase(channelAndInterface.first); + channelsToClear.insert(channelAndInterface.first); + } else { + ACSDK_INFO(LX(__func__) + .d("reason", "channel has other ownership") + .d("channel", channelAndInterface.first->getName()) + .d("currentInterface", channelAndInterface.first->getInterface()) + .d("originalInterface", channelAndInterface.second)); + } + } + + lock.unlock(); + + for (const auto& channel : channelsToClear) { + setChannelFocus(channel, FocusState::NONE); + } + foregroundHighestPriorityActiveChannel(); + notifyActivityTracker(); +} + std::shared_ptr FocusManager::getChannel(const std::string& channelName) const { auto search = m_allChannels.find(channelName); if (search != m_allChannels.end()) { @@ -238,7 +287,6 @@ bool FocusManager::doesChannelPriorityExist(const unsigned int priority) const { } void FocusManager::foregroundHighestPriorityActiveChannel() { - // Lock here to update internal state which stopForegroundActivity may concurrently access. std::unique_lock lock(m_mutex); std::shared_ptr channelToForeground = getHighestPriorityActiveChannelLocked(); lock.unlock(); @@ -258,7 +306,7 @@ void FocusManager::notifyActivityTracker() { const std::vector FocusManager::getDefaultAudioChannels() { static const std::vector defaultAudioChannels = { {FocusManagerInterface::DIALOG_CHANNEL_NAME, FocusManagerInterface::DIALOG_CHANNEL_PRIORITY}, - {FocusManagerInterface::ALERTS_CHANNEL_NAME, FocusManagerInterface::ALERTS_CHANNEL_PRIORITY}, + {FocusManagerInterface::ALERT_CHANNEL_NAME, FocusManagerInterface::ALERT_CHANNEL_PRIORITY}, {FocusManagerInterface::COMMUNICATIONS_CHANNEL_NAME, FocusManagerInterface::COMMUNICATIONS_CHANNEL_PRIORITY}, {FocusManagerInterface::CONTENT_CHANNEL_NAME, FocusManagerInterface::CONTENT_CHANNEL_PRIORITY}}; diff --git a/AFML/test/AudioActivityTrackerTest.cpp b/AFML/test/AudioActivityTrackerTest.cpp index f3aa38e6ca..523285a0c4 100644 --- a/AFML/test/AudioActivityTrackerTest.cpp +++ b/AFML/test/AudioActivityTrackerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -216,7 +216,7 @@ SetStateResult AudioActivityTrackerTest::wakeOnSetState() { } /// Test if there's no activity updates, AudioActivityTracker will return an empty context. -TEST_F(AudioActivityTrackerTest, noActivityUpdate) { +TEST_F(AudioActivityTrackerTest, test_noActivityUpdate) { EXPECT_CALL( *(m_mockContextManager.get()), setState(NAMESPACE_AND_NAME_STATE, "", StateRefreshPolicy::SOMETIMES, PROVIDE_STATE_TOKEN_TEST)) @@ -228,7 +228,7 @@ TEST_F(AudioActivityTrackerTest, noActivityUpdate) { } /// Test if there's an empty set of activity updates, AudioActivityTracker will return an empty context. -TEST_F(AudioActivityTrackerTest, emptyActivityUpdate) { +TEST_F(AudioActivityTrackerTest, test_emptyActivityUpdate) { const std::vector channels; EXPECT_CALL( *(m_mockContextManager.get()), @@ -242,7 +242,7 @@ TEST_F(AudioActivityTrackerTest, emptyActivityUpdate) { } /// Test if there's an activityUpdate for one active channel, context will be reported correctly. -TEST_F(AudioActivityTrackerTest, oneActiveChannel) { +TEST_F(AudioActivityTrackerTest, test_oneActiveChannel) { std::vector channels; m_dialogChannel->setFocus(FocusState::FOREGROUND); channels.push_back(m_dialogChannel->getState()); @@ -253,7 +253,7 @@ TEST_F(AudioActivityTrackerTest, oneActiveChannel) { * Test if there's an activityUpdate for one Dialog channel with "SpeechRecognizer" as an interface, * AudioActivityTracker will ignore it and report empty context. */ -TEST_F(AudioActivityTrackerTest, oneActiveChannelWithAIPAsInterface) { +TEST_F(AudioActivityTrackerTest, test_oneActiveChannelWithAIPAsInterface) { std::vector channels; m_dialogChannel->setInterface(AIP_INTERFACE_NAME); m_dialogChannel->setFocus(FocusState::FOREGROUND); @@ -275,7 +275,7 @@ TEST_F(AudioActivityTrackerTest, oneActiveChannelWithAIPAsInterface) { * interface, AudioActivityTracker will ignore the "SpeechRecognizer" interface going active but report * "SpeechSynthesizer" with idleTime not equal to zero. */ -TEST_F(AudioActivityTrackerTest, oneActiveChannelWithDefaultAndAIPAsInterfaces) { +TEST_F(AudioActivityTrackerTest, test_oneActiveChannelWithDefaultAndAIPAsInterfaces) { std::vector channels; m_dialogChannel->setFocus(FocusState::FOREGROUND); channels.push_back(m_dialogChannel->getState()); @@ -283,7 +283,7 @@ TEST_F(AudioActivityTrackerTest, oneActiveChannelWithDefaultAndAIPAsInterfaces) } /// Test if there's an activityUpdate for two active channels, context will be reported correctly. -TEST_F(AudioActivityTrackerTest, twoActiveChannels) { +TEST_F(AudioActivityTrackerTest, test_twoActiveChannels) { std::vector channels; m_dialogChannel->setFocus(FocusState::FOREGROUND); m_contentChannel->setFocus(FocusState::BACKGROUND); @@ -293,7 +293,7 @@ TEST_F(AudioActivityTrackerTest, twoActiveChannels) { } /// Test if there's an activityUpdate for one active and one idle channels, context will be reported correctly. -TEST_F(AudioActivityTrackerTest, oneActiveOneIdleChannels) { +TEST_F(AudioActivityTrackerTest, test_oneActiveOneIdleChannels) { std::vector channels; m_dialogChannel->setFocus(FocusState::FOREGROUND); m_contentChannel->setFocus(FocusState::BACKGROUND); diff --git a/AFML/test/FocusManagerTest.cpp b/AFML/test/FocusManagerTest.cpp index 215e18e1bf..6798968a62 100644 --- a/AFML/test/FocusManagerTest.cpp +++ b/AFML/test/FocusManagerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -275,12 +275,12 @@ class FocusManagerTest }; /// Tests acquireChannel with an invalid Channel name, expecting no focus changes to be made. -TEST_F(FocusManagerTest, acquireInvalidChannelName) { +TEST_F(FocusManagerTest, test_acquireInvalidChannelName) { ASSERT_FALSE(m_focusManager->acquireChannel(INCORRECT_CHANNEL_NAME, dialogClient, DIALOG_INTERFACE_NAME)); } /// Tests acquireChannel, expecting to get Foreground status since no other Channels are active. -TEST_F(FocusManagerTest, acquireChannelWithNoOtherChannelsActive) { +TEST_F(FocusManagerTest, test_acquireChannelWithNoOtherChannelsActive) { ASSERT_TRUE(m_focusManager->acquireChannel(DIALOG_CHANNEL_NAME, dialogClient, DIALOG_INTERFACE_NAME)); assertFocusChange(dialogClient, FocusState::FOREGROUND); } @@ -289,7 +289,7 @@ TEST_F(FocusManagerTest, acquireChannelWithNoOtherChannelsActive) { * Tests acquireChannel with two Channels. The lower priority Channel should get Background focus and the higher * priority Channel should get Foreground focus. */ -TEST_F(FocusManagerTest, acquireLowerPriorityChannelWithOneHigherPriorityChannelTaken) { +TEST_F(FocusManagerTest, test_acquireLowerPriorityChannelWithOneHigherPriorityChannelTaken) { ASSERT_TRUE(m_focusManager->acquireChannel(DIALOG_CHANNEL_NAME, dialogClient, DIALOG_INTERFACE_NAME)); ASSERT_TRUE(m_focusManager->acquireChannel(ALERTS_CHANNEL_NAME, alertsClient, ALERTS_INTERFACE_NAME)); assertFocusChange(dialogClient, FocusState::FOREGROUND); @@ -300,7 +300,7 @@ TEST_F(FocusManagerTest, acquireLowerPriorityChannelWithOneHigherPriorityChannel * Tests acquireChannel with three Channels. The two lowest priority Channels should get Background focus while the * highest priority Channel should be Foreground focused. */ -TEST_F(FocusManagerTest, aquireLowerPriorityChannelWithTwoHigherPriorityChannelsTaken) { +TEST_F(FocusManagerTest, test_aquireLowerPriorityChannelWithTwoHigherPriorityChannelsTaken) { ASSERT_TRUE(m_focusManager->acquireChannel(DIALOG_CHANNEL_NAME, dialogClient, DIALOG_INTERFACE_NAME)); ASSERT_TRUE(m_focusManager->acquireChannel(ALERTS_CHANNEL_NAME, alertsClient, ALERTS_INTERFACE_NAME)); ASSERT_TRUE(m_focusManager->acquireChannel(CONTENT_CHANNEL_NAME, contentClient, CONTENT_INTERFACE_NAME)); @@ -314,7 +314,7 @@ TEST_F(FocusManagerTest, aquireLowerPriorityChannelWithTwoHigherPriorityChannels * Channel should at first be Foreground focused and then get a change to Background focus while the higher priority * should be Foreground focused. */ -TEST_F(FocusManagerTest, acquireHigherPriorityChannelWithOneLowerPriorityChannelTaken) { +TEST_F(FocusManagerTest, test_acquireHigherPriorityChannelWithOneLowerPriorityChannelTaken) { ASSERT_TRUE(m_focusManager->acquireChannel(CONTENT_CHANNEL_NAME, contentClient, CONTENT_INTERFACE_NAME)); assertFocusChange(contentClient, FocusState::FOREGROUND); @@ -327,7 +327,7 @@ TEST_F(FocusManagerTest, acquireHigherPriorityChannelWithOneLowerPriorityChannel * Tests acquireChannel with a single Channel. The original observer should be notified to stop and the new observer * should obtain Foreground focus. */ -TEST_F(FocusManagerTest, kickOutActivityOnSameChannel) { +TEST_F(FocusManagerTest, test_kickOutActivityOnSameChannel) { ASSERT_TRUE(m_focusManager->acquireChannel(DIALOG_CHANNEL_NAME, dialogClient, DIALOG_INTERFACE_NAME)); assertFocusChange(dialogClient, FocusState::FOREGROUND); @@ -340,7 +340,7 @@ TEST_F(FocusManagerTest, kickOutActivityOnSameChannel) { /** * Tests releaseChannel with a single Channel. The observer should be notified to stop. */ -TEST_F(FocusManagerTest, simpleReleaseChannel) { +TEST_F(FocusManagerTest, test_simpleReleaseChannel) { ASSERT_TRUE(m_focusManager->acquireChannel(DIALOG_CHANNEL_NAME, dialogClient, DIALOG_INTERFACE_NAME)); assertFocusChange(dialogClient, FocusState::FOREGROUND); @@ -351,7 +351,7 @@ TEST_F(FocusManagerTest, simpleReleaseChannel) { /** * Tests releaseChannel on a Channel with an incorrect observer. The client should not receive any callback. */ -TEST_F(FocusManagerTest, simpleReleaseChannelWithIncorrectObserver) { +TEST_F(FocusManagerTest, test_simpleReleaseChannelWithIncorrectObserver) { ASSERT_TRUE(m_focusManager->acquireChannel(DIALOG_CHANNEL_NAME, dialogClient, DIALOG_INTERFACE_NAME)); assertFocusChange(dialogClient, FocusState::FOREGROUND); @@ -367,7 +367,7 @@ TEST_F(FocusManagerTest, simpleReleaseChannelWithIncorrectObserver) { * focused Channel should be notified to come to the Foreground while the originally Foreground focused Channel should * be notified to stop. */ -TEST_F(FocusManagerTest, releaseForegroundChannelWhileBackgroundChannelTaken) { +TEST_F(FocusManagerTest, test_releaseForegroundChannelWhileBackgroundChannelTaken) { ASSERT_TRUE(m_focusManager->acquireChannel(DIALOG_CHANNEL_NAME, dialogClient, DIALOG_INTERFACE_NAME)); assertFocusChange(dialogClient, FocusState::FOREGROUND); @@ -382,7 +382,7 @@ TEST_F(FocusManagerTest, releaseForegroundChannelWhileBackgroundChannelTaken) { /** * Tests stopForegroundActivity with a single Channel. The observer should be notified to stop. */ -TEST_F(FocusManagerTest, simpleNonTargetedStop) { +TEST_F(FocusManagerTest, test_simpleNonTargetedStop) { ASSERT_TRUE(m_focusManager->acquireChannel(DIALOG_CHANNEL_NAME, dialogClient, DIALOG_INTERFACE_NAME)); assertFocusChange(dialogClient, FocusState::FOREGROUND); @@ -394,7 +394,7 @@ TEST_F(FocusManagerTest, simpleNonTargetedStop) { * Tests stopForegroundActivity with a three active Channels. The Foreground Channel observer should be notified to * stop each time and the next highest priority background Channel should be brought to the foreground each time. */ -TEST_F(FocusManagerTest, threeNonTargetedStopsWithThreeActivitiesHappening) { +TEST_F(FocusManagerTest, test_threeNonTargetedStopsWithThreeActivitiesHappening) { ASSERT_TRUE(m_focusManager->acquireChannel(DIALOG_CHANNEL_NAME, dialogClient, DIALOG_INTERFACE_NAME)); assertFocusChange(dialogClient, FocusState::FOREGROUND); @@ -420,7 +420,7 @@ TEST_F(FocusManagerTest, threeNonTargetedStopsWithThreeActivitiesHappening) { * Tests stopForegroundActivity with a single Channel. The next client to request a different Channel should be given * foreground focus. */ -TEST_F(FocusManagerTest, stopForegroundActivityAndAcquireDifferentChannel) { +TEST_F(FocusManagerTest, test_stopForegroundActivityAndAcquireDifferentChannel) { ASSERT_TRUE(m_focusManager->acquireChannel(DIALOG_CHANNEL_NAME, dialogClient, DIALOG_INTERFACE_NAME)); assertFocusChange(dialogClient, FocusState::FOREGROUND); @@ -435,7 +435,7 @@ TEST_F(FocusManagerTest, stopForegroundActivityAndAcquireDifferentChannel) { * Tests stopForegroundActivity with a single Channel. The next client to request the same Channel should be given * foreground focus. */ -TEST_F(FocusManagerTest, stopForegroundActivityAndAcquireSameChannel) { +TEST_F(FocusManagerTest, test_stopForegroundActivityAndAcquireSameChannel) { ASSERT_TRUE(m_focusManager->acquireChannel(DIALOG_CHANNEL_NAME, dialogClient, DIALOG_INTERFACE_NAME)); assertFocusChange(dialogClient, FocusState::FOREGROUND); @@ -446,11 +446,53 @@ TEST_F(FocusManagerTest, stopForegroundActivityAndAcquireSameChannel) { assertFocusChange(dialogClient, FocusState::FOREGROUND); } +/** + * Test stopAllActivities with a single channel. + * Expect focus change only on that channel and reacquiring the same channel should resulted in foreground focus. + */ +TEST_F(FocusManagerTest, test_stopAllActivitiesWithSingleChannel) { + ASSERT_TRUE(m_focusManager->acquireChannel(DIALOG_CHANNEL_NAME, dialogClient, DIALOG_INTERFACE_NAME)); + assertFocusChange(dialogClient, FocusState::FOREGROUND); + + m_focusManager->stopAllActivities(); + assertFocusChange(dialogClient, FocusState::NONE); + + assertNoFocusChange(contentClient); + assertNoFocusChange(alertsClient); + + ASSERT_TRUE(m_focusManager->acquireChannel(DIALOG_CHANNEL_NAME, dialogClient, DIALOG_INTERFACE_NAME)); + assertFocusChange(dialogClient, FocusState::FOREGROUND); +} + +/** + * Test stopAllActivities with three channels. + * Expect focus change to none for all channels and a channel should resulted in foreground focus. + */ +TEST_F(FocusManagerTest, test_stopAllActivitiesWithThreeChannels) { + ASSERT_TRUE(m_focusManager->acquireChannel(DIALOG_CHANNEL_NAME, dialogClient, DIALOG_INTERFACE_NAME)); + assertFocusChange(dialogClient, FocusState::FOREGROUND); + + ASSERT_TRUE(m_focusManager->acquireChannel(CONTENT_CHANNEL_NAME, contentClient, CONTENT_INTERFACE_NAME)); + assertFocusChange(contentClient, FocusState::BACKGROUND); + + ASSERT_TRUE(m_focusManager->acquireChannel(ALERTS_CHANNEL_NAME, alertsClient, ALERTS_INTERFACE_NAME)); + assertFocusChange(alertsClient, FocusState::BACKGROUND); + + m_focusManager->stopAllActivities(); + + assertFocusChange(dialogClient, FocusState::NONE); + assertFocusChange(contentClient, FocusState::NONE); + assertFocusChange(alertsClient, FocusState::NONE); + + ASSERT_TRUE(m_focusManager->acquireChannel(DIALOG_CHANNEL_NAME, dialogClient, DIALOG_INTERFACE_NAME)); + assertFocusChange(dialogClient, FocusState::FOREGROUND); +} + /** * Tests releaseChannel with the background Channel while there is a foreground Channel. The foreground Channel * should remain foregrounded while the background Channel's observer should be notified to stop. */ -TEST_F(FocusManagerTest, releaseBackgroundChannelWhileTwoChannelsTaken) { +TEST_F(FocusManagerTest, test_releaseBackgroundChannelWhileTwoChannelsTaken) { ASSERT_TRUE(m_focusManager->acquireChannel(DIALOG_CHANNEL_NAME, dialogClient, DIALOG_INTERFACE_NAME)); assertFocusChange(dialogClient, FocusState::FOREGROUND); @@ -468,7 +510,7 @@ TEST_F(FocusManagerTest, releaseBackgroundChannelWhileTwoChannelsTaken) { * observer of the foreground be notified to stop and the new observer of the Channel will be notified that it has * Foreground focus. The originally backgrounded Channel should not change focus. */ -TEST_F(FocusManagerTest, kickOutActivityOnSameChannelWhileOtherChannelsActive) { +TEST_F(FocusManagerTest, test_kickOutActivityOnSameChannelWhileOtherChannelsActive) { ASSERT_TRUE(m_focusManager->acquireChannel(DIALOG_CHANNEL_NAME, dialogClient, DIALOG_INTERFACE_NAME)); assertFocusChange(dialogClient, FocusState::FOREGROUND); @@ -484,7 +526,7 @@ TEST_F(FocusManagerTest, kickOutActivityOnSameChannelWhileOtherChannelsActive) { } /// Tests that multiple observers can be added, and that they are notified of all focus changes. -TEST_F(FocusManagerTest, addObserver) { +TEST_F(FocusManagerTest, test_addObserver) { // These are all the observers that will be added. std::vector> observers; observers.push_back(std::make_shared()); @@ -524,7 +566,7 @@ TEST_F(FocusManagerTest, addObserver) { } /// Tests that observers can be removed, and that they are no longer notified of focus changes after removal. -TEST_F(FocusManagerTest, removeObserver) { +TEST_F(FocusManagerTest, test_removeObserver) { // These are all the observers that will ever be added. std::vector> allObservers; @@ -582,7 +624,7 @@ TEST_F(FocusManagerTest, removeObserver) { /** * Tests activityTracker with three Channels and make sure notifyOfActivityUpdates() is called correctly. */ -TEST_F(FocusManagerTest, activityTracker) { +TEST_F(FocusManagerTest, test_activityTracker) { // Acquire Content channel and expect notifyOfActivityUpdates() to notify activities on the Content channel. const std::vector test1 = { {CONTENT_CHANNEL_NAME, CONTENT_INTERFACE_NAME, FocusState::FOREGROUND}}; @@ -657,17 +699,17 @@ class ChannelTest }; /// Tests that the getName method of Channel works properly. -TEST_F(ChannelTest, getName) { +TEST_F(ChannelTest, test_getName) { ASSERT_EQ(testChannel->getName(), DIALOG_CHANNEL_NAME); } /// Tests that the getPriority method of Channel works properly. -TEST_F(ChannelTest, getPriority) { +TEST_F(ChannelTest, test_getPriority) { ASSERT_EQ(testChannel->getPriority(), DIALOG_CHANNEL_PRIORITY); } /// Tests that the observer properly gets notified of focus changes. -TEST_F(ChannelTest, setObserverThenSetFocus) { +TEST_F(ChannelTest, test_setObserverThenSetFocus) { testChannel->setObserver(clientA); ASSERT_TRUE(testChannel->setFocus(FocusState::FOREGROUND)); @@ -683,7 +725,7 @@ TEST_F(ChannelTest, setObserverThenSetFocus) { } /// Tests that Channels are compared properly -TEST_F(ChannelTest, priorityComparison) { +TEST_F(ChannelTest, test_priorityComparison) { std::shared_ptr lowerPriorityChannel = std::make_shared(CONTENT_CHANNEL_NAME, CONTENT_CHANNEL_PRIORITY); ASSERT_TRUE(*testChannel > *lowerPriorityChannel); @@ -691,7 +733,7 @@ TEST_F(ChannelTest, priorityComparison) { } /// Tests that a Channel correctly reports whether it has an observer. -TEST_F(ChannelTest, hasObserver) { +TEST_F(ChannelTest, test_hasObserver) { ASSERT_FALSE(testChannel->hasObserver()); testChannel->setObserver(clientA); ASSERT_TRUE(testChannel->hasObserver()); @@ -705,7 +747,7 @@ TEST_F(ChannelTest, hasObserver) { * Tests that the timeAtIdle only gets updated when channel goes to idle and not when channel goes to Foreground or * Background. */ -TEST_F(ChannelTest, getTimeAtIdle) { +TEST_F(ChannelTest, test_getTimeAtIdle) { auto startTime = testChannel->getState().timeAtIdle; ASSERT_TRUE(testChannel->setFocus(FocusState::FOREGROUND)); auto afterForegroundTime = testChannel->getState().timeAtIdle; diff --git a/AFML/test/VisualActivityTrackerTest.cpp b/AFML/test/VisualActivityTrackerTest.cpp index f768c231d4..e9780ec66b 100644 --- a/AFML/test/VisualActivityTrackerTest.cpp +++ b/AFML/test/VisualActivityTrackerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -206,7 +206,7 @@ SetStateResult VisualActivityTrackerTest::wakeOnSetState() { } /// Test if there's no activity updates, VisualActivityTracker will return an empty context. -TEST_F(VisualActivityTrackerTest, noActivityUpdate) { +TEST_F(VisualActivityTrackerTest, test_noActivityUpdate) { EXPECT_CALL( *(m_mockContextManager.get()), setState(NAMESPACE_AND_NAME_STATE, "", StateRefreshPolicy::SOMETIMES, PROVIDE_STATE_TOKEN_TEST)) @@ -218,13 +218,13 @@ TEST_F(VisualActivityTrackerTest, noActivityUpdate) { } /// Test if there's an empty vector of activity updates, VisualActivityTracker will return an empty context. -TEST_F(VisualActivityTrackerTest, emptyActivityUpdate) { +TEST_F(VisualActivityTrackerTest, test_emptyActivityUpdate) { std::vector channels; provideUpdate(channels); } /// Test if there's an activityUpdate for one idle channel, VisualActivityTracker will return an empty context. -TEST_F(VisualActivityTrackerTest, oneIdleChannel) { +TEST_F(VisualActivityTrackerTest, test_oneIdleChannel) { std::vector channels; m_visualChannel->setFocus(FocusState::NONE); channels.push_back(m_visualChannel->getState()); @@ -232,7 +232,7 @@ TEST_F(VisualActivityTrackerTest, oneIdleChannel) { } /// Test if there's an activityUpdate for one active channel, context will be reported correctly. -TEST_F(VisualActivityTrackerTest, oneActiveChannel) { +TEST_F(VisualActivityTrackerTest, test_oneActiveChannel) { std::vector channels; m_visualChannel->setFocus(FocusState::FOREGROUND); channels.push_back(m_visualChannel->getState()); @@ -243,7 +243,7 @@ TEST_F(VisualActivityTrackerTest, oneActiveChannel) { * Test if there's an vector of activity updates with one valid and one invalid channel, VisualActivityTracker will * return an empty context. */ -TEST_F(VisualActivityTrackerTest, invalidChannelActivityUpdate) { +TEST_F(VisualActivityTrackerTest, test_invalidChannelActivityUpdate) { std::vector channels; auto invalidChannel = std::make_shared(INVALID_CHANNEL_NAME, INVALID_CHANNEL_PRIORITY); m_visualChannel->setFocus(FocusState::FOREGROUND); @@ -256,7 +256,7 @@ TEST_F(VisualActivityTrackerTest, invalidChannelActivityUpdate) { * Test if there's an vector of activity updates with one valid channel, VisualActivityTracker take the state from the * last element of the vector. */ -TEST_F(VisualActivityTrackerTest, validChannelTwoActivityUpdates) { +TEST_F(VisualActivityTrackerTest, test_validChannelTwoActivityUpdates) { std::vector channels; m_visualChannel->setFocus(FocusState::FOREGROUND); channels.push_back(m_visualChannel->getState()); diff --git a/AVSCommon/AVS/include/AVSCommon/AVS/MessageRequest.h b/AVSCommon/AVS/include/AVSCommon/AVS/MessageRequest.h index a96ede725e..d6dbd0ccb1 100644 --- a/AVSCommon/AVS/include/AVSCommon/AVS/MessageRequest.h +++ b/AVSCommon/AVS/include/AVSCommon/AVS/MessageRequest.h @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -138,14 +138,6 @@ class MessageRequest { */ void removeObserver(std::shared_ptr observer); - /** - * A function to evaluate if the given status reflects receipt of the message by the server. - * - * @param status The status being queried. - * @return Whether the status reflects receipt of the message by the server. - */ - static bool isServerStatus(sdkInterfaces::MessageRequestObserverInterface::Status status); - protected: /// Mutex to guard access of m_observers. std::mutex m_observerMutex; diff --git a/AVSCommon/AVS/include/AVSCommon/AVS/SpeakerConstants/SpeakerConstants.h b/AVSCommon/AVS/include/AVSCommon/AVS/SpeakerConstants/SpeakerConstants.h index b6f1f08ec9..01c792b877 100644 --- a/AVSCommon/AVS/include/AVSCommon/AVS/SpeakerConstants/SpeakerConstants.h +++ b/AVSCommon/AVS/include/AVSCommon/AVS/SpeakerConstants/SpeakerConstants.h @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -38,9 +38,12 @@ const int8_t AVS_ADJUST_VOLUME_MIN = -100; /// AVS adjustVolume Maximum. const int8_t AVS_ADJUST_VOLUME_MAX = 100; +/// Default unmute volume level. +const int8_t MIN_UNMUTE_VOLUME = 10; + } // namespace speakerConstants } // namespace avs } // namespace avsCommon } // namespace alexaClientSDK -#endif // ALEXA_CLIENT_SDK_AVSCOMMON_AVS_INCLUDE_AVSCOMMON_AVS_SPEAKERCONSTANTS_SPEAKERCONSTANTS_H_ +#endif // ALEXA_CLIENT_SDK_AVSCOMMON_AVS_INCLUDE_AVSCOMMON_AVS_SPEAKERCONSTANTS_SPEAKERCONSTANTS_H_ \ No newline at end of file diff --git a/AVSCommon/AVS/src/BlockingPolicy.cpp b/AVSCommon/AVS/src/BlockingPolicy.cpp index e86209c900..a82b2713cd 100644 --- a/AVSCommon/AVS/src/BlockingPolicy.cpp +++ b/AVSCommon/AVS/src/BlockingPolicy.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -30,10 +30,10 @@ using namespace avsCommon::avs; using namespace avsCommon::utils::json; /// Flag indicating @c AUDIO medium is used. -static const BlockingPolicy::Mediums MEDIUM_FLAG_AUDIO{1}; +static const long MEDIUM_FLAG_AUDIO = 1; /// Flag indicating @c VISUAL medium is used. -static const BlockingPolicy::Mediums MEDIUM_FLAG_VISUAL{2}; +static const long MEDIUM_FLAG_VISUAL = 2; /// String to identify log entries originating from this file. static const std::string TAG("BlockingPolicy"); diff --git a/AVSCommon/AVS/src/MessageRequest.cpp b/AVSCommon/AVS/src/MessageRequest.cpp index 61cb73c25b..1d58b4537e 100644 --- a/AVSCommon/AVS/src/MessageRequest.cpp +++ b/AVSCommon/AVS/src/MessageRequest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -118,30 +118,6 @@ void MessageRequest::removeObserver( using namespace avsCommon::sdkInterfaces; -bool MessageRequest::isServerStatus(MessageRequestObserverInterface::Status status) { - switch (status) { - case MessageRequestObserverInterface::Status::SUCCESS: - case MessageRequestObserverInterface::Status::SUCCESS_NO_CONTENT: - case MessageRequestObserverInterface::Status::SERVER_INTERNAL_ERROR_V2: - case MessageRequestObserverInterface::Status::CANCELED: - case MessageRequestObserverInterface::Status::THROTTLED: - case MessageRequestObserverInterface::Status::BAD_REQUEST: - case MessageRequestObserverInterface::Status::SERVER_OTHER_ERROR: - return true; - case MessageRequestObserverInterface::Status::PENDING: - case MessageRequestObserverInterface::Status::NOT_CONNECTED: - case MessageRequestObserverInterface::Status::NOT_SYNCHRONIZED: - case MessageRequestObserverInterface::Status::TIMEDOUT: - case MessageRequestObserverInterface::Status::PROTOCOL_ERROR: - case MessageRequestObserverInterface::Status::INTERNAL_ERROR: - case MessageRequestObserverInterface::Status::REFUSED: - case MessageRequestObserverInterface::Status::INVALID_AUTH: - return false; - } - - return false; -} - } // namespace avs } // namespace avsCommon } // namespace alexaClientSDK diff --git a/AVSCommon/AVS/test/AlexaClientSDKInitTest.cpp b/AVSCommon/AVS/test/AlexaClientSDKInitTest.cpp index f38697bd27..964ab4d482 100644 --- a/AVSCommon/AVS/test/AlexaClientSDKInitTest.cpp +++ b/AVSCommon/AVS/test/AlexaClientSDKInitTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ using namespace std; * * @note This test also validates whether libcurl supports HTTP2. */ -TEST(AlexaClientSDKInitTest, initializeNoJSONConfig) { +TEST(AlexaClientSDKInitTest, test_initializeNoJSONConfig) { ASSERT_TRUE(AlexaClientSDKInit::initialize({})); AlexaClientSDKInit::uninitialize(); } @@ -43,7 +43,7 @@ TEST(AlexaClientSDKInitTest, initializeNoJSONConfig) { * * @note This test also validates whether libcurl supports HTTP2. */ -TEST(AlexaClientSDKInitTest, initializeInvalidJSONConfig) { +TEST(AlexaClientSDKInitTest, test_initializeInvalidJSONConfig) { auto invalidJSON = std::shared_ptr(new std::stringstream()); (*invalidJSON) << "{"; ASSERT_FALSE(AlexaClientSDKInit::initialize({invalidJSON})); @@ -54,7 +54,7 @@ TEST(AlexaClientSDKInitTest, initializeInvalidJSONConfig) { * * @note This test also validates whether libcurl supports HTTP2. */ -TEST(AlexaClientSDKInitTest, initializeValidJSONConfig) { +TEST(AlexaClientSDKInitTest, test_initializeValidJSONConfig) { auto validJSON = std::shared_ptr(new std::stringstream()); (*validJSON) << R"({"key":"value"})"; ASSERT_TRUE(AlexaClientSDKInit::initialize({validJSON})); @@ -64,14 +64,14 @@ TEST(AlexaClientSDKInitTest, initializeValidJSONConfig) { /** * Tests @c isInitialized when the SDK has not been initialized yet, expecting it to return @c false. */ -TEST(AlexaClientSDKInitTest, uninitializedIsInitialized) { +TEST(AlexaClientSDKInitTest, test_uninitializedIsInitialized) { ASSERT_FALSE(AlexaClientSDKInit::isInitialized()); } /** * Tests @c isInitialized when the SDK is initialized, expecting it to return @c true. */ -TEST(AlexaClientSDKInitTest, isInitialized) { +TEST(AlexaClientSDKInitTest, test_isInitialized) { ASSERT_TRUE(AlexaClientSDKInit::initialize({})); // Expect used to ensure we uninitialize. EXPECT_TRUE(AlexaClientSDKInit::isInitialized()); @@ -81,7 +81,7 @@ TEST(AlexaClientSDKInitTest, isInitialized) { /** * Tests @c uninitialize when the SDK has not been initialized yet, expecting no crashes or exceptions. */ -TEST(AlexaClientSDKInitTest, uninitialize) { +TEST(AlexaClientSDKInitTest, test_uninitialize) { AlexaClientSDKInit::uninitialize(); } diff --git a/AVSCommon/AVS/test/Attachment/AttachmentManagerV2Test.cpp b/AVSCommon/AVS/test/Attachment/AttachmentManagerV2Test.cpp index 3cab3e7920..375614165e 100644 --- a/AVSCommon/AVS/test/Attachment/AttachmentManagerV2Test.cpp +++ b/AVSCommon/AVS/test/Attachment/AttachmentManagerV2Test.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -118,7 +118,7 @@ void AttachmentManagerTest::testReaders(const ReaderVec& readers, bool expectedV /** * Test that the AttachmentManager's generate attachment id function works as expected. */ -TEST_F(AttachmentManagerTest, testAttachmentManagerGenerateAttachmentId) { +TEST_F(AttachmentManagerTest, test_attachmentManagerGenerateAttachmentId) { // Normal use cases. auto id1 = m_manager.generateAttachmentId(TEST_CONTEXT_ID_STRING, TEST_CONTENT_ID_STRING); auto id2 = m_manager.generateAttachmentId(TEST_CONTEXT_ID_STRING, TEST_CONTENT_ID_STRING); @@ -143,7 +143,7 @@ TEST_F(AttachmentManagerTest, testAttachmentManagerGenerateAttachmentId) { /** * Test that the AttachmentManager's set timeout function works as expected. */ -TEST_F(AttachmentManagerTest, testAttachmentManagerSetTimeout) { +TEST_F(AttachmentManagerTest, test_attachmentManagerSetTimeout) { ASSERT_TRUE(m_manager.setAttachmentTimeoutMinutes(TIMEOUT_REGULAR)); ASSERT_TRUE(m_manager.setAttachmentTimeoutMinutes(AttachmentManager::ATTACHMENT_MANAGER_TIMOUT_MINUTES_MINIMUM)); ASSERT_FALSE(m_manager.setAttachmentTimeoutMinutes(TIMEOUT_ZERO)); @@ -153,7 +153,7 @@ TEST_F(AttachmentManagerTest, testAttachmentManagerSetTimeout) { /** * Test that the AttachmentManager's create* functions work in this particular order. */ -TEST_F(AttachmentManagerTest, testAttachmentManagerCreateWriterThenReader) { +TEST_F(AttachmentManagerTest, test_attachmentManagerCreateWriterThenReader) { // Create the writer before the reader. auto writer = m_manager.createWriter(TEST_ATTACHMENT_ID_STRING_ONE); auto reader = m_manager.createReader(TEST_ATTACHMENT_ID_STRING_ONE, utils::sds::ReaderPolicy::BLOCKING); @@ -164,7 +164,7 @@ TEST_F(AttachmentManagerTest, testAttachmentManagerCreateWriterThenReader) { /** * Test that the AttachmentManager's create* functions work in this particular order. */ -TEST_F(AttachmentManagerTest, testAttachmentManagerCreateReaderThenWriter) { +TEST_F(AttachmentManagerTest, test_attachmentManagerCreateReaderThenWriter) { // Create the reader before the writer. auto reader = m_manager.createReader(TEST_ATTACHMENT_ID_STRING_ONE, utils::sds::ReaderPolicy::BLOCKING); auto writer = m_manager.createWriter(TEST_ATTACHMENT_ID_STRING_ONE); @@ -175,7 +175,7 @@ TEST_F(AttachmentManagerTest, testAttachmentManagerCreateReaderThenWriter) { /** * Test that the AttachmentManager's create reader function works as expected. */ -TEST_F(AttachmentManagerTest, testAttachmentManagerCreateReader) { +TEST_F(AttachmentManagerTest, test_attachmentManagerCreateReader) { // Create the reader. auto reader = m_manager.createReader(TEST_ATTACHMENT_ID_STRING_ONE, utils::sds::ReaderPolicy::BLOCKING); ASSERT_NE(reader, nullptr); @@ -184,7 +184,7 @@ TEST_F(AttachmentManagerTest, testAttachmentManagerCreateReader) { /** * Test that a reader created from an attachment that doesn't have a writer will wait for the writer. */ -TEST_F(AttachmentManagerTest, testAttachmentManagerReadAttachmentWithoutWriter) { +TEST_F(AttachmentManagerTest, test_attachmentManagerReadAttachmentWithoutWriter) { auto testPattern = createTestPattern(TEST_SDS_BUFFER_SIZE_IN_BYTES); std::vector result(testPattern.size()); @@ -219,7 +219,7 @@ TEST_F(AttachmentManagerTest, testAttachmentManagerReadAttachmentWithoutWriter) * Test that the AttachmentManager's cleanup logic works as expected, and that it does not impact readers and * writers that are returned before the cleanup. */ -TEST_F(AttachmentManagerTest, testAttachmentManagerTestCreateReadersThenWriters) { +TEST_F(AttachmentManagerTest, test_attachmentManagerTestCreateReadersThenWriters) { WriterVec writers; ReaderVec readers; @@ -234,7 +234,7 @@ TEST_F(AttachmentManagerTest, testAttachmentManagerTestCreateReadersThenWriters) * Test that the AttachmentManager's cleanup logic works as expected, and that it does not impact readers and * writers that are returned before the cleanup. */ -TEST_F(AttachmentManagerTest, testAttachmentManagerTestCreateWritersThenReaders) { +TEST_F(AttachmentManagerTest, test_attachmentManagerTestCreateWritersThenReaders) { WriterVec writers; ReaderVec readers; @@ -248,7 +248,7 @@ TEST_F(AttachmentManagerTest, testAttachmentManagerTestCreateWritersThenReaders) /** * Verify an AttachmentManager can't create multiple writers. */ -TEST_F(AttachmentManagerTest, testAttachmentManagerCreateMultipleWriters) { +TEST_F(AttachmentManagerTest, test_attachmentManagerCreateMultipleWriters) { auto writer1 = m_manager.createWriter(TEST_ATTACHMENT_ID_STRING_ONE); auto writer2 = m_manager.createWriter(TEST_ATTACHMENT_ID_STRING_ONE); ASSERT_NE(writer1, nullptr); @@ -258,7 +258,7 @@ TEST_F(AttachmentManagerTest, testAttachmentManagerCreateMultipleWriters) { /** * Verify an AttachmentManager can't create multiple readers. */ -TEST_F(AttachmentManagerTest, testAttachmentManagerCreateMultipleReaders) { +TEST_F(AttachmentManagerTest, test_attachmentManagerCreateMultipleReaders) { auto reader1 = m_manager.createReader(TEST_ATTACHMENT_ID_STRING_ONE, utils::sds::ReaderPolicy::BLOCKING); auto reader2 = m_manager.createReader(TEST_ATTACHMENT_ID_STRING_ONE, utils::sds::ReaderPolicy::BLOCKING); ASSERT_NE(reader1, nullptr); @@ -268,7 +268,7 @@ TEST_F(AttachmentManagerTest, testAttachmentManagerCreateMultipleReaders) { /** * Test a one-pass write and read with both Attachment wrapper classes. */ -TEST_F(AttachmentManagerTest, testAttachmentWriterAndReaderInOnePass) { +TEST_F(AttachmentManagerTest, test_attachmentWriterAndReaderInOnePass) { auto writer = m_manager.createWriter(TEST_ATTACHMENT_ID_STRING_ONE); auto reader = m_manager.createReader(TEST_ATTACHMENT_ID_STRING_ONE, utils::sds::ReaderPolicy::BLOCKING); ASSERT_NE(writer, nullptr); diff --git a/AVSCommon/AVS/test/Attachment/AttachmentReaderTest.cpp b/AVSCommon/AVS/test/Attachment/AttachmentReaderTest.cpp index 98e9752bdb..425ccccf91 100644 --- a/AVSCommon/AVS/test/Attachment/AttachmentReaderTest.cpp +++ b/AVSCommon/AVS/test/Attachment/AttachmentReaderTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -166,7 +166,7 @@ void AttachmentReaderTest::readAndVerifyResult( /** * Test reading an invalid SDS. */ -TEST_F(AttachmentReaderTest, testAttachmentReaderWithInvalidSDS) { +TEST_F(AttachmentReaderTest, test_attachmentReaderWithInvalidSDS) { auto reader = InProcessAttachmentReader::create(m_readerPolicy, nullptr); ASSERT_EQ(reader, nullptr); } @@ -174,7 +174,7 @@ TEST_F(AttachmentReaderTest, testAttachmentReaderWithInvalidSDS) { /** * Test reading an SDS with a bad seek position. */ -TEST_F(AttachmentReaderTest, testAttachmentReaderWithBadSeekPosition) { +TEST_F(AttachmentReaderTest, test_attachmentReaderWithBadSeekPosition) { auto reader = InProcessAttachmentReader::create(m_readerPolicy, m_sds, TEST_SDS_BAD_SEEK_POSITION); ASSERT_EQ(reader, nullptr); } @@ -182,7 +182,7 @@ TEST_F(AttachmentReaderTest, testAttachmentReaderWithBadSeekPosition) { /** * Test a one-pass write and read. */ -TEST_F(AttachmentReaderTest, testAttachmentReaderReadInOnePass) { +TEST_F(AttachmentReaderTest, test_attachmentReaderReadInOnePass) { init(); auto testPattern = createTestPattern(TEST_SDS_BUFFER_SIZE_IN_BYTES); @@ -195,7 +195,7 @@ TEST_F(AttachmentReaderTest, testAttachmentReaderReadInOnePass) { /** * Test a partial read. */ -TEST_F(AttachmentReaderTest, testAttachmentReaderPartialRead) { +TEST_F(AttachmentReaderTest, test_attachmentReaderPartialRead) { init(); auto numWritten = m_writer->write(m_testPattern.data(), m_testPattern.size()); @@ -207,7 +207,7 @@ TEST_F(AttachmentReaderTest, testAttachmentReaderPartialRead) { /** * Test a partial read with a seek. */ -TEST_F(AttachmentReaderTest, testAttachmentReaderPartialReadWithSeek) { +TEST_F(AttachmentReaderTest, test_attachmentReaderPartialReadWithSeek) { init(false); // test a single write & read. @@ -226,14 +226,14 @@ TEST_F(AttachmentReaderTest, testAttachmentReaderPartialReadWithSeek) { /** * Test multiple partial reads of complete data, where the writer closes. */ -TEST_F(AttachmentReaderTest, testAttachmentReaderMultipleReads) { +TEST_F(AttachmentReaderTest, test_attachmentReaderMultipleReads) { testMultipleReads(false); } /** * Test multiple partial reads of complete data, where the writer remains open. */ -TEST_F(AttachmentReaderTest, testAttachmentReaderMultipleReadsOfUnfinishedData) { +TEST_F(AttachmentReaderTest, test_attachmentReaderMultipleReadsOfUnfinishedData) { testMultipleReads(true); } @@ -241,7 +241,7 @@ TEST_F(AttachmentReaderTest, testAttachmentReaderMultipleReadsOfUnfinishedData) * Test that reading at much slower pace than writing causes reader to eventually receive * overrun error. */ -TEST_F(AttachmentReaderTest, testOverrunResultsInError) { +TEST_F(AttachmentReaderTest, test_overrunResultsInError) { m_writerPolicy = InProcessSDS::Writer::Policy::NONBLOCKABLE; init(); @@ -277,7 +277,7 @@ TEST_F(AttachmentReaderTest, testOverrunResultsInError) { * Test that reading at much slower pace than writing causes reader cursor position to be reset * to writer cursor position. */ -TEST_F(AttachmentReaderTest, testOverrunResultsInReaderReset) { +TEST_F(AttachmentReaderTest, test_overrunResultsInReaderReset) { m_writerPolicy = InProcessSDS::Writer::Policy::NONBLOCKABLE; init(true, true); diff --git a/AVSCommon/AVS/test/Attachment/AttachmentTest.cpp b/AVSCommon/AVS/test/Attachment/AttachmentTest.cpp index 052b412666..94178ed43c 100644 --- a/AVSCommon/AVS/test/Attachment/AttachmentTest.cpp +++ b/AVSCommon/AVS/test/Attachment/AttachmentTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -76,28 +76,28 @@ void AttachmentTest::testCreateReader(ReaderPolicy policy) { /** * Verify the ID is correctly stored and accessed from an Attachment. */ -TEST_F(AttachmentTest, testGetAttachmentId) { +TEST_F(AttachmentTest, test_getAttachmentId) { ASSERT_EQ(TEST_ATTACHMENT_ID_STRING_ONE, m_attachment->getId()); } /** * Verify that an Attachment can create a blocking reader in various scenarios. */ -TEST_F(AttachmentTest, testAttachmentCreateBlockingReader) { +TEST_F(AttachmentTest, test_attachmentCreateBlockingReader) { testCreateReader(ReaderPolicy::BLOCKING); } /** * Verify that an Attachment can create a non-blocking reader in various scenarios. */ -TEST_F(AttachmentTest, testAttachmentCreateNonBlockingReader) { +TEST_F(AttachmentTest, test_attachmentCreateNonBlockingReader) { testCreateReader(ReaderPolicy::NONBLOCKING); } /** * Verify that an Attachment can create a writer in various scenarios. */ -TEST_F(AttachmentTest, testAttachmentCreateWriter) { +TEST_F(AttachmentTest, test_attachmentCreateWriter) { // Test create writer where there is no reader. auto writer = m_attachment->createWriter(); ASSERT_NE(writer, nullptr); @@ -122,7 +122,7 @@ TEST_F(AttachmentTest, testAttachmentCreateWriter) { /** * Test creating an Attachment with an existing SDS. */ -TEST_F(AttachmentTest, testCreateAttachmentWithSDS) { +TEST_F(AttachmentTest, test_createAttachmentWithSDS) { auto sds = createSDS(TEST_SDS_BUFFER_SIZE_IN_BYTES); auto attachment = std::make_shared(TEST_ATTACHMENT_ID_STRING_ONE, std::move(sds)); @@ -139,7 +139,7 @@ TEST_F(AttachmentTest, testCreateAttachmentWithSDS) { /** * Verify an Attachment can't create multiple writers. */ -TEST_F(AttachmentTest, testAttachmentCreateMultipleWriters) { +TEST_F(AttachmentTest, test_attachmentCreateMultipleWriters) { auto writer1 = m_attachment->createWriter(); auto writer2 = m_attachment->createWriter(); ASSERT_NE(writer1, nullptr); diff --git a/AVSCommon/AVS/test/Attachment/AttachmentUtilsTest.cpp b/AVSCommon/AVS/test/Attachment/AttachmentUtilsTest.cpp index b4e74df51d..49dfac04f8 100644 --- a/AVSCommon/AVS/test/Attachment/AttachmentUtilsTest.cpp +++ b/AVSCommon/AVS/test/Attachment/AttachmentUtilsTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -50,7 +50,7 @@ void AttachmentUtilsTest::SetUp() { /** * Test read until end of buffer */ -TEST_F(AttachmentUtilsTest, testReadCompleteBuffer) { +TEST_F(AttachmentUtilsTest, test_readCompleteBuffer) { char dstBuffer[sampleBuffer.length() + 10]; memset(dstBuffer, 0, sampleBuffer.length() + 10); @@ -69,7 +69,7 @@ TEST_F(AttachmentUtilsTest, testReadCompleteBuffer) { /* * Test empty buffer */ -TEST_F(AttachmentUtilsTest, testEmptyBuffer) { +TEST_F(AttachmentUtilsTest, test_emptyBuffer) { std::vector emptySrcBuffer; auto emptyAttachmentReader = AttachmentUtils::createAttachmentReader(emptySrcBuffer); ASSERT_FALSE(emptyAttachmentReader); diff --git a/AVSCommon/AVS/test/Attachment/AttachmentWriterTest.cpp b/AVSCommon/AVS/test/Attachment/AttachmentWriterTest.cpp index 1102b4f9bc..77ca2f52b6 100644 --- a/AVSCommon/AVS/test/Attachment/AttachmentWriterTest.cpp +++ b/AVSCommon/AVS/test/Attachment/AttachmentWriterTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -117,7 +117,7 @@ void AttachmentWriterTest::testMultipleReads(bool closeWriterBeforeReading) { /** * Test writing to an invalid SDS. */ -TEST_F(AttachmentWriterTest, testAttachmentWriterWithInvalidSDS) { +TEST_F(AttachmentWriterTest, test_attachmentWriterWithInvalidSDS) { auto writer = InProcessAttachmentWriter::create(nullptr); ASSERT_EQ(writer, nullptr); } @@ -125,7 +125,7 @@ TEST_F(AttachmentWriterTest, testAttachmentWriterWithInvalidSDS) { /** * Test writing to a closed writer. */ -TEST_F(AttachmentWriterTest, testAttachmentWriterOnClosedWriter) { +TEST_F(AttachmentWriterTest, test_attachmentWriterOnClosedWriter) { init(); m_writer->close(); @@ -139,7 +139,7 @@ TEST_F(AttachmentWriterTest, testAttachmentWriterOnClosedWriter) { /** * Test writing a single pass of data. */ -TEST_F(AttachmentWriterTest, testAttachmentWriterWriteSinglePass) { +TEST_F(AttachmentWriterTest, test_attachmentWriterWriteSinglePass) { init(); AttachmentWriter::WriteStatus writeStatus = AttachmentWriter::WriteStatus::OK; @@ -151,7 +151,7 @@ TEST_F(AttachmentWriterTest, testAttachmentWriterWriteSinglePass) { /** * Test a one-pass write and read with both wrapper classes. */ -TEST_F(AttachmentWriterTest, testAttachmentWriterAndReadInOnePass) { +TEST_F(AttachmentWriterTest, test_attachmentWriterAndReadInOnePass) { init(); auto writeStatus = InProcessAttachmentWriter::WriteStatus::OK; @@ -173,14 +173,14 @@ TEST_F(AttachmentWriterTest, testAttachmentWriterAndReadInOnePass) { /** * Test multiple partial reads of complete data, where the writer is closed. */ -TEST_F(AttachmentWriterTest, testAttachmentReaderAndWriterMultipleReads) { +TEST_F(AttachmentWriterTest, test_attachmentReaderAndWriterMultipleReads) { testMultipleReads(true); } /** * Test multiple partial reads of complete data, where the writer remains open. */ -TEST_F(AttachmentWriterTest, testAttachmentWriterAndReaderMultipleReadsOfUnfinishedData) { +TEST_F(AttachmentWriterTest, test_attachmentWriterAndReaderMultipleReadsOfUnfinishedData) { testMultipleReads(false); } diff --git a/AVSCommon/AVS/test/BlockingPolicyTest.cpp b/AVSCommon/AVS/test/BlockingPolicyTest.cpp index 367504d559..378653133a 100644 --- a/AVSCommon/AVS/test/BlockingPolicyTest.cpp +++ b/AVSCommon/AVS/test/BlockingPolicyTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -29,14 +29,14 @@ using namespace avsCommon::avs; class BlockingPolicyTest : public ::testing::Test {}; // test defaultConstructor -TEST_F(BlockingPolicyTest, testDefaultConstructor) { +TEST_F(BlockingPolicyTest, test_defaultConstructor) { BlockingPolicy blockingPolicy; ASSERT_FALSE(blockingPolicy.isValid()); } /// Test isBlocking -TEST_F(BlockingPolicyTest, testisBlocking) { +TEST_F(BlockingPolicyTest, test_isBlocking) { BlockingPolicy blocking(BlockingPolicy::MEDIUM_VISUAL, true); BlockingPolicy nonBlocking(BlockingPolicy::MEDIUM_VISUAL, false); @@ -45,7 +45,7 @@ TEST_F(BlockingPolicyTest, testisBlocking) { } /// Test getMediums -TEST_F(BlockingPolicyTest, testgetMediums) { +TEST_F(BlockingPolicyTest, test_getMediums) { BlockingPolicy audio(BlockingPolicy::MEDIUM_AUDIO, false); BlockingPolicy visual(BlockingPolicy::MEDIUM_VISUAL, false); BlockingPolicy audioAndVisual(BlockingPolicy::MEDIUMS_AUDIO_AND_VISUAL, false); diff --git a/AVSCommon/AVS/test/CapabilityAgentTest.cpp b/AVSCommon/AVS/test/CapabilityAgentTest.cpp index 6e582e8fda..9b2b3b651a 100644 --- a/AVSCommon/AVS/test/CapabilityAgentTest.cpp +++ b/AVSCommon/AVS/test/CapabilityAgentTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -465,7 +465,7 @@ void CapabilityAgentTest::testBuildJsonEventString( * Call the @c handleDirectiveImmediately from the @c CapabilityAgent base class with a directive as the argument. * Expect the @c handleDirectiveImmediately with the argument of @c DirectiveAndResultInterface will be called. */ -TEST_F(CapabilityAgentTest, testCallToHandleImmediately) { +TEST_F(CapabilityAgentTest, test_callToHandleImmediately) { auto avsMessageHeader = std::make_shared( NAMESPACE_SPEECH_RECOGNIZER, NAME_STOP_CAPTURE, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); std::shared_ptr directive = @@ -479,7 +479,7 @@ TEST_F(CapabilityAgentTest, testCallToHandleImmediately) { * Call the @c preHandleDirective from the @c CapabilityAgent base class with a directive as the argument. * Expect the @c preHandleDirective with the argument of @c DirectiveAndResultInterface will be called. */ -TEST_F(CapabilityAgentTest, testCallToPrehandleDirective) { +TEST_F(CapabilityAgentTest, test_callToPrehandleDirective) { auto avsMessageHeader = std::make_shared( NAMESPACE_SPEECH_RECOGNIZER, NAME_STOP_CAPTURE, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); std::shared_ptr directive = @@ -494,7 +494,7 @@ TEST_F(CapabilityAgentTest, testCallToPrehandleDirective) { * Call the @c handleDirective from the @c CapabilityAgent base class with a directive as the argument. * Expect the @c handleDirective with the argument of @c DirectiveAndResultInterface will be called. */ -TEST_F(CapabilityAgentTest, testCallToHandleDirective) { +TEST_F(CapabilityAgentTest, test_callToHandleDirective) { auto avsMessageHeader = std::make_shared( NAMESPACE_SPEECH_RECOGNIZER, NAME_STOP_CAPTURE, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); std::shared_ptr directive = @@ -510,7 +510,7 @@ TEST_F(CapabilityAgentTest, testCallToHandleDirective) { * Call the @c handleDirective from the @c CapabilityAgent base class with a directive as the argument. No * @c preHandleDirective is called before handleDirective. Expect @c handleDirective to return @c false. */ -TEST_F(CapabilityAgentTest, testCallToHandleDirectiveWithNoPrehandle) { +TEST_F(CapabilityAgentTest, test_callToHandleDirectiveWithNoPrehandle) { auto avsMessageHeader = std::make_shared( NAMESPACE_SPEECH_RECOGNIZER, NAME_STOP_CAPTURE, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); std::shared_ptr directive = @@ -522,7 +522,7 @@ TEST_F(CapabilityAgentTest, testCallToHandleDirectiveWithNoPrehandle) { * Call the @c cancelDirective from the @c CapabilityAgent base class with a directive as the argument. * Expect the @c cancelDirective with the argument of @c DirectiveAndResultInterface will be called. */ -TEST_F(CapabilityAgentTest, testCallToCancelDirective) { +TEST_F(CapabilityAgentTest, test_callToCancelDirective) { auto avsMessageHeader = std::make_shared( NAMESPACE_SPEECH_RECOGNIZER, NAME_STOP_CAPTURE, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); std::shared_ptr directive = @@ -539,7 +539,7 @@ TEST_F(CapabilityAgentTest, testCallToCancelDirective) { * @c preHandleDirective is called before handleDirective. Expect the @c cancelDirective with the argument of * @c DirectiveAndResultInterface will not be called. */ -TEST_F(CapabilityAgentTest, testCallToCancelDirectiveWithNoPrehandle) { +TEST_F(CapabilityAgentTest, test_callToCancelDirectiveWithNoPrehandle) { auto avsMessageHeader = std::make_shared( NAMESPACE_SPEECH_RECOGNIZER, NAME_STOP_CAPTURE, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); std::shared_ptr directive = @@ -553,7 +553,7 @@ TEST_F(CapabilityAgentTest, testCallToCancelDirectiveWithNoPrehandle) { * corresponding @c testEvent. The messageId will not match since it is a random number. Verify the string before and * after the messageId. */ -TEST_F(CapabilityAgentTest, testWithDialogIdAndContext) { +TEST_F(CapabilityAgentTest, test_withDialogIdAndContext) { testBuildJsonEventString(testEventWithDialogReqIdAndContext, true); } @@ -562,7 +562,7 @@ TEST_F(CapabilityAgentTest, testWithDialogIdAndContext) { * matches the corresponding @c testEvent. The messageId will not match since it is a random number. Verify the string * before and after the messageId. */ -TEST_F(CapabilityAgentTest, testWithDialogIdAndNoContext) { +TEST_F(CapabilityAgentTest, test_withDialogIdAndNoContext) { testBuildJsonEventString(testEventWithDialogReqIdNoContext, true); } @@ -571,7 +571,7 @@ TEST_F(CapabilityAgentTest, testWithDialogIdAndNoContext) { * that matches the corresponding @c testEvent. The messageId will not match since it is a random number. * Verify the string before and after the messageId. */ -TEST_F(CapabilityAgentTest, testWithoutDialogIdOrContext) { +TEST_F(CapabilityAgentTest, test_withoutDialogIdOrContext) { testBuildJsonEventString(testEventWithoutDialogReqIdOrContext, false); } @@ -580,7 +580,7 @@ TEST_F(CapabilityAgentTest, testWithoutDialogIdOrContext) { * string that matches the corresponding @c testEvent. The messageId will not match since it is a random number. * Verify the string before and after the messageId. */ -TEST_F(CapabilityAgentTest, testWithContextAndNoDialogId) { +TEST_F(CapabilityAgentTest, test_withContextAndNoDialogId) { testBuildJsonEventString(testEventWithContextAndNoDialogReqId, false); } @@ -588,7 +588,7 @@ TEST_F(CapabilityAgentTest, testWithContextAndNoDialogId) { * Call sendExceptionEncounteredAndReportFailed with info pointing to null directive. Expect sendExceptionEncountered to * not be called. Send again with info pointing to a valid directive. Expect sendExceptionEncountered to be called */ -TEST_F(CapabilityAgentTest, testsendExceptionEncounteredWithNullInfo) { +TEST_F(CapabilityAgentTest, test_sendExceptionEncounteredWithNullInfo) { EXPECT_CALL(*(m_exceptionSender.get()), sendExceptionEncountered(_, _, _)).Times(0); m_capabilityAgent->testsendExceptionEncounteredAndReportFailed(nullptr, nullptr); diff --git a/AVSCommon/AVS/test/CapabilityConfigurationTest.cpp b/AVSCommon/AVS/test/CapabilityConfigurationTest.cpp index 622f74b59d..0b0e0b40b5 100644 --- a/AVSCommon/AVS/test/CapabilityConfigurationTest.cpp +++ b/AVSCommon/AVS/test/CapabilityConfigurationTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -42,14 +42,14 @@ static const std::string VALUE2 = "value2"; class CapabilityConfigurationTest : public ::testing::Test {}; /// Test the constructor -TEST_F(CapabilityConfigurationTest, testConstructor) { +TEST_F(CapabilityConfigurationTest, test_constructor) { std::unordered_map capabilityConfigurationMap; CapabilityConfiguration instance(capabilityConfigurationMap); ASSERT_TRUE(instance.capabilityConfiguration.empty()); } /// Test the == operator -TEST_F(CapabilityConfigurationTest, testEquality) { +TEST_F(CapabilityConfigurationTest, test_equality) { std::unordered_map lhsCapabilityConfigurationMap; lhsCapabilityConfigurationMap.insert({KEY1, VALUE1}); @@ -64,7 +64,7 @@ TEST_F(CapabilityConfigurationTest, testEquality) { } /// Test the != operator -TEST_F(CapabilityConfigurationTest, testInequality) { +TEST_F(CapabilityConfigurationTest, test_inequality) { std::unordered_map lhsCapabilityConfigurationMap; lhsCapabilityConfigurationMap.insert({KEY1, VALUE1}); @@ -79,7 +79,7 @@ TEST_F(CapabilityConfigurationTest, testInequality) { } /// Test if equality and hash works if you have multiple entries in maps that are the same but in different order -TEST_F(CapabilityConfigurationTest, testMultipleValues) { +TEST_F(CapabilityConfigurationTest, test_multipleValues) { std::unordered_map lhsCapabilityConfigurationMap; lhsCapabilityConfigurationMap.insert({KEY1, VALUE1}); lhsCapabilityConfigurationMap.insert({KEY2, VALUE2}); diff --git a/AVSCommon/AVS/test/DialogUXStateAggregatorTest.cpp b/AVSCommon/AVS/test/DialogUXStateAggregatorTest.cpp index 1997c343c5..24823df882 100644 --- a/AVSCommon/AVS/test/DialogUXStateAggregatorTest.cpp +++ b/AVSCommon/AVS/test/DialogUXStateAggregatorTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -157,12 +157,12 @@ class DialogUXAggregatorTest }; /// Tests that an observer starts off in the IDLE state. -TEST_F(DialogUXAggregatorTest, testIdleAtBeginning) { +TEST_F(DialogUXAggregatorTest, test_idleAtBeginning) { assertStateChange(m_testObserver, DialogUXStateObserverInterface::DialogUXState::IDLE); } /// Tests that a new observer added receives the current state. -TEST_F(DialogUXAggregatorTest, testInvalidAtBeginningForMultipleObservers) { +TEST_F(DialogUXAggregatorTest, test_invalidAtBeginningForMultipleObservers) { assertStateChange(m_testObserver, DialogUXStateObserverInterface::DialogUXState::IDLE); m_aggregator->addObserver(m_anotherTestObserver); @@ -171,7 +171,7 @@ TEST_F(DialogUXAggregatorTest, testInvalidAtBeginningForMultipleObservers) { } /// Tests that the removing observer functionality works properly by asserting no state change on a removed observer. -TEST_F(DialogUXAggregatorTest, testRemoveObserver) { +TEST_F(DialogUXAggregatorTest, test_removeObserver) { assertStateChange(m_testObserver, DialogUXStateObserverInterface::DialogUXState::IDLE); m_aggregator->addObserver(m_anotherTestObserver); @@ -184,7 +184,7 @@ TEST_F(DialogUXAggregatorTest, testRemoveObserver) { } /// Tests that multiple callbacks aren't issued if the state shouldn't change. -TEST_F(DialogUXAggregatorTest, aipIdleLeadsToIdleState) { +TEST_F(DialogUXAggregatorTest, test_aipIdleLeadsToIdleState) { assertStateChange(m_testObserver, DialogUXStateObserverInterface::DialogUXState::IDLE); m_aggregator->onStateChanged(AudioInputProcessorObserverInterface::State::IDLE); @@ -192,7 +192,7 @@ TEST_F(DialogUXAggregatorTest, aipIdleLeadsToIdleState) { } /// Tests that the AIP recognizing state leads to the LISTENING state. -TEST_F(DialogUXAggregatorTest, aipRecognizeLeadsToListeningState) { +TEST_F(DialogUXAggregatorTest, test_aipRecognizeLeadsToListeningState) { assertStateChange(m_testObserver, DialogUXStateObserverInterface::DialogUXState::IDLE); m_aggregator->onStateChanged(AudioInputProcessorObserverInterface::State::RECOGNIZING); @@ -200,7 +200,7 @@ TEST_F(DialogUXAggregatorTest, aipRecognizeLeadsToListeningState) { } /// Tests that the AIP recognizing state leads to the LISTENING state. -TEST_F(DialogUXAggregatorTest, aipIdleLeadsToIdle) { +TEST_F(DialogUXAggregatorTest, test_aipIdleLeadsToIdle) { assertStateChange(m_testObserver, DialogUXStateObserverInterface::DialogUXState::IDLE); m_aggregator->onStateChanged(AudioInputProcessorObserverInterface::State::RECOGNIZING); @@ -211,7 +211,7 @@ TEST_F(DialogUXAggregatorTest, aipIdleLeadsToIdle) { } /// Tests that the AIP expecting speech state leads to the EXPECTING state. -TEST_F(DialogUXAggregatorTest, aipExpectingSpeechLeadsToListeningState) { +TEST_F(DialogUXAggregatorTest, test_aipExpectingSpeechLeadsToListeningState) { assertStateChange(m_testObserver, DialogUXStateObserverInterface::DialogUXState::IDLE); m_aggregator->onStateChanged(AudioInputProcessorObserverInterface::State::EXPECTING_SPEECH); @@ -219,7 +219,7 @@ TEST_F(DialogUXAggregatorTest, aipExpectingSpeechLeadsToListeningState) { } /// Tests that the AIP busy state leads to the THINKING state. -TEST_F(DialogUXAggregatorTest, aipBusyLeadsToThinkingState) { +TEST_F(DialogUXAggregatorTest, test_aipBusyLeadsToThinkingState) { assertStateChange(m_testObserver, DialogUXStateObserverInterface::DialogUXState::IDLE); m_aggregator->onStateChanged(AudioInputProcessorObserverInterface::State::BUSY); @@ -227,7 +227,7 @@ TEST_F(DialogUXAggregatorTest, aipBusyLeadsToThinkingState) { } /// Tests that BUSY state goes to IDLE after the specified timeout. -TEST_F(DialogUXAggregatorTest, busyGoesToIdleAfterTimeout) { +TEST_F(DialogUXAggregatorTest, test_busyGoesToIdleAfterTimeout) { std::shared_ptr anotherAggregator = std::make_shared(std::chrono::milliseconds(200)); @@ -243,7 +243,7 @@ TEST_F(DialogUXAggregatorTest, busyGoesToIdleAfterTimeout) { } /// Tests that the BUSY state remains in BUSY immediately if a message is received. -TEST_F(DialogUXAggregatorTest, busyThenReceiveRemainsInBusyImmediately) { +TEST_F(DialogUXAggregatorTest, test_busyThenReceiveRemainsInBusyImmediately) { assertStateChange(m_testObserver, DialogUXStateObserverInterface::DialogUXState::IDLE); m_aggregator->onStateChanged(AudioInputProcessorObserverInterface::State::BUSY); @@ -255,7 +255,7 @@ TEST_F(DialogUXAggregatorTest, busyThenReceiveRemainsInBusyImmediately) { } /// Tests that the BUSY state goes to IDLE after a message is received after a short timeout. -TEST_F(DialogUXAggregatorTest, busyThenReceiveGoesToIdleAfterShortTimeout) { +TEST_F(DialogUXAggregatorTest, test_busyThenReceiveGoesToIdleAfterShortTimeout) { assertStateChange(m_testObserver, DialogUXStateObserverInterface::DialogUXState::IDLE); m_aggregator->onStateChanged(AudioInputProcessorObserverInterface::State::BUSY); @@ -268,7 +268,7 @@ TEST_F(DialogUXAggregatorTest, busyThenReceiveGoesToIdleAfterShortTimeout) { } /// Tests that the BUSY state goes to IDLE after a SpeechSynthesizer speak state is received. -TEST_F(DialogUXAggregatorTest, busyThenReceiveThenSpeakGoesToSpeak) { +TEST_F(DialogUXAggregatorTest, test_busyThenReceiveThenSpeakGoesToSpeak) { assertStateChange(m_testObserver, DialogUXStateObserverInterface::DialogUXState::IDLE); m_aggregator->onStateChanged(AudioInputProcessorObserverInterface::State::BUSY); @@ -285,7 +285,7 @@ TEST_F(DialogUXAggregatorTest, busyThenReceiveThenSpeakGoesToSpeak) { * Tests that the BUSY state goes to SPEAKING but not IDLE after both a message is received and a SpeechSynthesizer * speak state is received. */ -TEST_F(DialogUXAggregatorTest, busyThenReceiveThenSpeakGoesToSpeakButNotIdle) { +TEST_F(DialogUXAggregatorTest, test_busyThenReceiveThenSpeakGoesToSpeakButNotIdle) { assertStateChange(m_testObserver, DialogUXStateObserverInterface::DialogUXState::IDLE); m_aggregator->onStateChanged(AudioInputProcessorObserverInterface::State::BUSY); @@ -301,7 +301,7 @@ TEST_F(DialogUXAggregatorTest, busyThenReceiveThenSpeakGoesToSpeakButNotIdle) { } /// Tests that both SpeechSynthesizer and AudioInputProcessor finished/idle state leads to the IDLE state. -TEST_F(DialogUXAggregatorTest, speakingAndRecognizingFinishedGoesToIdle) { +TEST_F(DialogUXAggregatorTest, test_speakingAndRecognizingFinishedGoesToIdle) { assertStateChange(m_testObserver, DialogUXStateObserverInterface::DialogUXState::IDLE); m_aggregator->onStateChanged(AudioInputProcessorObserverInterface::State::BUSY); @@ -320,7 +320,7 @@ TEST_F(DialogUXAggregatorTest, speakingAndRecognizingFinishedGoesToIdle) { } /// Tests that SpeechSynthesizer or AudioInputProcessor non-idle state prevents the IDLE state. -TEST_F(DialogUXAggregatorTest, nonIdleObservantsPreventsIdle) { +TEST_F(DialogUXAggregatorTest, test_nonIdleObservantsPreventsIdle) { assertStateChange(m_testObserver, DialogUXStateObserverInterface::DialogUXState::IDLE); // AIP is active, SS is not. Expected: non idle @@ -344,7 +344,7 @@ TEST_F(DialogUXAggregatorTest, nonIdleObservantsPreventsIdle) { } /// Tests that a SpeechSynthesizer finished state does not go to the IDLE state after a very short timeout. -TEST_F(DialogUXAggregatorTest, speakingFinishedDoesNotGoesToIdleImmediately) { +TEST_F(DialogUXAggregatorTest, test_speakingFinishedDoesNotGoesToIdleImmediately) { assertStateChange(m_testObserver, DialogUXStateObserverInterface::DialogUXState::IDLE); m_aggregator->onStateChanged(AudioInputProcessorObserverInterface::State::BUSY); @@ -362,7 +362,7 @@ TEST_F(DialogUXAggregatorTest, speakingFinishedDoesNotGoesToIdleImmediately) { } /// Tests that a simple message receive does nothing. -TEST_F(DialogUXAggregatorTest, simpleReceiveDoesNothing) { +TEST_F(DialogUXAggregatorTest, test_simpleReceiveDoesNothing) { assertStateChange(m_testObserver, DialogUXStateObserverInterface::DialogUXState::IDLE); m_aggregator->receive("", ""); @@ -380,7 +380,7 @@ TEST_F(DialogUXAggregatorTest, simpleReceiveDoesNothing) { /// Tests that the THINKING state remains in THINKING if SpeechSynthesizer reports GAINING_FOCUS and a new message is /// received. -TEST_F(DialogUXAggregatorTest, thinkingThenReceiveRemainsInThinkingIfSpeechSynthesizerReportsGainingFocus) { +TEST_F(DialogUXAggregatorTest, test_thinkingThenReceiveRemainsInThinkingIfSpeechSynthesizerReportsGainingFocus) { assertStateChange(m_testObserver, DialogUXStateObserverInterface::DialogUXState::IDLE); m_aggregator->onStateChanged(AudioInputProcessorObserverInterface::State::BUSY); diff --git a/AVSCommon/AVS/test/ExceptionEncounteredSenderTest.cpp b/AVSCommon/AVS/test/ExceptionEncounteredSenderTest.cpp index 1a7b1fee61..bcb7c74dd6 100644 --- a/AVSCommon/AVS/test/ExceptionEncounteredSenderTest.cpp +++ b/AVSCommon/AVS/test/ExceptionEncounteredSenderTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -223,7 +223,7 @@ bool ExceptionEncounteredSenderTest::testExceptionEncounteredSucceeds( * This function sends @c ExceptionErrorType::UNEXPECTED_INFORMATION_RECEIVED and verifies that * @c ExceptionEncounteredSender::sendExceptionEncountered send the event. */ -TEST_F(ExceptionEncounteredSenderTest, errorTypeUnexpectedInformationReceived) { +TEST_F(ExceptionEncounteredSenderTest, test_errorTypeUnexpectedInformationReceived) { ASSERT_TRUE(testExceptionEncounteredSucceeds( UNPARSED_DIRECTIVE_JSON_STRING, avs::ExceptionErrorType::UNEXPECTED_INFORMATION_RECEIVED, @@ -233,7 +233,7 @@ TEST_F(ExceptionEncounteredSenderTest, errorTypeUnexpectedInformationReceived) { * This function sends @c ExceptionErrorType::UNSUPPORTED_OPERATION and verifies that * @c ExceptionEncounteredSender::sendExceptionEncountered send the event. */ -TEST_F(ExceptionEncounteredSenderTest, errorTypeUnexpectedOperation) { +TEST_F(ExceptionEncounteredSenderTest, test_errorTypeUnexpectedOperation) { ASSERT_TRUE(testExceptionEncounteredSucceeds( UNPARSED_DIRECTIVE_JSON_STRING, avs::ExceptionErrorType::UNSUPPORTED_OPERATION, "Operation not supported")); } @@ -241,7 +241,7 @@ TEST_F(ExceptionEncounteredSenderTest, errorTypeUnexpectedOperation) { * This function sends @c ExceptionErrorType::INTERNAL_ERROR and verifies that * @c ExceptionEncounteredSender::sendExceptionEncountered send the event. */ -TEST_F(ExceptionEncounteredSenderTest, errorTypeInternalError) { +TEST_F(ExceptionEncounteredSenderTest, test_errorTypeInternalError) { ASSERT_TRUE(testExceptionEncounteredSucceeds( UNPARSED_DIRECTIVE_JSON_STRING, avs::ExceptionErrorType::INTERNAL_ERROR, "An error occurred with the device")); } diff --git a/AVSCommon/AVS/test/HandlerAndPolicyTest.cpp b/AVSCommon/AVS/test/HandlerAndPolicyTest.cpp index 691717b803..f97b844e4c 100644 --- a/AVSCommon/AVS/test/HandlerAndPolicyTest.cpp +++ b/AVSCommon/AVS/test/HandlerAndPolicyTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -56,7 +56,7 @@ class HandlerAndPolicyTest : public ::testing::Test {}; /** * Invoke default constructor. Expect @c nameSpace and @c name properties are both empty strings. */ -TEST_F(HandlerAndPolicyTest, testDefaultConstructor) { +TEST_F(HandlerAndPolicyTest, test_defaultConstructor) { HandlerAndPolicy handlerAndPolicy; ASSERT_EQ(handlerAndPolicy.handler, nullptr); ASSERT_FALSE(handlerAndPolicy.policy.isValid()); @@ -65,7 +65,7 @@ TEST_F(HandlerAndPolicyTest, testDefaultConstructor) { /** * Invoke constructor with member values. Expect properties match those provided to the constructor. */ -TEST_F(HandlerAndPolicyTest, testConstructorWithValues) { +TEST_F(HandlerAndPolicyTest, test_constructorWithValues) { auto handler = std::make_shared(); auto neitherNonBlockingPolicy = BlockingPolicy(BlockingPolicy::MEDIUMS_NONE, false); HandlerAndPolicy handlerAndPolicy(handler, neitherNonBlockingPolicy); @@ -77,7 +77,7 @@ TEST_F(HandlerAndPolicyTest, testConstructorWithValues) { * Create empty and non-empty HandlerAndPolicy instances. Expect that empty instances are interpreted as false and * non-empty values are interpreted as true. */ -TEST_F(HandlerAndPolicyTest, testOperatorBool) { +TEST_F(HandlerAndPolicyTest, test_operatorBool) { auto handler = std::make_shared(); HandlerAndPolicy defaultHandlerAndPolicy; auto audioBlockingPolicy = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, true); @@ -95,7 +95,7 @@ TEST_F(HandlerAndPolicyTest, testOperatorBool) { * Create instances with different and identical values. Expect that instances with different values test as * not equal and that instances with identical values test as equal. */ -TEST_F(HandlerAndPolicyTest, testOperatorEqualandNotEqual) { +TEST_F(HandlerAndPolicyTest, test_operatorEqualandNotEqual) { auto handler1 = std::make_shared(); auto handler2 = std::make_shared(); HandlerAndPolicy defaultHandlerAndPolicy; diff --git a/AVSCommon/AVS/test/NamespaceAndNameTest.cpp b/AVSCommon/AVS/test/NamespaceAndNameTest.cpp index 738207c5aa..c7e5b87371 100644 --- a/AVSCommon/AVS/test/NamespaceAndNameTest.cpp +++ b/AVSCommon/AVS/test/NamespaceAndNameTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ class NamespaceAndNameTest : public ::testing::Test {}; /** * Invoke default constructor. Expect @c nameSpace and @c name properties are both empty strings. */ -TEST_F(NamespaceAndNameTest, testDefaultConstructor) { +TEST_F(NamespaceAndNameTest, test_defaultConstructor) { NamespaceAndName instance; ASSERT_TRUE(instance.nameSpace.empty()); ASSERT_TRUE(instance.name.empty()); @@ -56,7 +56,7 @@ TEST_F(NamespaceAndNameTest, testDefaultConstructor) { /** * Invoke constructor with member values. Expect properties match those provided to the constructor. */ -TEST_F(NamespaceAndNameTest, testConstructorWithValues) { +TEST_F(NamespaceAndNameTest, test_constructorWithValues) { NamespaceAndName instance(NAMESPACE_SPEECH_RECOGNIZER, NAME_RECOGNIZE); ASSERT_EQ(instance.nameSpace, NAMESPACE_SPEECH_RECOGNIZER); ASSERT_EQ(instance.name, NAME_RECOGNIZE); @@ -65,7 +65,7 @@ TEST_F(NamespaceAndNameTest, testConstructorWithValues) { /** * Create an @c std::unordered_map using NamespaceAndName values as keys. Expect that the keys map to distinct values. */ -TEST_F(NamespaceAndNameTest, testInUnorderedMap) { +TEST_F(NamespaceAndNameTest, test_inUnorderedMap) { std::unordered_map testMap; NamespaceAndName key1(NAMESPACE_SPEECH_RECOGNIZER, NAME_RECOGNIZE); NamespaceAndName key2(NAMESPACE_SPEAKER, NAME_SET_VOLUME); diff --git a/AVSCommon/SDKInterfaces/include/AVSCommon/SDKInterfaces/FocusManagerInterface.h b/AVSCommon/SDKInterfaces/include/AVSCommon/SDKInterfaces/FocusManagerInterface.h index 06383d36d2..fc550ebc6f 100644 --- a/AVSCommon/SDKInterfaces/include/AVSCommon/SDKInterfaces/FocusManagerInterface.h +++ b/AVSCommon/SDKInterfaces/include/AVSCommon/SDKInterfaces/FocusManagerInterface.h @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -40,6 +40,8 @@ namespace sdkInterfaces { * * stop foreground Channel - clients should call the stopForegroundActivity() method. * + * stop all activities - client should call stopAllActivities + * * All of these methods will notify the observer of the Channel of focus changes via an asynchronous callback to the * ChannelObserverInterface##onFocusChanged() method, at which point the client should make a user observable change * based on the focus it receives. @@ -58,11 +60,11 @@ class FocusManagerInterface { /// The default Communications Channel priority. static constexpr unsigned int COMMUNICATIONS_CHANNEL_PRIORITY = 150; - /// The default Alerts Channel name. - static constexpr const char* ALERTS_CHANNEL_NAME = "Alerts"; + /// The default Alert Channel name. + static constexpr const char* ALERT_CHANNEL_NAME = "Alert"; - /// The default Alerts Channel priority. - static constexpr unsigned int ALERTS_CHANNEL_PRIORITY = 200; + /// The default Alert Channel priority. + static constexpr unsigned int ALERT_CHANNEL_PRIORITY = 200; /// The default Content Channel name. static constexpr const char* CONTENT_CHANNEL_NAME = "Content"; @@ -120,6 +122,12 @@ class FocusManagerInterface { */ virtual void stopForegroundActivity() = 0; + /** + * This method will request to stop all active channels. This will be performed asynchronously, and so, if at the + * time performing the stop, the channel is owned by another interface, this channel won't get stopped. + */ + virtual void stopAllActivities() = 0; + /** * Add an observer to the focus manager. * diff --git a/AVSCommon/SDKInterfaces/include/AVSCommon/SDKInterfaces/InternetConnectionMonitorInterface.h b/AVSCommon/SDKInterfaces/include/AVSCommon/SDKInterfaces/InternetConnectionMonitorInterface.h index 40780ee1e7..4c9da5e6e6 100644 --- a/AVSCommon/SDKInterfaces/include/AVSCommon/SDKInterfaces/InternetConnectionMonitorInterface.h +++ b/AVSCommon/SDKInterfaces/include/AVSCommon/SDKInterfaces/InternetConnectionMonitorInterface.h @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ #ifndef ALEXA_CLIENT_SDK_AVSCOMMON_SDKINTERFACES_INCLUDE_AVSCOMMON_SDKINTERFACES_INTERNETCONNECTIONMONITORINTERFACE_H_ #define ALEXA_CLIENT_SDK_AVSCOMMON_SDKINTERFACES_INCLUDE_AVSCOMMON_SDKINTERFACES_INTERNETCONNECTIONMONITORINTERFACE_H_ +#include + #include "AVSCommon/SDKInterfaces/InternetConnectionObserverInterface.h" namespace alexaClientSDK { diff --git a/AVSCommon/SDKInterfaces/include/AVSCommon/SDKInterfaces/Storage/MiscStorageInterface.h b/AVSCommon/SDKInterfaces/include/AVSCommon/SDKInterfaces/Storage/MiscStorageInterface.h index c9f2bf0824..f06f9b4300 100644 --- a/AVSCommon/SDKInterfaces/include/AVSCommon/SDKInterfaces/Storage/MiscStorageInterface.h +++ b/AVSCommon/SDKInterfaces/include/AVSCommon/SDKInterfaces/Storage/MiscStorageInterface.h @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -141,6 +141,7 @@ class MiscStorageInterface { * @param tableName The table name. * @param key The key for the table entry. * @param value The value of the table entry. + * @note @c value should be a string literal. * @return @c true If the value was added ok, @c false if not. */ virtual bool add( @@ -155,6 +156,7 @@ class MiscStorageInterface { * @param tableName The table name. * @param key The key for the table entry. * @param value The value of the table entry. + * @note @c value should be a literal string. * @return @c true If the value was updated ok, @c false if not (including if the entry does not exist). */ virtual bool update( @@ -172,6 +174,7 @@ class MiscStorageInterface { * @param tableName The table name. * @param key The key for the table entry. * @param value The value of the table entry. + * @note @c value should be a literal string. * @return @c true If the value was put ok, @c false if not. */ virtual bool put( diff --git a/AVSCommon/SDKInterfaces/test/AVSCommon/SDKInterfaces/MockFocusManager.h b/AVSCommon/SDKInterfaces/test/AVSCommon/SDKInterfaces/MockFocusManager.h index f3ede1512c..c2404fe9f3 100644 --- a/AVSCommon/SDKInterfaces/test/AVSCommon/SDKInterfaces/MockFocusManager.h +++ b/AVSCommon/SDKInterfaces/test/AVSCommon/SDKInterfaces/MockFocusManager.h @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -45,6 +45,7 @@ class MockFocusManager : public FocusManagerInterface { MOCK_METHOD1( removeObserver, void(const std::shared_ptr& observer)); + MOCK_METHOD0(stopAllActivities, void()); }; } // namespace test diff --git a/AVSCommon/SDKInterfaces/test/AVSCommon/SDKInterfaces/MockSpeakerInterface.h b/AVSCommon/SDKInterfaces/test/AVSCommon/SDKInterfaces/MockSpeakerInterface.h index 071ea1e013..3e279ca01c 100644 --- a/AVSCommon/SDKInterfaces/test/AVSCommon/SDKInterfaces/MockSpeakerInterface.h +++ b/AVSCommon/SDKInterfaces/test/AVSCommon/SDKInterfaces/MockSpeakerInterface.h @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -38,6 +38,9 @@ static const std::string MUTE_STRING("true"); /// Value for unmute. static const bool UNMUTE(false); +/// String value for unmute. +static const std::string UNMUTE_STRING("false"); + /// Value for default volume settings. static const SpeakerInterface::SpeakerSettings DEFAULT_SETTINGS{AVS_SET_VOLUME_MIN, UNMUTE}; @@ -144,4 +147,4 @@ inline MockSpeakerInterface::MockSpeakerInterface(SpeakerInterface::Type type) : } // namespace avsCommon } // namespace alexaClientSDK -#endif // ALEXA_CLIENT_SDK_AVSCOMMON_SDKINTERFACES_TEST_AVSCOMMON_SDKINTERFACES_MOCKSPEAKERINTERFACE_H_ +#endif // ALEXA_CLIENT_SDK_AVSCOMMON_SDKINTERFACES_TEST_AVSCOMMON_SDKINTERFACES_MOCKSPEAKERINTERFACE_H_ \ No newline at end of file diff --git a/AVSCommon/SDKInterfaces/test/src/EqualizerStorageInterfaceTest.cpp b/AVSCommon/SDKInterfaces/test/src/EqualizerStorageInterfaceTest.cpp index d4209b471e..c3d2edf6e0 100644 --- a/AVSCommon/SDKInterfaces/test/src/EqualizerStorageInterfaceTest.cpp +++ b/AVSCommon/SDKInterfaces/test/src/EqualizerStorageInterfaceTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ void EqualizerStorageInterfaceTest::SetUp() { /** * Save state to the storage and see if loadState() returns the saved state. */ -TEST_P(EqualizerStorageInterfaceTest, saveState_ExpectLoadReturnSame) { +TEST_P(EqualizerStorageInterfaceTest, test_saveState_ExpectLoadReturnSame) { EqualizerState defaultState = {EqualizerMode::MOVIE, EqualizerBandLevelMap({{EqualizerBand::TREBLE, 0}, {EqualizerBand::MIDRANGE, 1}})}; m_storage->saveState(defaultState); @@ -58,7 +58,7 @@ TEST_P(EqualizerStorageInterfaceTest, saveState_ExpectLoadReturnSame) { /** * Perform cleaning of the data in the storage and see if next loadState() returns the default state. */ -TEST_P(EqualizerStorageInterfaceTest, clearSavedData_ExpectAllDefaultsOnLoad) { +TEST_P(EqualizerStorageInterfaceTest, test_clearSavedData_ExpectAllDefaultsOnLoad) { EqualizerState defaultState = {EqualizerMode::MOVIE, EqualizerBandLevelMap({{EqualizerBand::TREBLE, 0}, {EqualizerBand::MIDRANGE, 1}})}; diff --git a/AVSCommon/Utils/include/AVSCommon/Utils/Configuration/ConfigurationNode.h b/AVSCommon/Utils/include/AVSCommon/Utils/Configuration/ConfigurationNode.h index 6e4e7f2d9b..d0bcda78a2 100644 --- a/AVSCommon/Utils/include/AVSCommon/Utils/Configuration/ConfigurationNode.h +++ b/AVSCommon/Utils/include/AVSCommon/Utils/Configuration/ConfigurationNode.h @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ #define ALEXA_CLIENT_SDK_AVSCOMMON_UTILS_INCLUDE_AVSCOMMON_UTILS_CONFIGURATION_CONFIGURATIONNODE_H_ #include +#include #include #include #include @@ -198,6 +199,31 @@ class ConfigurationNode { */ std::string serialize() const; + /** + * Get the @c ConfigurationNode value that contains an array with @c key from this @c ConfigurationNode. + * + * @param key The key of the @c ConfigurationNode value to get. + * @return The @c ConfigurationNode value, or an empty node if this @c ConfigurationNode does not have + * a @c ConfigurationNode value for @c key that contains an array. + */ + ConfigurationNode getArray(const std::string& key) const; + + /** + * Get the size of the array from this @c ConfigurationNode. + * + * @return 0 if this @c ConfigurationNode is not an array. Else return the size of the array. + */ + std::size_t getArraySize() const; + + /** + * operator[] to get @c ConfigurationNode value from an array from @c index of this @c ConfigurationNode. + * + * @param index The index of the array of the @c ConfigurationNode to get. + * @return The @c ConfigurationNode value, or an empty node if this @c ConfigurationNode is not an array or the + * the index is out of range. + */ + ConfigurationNode operator[](const std::size_t index) const; + private: /** * Constructor. diff --git a/AVSCommon/Utils/include/AVSCommon/Utils/Network/InternetConnectionMonitor.h b/AVSCommon/Utils/include/AVSCommon/Utils/Network/InternetConnectionMonitor.h index d69ebf665c..416505a886 100644 --- a/AVSCommon/Utils/include/AVSCommon/Utils/Network/InternetConnectionMonitor.h +++ b/AVSCommon/Utils/include/AVSCommon/Utils/Network/InternetConnectionMonitor.h @@ -117,9 +117,6 @@ class InternetConnectionMonitor : public sdkInterfaces::InternetConnectionMonito /// A flag to tell the HTTP content fetcher that it is time to shutdown. std::atomic m_isShuttingDown; - /// The stream that will hold downloaded data. - std::shared_ptr m_stream; - /// The content fetcher factory that will produce a content fetcher. std::shared_ptr m_contentFetcherFactory; diff --git a/AVSCommon/Utils/include/AVSCommon/Utils/Optional.h b/AVSCommon/Utils/include/AVSCommon/Utils/Optional.h new file mode 100644 index 0000000000..7d13d31e66 --- /dev/null +++ b/AVSCommon/Utils/include/AVSCommon/Utils/Optional.h @@ -0,0 +1,228 @@ +/* + * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0/ + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ +#ifndef ALEXA_CLIENT_SDK_AVSCOMMON_UTILS_INCLUDE_AVSCOMMON_UTILS_OPTIONAL_H_ +#define ALEXA_CLIENT_SDK_AVSCOMMON_UTILS_INCLUDE_AVSCOMMON_UTILS_OPTIONAL_H_ + +#include + +namespace alexaClientSDK { +namespace avsCommon { +namespace utils { + +/** + * Auxiliary class that implements an optional object, where the value may or may not be present. + * + * @note @c ValueT MUST have a copy constructor. + * @note Method @c value() is available only for @c ValueT types that have a default constructor. + * @warning This class is not thread-safe. + */ +template +class Optional { +public: + /** + * Creates an optional object with no valid value. + */ + Optional(); + + /** + * Creates an optional object with a valid value. + * + * @param value Object used to initialize the new optional value. + * @note This method required @c ValueT to have a copy constructor is available. + */ + Optional(const ValueT& value); + + /** + * Copy constructor. + * + * @param other Object used to initialize the new optional object. + */ + Optional(const Optional& other); + + /** + * Sets optional value to the given ValueT. + * + * @param value Object that will be assigned to the optional value. + * @note ValueT MUST have an assignment operator defined. + */ + void set(const ValueT& value); + + /** + * Modifies the optional object so it no longer holds any valid value. + */ + void reset(); + + /** + * Checks whether the optional contains a value or not. + * + * @return true if it contains a value, false if it does not contain a value. + */ + bool hasValue() const; + + /** + * Gets the value if present or return other. @c ValueT must have a copy constructor. + * + * @param other Object that will be returned if this optional does not hold a value. + * @return This optional value if *this has a value; otherwise, return @c other. + */ + ValueT valueOr(const ValueT& other) const; + + /** + * Gets the value if present or return other. @c ValueT must have a default constructor. + * + * @return The object being held by this if @c m_object is valid; otherwise, return @c ValueT(). + */ + ValueT value() const; + + /** + * Optional destructor. + */ + ~Optional(); + + /** + * Assignment operator. + * + * @param rhs The optional object source of the assignment. + * @return A reference to @c *this. + */ + Optional& operator=(const Optional& rhs); + + /** + * Equality operator. + * + * @param rhs The object to compare *this against. + * @return @c true if both objects don't hold a value, and @c false if only one object holds a value. If both + * optionals hold valid values, return the result of operator== for their values. + */ + bool operator==(const Optional& rhs) const; + + /** + * Inequality operator. + * + * @param rhs The object to compare *this against. + * @return @c true if only one object holds a value, and @c false if both objects don't hold a value. If both + * optionals hold valid values, return the result of operator!= for their values. + */ + bool operator!=(const Optional& rhs) const; + +private: + /// Boolean flag indicating whether the value exists or not. + bool m_hasValue; + + /// Place holder for the actual value. + /// + /// @note We chose to use @c std::aligned_storage so we can control the underlying object lifecycle without the + /// burden of always using the heap. + typename std::aligned_storage::type m_value; +}; + +template +Optional::Optional() : m_hasValue{false} { +} + +template +Optional::Optional(const ValueT& other) : m_hasValue{true} { + // Create object in the allocated space. + new (&m_value) ValueT(other); +} + +template +Optional::Optional(const Optional& other) : m_hasValue{other.m_hasValue} { + if (hasValue()) { + new (&m_value) ValueT(*reinterpret_cast(&other.m_value)); + } +} + +template +void Optional::set(const ValueT& other) { + if (hasValue()) { + *reinterpret_cast(&m_value) = other; + } else { + m_hasValue = true; + new (&m_value) ValueT(other); + } +} + +template +void Optional::reset() { + if (hasValue()) { + m_hasValue = false; + reinterpret_cast(&m_value)->~ValueT(); + } +} + +template +bool Optional::hasValue() const { + return m_hasValue; +} + +template +ValueT Optional::value() const { + if (hasValue()) { + return *reinterpret_cast(&m_value); + } + logger::acsdkError(logger::LogEntry("Optional", "valueFailed").d("reason", "optionalHasNoValue")); + return ValueT(); +} + +template +ValueT Optional::valueOr(const ValueT& other) const { + if (hasValue()) { + return *reinterpret_cast(&m_value); + } + return other; +} + +template +Optional::~Optional() { + if (hasValue()) { + reinterpret_cast(&m_value)->~ValueT(); + } +} + +template +Optional& Optional::operator=(const Optional& rhs) { + if (hasValue()) { + if (rhs.hasValue()) { + *reinterpret_cast(&m_value) = rhs.value(); + } else { + m_hasValue = false; + reinterpret_cast(&m_value)->~ValueT(); + } + } else if (rhs.hasValue()) { + m_hasValue = true; + new (&m_value) ValueT(rhs.value()); + } + return *this; +} + +template +bool Optional::operator==(const Optional& rhs) const { + if (this->hasValue()) { + return rhs.hasValue() && (this->value() == rhs.value()); + } + return !rhs.hasValue(); +} + +template +bool Optional::operator!=(const Optional& rhs) const { + return !(*this == rhs); +} + +} // namespace utils +} // namespace avsCommon +} // namespace alexaClientSDK + +#endif // ALEXA_CLIENT_SDK_AVSCOMMON_UTILS_INCLUDE_AVSCOMMON_UTILS_OPTIONAL_ diff --git a/AVSCommon/Utils/include/AVSCommon/Utils/SDKVersion.h b/AVSCommon/Utils/include/AVSCommon/Utils/SDKVersion.h index 029388395f..4265b136ae 100644 --- a/AVSCommon/Utils/include/AVSCommon/Utils/SDKVersion.h +++ b/AVSCommon/Utils/include/AVSCommon/Utils/SDKVersion.h @@ -30,7 +30,7 @@ namespace utils { namespace sdkVersion{ inline static std::string getCurrentVersion(){ - return "1.12.1"; + return "1.13.0"; } inline static int getMajorVersion(){ @@ -38,11 +38,11 @@ inline static int getMajorVersion(){ } inline static int getMinorVersion(){ - return 12; + return 13; } inline static int getPatchVersion(){ - return 1; + return 0; } diff --git a/AVSCommon/Utils/include/AVSCommon/Utils/String/StringUtils.h b/AVSCommon/Utils/include/AVSCommon/Utils/String/StringUtils.h index 5cfcda6fca..b380a5e920 100644 --- a/AVSCommon/Utils/include/AVSCommon/Utils/String/StringUtils.h +++ b/AVSCommon/Utils/include/AVSCommon/Utils/String/StringUtils.h @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -89,6 +89,16 @@ std::string stringToLowerCase(const std::string& input); */ std::string stringToUpperCase(const std::string& input); +/** + * Replaces all occurrences of a substring with another string. + * + * @param str The reference string. + * @param from The string to find. + * @param to The replacement string. + * @return A new string with the replaced substrings. + */ +std::string replaceAllSubstring(const std::string& str, const std::string& from, const std::string& to); + } // namespace string } // namespace utils } // namespace avsCommon diff --git a/AVSCommon/Utils/src/Configuration/ConfigurationNode.cpp b/AVSCommon/Utils/src/Configuration/ConfigurationNode.cpp index 4a12a1fd2c..ae92779e1b 100644 --- a/AVSCommon/Utils/src/Configuration/ConfigurationNode.cpp +++ b/AVSCommon/Utils/src/Configuration/ConfigurationNode.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -193,6 +193,44 @@ std::string ConfigurationNode::serialize() const { return std::string(bufferData); } +ConfigurationNode ConfigurationNode::getArray(const std::string& key) const { + if (!*this) { + ACSDK_ERROR(LX("getArrayFailed").d("reason", "emptyConfigurationNode")); + return ConfigurationNode(); + } + auto it = m_object->FindMember(key.c_str()); + if (m_object->MemberEnd() == it) { + return ConfigurationNode(); + } + if (!it->value.IsArray()) { + ACSDK_ERROR(LX("getArrayFailed").d("reason", "notAnArray")); + return ConfigurationNode(); + } + return ConfigurationNode(&it->value); +} + +std::size_t ConfigurationNode::getArraySize() const { + if (!*this) { + ACSDK_ERROR(LX("getArraySizeFailed").d("reason", "emptyConfigurationNode")); + return 0; + } + if (!m_object->IsArray()) { + ACSDK_ERROR(LX("getArraySizeFailed").d("reason", "notAnArray")); + return 0; + } + return m_object->Size(); +} + +ConfigurationNode ConfigurationNode::operator[](const std::size_t index) const { + auto size = getArraySize(); + if (index >= size) { + ACSDK_ERROR(LX("operator[]Failed").d("reason", "indexOutOfRange").d("size", size).d("index", index)); + return ConfigurationNode(); + } + const rapidjson::Value& objectRef = *m_object; + return ConfigurationNode(&objectRef[index]); +} + } // namespace configuration } // namespace utils } // namespace avsCommon diff --git a/AVSCommon/Utils/src/HTTP2/HTTP2MimeResponseDecoder.cpp b/AVSCommon/Utils/src/HTTP2/HTTP2MimeResponseDecoder.cpp index 55b0386d62..7cdfc1bef7 100644 --- a/AVSCommon/Utils/src/HTTP2/HTTP2MimeResponseDecoder.cpp +++ b/AVSCommon/Utils/src/HTTP2/HTTP2MimeResponseDecoder.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. diff --git a/AVSCommon/Utils/src/JSON/JSONUtils.cpp b/AVSCommon/Utils/src/JSON/JSONUtils.cpp index de05b5d362..4a9d7bc418 100644 --- a/AVSCommon/Utils/src/JSON/JSONUtils.cpp +++ b/AVSCommon/Utils/src/JSON/JSONUtils.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -132,7 +132,7 @@ bool findNode( auto iterator = jsonNode.FindMember(key); if (iterator == jsonNode.MemberEnd()) { - ACSDK_ERROR(LX("findNodeFailed").d("reason", "missingDirectChild").d("child", key)); + ACSDK_DEBUG5(LX("findNode").d("reason", "missingDirectChild").d("child", key)); return false; } diff --git a/AVSCommon/Utils/src/LibcurlUtils/CurlEasyHandleWrapper.cpp b/AVSCommon/Utils/src/LibcurlUtils/CurlEasyHandleWrapper.cpp index b384584825..c3bda8f87c 100644 --- a/AVSCommon/Utils/src/LibcurlUtils/CurlEasyHandleWrapper.cpp +++ b/AVSCommon/Utils/src/LibcurlUtils/CurlEasyHandleWrapper.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2016-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. diff --git a/AVSCommon/Utils/src/LibcurlUtils/CurlMultiHandleWrapper.cpp b/AVSCommon/Utils/src/LibcurlUtils/CurlMultiHandleWrapper.cpp index 9d25c27ede..0c491fea43 100644 --- a/AVSCommon/Utils/src/LibcurlUtils/CurlMultiHandleWrapper.cpp +++ b/AVSCommon/Utils/src/LibcurlUtils/CurlMultiHandleWrapper.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. diff --git a/AVSCommon/Utils/src/LibcurlUtils/HttpPost.cpp b/AVSCommon/Utils/src/LibcurlUtils/HttpPost.cpp index 4574737a32..c39ac371e7 100644 --- a/AVSCommon/Utils/src/LibcurlUtils/HttpPost.cpp +++ b/AVSCommon/Utils/src/LibcurlUtils/HttpPost.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2016-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. diff --git a/AVSCommon/Utils/src/LibcurlUtils/HttpPut.cpp b/AVSCommon/Utils/src/LibcurlUtils/HttpPut.cpp index 295e4be7ca..394ac8aa2a 100644 --- a/AVSCommon/Utils/src/LibcurlUtils/HttpPut.cpp +++ b/AVSCommon/Utils/src/LibcurlUtils/HttpPut.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. diff --git a/AVSCommon/Utils/src/LibcurlUtils/LibcurlHTTP2Connection.cpp b/AVSCommon/Utils/src/LibcurlUtils/LibcurlHTTP2Connection.cpp index 48e91af134..42428132ff 100644 --- a/AVSCommon/Utils/src/LibcurlUtils/LibcurlHTTP2Connection.cpp +++ b/AVSCommon/Utils/src/LibcurlUtils/LibcurlHTTP2Connection.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. diff --git a/AVSCommon/Utils/src/LibcurlUtils/LibcurlHTTP2Request.cpp b/AVSCommon/Utils/src/LibcurlUtils/LibcurlHTTP2Request.cpp index 81a8aa23b9..402348abf6 100644 --- a/AVSCommon/Utils/src/LibcurlUtils/LibcurlHTTP2Request.cpp +++ b/AVSCommon/Utils/src/LibcurlUtils/LibcurlHTTP2Request.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. diff --git a/AVSCommon/Utils/src/Network/InternetConnectionMonitor.cpp b/AVSCommon/Utils/src/Network/InternetConnectionMonitor.cpp index 2cb204b3bb..1404bda621 100644 --- a/AVSCommon/Utils/src/Network/InternetConnectionMonitor.cpp +++ b/AVSCommon/Utils/src/Network/InternetConnectionMonitor.cpp @@ -69,8 +69,6 @@ InternetConnectionMonitor::InternetConnectionMonitor( m_period{DEFAULT_TEST_PERIOD}, m_isShuttingDown{false}, m_contentFetcherFactory{contentFetcherFactory} { - /// Using the test URL as the stream id. - m_stream = std::make_shared(S3_TEST_URL); startMonitoring(); } diff --git a/AVSCommon/Utils/src/StringUtils.cpp b/AVSCommon/Utils/src/StringUtils.cpp index 2948c8620e..4806598212 100644 --- a/AVSCommon/Utils/src/StringUtils.cpp +++ b/AVSCommon/Utils/src/StringUtils.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -127,6 +127,16 @@ bool stringToInt64(const char* str, int64_t* result) { return true; } +std::string replaceAllSubstring(const std::string& str, const std::string& from, const std::string& to) { + size_t pos = 0; + std::string subject = str; + while ((pos = subject.find(from, pos)) != std::string::npos) { + subject.replace(pos, from.length(), to); + pos += to.length(); + } + return subject; +} + } // namespace string } // namespace utils } // namespace avsCommon diff --git a/AVSCommon/Utils/test/AVSCommon/Utils/MediaPlayer/MockMediaPlayer.h b/AVSCommon/Utils/test/AVSCommon/Utils/MediaPlayer/MockMediaPlayer.h index 5154f3d829..276935afe1 100644 --- a/AVSCommon/Utils/test/AVSCommon/Utils/MediaPlayer/MockMediaPlayer.h +++ b/AVSCommon/Utils/test/AVSCommon/Utils/MediaPlayer/MockMediaPlayer.h @@ -237,6 +237,13 @@ class MockMediaPlayer */ SourceId getCurrentSourceId(); + /** + * Get the current observer. + * + * @return The current observer, or nullptr if there are none. + */ + std::shared_ptr getObserver() const; + private: struct Source; diff --git a/AVSCommon/Utils/test/AVSCommon/Utils/Network/MockInternetConnectionMonitor.h b/AVSCommon/Utils/test/AVSCommon/Utils/Network/MockInternetConnectionMonitor.h new file mode 100644 index 0000000000..391c0d100a --- /dev/null +++ b/AVSCommon/Utils/test/AVSCommon/Utils/Network/MockInternetConnectionMonitor.h @@ -0,0 +1,43 @@ +/* + * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0/ + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +#ifndef ALEXA_CLIENT_SDK_AVSCOMMON_UTILS_TEST_AVSCOMMON_UTILS_NETWORK_INTERNETCONNECTIONMONITOR_H_ +#define ALEXA_CLIENT_SDK_AVSCOMMON_UTILS_TEST_AVSCOMMON_UTILS_NETWORK_INTERNETCONNECTIONMONITOR_H_ + +#include + +namespace alexaClientSDK { +namespace avsCommon { +namespace utils { +namespace network { +namespace test { + +class MockInternetConnectionMonitor : public avsCommon::sdkInterfaces::InternetConnectionMonitorInterface { +public: + MOCK_METHOD1( + addInternetConnectionObserver, + void(std::shared_ptr observer)); + MOCK_METHOD1( + removeInternetConnectionObserver, + void(std::shared_ptr observer)); +}; + +} // namespace test +} // namespace network +} // namespace utils +} // namespace avsCommon +} // namespace alexaClientSDK + +#endif // ALEXA_CLIENT_SDK_AVSCOMMON_UTILS_TEST_AVSCOMMON_UTILS_NETWORK_INTERNETCONNECTIONMONITOR_H_ diff --git a/AVSCommon/Utils/test/AVSCommon/Utils/OptionalTest.cpp b/AVSCommon/Utils/test/AVSCommon/Utils/OptionalTest.cpp new file mode 100644 index 0000000000..a87cac7b44 --- /dev/null +++ b/AVSCommon/Utils/test/AVSCommon/Utils/OptionalTest.cpp @@ -0,0 +1,250 @@ +/* + * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0/ + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +#include + +#include + +#include + +namespace alexaClientSDK { +namespace avsCommon { +namespace utils { + +/** + * Dummy structure used for our tests. + */ +struct Dummy { + /// Dummy structure name used to validate the object content. + std::string m_name; +}; + +/** + * Test structure used to ensure that Optional can be used with types without default constructor. + */ +struct StructWithoutDefaultConstructor { + /// Explicitly delete the default constructor. + StructWithoutDefaultConstructor() = delete; + + /** + * Create default constructor. + */ + StructWithoutDefaultConstructor(const StructWithoutDefaultConstructor& other) = default; + /** + * Create object with the given id. + * + * @param id The id to assign to the new object. + */ + StructWithoutDefaultConstructor(int id); + + /// This object id. + int m_id; +}; + +/** + * Class with static counters for the constructor and the destructor methods. + */ +struct ReferenceCounter { + /// Count the amount of times the constructor has been called. + static size_t s_built; + + /// Count the amount of times the destructor has been called. + static size_t s_destroyed; + + /** + * Empty constructor. + */ + ReferenceCounter(); + + /** + * Copy constructor. + */ + ReferenceCounter(const ReferenceCounter& rhs); + + /** + * Destructor. + */ + ~ReferenceCounter(); +}; + +size_t ReferenceCounter::s_built = 0; +size_t ReferenceCounter::s_destroyed = 0; + +ReferenceCounter::ReferenceCounter() { + s_built++; +} + +ReferenceCounter::ReferenceCounter(const ReferenceCounter& rhs) { + s_built++; +} + +ReferenceCounter::~ReferenceCounter() { + s_destroyed++; +} + +StructWithoutDefaultConstructor::StructWithoutDefaultConstructor(int id) : m_id{id} { +} + +TEST(OptionalTest, test_createEmptyOptional) { + Optional empty; + EXPECT_FALSE(empty.hasValue()); +} + +TEST(OptionalTest, test_createOptionalWithValue) { + Optional dummy{Dummy{}}; + EXPECT_TRUE(dummy.hasValue()); +} + +TEST(OptionalTest, test_getValueOfOptionalWithValue) { + Optional dummy{Dummy{.m_name = "EXPECTED_NAME"}}; + ASSERT_TRUE(dummy.hasValue()); + + auto name = dummy.valueOr(Dummy{.m_name = "OTHER_NAME"}).m_name; + EXPECT_EQ(name, "EXPECTED_NAME"); + + name = dummy.value().m_name; + EXPECT_EQ(name, "EXPECTED_NAME"); +} + +TEST(OptionalTest, test_getValueOfEmptyOptional) { + Optional dummy; + ASSERT_FALSE(dummy.hasValue()); + + auto name = dummy.valueOr(Dummy{.m_name = "OTHER_NAME"}).m_name; + EXPECT_EQ(name, "OTHER_NAME"); + + name = dummy.value().m_name; + EXPECT_EQ(name, std::string()); +} + +TEST(OptionalTest, test_functionWithEmptyOptionalReturn) { + auto function = []() -> Optional { return Optional(); }; + auto empty = function(); + ASSERT_FALSE(empty.hasValue()); +} + +TEST(OptionalTest, test_functionWithNonEmptyOptionalReturn) { + auto function = []() -> Optional { return Optional{Dummy{.m_name = "EXPECTED_NAME"}}; }; + auto dummy = function(); + ASSERT_TRUE(dummy.hasValue()); + ASSERT_EQ(dummy.value().m_name, "EXPECTED_NAME"); +} + +TEST(OptionalTest, test_copyOptionalWithValue) { + Optional dummy1{Dummy{.m_name = "EXPECTED_NAME"}}; + ASSERT_TRUE(dummy1.hasValue()); + + Optional dummy2{dummy1}; + EXPECT_TRUE(dummy2.hasValue()); + EXPECT_EQ(dummy1.value().m_name, dummy2.value().m_name); +} + +TEST(OptionalTest, test_copyEmptyOptional) { + Optional dummy1; + ASSERT_FALSE(dummy1.hasValue()); + + Optional dummy2{dummy1}; + EXPECT_FALSE(dummy2.hasValue()); +} + +TEST(OptionalTest, test_setNewValueForEmptyOptional) { + Dummy dummy{.m_name = "EXPECTED_NAME"}; + Optional optionalDummy; + optionalDummy.set(dummy); + + EXPECT_TRUE(optionalDummy.hasValue()); + EXPECT_EQ(dummy.m_name, optionalDummy.value().m_name); +} + +TEST(OptionalTest, test_setNewValueForNonEmptyOptional) { + Optional optionalDummy{Dummy{.m_name = "OLD_NAME"}}; + ASSERT_TRUE(optionalDummy.hasValue()); + + optionalDummy.set(Dummy{.m_name = "EXPECTED_NAME"}); + + EXPECT_TRUE(optionalDummy.hasValue()); + EXPECT_EQ(optionalDummy.value().m_name, "EXPECTED_NAME"); +} + +TEST(OptionalTest, test_resetEmptyOptional) { + Optional dummy; + ASSERT_FALSE(dummy.hasValue()); + + dummy.reset(); + EXPECT_FALSE(dummy.hasValue()); +} + +TEST(OptionalTest, test_resetNonEmptyOptional) { + Optional optionalDummy{Dummy{.m_name = "OLD_NAME"}}; + ASSERT_TRUE(optionalDummy.hasValue()); + + optionalDummy.reset(); + EXPECT_FALSE(optionalDummy.hasValue()); +} + +TEST(OptionalTest, test_optionalObjectWithoutDefaultConstructor) { + Optional emptyOptional; + EXPECT_FALSE(emptyOptional.hasValue()); + + const int id = 10; + Optional validOptional{StructWithoutDefaultConstructor(id)}; + EXPECT_EQ(validOptional.valueOr(id + 1).m_id, id); +} + +TEST(OptionalTest, test_constructorCallsMatchDestructorCalls) { + { + Optional optional{ReferenceCounter()}; + EXPECT_GT(ReferenceCounter::s_built, ReferenceCounter::s_destroyed); + + optional.set(ReferenceCounter()); + EXPECT_GT(ReferenceCounter::s_built, ReferenceCounter::s_destroyed); + + optional.reset(); + EXPECT_EQ(ReferenceCounter::s_built, ReferenceCounter::s_destroyed); + + optional.set(ReferenceCounter()); + EXPECT_GT(ReferenceCounter::s_built, ReferenceCounter::s_destroyed); + + Optional other{optional}; + EXPECT_GT(ReferenceCounter::s_built, ReferenceCounter::s_destroyed); + } + EXPECT_EQ(ReferenceCounter::s_built, ReferenceCounter::s_destroyed); +} + +TEST(OptionalTest, test_equalityOperator) { + Optional empty; + Optional valid{"valid"}; + Optional other{"other"}; + Optional validCopy{valid}; + + EXPECT_FALSE(empty == valid); + EXPECT_FALSE(valid == other); + EXPECT_EQ(valid, validCopy); +} + +TEST(OptionalTest, test_inequalityOperator) { + Optional empty; + Optional valid{"valid"}; + Optional other{"other"}; + Optional validCopy{valid}; + + EXPECT_NE(empty, valid); + EXPECT_NE(valid, other); + EXPECT_FALSE(valid != validCopy); +} + +} // namespace utils +} // namespace avsCommon +} // namespace alexaClientSDK diff --git a/AVSCommon/Utils/test/Common/MockMediaPlayer.cpp b/AVSCommon/Utils/test/Common/MockMediaPlayer.cpp index 6a238a95b4..edd5a33abc 100644 --- a/AVSCommon/Utils/test/Common/MockMediaPlayer.cpp +++ b/AVSCommon/Utils/test/Common/MockMediaPlayer.cpp @@ -69,6 +69,10 @@ void MockMediaPlayer::setObserver(std::shared_ptr m_playerObserver = playerObserver; } +std::shared_ptr MockMediaPlayer::getObserver() const { + return m_playerObserver; +} + void MockMediaPlayer::doShutdown() { std::lock_guard lock(m_mutex); m_playerObserver.reset(); diff --git a/AVSCommon/Utils/test/ConfigurationNodeTest.cpp b/AVSCommon/Utils/test/ConfigurationNodeTest.cpp index 4d33fcd02e..9ff130127e 100644 --- a/AVSCommon/Utils/test/ConfigurationNodeTest.cpp +++ b/AVSCommon/Utils/test/ConfigurationNodeTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -80,6 +80,9 @@ static const std::string NEW_STRING_VALUE2_1_1 = "new-stringValue2.1.1"; /// Bad JSON string to verify handling the failure to parse JSON static const std::string BAD_JSON = "{ bad json }"; +/// Name of array root level object. +static const std::string ARRAY_OBJECT = "arrayObject"; + /// First JSON string to parse, serving as default for configuration values. // clang-format off static const std::string FIRST_JSON = R"( @@ -124,6 +127,21 @@ static const std::string THIRD_JSON = R"( })"; // clang-format on +/// A JSON string to test array. +// clang-format off +static const std::string ARRAY_JSON = R"( + { + "arrayObject" : [ + { + "object2.1" : "new-stringValue2.1" + }, + { + "object2.1" : "new-stringValue2.1.1" + } + ] + })"; +// clang-format on + /** * Class for testing the ConfigurationNode class */ @@ -133,7 +151,7 @@ class ConfigurationNodeTest : public ::testing::Test {}; * Verify initialization a configuration. Verify both the implementation of accessor methods and the results * of merging JSON streams. */ -TEST_F(ConfigurationNodeTest, testInitializationAndAccess) { +TEST_F(ConfigurationNodeTest, test_initializationAndAccess) { // Verify a null configuration results in failure std::vector> jsonStream; jsonStream.push_back(nullptr); @@ -154,9 +172,12 @@ TEST_F(ConfigurationNodeTest, testInitializationAndAccess) { (*secondStream) << SECOND_JSON; auto thirdStream = std::shared_ptr(new std::stringstream()); (*thirdStream) << THIRD_JSON; + auto arrayStream = std::shared_ptr(new std::stringstream()); + (*arrayStream) << ARRAY_JSON; jsonStream.push_back(firstStream); jsonStream.push_back(secondStream); jsonStream.push_back(thirdStream); + jsonStream.push_back(arrayStream); ASSERT_TRUE(ConfigurationNode::initialize(jsonStream)); jsonStream.clear(); @@ -210,6 +231,33 @@ TEST_F(ConfigurationNodeTest, testInitializationAndAccess) { std::string string211; ASSERT_TRUE(ConfigurationNode::getRoot()[OBJECT2][OBJECT2_1].getString(STRING2_1_1, &string211)); ASSERT_EQ(string211, NEW_STRING_VALUE2_1_1); + + // Verify getting a non-array object with getArray will return an empty Configuration node. + ASSERT_FALSE(ConfigurationNode::getRoot().getArray(OBJECT1)); + + // Verify getting the array size of a non-array object will return zero. + ASSERT_TRUE(0 == ConfigurationNode::getRoot()[OBJECT1].getArraySize()); + + // Verify getting the array from a non-array object will return an empty Configuration node. + ASSERT_FALSE(ConfigurationNode::getRoot()[OBJECT1][1]); + + // Verify getting a array object with getArray will return an valid Configuration node. + auto array = ConfigurationNode::getRoot().getArray(ARRAY_OBJECT); + ASSERT_TRUE(array); + + // Make sure that the array size is 2 + auto arraySize = array.getArraySize(); + ASSERT_TRUE(2U == arraySize); + + // Make sure accessing an array outside range will return an empty Configuration Node. + ASSERT_FALSE(array[arraySize]); + + // Check if we can get the string from the first and second array item + std::string arrayString; + ASSERT_TRUE(array[0].getString(OBJECT2_1, &arrayString)); + ASSERT_EQ(arrayString, NEW_STRING_VALUE2_1); + ASSERT_TRUE(array[1].getString(OBJECT2_1, &arrayString)); + ASSERT_EQ(arrayString, NEW_STRING_VALUE2_1_1); } } // namespace test diff --git a/AVSCommon/Utils/test/ExecutorTest.cpp b/AVSCommon/Utils/test/ExecutorTest.cpp index 2cff25a608..992a800809 100644 --- a/AVSCommon/Utils/test/ExecutorTest.cpp +++ b/AVSCommon/Utils/test/ExecutorTest.cpp @@ -33,39 +33,39 @@ class ExecutorTest : public ::testing::Test { Executor executor; }; -TEST_F(ExecutorTest, submitStdFunctionAndVerifyExecution) { +TEST_F(ExecutorTest, test_submitStdFunctionAndVerifyExecution) { std::function function = []() {}; auto future = executor.submit(function); auto future_status = future.wait_for(SHORT_TIMEOUT_MS); ASSERT_EQ(future_status, std::future_status::ready); } -TEST_F(ExecutorTest, submitStdBindAndVerifyExecution) { +TEST_F(ExecutorTest, test_submitStdBindAndVerifyExecution) { auto future = executor.submit(std::bind(exampleFunctionParams, 0)); auto future_status = future.wait_for(SHORT_TIMEOUT_MS); ASSERT_EQ(future_status, std::future_status::ready); } -TEST_F(ExecutorTest, submitLambdaAndVerifyExecution) { +TEST_F(ExecutorTest, test_submitLambdaAndVerifyExecution) { auto future = executor.submit([]() {}); auto future_status = future.wait_for(SHORT_TIMEOUT_MS); ASSERT_EQ(future_status, std::future_status::ready); } -TEST_F(ExecutorTest, submitFunctionPointerAndVerifyExecution) { +TEST_F(ExecutorTest, test_submitFunctionPointerAndVerifyExecution) { auto future = executor.submit(&exampleFunction); auto future_status = future.wait_for(SHORT_TIMEOUT_MS); ASSERT_EQ(future_status, std::future_status::ready); } -TEST_F(ExecutorTest, submitFunctorAndVerifyExecution) { +TEST_F(ExecutorTest, test_submitFunctorAndVerifyExecution) { ExampleFunctor exampleFunctor; auto future = executor.submit(exampleFunctor); auto future_status = future.wait_for(SHORT_TIMEOUT_MS); ASSERT_EQ(future_status, std::future_status::ready); } -TEST_F(ExecutorTest, submitFunctionWithPrimitiveReturnTypeNoArgsAndVerifyExecution) { +TEST_F(ExecutorTest, test_submitFunctionWithPrimitiveReturnTypeNoArgsAndVerifyExecution) { int value = VALUE; auto future = executor.submit([=]() { return value; }); auto future_status = future.wait_for(SHORT_TIMEOUT_MS); @@ -73,7 +73,7 @@ TEST_F(ExecutorTest, submitFunctionWithPrimitiveReturnTypeNoArgsAndVerifyExecuti ASSERT_EQ(future.get(), value); } -TEST_F(ExecutorTest, submitFunctionWithObjectReturnTypeNoArgsAndVerifyExecution) { +TEST_F(ExecutorTest, test_submitFunctionWithObjectReturnTypeNoArgsAndVerifyExecution) { SimpleObject value(VALUE); auto future = executor.submit([=]() { return value; }); auto future_status = future.wait_for(SHORT_TIMEOUT_MS); @@ -81,21 +81,21 @@ TEST_F(ExecutorTest, submitFunctionWithObjectReturnTypeNoArgsAndVerifyExecution) ASSERT_EQ(future.get().getValue(), value.getValue()); } -TEST_F(ExecutorTest, submitFunctionWithNoReturnTypePrimitiveArgsAndVerifyExecution) { +TEST_F(ExecutorTest, test_submitFunctionWithNoReturnTypePrimitiveArgsAndVerifyExecution) { int value = VALUE; auto future = executor.submit([](int number) {}, value); auto future_status = future.wait_for(SHORT_TIMEOUT_MS); ASSERT_EQ(future_status, std::future_status::ready); } -TEST_F(ExecutorTest, submitFunctionWithNoReturnTypeObjectArgsAndVerifyExecution) { +TEST_F(ExecutorTest, test_submitFunctionWithNoReturnTypeObjectArgsAndVerifyExecution) { SimpleObject arg(0); auto future = executor.submit([](SimpleObject object) {}, arg); auto future_status = future.wait_for(SHORT_TIMEOUT_MS); ASSERT_EQ(future_status, std::future_status::ready); } -TEST_F(ExecutorTest, submitFunctionWithPrimitiveReturnTypeObjectArgsAndVerifyExecution) { +TEST_F(ExecutorTest, test_submitFunctionWithPrimitiveReturnTypeObjectArgsAndVerifyExecution) { int value = VALUE; SimpleObject arg(0); auto future = executor.submit([=](SimpleObject object) { return value; }, arg); @@ -104,7 +104,7 @@ TEST_F(ExecutorTest, submitFunctionWithPrimitiveReturnTypeObjectArgsAndVerifyExe ASSERT_EQ(future.get(), value); } -TEST_F(ExecutorTest, submitFunctionWithObjectReturnTypePrimitiveArgsAndVerifyExecution) { +TEST_F(ExecutorTest, test_submitFunctionWithObjectReturnTypePrimitiveArgsAndVerifyExecution) { int arg = 0; SimpleObject value(VALUE); auto future = executor.submit([=](int primitive) { return value; }, arg); @@ -113,7 +113,7 @@ TEST_F(ExecutorTest, submitFunctionWithObjectReturnTypePrimitiveArgsAndVerifyExe ASSERT_EQ(future.get().getValue(), value.getValue()); } -TEST_F(ExecutorTest, submitFunctionWithPrimitiveReturnTypePrimitiveArgsAndVerifyExecution) { +TEST_F(ExecutorTest, test_submitFunctionWithPrimitiveReturnTypePrimitiveArgsAndVerifyExecution) { int arg = 0; int value = VALUE; auto future = executor.submit([=](int number) { return value; }, arg); @@ -122,7 +122,7 @@ TEST_F(ExecutorTest, submitFunctionWithPrimitiveReturnTypePrimitiveArgsAndVerify ASSERT_EQ(future.get(), value); } -TEST_F(ExecutorTest, submitFunctionWithObjectReturnTypeObjectArgsAndVerifyExecution) { +TEST_F(ExecutorTest, test_submitFunctionWithObjectReturnTypeObjectArgsAndVerifyExecution) { SimpleObject value(VALUE); SimpleObject arg(0); auto future = executor.submit([=](SimpleObject object) { return value; }, arg); @@ -131,7 +131,7 @@ TEST_F(ExecutorTest, submitFunctionWithObjectReturnTypeObjectArgsAndVerifyExecut ASSERT_EQ(future.get().getValue(), value.getValue()); } -TEST_F(ExecutorTest, submitToFront) { +TEST_F(ExecutorTest, test_submitToFront) { std::atomic ready(false); std::atomic blocked(false); std::list order; @@ -170,7 +170,7 @@ TEST_F(ExecutorTest, submitToFront) { ASSERT_EQ(order.back(), 2); } -TEST_F(ExecutorTest, testExecutionOrderEqualToSubmitOrder) { +TEST_F(ExecutorTest, test_executionOrderEqualToSubmitOrder) { WaitEvent waitSetUp; executor.submit([&waitSetUp] { waitSetUp.wait(SHORT_TIMEOUT_MS); }); @@ -220,7 +220,7 @@ struct SlowDestructor { }; /// This test verifies that the executor waits to fulfill its promise until after the task is cleaned up. -TEST_F(ExecutorTest, futureWaitsForTaskCleanup) { +TEST_F(ExecutorTest, test_futureWaitsForTaskCleanup) { std::atomic cleanedUp(false); SlowDestructor slowDestructor; @@ -239,7 +239,7 @@ TEST_F(ExecutorTest, futureWaitsForTaskCleanup) { } /// This test verifies that the shutdown function completes the current task and does not accept new tasks. -TEST_F(ExecutorTest, shutdown) { +TEST_F(ExecutorTest, test_shutdown) { std::atomic ready(false); std::atomic blocked(false); @@ -275,7 +275,7 @@ TEST_F(ExecutorTest, shutdown) { } /// Test that calling submit after shutdown will fail the job. -TEST_F(ExecutorTest, testPushAfterExecutordownFail) { +TEST_F(ExecutorTest, test_pushAfterExecutordownFail) { executor.shutdown(); ASSERT_TRUE(executor.isShutdown()); @@ -284,7 +284,7 @@ TEST_F(ExecutorTest, testPushAfterExecutordownFail) { } /// Test that shutdown cancel jobs in the queue. -TEST_F(ExecutorTest, testShutdownCancelJob) { +TEST_F(ExecutorTest, test_shutdownCancelJob) { bool executed = false; WaitEvent waitSetUp, waitJobStart; std::future jobToDropResult; diff --git a/AVSCommon/Utils/test/HTTPContentTest.cpp b/AVSCommon/Utils/test/HTTPContentTest.cpp index 5d28d87668..da8a1a6ec8 100644 --- a/AVSCommon/Utils/test/HTTPContentTest.cpp +++ b/AVSCommon/Utils/test/HTTPContentTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -70,7 +70,7 @@ void HTTPContentTest::SetUp() { } /// Test that isStatusCodeSuccess returns true for @c SUCCESS_STATUS_CODE. -TEST_F(HTTPContentTest, readStatusCodeSuccess) { +TEST_F(HTTPContentTest, test_readStatusCodeSuccess) { m_statusCodePromise.set_value(SUCCESS_STATUS_CODE); m_contentTypePromise.set_value(TEST_CONTENT_TYPE); @@ -78,7 +78,7 @@ TEST_F(HTTPContentTest, readStatusCodeSuccess) { } /// Test that isStatusCodeSuccess returns true for @c SUCCESS_PARTIAL_CONTENT_STATUS_CODE. -TEST_F(HTTPContentTest, readStatusCodePartialContentSuccess) { +TEST_F(HTTPContentTest, test_readStatusCodePartialContentSuccess) { m_statusCodePromise.set_value(SUCCESS_PARTIAL_CONTENT_STATUS_CODE); m_contentTypePromise.set_value(TEST_CONTENT_TYPE); @@ -86,7 +86,7 @@ TEST_F(HTTPContentTest, readStatusCodePartialContentSuccess) { } /// Test that isStatusCodeSuccess returns false for @c BAD_STATUS_CODE. -TEST_F(HTTPContentTest, readStatusCodeNotSuccess) { +TEST_F(HTTPContentTest, test_readStatusCodeNotSuccess) { m_statusCodePromise.set_value(BAD_STATUS_CODE); m_contentTypePromise.set_value(TEST_CONTENT_TYPE); @@ -94,7 +94,7 @@ TEST_F(HTTPContentTest, readStatusCodeNotSuccess) { } /// Test that we can use @c getStatusCode() to get the status code after using @c isStatusCodeSuccess(). -TEST_F(HTTPContentTest, readStatusCodeMoreThanOnce) { +TEST_F(HTTPContentTest, test_readStatusCodeMoreThanOnce) { m_statusCodePromise.set_value(BAD_STATUS_CODE); m_contentTypePromise.set_value(TEST_CONTENT_TYPE); @@ -104,7 +104,7 @@ TEST_F(HTTPContentTest, readStatusCodeMoreThanOnce) { } /// Test that we can use @c getContentType() to get the status code after using @c isStatusCodeSuccess(). -TEST_F(HTTPContentTest, readContentTypeMoreThanOnce) { +TEST_F(HTTPContentTest, test_readContentTypeMoreThanOnce) { m_statusCodePromise.set_value(BAD_STATUS_CODE); m_contentTypePromise.set_value(TEST_CONTENT_TYPE); @@ -113,7 +113,7 @@ TEST_F(HTTPContentTest, readContentTypeMoreThanOnce) { } /// Test that we can retrieve the attachment reader, even if it's nullptr. -TEST_F(HTTPContentTest, getDataStream) { +TEST_F(HTTPContentTest, test_getDataStream) { EXPECT_EQ(m_httpContent->getDataStream(), nullptr); } diff --git a/AVSCommon/Utils/test/JSONGeneratorTest.cpp b/AVSCommon/Utils/test/JSONGeneratorTest.cpp index ae50df5b92..ebfa2de1d5 100644 --- a/AVSCommon/Utils/test/JSONGeneratorTest.cpp +++ b/AVSCommon/Utils/test/JSONGeneratorTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -32,12 +32,12 @@ class JsonGeneratorTest : public Test { }; /// Test json generator when no member is given. -TEST_F(JsonGeneratorTest, testEmptyJson) { +TEST_F(JsonGeneratorTest, test_emptyJson) { EXPECT_EQ(m_generator.toString(), "{}"); } /// Test json generator object creation. -TEST_F(JsonGeneratorTest, testJsonObject) { +TEST_F(JsonGeneratorTest, test_jsonObject) { EXPECT_TRUE(m_generator.startObject("key")); EXPECT_TRUE(m_generator.finishObject()); @@ -46,7 +46,7 @@ TEST_F(JsonGeneratorTest, testJsonObject) { } /// Test json generator int creation. -TEST_F(JsonGeneratorTest, testJsonInt) { +TEST_F(JsonGeneratorTest, test_jsonInt) { int value = std::numeric_limits::max(); EXPECT_TRUE(m_generator.addMember("member", value)); @@ -55,7 +55,7 @@ TEST_F(JsonGeneratorTest, testJsonInt) { } /// Test json generator long creation. -TEST_F(JsonGeneratorTest, testJsonLong) { +TEST_F(JsonGeneratorTest, test_jsonLong) { int64_t value = std::numeric_limits::max(); EXPECT_TRUE(m_generator.addMember("member", value)); @@ -64,7 +64,7 @@ TEST_F(JsonGeneratorTest, testJsonLong) { } /// Test json generator long creation. -TEST_F(JsonGeneratorTest, testJsonUInt) { +TEST_F(JsonGeneratorTest, test_jsonUInt) { unsigned int value = std::numeric_limits::max(); EXPECT_TRUE(m_generator.addMember("member", value)); @@ -73,7 +73,7 @@ TEST_F(JsonGeneratorTest, testJsonUInt) { } /// Test json generator long creation. -TEST_F(JsonGeneratorTest, testJsonULong) { +TEST_F(JsonGeneratorTest, test_jsonULong) { uint64_t value = std::numeric_limits::max(); EXPECT_TRUE(m_generator.addMember("member", value)); @@ -82,7 +82,7 @@ TEST_F(JsonGeneratorTest, testJsonULong) { } /// Test json generator boolean creation. -TEST_F(JsonGeneratorTest, testJsonBool) { +TEST_F(JsonGeneratorTest, test_jsonBool) { bool value = true; EXPECT_TRUE(m_generator.addMember("member", value)); @@ -91,7 +91,7 @@ TEST_F(JsonGeneratorTest, testJsonBool) { } /// Test json generator char creation. -TEST_F(JsonGeneratorTest, testJsonCString) { +TEST_F(JsonGeneratorTest, test_jsonCString) { EXPECT_TRUE(m_generator.addMember("member", "value")); auto expected = R"({"member":"value"})"; @@ -99,7 +99,7 @@ TEST_F(JsonGeneratorTest, testJsonCString) { } /// Test json generator char creation. -TEST_F(JsonGeneratorTest, testJsonNullCString) { +TEST_F(JsonGeneratorTest, test_jsonNullCString) { EXPECT_FALSE(m_generator.addMember("member", nullptr)); auto expected = R"({})"; @@ -107,7 +107,7 @@ TEST_F(JsonGeneratorTest, testJsonNullCString) { } /// Test json raw creation. -TEST_F(JsonGeneratorTest, testJsonRawJsonMember) { +TEST_F(JsonGeneratorTest, test_jsonRawJsonMember) { EXPECT_TRUE(m_generator.addRawJsonMember("member1", R"({"member11":"value11"})")); EXPECT_TRUE(m_generator.addMember("member2", "value2")); @@ -116,7 +116,7 @@ TEST_F(JsonGeneratorTest, testJsonRawJsonMember) { } /// Test json raw validation. -TEST_F(JsonGeneratorTest, testJsonRawJsonMemberFailed) { +TEST_F(JsonGeneratorTest, test_jsonRawJsonMemberFailed) { EXPECT_FALSE(m_generator.addRawJsonMember("member1", R"(invalid)")); EXPECT_TRUE(m_generator.addMember("member2", "value2")); @@ -125,13 +125,13 @@ TEST_F(JsonGeneratorTest, testJsonRawJsonMemberFailed) { } /// Test close when there is no open object. -TEST_F(JsonGeneratorTest, testCloseTooMany) { +TEST_F(JsonGeneratorTest, test_closeTooMany) { EXPECT_TRUE(m_generator.finishObject()); EXPECT_FALSE(m_generator.finishObject()); } /// Test to string with open objects. -TEST_F(JsonGeneratorTest, testOpenObjects) { +TEST_F(JsonGeneratorTest, test_openObjects) { EXPECT_TRUE(m_generator.startObject("key")); auto expected = R"({"key":{)"; @@ -139,7 +139,7 @@ TEST_F(JsonGeneratorTest, testOpenObjects) { } /// Test finalize open objects. -TEST_F(JsonGeneratorTest, testFinalizeObjects) { +TEST_F(JsonGeneratorTest, test_finalizeObjects) { EXPECT_TRUE(m_generator.startObject("key1")); EXPECT_TRUE(m_generator.startObject("key2")); @@ -148,7 +148,7 @@ TEST_F(JsonGeneratorTest, testFinalizeObjects) { } /// Test operations after finalize. -TEST_F(JsonGeneratorTest, testAddMemberAfterFinalize) { +TEST_F(JsonGeneratorTest, test_addMemberAfterFinalize) { EXPECT_EQ(m_generator.toString(), "{}"); EXPECT_EQ(m_generator.toString(), "{}"); ASSERT_TRUE(m_generator.isFinalized()); diff --git a/AVSCommon/Utils/test/JSONUtilTest.cpp b/AVSCommon/Utils/test/JSONUtilTest.cpp index 7335d4809f..5b4898a684 100644 --- a/AVSCommon/Utils/test/JSONUtilTest.cpp +++ b/AVSCommon/Utils/test/JSONUtilTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -133,7 +133,7 @@ class JSONUtilTest : public ::testing::Test {}; * Tests retrieveValue(const std::string jsonString, const std::string& key, T* value) * with T = std::string for getting child object as a string. */ -TEST_F(JSONUtilTest, validJsonChildObjectAsString) { +TEST_F(JSONUtilTest, test_validJsonChildObjectAsString) { std::string value; ASSERT_TRUE(jsonUtils::retrieveValue(EMPTY_DIRECTIVE, DIRECTIVE_KEY, &value)); ASSERT_EQ(value, STRING_VALUE_EMPTY_JSON_OBJECT); @@ -143,7 +143,7 @@ TEST_F(JSONUtilTest, validJsonChildObjectAsString) { * Tests retrieveValue(const std::string jsonString, const std::string& key, T* value) * with T = std::string for getting value of a scalar string. */ -TEST_F(JSONUtilTest, validJsonScalarString) { +TEST_F(JSONUtilTest, test_validJsonScalarString) { std::string value; ASSERT_TRUE(jsonUtils::retrieveValue(VALID_JSON_STRING_VALUE, VALUE_KEY, &value)); ASSERT_EQ(value, EXPECTED_STRING_VALUE); @@ -153,7 +153,7 @@ TEST_F(JSONUtilTest, validJsonScalarString) { * Tests retrieveValue(const std::string jsonString, const std::string& key, T* value) * with T = int64 for getting an integer value. */ -TEST_F(JSONUtilTest, validJsonInteger) { +TEST_F(JSONUtilTest, test_validJsonInteger) { int64_t value = OUTPUT_DEFAULT_INT_VALUE; ASSERT_TRUE(jsonUtils::retrieveValue(VALID_JSON_INTEGER_VALUE, VALUE_KEY, &value)); ASSERT_EQ(value, EXPECTED_INT_VALUE); @@ -163,7 +163,7 @@ TEST_F(JSONUtilTest, validJsonInteger) { * Tests retrieveValue(const std::string jsonString, const std::string& key, T* value) * with T = int64 and an invalid JSON. Returns false. */ -TEST_F(JSONUtilTest, retrieveValueStringBasedInt64FromInvalidJSON) { +TEST_F(JSONUtilTest, test_retrieveValueStringBasedInt64FromInvalidJSON) { int64_t value = OUTPUT_DEFAULT_INT_VALUE; ASSERT_FALSE(retrieveValue(INVALID_JSON, VALUE_KEY, &value)); ASSERT_EQ(value, OUTPUT_DEFAULT_INT_VALUE); @@ -173,7 +173,7 @@ TEST_F(JSONUtilTest, retrieveValueStringBasedInt64FromInvalidJSON) { * Tests retrieveValue(const std::string jsonString, const std::string& key, T* value) * with T = std::string and an invalid JSON. Returns false. */ -TEST_F(JSONUtilTest, retrieveValueStringBasedStringFromInvalidJSON) { +TEST_F(JSONUtilTest, test_retrieveValueStringBasedStringFromInvalidJSON) { std::string value = OUTPUT_DEFAULT_TEXT_STRING; ASSERT_FALSE(retrieveValue(INVALID_JSON, VALUE_KEY, &value)); ASSERT_EQ(value, OUTPUT_DEFAULT_TEXT_STRING); @@ -183,7 +183,7 @@ TEST_F(JSONUtilTest, retrieveValueStringBasedStringFromInvalidJSON) { * Tests retrieveValue(const std::string jsonString, const std::string& key, T* value) * with T = int64 and an incorrect key. Returns false. */ -TEST_F(JSONUtilTest, retrieveValueStringBasedWithIncorrectKey) { +TEST_F(JSONUtilTest, test_retrieveValueStringBasedWithIncorrectKey) { int64_t value = OUTPUT_DEFAULT_INT_VALUE; ASSERT_FALSE(retrieveValue(VALID_JSON_INTEGER_VALUE, MISSING_KEY, &value)); ASSERT_EQ(value, OUTPUT_DEFAULT_INT_VALUE); @@ -193,7 +193,7 @@ TEST_F(JSONUtilTest, retrieveValueStringBasedWithIncorrectKey) { * Tests retrieveValue(const std::string jsonString, const std::string& key, T* value) * with T = int64 and a null output param. Returns false. */ -TEST_F(JSONUtilTest, retrieveValueStringBasedWithNull) { +TEST_F(JSONUtilTest, test_retrieveValueStringBasedWithNull) { int64_t* value = nullptr; ASSERT_FALSE(retrieveValue(VALID_JSON_INTEGER_VALUE, VALUE_KEY, value)); } @@ -202,7 +202,7 @@ TEST_F(JSONUtilTest, retrieveValueStringBasedWithNull) { * Tests retrieveValue(const rapidjson::Value& jsonNode, const std::string& key, T* value) * with T = int64 and a value of invalid type. Returns false. */ -TEST_F(JSONUtilTest, retrieveValueDocumentBasedWithInvalidValueType) { +TEST_F(JSONUtilTest, test_retrieveValueDocumentBasedWithInvalidValueType) { Document doc; doc.Parse(VALID_JSON_STRING_VALUE); int64_t value; @@ -213,7 +213,7 @@ TEST_F(JSONUtilTest, retrieveValueDocumentBasedWithInvalidValueType) { * Tests retrieveValue(const rapidjson::Value& jsonNode, const std::string& key, T* value) * with T = int64 and a null output param. Returns false. */ -TEST_F(JSONUtilTest, retrieveValueDocumentBasedWithNull) { +TEST_F(JSONUtilTest, test_retrieveValueDocumentBasedWithNull) { Document doc; doc.Parse(VALID_JSON_INTEGER_VALUE); int64_t* value = nullptr; @@ -224,7 +224,7 @@ TEST_F(JSONUtilTest, retrieveValueDocumentBasedWithNull) { * Tests retrieveValue(const rapidjson::Value& jsonNode, const std::string& key, T* value) * with T = int64 and a valid value. Returns true and obtains the correct value. */ -TEST_F(JSONUtilTest, retrieveValueDocumentBasedWithValidInt64) { +TEST_F(JSONUtilTest, test_retrieveValueDocumentBasedWithValidInt64) { Document doc; doc.Parse(VALID_JSON_INTEGER_VALUE); int64_t value; @@ -235,7 +235,7 @@ TEST_F(JSONUtilTest, retrieveValueDocumentBasedWithValidInt64) { /** * Tests findNode with a Null output param. Returns false. */ -TEST_F(JSONUtilTest, findNodeNull) { +TEST_F(JSONUtilTest, test_findNodeNull) { Document doc; doc.Parse(SPEAK_DIRECTIVE); ASSERT_FALSE(findNode(doc, JSON_MESSAGE_HEADER_STRING, nullptr)); @@ -244,7 +244,7 @@ TEST_F(JSONUtilTest, findNodeNull) { /** * Tests findNode with a valid key. Returns true with iterator != MemberEnd(). */ -TEST_F(JSONUtilTest, findNodeKeyExists) { +TEST_F(JSONUtilTest, test_findNodeKeyExists) { Document doc; doc.Parse(SPEAK_DIRECTIVE); Value::ConstMemberIterator iterator; @@ -255,7 +255,7 @@ TEST_F(JSONUtilTest, findNodeKeyExists) { /** * Tests findNode with a non-existent key. Returns false. */ -TEST_F(JSONUtilTest, findNodeKeyMissing) { +TEST_F(JSONUtilTest, test_findNodeKeyMissing) { Document doc; doc.Parse(SPEAK_DIRECTIVE); Value::ConstMemberIterator iterator; @@ -265,14 +265,14 @@ TEST_F(JSONUtilTest, findNodeKeyMissing) { /** * Tests parseJSON with a null output param. Returns false. */ -TEST_F(JSONUtilTest, parseJSONNullOutputParam) { +TEST_F(JSONUtilTest, test_parseJSONNullOutputParam) { ASSERT_FALSE(parseJSON(SPEAK_DIRECTIVE, nullptr)); } /** * Tests parseJSON with a valid json. Returns true. */ -TEST_F(JSONUtilTest, parseJSONValidJSON) { +TEST_F(JSONUtilTest, test_parseJSONValidJSON) { Document doc; ASSERT_TRUE(parseJSON(SPEAK_DIRECTIVE, &doc)); ASSERT_FALSE(doc.HasParseError()); @@ -281,7 +281,7 @@ TEST_F(JSONUtilTest, parseJSONValidJSON) { /** * Tests parseJSON with an invalid json. Returns false. */ -TEST_F(JSONUtilTest, parseJSONInvalidJSON) { +TEST_F(JSONUtilTest, test_parseJSONInvalidJSON) { Document doc; ASSERT_FALSE(parseJSON(INVALID_JSON, &doc)); ASSERT_TRUE(doc.HasParseError()); @@ -291,7 +291,7 @@ TEST_F(JSONUtilTest, parseJSONInvalidJSON) { * Tests convertToValue with Value of rapidjson::Type::kStringType. Returns * true and contains the correct value. */ -TEST_F(JSONUtilTest, convertToStringValueWithString) { +TEST_F(JSONUtilTest, test_convertToStringValueWithString) { rapidjson::Value expected; expected.SetString(STRING_VALUE.c_str(), STRING_VALUE.length()); std::string actual; @@ -303,7 +303,7 @@ TEST_F(JSONUtilTest, convertToStringValueWithString) { * Tests convertToValue with Value of rapidjson::Type::kObjectType. * Returns true and contains the correct value. */ -TEST_F(JSONUtilTest, convertToStringValueWithObject) { +TEST_F(JSONUtilTest, test_convertToStringValueWithObject) { rapidjson::Value emptyObject(kObjectType); std::string actual; ASSERT_TRUE(convertToValue(emptyObject, &actual)); @@ -314,7 +314,7 @@ TEST_F(JSONUtilTest, convertToStringValueWithObject) { * Tests convertToValue with and invalid Value of rapidjson::Type::kNullType. * Returns false. */ -TEST_F(JSONUtilTest, convertToStringValueWithInvalidValue) { +TEST_F(JSONUtilTest, test_convertToStringValueWithInvalidValue) { rapidjson::Value nullValue(kNullType); std::string value; ASSERT_FALSE(convertToValue(nullValue, &value)); @@ -324,7 +324,7 @@ TEST_F(JSONUtilTest, convertToStringValueWithInvalidValue) { * Tests convertToValue with null output param. * Returns false. */ -TEST_F(JSONUtilTest, convertToStringValueWithNullOutputParam) { +TEST_F(JSONUtilTest, test_convertToStringValueWithNullOutputParam) { rapidjson::Value node; node.SetString(STRING_VALUE.c_str(), STRING_VALUE.length()); std::string* value = nullptr; @@ -334,7 +334,7 @@ TEST_F(JSONUtilTest, convertToStringValueWithNullOutputParam) { /** * Tests convertToValue with valid int64_6. Returns true and contains the correct value. */ -TEST_F(JSONUtilTest, convertToInt64ValueWithInt64) { +TEST_F(JSONUtilTest, test_convertToInt64ValueWithInt64) { rapidjson::Value expected(EXPECTED_INT_VALUE); int64_t actual; ASSERT_TRUE(convertToValue(expected, &actual)); @@ -344,7 +344,7 @@ TEST_F(JSONUtilTest, convertToInt64ValueWithInt64) { /** * Tests convertToValue with double. Returns false. */ -TEST_F(JSONUtilTest, convertToInt64ValueWithDouble) { +TEST_F(JSONUtilTest, test_convertToInt64ValueWithDouble) { rapidjson::Value expected(A_DOUBLE); int64_t actual; ASSERT_FALSE(convertToValue(expected, &actual)); @@ -354,7 +354,7 @@ TEST_F(JSONUtilTest, convertToInt64ValueWithDouble) { * Tests convertToValue with null output param. * Returns false. */ -TEST_F(JSONUtilTest, convertToUint64ValueWithNullOutputParam) { +TEST_F(JSONUtilTest, test_convertToUint64ValueWithNullOutputParam) { rapidjson::Value node(EXPECTED_UNSIGNED_INT64_VALUE); uint64_t* value = nullptr; ASSERT_FALSE(convertToValue(node, value)); @@ -363,7 +363,7 @@ TEST_F(JSONUtilTest, convertToUint64ValueWithNullOutputParam) { /** * Tests convertToValue with valid uint64_t. Returns true and contains the correct value. */ -TEST_F(JSONUtilTest, convertToUint64ValueWithUint64) { +TEST_F(JSONUtilTest, test_convertToUint64ValueWithUint64) { rapidjson::Value expected(EXPECTED_UNSIGNED_INT64_VALUE); uint64_t actual; ASSERT_TRUE(convertToValue(expected, &actual)); @@ -373,7 +373,7 @@ TEST_F(JSONUtilTest, convertToUint64ValueWithUint64) { /** * Tests convertToValue with double. Returns false. */ -TEST_F(JSONUtilTest, convertToUint64ValueWithDouble) { +TEST_F(JSONUtilTest, test_convertToUint64ValueWithDouble) { rapidjson::Value expected(A_DOUBLE); uint64_t actual; ASSERT_FALSE(convertToValue(expected, &actual)); @@ -383,7 +383,7 @@ TEST_F(JSONUtilTest, convertToUint64ValueWithDouble) { * Tests convertToValue with null output param. * Returns false. */ -TEST_F(JSONUtilTest, convertToInt64ValueWithNullOutputParam) { +TEST_F(JSONUtilTest, test_convertToInt64ValueWithNullOutputParam) { rapidjson::Value node(EXPECTED_INT_VALUE); int64_t* value = nullptr; ASSERT_FALSE(convertToValue(node, value)); @@ -393,7 +393,7 @@ TEST_F(JSONUtilTest, convertToInt64ValueWithNullOutputParam) { * Tests convertToValue with null output param. * Returns false. */ -TEST_F(JSONUtilTest, convertToBoolValueWithNullOutputParam) { +TEST_F(JSONUtilTest, test_convertToBoolValueWithNullOutputParam) { rapidjson::Value node(A_BOOL); bool* value = nullptr; ASSERT_FALSE(convertToValue(node, value)); @@ -402,7 +402,7 @@ TEST_F(JSONUtilTest, convertToBoolValueWithNullOutputParam) { /** * Tests convertToValue with a nonbool. Returns false. */ -TEST_F(JSONUtilTest, convertToBoolValueWithNonBool) { +TEST_F(JSONUtilTest, test_convertToBoolValueWithNonBool) { rapidjson::Value expected(A_DOUBLE); bool actual; ASSERT_FALSE(convertToValue(expected, &actual)); @@ -411,7 +411,7 @@ TEST_F(JSONUtilTest, convertToBoolValueWithNonBool) { /** * Tests convertToValue with valid bool. Returns true and contains the correct value. */ -TEST_F(JSONUtilTest, convertToBoolValueWithBool) { +TEST_F(JSONUtilTest, test_convertToBoolValueWithBool) { rapidjson::Value expected(A_BOOL); bool actual; ASSERT_TRUE(convertToValue(expected, &actual)); diff --git a/AVSCommon/Utils/test/LogEntryStreamTest.cpp b/AVSCommon/Utils/test/LogEntryStreamTest.cpp index 36d71d62ed..c84f5e76c7 100644 --- a/AVSCommon/Utils/test/LogEntryStreamTest.cpp +++ b/AVSCommon/Utils/test/LogEntryStreamTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -35,13 +35,13 @@ class LogEntryStreamTest : public ::testing::Test { }; /// Test that a new LogEntryStream instance's c_str() returns an empty string. -TEST_F(LogEntryStreamTest, emptyStream) { +TEST_F(LogEntryStreamTest, test_emptyStream) { ASSERT_NE(m_stream.c_str(), nullptr); ASSERT_EQ(strlen(m_stream.c_str()), 0u); } /// Send a character to an empty LogEntryStream. Expect that c_str() returns a string with just that character. -TEST_F(LogEntryStreamTest, shortString) { +TEST_F(LogEntryStreamTest, test_shortString) { const char SOME_CHAR = 'x'; m_stream << SOME_CHAR; ASSERT_EQ(SOME_CHAR, m_stream.c_str()[0]); @@ -49,7 +49,7 @@ TEST_F(LogEntryStreamTest, shortString) { } /// Send a medium sized string test to an empty LogEntryStream. Expect that c_str() returns a matching string. -TEST_F(LogEntryStreamTest, mediumString) { +TEST_F(LogEntryStreamTest, test_mediumString) { const std::string MEDIUM_STRING = "Hello World!"; m_stream << MEDIUM_STRING; ASSERT_EQ(MEDIUM_STRING, m_stream.c_str()); @@ -57,7 +57,7 @@ TEST_F(LogEntryStreamTest, mediumString) { } /// Send a long string test to an empty LogEntryStream. Expect that c_str() returns a matching string. -TEST_F(LogEntryStreamTest, longString) { +TEST_F(LogEntryStreamTest, test_longString) { std::string longString; for (int ix = 0; ix < 100; ix++) { longString += "The quick brown fox jumped over the lazy dog."; @@ -68,7 +68,7 @@ TEST_F(LogEntryStreamTest, longString) { } /// Send a few short strings. Expect that c_str() returns the concatenation of those strings. -TEST_F(LogEntryStreamTest, aFewStrings) { +TEST_F(LogEntryStreamTest, test_aFewStrings) { const std::string SHORT_STRING_1 = "abc"; m_stream << SHORT_STRING_1; const std::string SHORT_STRING_2 = "xyz"; @@ -81,7 +81,7 @@ TEST_F(LogEntryStreamTest, aFewStrings) { } /// Send a bunch of ints and strings. Expect that c_str() matches the result of sending the same to ostringstream. -TEST_F(LogEntryStreamTest, aLotOfStrings) { +TEST_F(LogEntryStreamTest, test_aLotOfStrings) { std::ostringstream expected; const std::string MEDIUM_STRING = "Half a bee, philosophically\nMust, ipso facto, half not be."; for (int ix = 0; ix < 100; ix++) { diff --git a/AVSCommon/Utils/test/LoggerTest.cpp b/AVSCommon/Utils/test/LoggerTest.cpp index cd1b7b8a83..8e430a0a3e 100644 --- a/AVSCommon/Utils/test/LoggerTest.cpp +++ b/AVSCommon/Utils/test/LoggerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -338,7 +338,7 @@ void LoggerTest::exerciseLevels() { * Test delivery of log messages when the log level is set to DEBUG9. This test sets the log level to DEBUG9 * and then verifies that all logs (except those compiled off) are passed through to the emit() method. */ -TEST_F(LoggerTest, logDebug9Level) { +TEST_F(LoggerTest, test_logDebug9Level) { setLevelExpectations(Level::DEBUG9); exerciseLevels(); } @@ -347,7 +347,7 @@ TEST_F(LoggerTest, logDebug9Level) { * Test delivery of log messages when the log level is set to DEBUG8. This test sets the log level to DEBUG8 * and then verifies that all logs (except those compiled off) are passed through to the emit() method. */ -TEST_F(LoggerTest, logDebug8Level) { +TEST_F(LoggerTest, test_logDebug8Level) { setLevelExpectations(Level::DEBUG8); exerciseLevels(); } @@ -356,7 +356,7 @@ TEST_F(LoggerTest, logDebug8Level) { * Test delivery of log messages when the log level is set to DEBUG7. This test sets the log level to DEBUG7 * and then verifies that all logs (except those compiled off) are passed through to the emit() method. */ -TEST_F(LoggerTest, logDebug7Level) { +TEST_F(LoggerTest, test_logDebug7Level) { setLevelExpectations(Level::DEBUG7); exerciseLevels(); } @@ -365,7 +365,7 @@ TEST_F(LoggerTest, logDebug7Level) { * Test delivery of log messages when the log level is set to DEBUG6. This test sets the log level to DEBUG6 * and then verifies that all logs (except those compiled off) are passed through to the emit() method. */ -TEST_F(LoggerTest, logDebug6Level) { +TEST_F(LoggerTest, test_logDebug6Level) { setLevelExpectations(Level::DEBUG6); exerciseLevels(); } @@ -374,7 +374,7 @@ TEST_F(LoggerTest, logDebug6Level) { * Test delivery of log messages when the log level is set to DEBUG5. This test sets the log level to DEBUG5 * and then verifies that all logs (except those compiled off) are passed through to the emit() method. */ -TEST_F(LoggerTest, logDebug5Level) { +TEST_F(LoggerTest, test_logDebug5Level) { setLevelExpectations(Level::DEBUG5); exerciseLevels(); } @@ -383,7 +383,7 @@ TEST_F(LoggerTest, logDebug5Level) { * Test delivery of log messages when the log level is set to DEBUG4. This test sets the log level to DEBUG4 * and then verifies that all logs (except those compiled off) are passed through to the emit() method. */ -TEST_F(LoggerTest, logDebug4Level) { +TEST_F(LoggerTest, test_logDebug4Level) { setLevelExpectations(Level::DEBUG4); exerciseLevels(); } @@ -392,7 +392,7 @@ TEST_F(LoggerTest, logDebug4Level) { * Test delivery of log messages when the log level is set to DEBUG3. This test sets the log level to DEBUG3 * and then verifies that all logs (except those compiled off) are passed through to the emit() method. */ -TEST_F(LoggerTest, logDebug3Level) { +TEST_F(LoggerTest, test_logDebug3Level) { setLevelExpectations(Level::DEBUG3); exerciseLevels(); } @@ -401,7 +401,7 @@ TEST_F(LoggerTest, logDebug3Level) { * Test delivery of log messages when the log level is set to DEBUG2. This test sets the log level to DEBUG2 * and then verifies that all logs (except those compiled off) are passed through to the emit() method. */ -TEST_F(LoggerTest, logDebug2Level) { +TEST_F(LoggerTest, test_logDebug2Level) { setLevelExpectations(Level::DEBUG2); exerciseLevels(); } @@ -410,7 +410,7 @@ TEST_F(LoggerTest, logDebug2Level) { * Test delivery of log messages when the log level is set to DEBUG1. This test sets the log level to DEBUG1 * and then verifies that only logs of DEBUG or above are passed through to the emit() method. */ -TEST_F(LoggerTest, logDebug1Level) { +TEST_F(LoggerTest, test_logDebug1Level) { setLevelExpectations(Level::DEBUG1); exerciseLevels(); } @@ -419,7 +419,7 @@ TEST_F(LoggerTest, logDebug1Level) { * Test delivery of log messages when the log level is set to DEBUG1. This test sets the log level to DEBUG0 * and then verifies that only logs of DEBUG or above are passed through to the emit() method. */ -TEST_F(LoggerTest, logDebug0Level) { +TEST_F(LoggerTest, test_logDebug0Level) { setLevelExpectations(Level::DEBUG0); exerciseLevels(); } @@ -428,7 +428,7 @@ TEST_F(LoggerTest, logDebug0Level) { * Test delivery of log messages when the log level is set to INFO. This test sets the log level to INFO * and then verifies that only logs of INFO or above are passed through to the emit() method. */ -TEST_F(LoggerTest, logInfoLevel) { +TEST_F(LoggerTest, test_logInfoLevel) { setLevelExpectations(Level::INFO); exerciseLevels(); } @@ -437,7 +437,7 @@ TEST_F(LoggerTest, logInfoLevel) { * Test delivery of log messages when the log level is set to WARN. This test sets the log level to WARN * and then verifies that only logs of WARN or above are passed through to the emit() method. */ -TEST_F(LoggerTest, logWarnLevel) { +TEST_F(LoggerTest, test_logWarnLevel) { setLevelExpectations(Level::WARN); exerciseLevels(); } @@ -446,7 +446,7 @@ TEST_F(LoggerTest, logWarnLevel) { * Test delivery of log messages when the log level is set to ERROR. This test sets the log level to ERROR * and then verifies that only logs of ERROR or above are passed through to the emit() method. */ -TEST_F(LoggerTest, logErrorLevel) { +TEST_F(LoggerTest, test_logErrorLevel) { setLevelExpectations(Level::ERROR); exerciseLevels(); } @@ -455,7 +455,7 @@ TEST_F(LoggerTest, logErrorLevel) { * Test delivery of log messages when the log level is set to CRITICAL. This test sets the log level to CRITICAL * and then verifies that only CRITICAL logs are passed through to the emit() method. */ -TEST_F(LoggerTest, logCriticalLevel) { +TEST_F(LoggerTest, test_logCriticalLevel) { setLevelExpectations(Level::CRITICAL); exerciseLevels(); } @@ -464,7 +464,7 @@ TEST_F(LoggerTest, logCriticalLevel) { * Test delivery of log messages when the log level is set to NONE. This test sets the log level to NONE * and then verifies that no logs are passed through to the emit() method. */ -TEST_F(LoggerTest, logNoneLevel) { +TEST_F(LoggerTest, test_logNoneLevel) { setLevelExpectations(Level::NONE); exerciseLevels(); } @@ -473,7 +473,7 @@ TEST_F(LoggerTest, logNoneLevel) { * Test to ensure that logger usage with possible nullptr inputs is robust. As some functionality is templated, * we must test both char* and const char* variants, for LogEntry construction, and the .d() and .m() functionality. */ -TEST_F(LoggerTest, testNullInputs) { +TEST_F(LoggerTest, test_nullInputs) { ACSDK_GET_LOGGER_FUNCTION().setLevel(Level::INFO); EXPECT_CALL(*(g_log.get()), emit(Level::INFO, _, _, _)).Times(13); @@ -505,7 +505,7 @@ TEST_F(LoggerTest, testNullInputs) { * both before and after an invocation of ACDK_LOG_INFO and verifies that the time value passed to the * emit() method is between (inclusive) the before and after times. */ -TEST_F(LoggerTest, verifyTime) { +TEST_F(LoggerTest, test_verifyTime) { ACSDK_GET_LOGGER_FUNCTION().setLevel(Level::INFO); EXPECT_CALL(*(g_log.get()), emit(Level::INFO, _, _, _)).Times(1); @@ -520,7 +520,7 @@ TEST_F(LoggerTest, verifyTime) { * Test delivery of appropriate thread moniker values from the logging system. This test invokes ACSDK_INFO from * two threads and verifies that the thread moniker values passed to the emit() method are in fact different. */ -TEST_F(LoggerTest, verifyThreadMoniker) { +TEST_F(LoggerTest, test_verifyThreadMoniker) { ACSDK_GET_LOGGER_FUNCTION().setLevel(Level::INFO); EXPECT_CALL(*(g_log.get()), emit(Level::INFO, _, _, _)).Times(2); ACSDK_INFO(LX("testing threadMoniker (1 of 2)")); @@ -537,7 +537,7 @@ TEST_F(LoggerTest, verifyThreadMoniker) { * constructor. Expect that the source parameter passed to the LogEntry constructor is included in the text * passed to the emit() method. */ -TEST_F(LoggerTest, verifySource) { +TEST_F(LoggerTest, test_verifySource) { ACSDK_GET_LOGGER_FUNCTION().setLevel(Level::INFO); EXPECT_CALL(*(g_log.get()), emit(Level::INFO, _, _, _)).Times(1); ACSDK_INFO(LX("random_event")); @@ -549,7 +549,7 @@ TEST_F(LoggerTest, verifySource) { * constructor. Expect that the event parameter passed to the LogEntry constructor is included in the text * passed to the emit() method. */ -TEST_F(LoggerTest, verifyEvent) { +TEST_F(LoggerTest, test_verifyEvent) { ACSDK_GET_LOGGER_FUNCTION().setLevel(Level::INFO); EXPECT_CALL(*(g_log.get()), emit(Level::INFO, _, _, _)).Times(1); std::string event(TEST_EVENT_STRING); @@ -562,7 +562,7 @@ TEST_F(LoggerTest, verifyEvent) { * Expects that that metadata is constructed properly (including the escaping of reserved characters) and that * both the key and escaped value are included in the text passed to the emit() method. */ -TEST_F(LoggerTest, verifyMetadata) { +TEST_F(LoggerTest, test_verifyMetadata) { ACSDK_GET_LOGGER_FUNCTION().setLevel(Level::INFO); EXPECT_CALL(*(g_log.get()), emit(Level::INFO, _, _, _)).Times(1); ACSDK_INFO(LX("testing metadata") @@ -577,7 +577,7 @@ TEST_F(LoggerTest, verifyMetadata) { * Test passing a message parameter to the logging system. Invokes ACSDK_INFO with a message parameter. * Expects that the message is included in text passed to the emit() method. */ -TEST_F(LoggerTest, verifyMessage) { +TEST_F(LoggerTest, test_verifyMessage) { ACSDK_GET_LOGGER_FUNCTION().setLevel(Level::INFO); EXPECT_CALL(*(g_log.get()), emit(Level::INFO, _, _, _)).Times(1); std::string message(TEST_MESSAGE_STRING); @@ -588,7 +588,7 @@ TEST_F(LoggerTest, verifyMessage) { /** * Test passing sensitive data to the logging system. It should only be emitted in DEBUG builds. */ -TEST_F(LoggerTest, testSensitiveDataSuppressed) { +TEST_F(LoggerTest, test_sensitiveDataSuppressed) { ACSDK_GET_LOGGER_FUNCTION().setLevel(Level::INFO); EXPECT_CALL(*(g_log.get()), emit(Level::INFO, _, _, _)).Times(1); ACSDK_INFO(LX("testing metadata").sensitive(METADATA_KEY, UNESCAPED_METADATA_VALUE)); @@ -605,7 +605,7 @@ TEST_F(LoggerTest, testSensitiveDataSuppressed) { * callback of the MockModuleLogger is triggered. Also make sure any changes to sink's logLevel is ignored * after the MockModuleLogger's logLevel has been set. */ -TEST_F(LoggerTest, testModuleLoggerObserver) { +TEST_F(LoggerTest, test_moduleLoggerObserver) { MockModuleLogger mockModuleLogger; getLoggerTestLogger()->setLevel(Level::WARN); ASSERT_EQ(mockModuleLogger.getLogLevel(), Level::WARN); @@ -618,7 +618,7 @@ TEST_F(LoggerTest, testModuleLoggerObserver) { /** * Test observer mechanism with multiple observers. Expects all observers to be notified of the logLevel change. */ -TEST_F(LoggerTest, testMultipleModuleLoggerObservers) { +TEST_F(LoggerTest, test_multipleModuleLoggerObservers) { MockModuleLogger mockModuleLogger1; MockModuleLogger mockModuleLogger2; MockModuleLogger mockModuleLogger3; @@ -643,7 +643,7 @@ TEST_F(LoggerTest, testMultipleModuleLoggerObservers) { * Test changing of sink logger using the LoggerSinkManager. Expect the sink in * ModuleLoggers will be changed. */ -TEST_F(LoggerTest, testChangeSinkLogger) { +TEST_F(LoggerTest, test_changeSinkLogger) { std::shared_ptr sink1 = MockLogger::create(); std::shared_ptr sink1Logger = sink1; diff --git a/AVSCommon/Utils/test/MIMEParserTest.cpp b/AVSCommon/Utils/test/MIMEParserTest.cpp index 3bf37e1b29..5fe51b2eb0 100644 --- a/AVSCommon/Utils/test/MIMEParserTest.cpp +++ b/AVSCommon/Utils/test/MIMEParserTest.cpp @@ -185,7 +185,7 @@ class MIMEParserTest : public ::testing::Test { * Test for correct encoded size, header presence and validity * of Return status for every call as well as bytes written. */ -TEST_F(MIMEParserTest, encodingSanityTest) { +TEST_F(MIMEParserTest, test_encodingSanity) { /// We choose an arbitrary buffer size const int bufferSize{25}; @@ -223,7 +223,7 @@ TEST_F(MIMEParserTest, encodingSanityTest) { ASSERT_EQ(index, encodedSize); } -TEST_F(MIMEParserTest, decodingSanityTest) { +TEST_F(MIMEParserTest, test_decodingSanity) { /// We choose an arbitrary buffer size const int bufferSize{25}; /// We need to pass a header with boundary info @@ -307,7 +307,7 @@ void runCodecTest( ASSERT_EQ(pauseCount, sink->m_pauseCount); } -TEST_F(MIMEParserTest, singlePayloadSinglePass) { +TEST_F(MIMEParserTest, test_singlePayloadSinglePass) { // Sufficiently large buffer to accommodate payload const int bufferSize{LARGE}; @@ -329,7 +329,7 @@ TEST_F(MIMEParserTest, singlePayloadSinglePass) { runCodecTest(source, sink, bufferSize); } -TEST_F(MIMEParserTest, singlePayloadMultiplePasses) { +TEST_F(MIMEParserTest, test_singlePayloadMultiplePasses) { // Medium sized payload and buffer const int bufferSize{SMALL}; // setup source @@ -352,7 +352,7 @@ TEST_F(MIMEParserTest, singlePayloadMultiplePasses) { runCodecTest(source, sink, bufferSize); } -TEST_F(MIMEParserTest, multiplePayloadsSinglePass) { +TEST_F(MIMEParserTest, test_multiplePayloadsSinglePass) { const int bufferSize{LARGE}; std::vector data; std::vector> headerSets; @@ -375,7 +375,7 @@ TEST_F(MIMEParserTest, multiplePayloadsSinglePass) { runCodecTest(source, sink, bufferSize); } -TEST_F(MIMEParserTest, multiplePayloadsMultiplePasses) { +TEST_F(MIMEParserTest, test_multiplePayloadsMultiplePasses) { const int bufferSize{SMALL}; std::vector data; std::vector> headerSets; @@ -401,7 +401,7 @@ TEST_F(MIMEParserTest, multiplePayloadsMultiplePasses) { /** * Test feeding mime text including duplicate boundaries that we want to just skip over. */ -TEST_F(MIMEParserTest, duplicateBoundaries) { +TEST_F(MIMEParserTest, test_duplicateBoundaries) { /// We choose an arbitrary buffer size const int bufferSize{25}; /// We need to pass a header with boundary info @@ -454,7 +454,7 @@ TEST_F(MIMEParserTest, duplicateBoundaries) { } } -TEST_F(MIMEParserTest, testABORT) { +TEST_F(MIMEParserTest, test_aBORT) { // setup source std::vector data; std::vector> headerSets; @@ -490,7 +490,7 @@ TEST_F(MIMEParserTest, testABORT) { ASSERT_EQ(decoder.onReceiveData(encodedPayload.c_str(), SMALL), HTTP2ReceiveDataStatus::ABORT); } -TEST_F(MIMEParserTest, testPAUSE) { +TEST_F(MIMEParserTest, test_pAUSE) { const int bufferSize{SMALL}; std::vector data; std::vector> headerSets; @@ -522,7 +522,7 @@ TEST_F(MIMEParserTest, testPAUSE) { * We test for cases when the amount of data to be encoded/decoded from chunk varies a lot * between calls */ -TEST_F(MIMEParserTest, testVariableChunkSizes) { +TEST_F(MIMEParserTest, test_variableChunkSizes) { std::vector data; std::vector> headerSets; // 3 medium payloads @@ -656,7 +656,7 @@ static void testPrefixCase( } } -TEST_F(MIMEParserTest, testPrefixCases) { +TEST_F(MIMEParserTest, test_prefixCases) { // Value used to drive testes of first chunk sizes 0 (i.e. none), 1, 2, and 3. static const int MAX_FIRST_CHUNK_SIZE = 3; diff --git a/AVSCommon/Utils/test/RequiresShutdownTest.cpp b/AVSCommon/Utils/test/RequiresShutdownTest.cpp index 01ef70ab42..294d314d56 100644 --- a/AVSCommon/Utils/test/RequiresShutdownTest.cpp +++ b/AVSCommon/Utils/test/RequiresShutdownTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -58,7 +58,7 @@ void Object::doShutdown() { * verifies that we don't crash, but functional verification currently requires a manual examination of the console * output from this test. */ -TEST(RequiresShutdownTest, allTestCases) { +TEST(RequiresShutdownTest, test_allTestCases) { // shared_ptr loop that implements and calls proper shutdown functions auto loopCallGoodShutdownMemberA = std::make_shared("loopCallGoodShutdownMemberA"); auto loopCallGoodShutdownMemberB = std::make_shared("loopCallGoodShutdownMemberB"); diff --git a/AVSCommon/Utils/test/SafeTimeAccessTest.cpp b/AVSCommon/Utils/test/SafeTimeAccessTest.cpp index 6e56dc436d..2304bb665c 100644 --- a/AVSCommon/Utils/test/SafeTimeAccessTest.cpp +++ b/AVSCommon/Utils/test/SafeTimeAccessTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -30,13 +30,13 @@ namespace test { const time_t LARGE_TIME_VALUE = (0x1 << 30) - 1; /// Test to verify that getGmtime returns failure if a nullptr is passed for the result variable. -TEST(SafeCTimeAccessTest, getGmtimeNullReturnValue) { +TEST(SafeCTimeAccessTest, test_getGmtimeNullReturnValue) { auto safeCTimeAccess = SafeCTimeAccess::instance(); ASSERT_FALSE(safeCTimeAccess->getGmtime(0, nullptr)); } /// Test to verify that getLocaltime returns failure if a nullptr is passed for the result variable. -TEST(SafeCTimeAccessTest, getLocaltimeNullReturnValue) { +TEST(SafeCTimeAccessTest, test_getLocaltimeNullReturnValue) { auto safeCTimeAccess = SafeCTimeAccess::instance(); ASSERT_FALSE(safeCTimeAccess->getLocaltime(0, nullptr)); } @@ -86,7 +86,7 @@ static void testLocaltimeHelper(const std::tm& expected, const time_t& t) { } /// Test to verify that getGmtime returns the correct calendar date for the Unix epoch. -TEST(SafeCTimeAccessTest, getGmtimeAtTheEpoch) { +TEST(SafeCTimeAccessTest, test_getGmtimeAtTheEpoch) { std::tm epoch; epoch.tm_sec = 0; epoch.tm_min = 0; @@ -101,7 +101,7 @@ TEST(SafeCTimeAccessTest, getGmtimeAtTheEpoch) { } /// Test to verify that getGmtime returns the same calendar date as std::gmtime. -TEST(SafeCTimeAccessTest, getGmtime) { +TEST(SafeCTimeAccessTest, test_getGmtime) { for (time_t t = 0; t < LARGE_TIME_VALUE; t = 2 * (t + 1)) { auto gmtimeResult = std::gmtime(&t); ASSERT_NE(nullptr, gmtimeResult); @@ -110,7 +110,7 @@ TEST(SafeCTimeAccessTest, getGmtime) { } /// Test to verify that getLocaltime returns the same calendar date as std::localtime. -TEST(SafeCTimeAccessTest, getLocaltime) { +TEST(SafeCTimeAccessTest, test_getLocaltime) { for (time_t t = 0; t < LARGE_TIME_VALUE; t = 2 * (t + 1)) { auto localtimeResult = std::localtime(&t); ASSERT_NE(nullptr, localtimeResult); @@ -201,13 +201,13 @@ static void checkSafeCTimeFunction(const TestType& type) { } /// Test to make sure that multithreaded access SafeCTimeAccess::getGmtime is safe. -TEST(SafeCTimeAccessTest, DISABLED_gmTimeMultithreadedAccess) { +TEST(SafeCTimeAccessTest, DISABLED_test_gmTimeMultithreadedAccess) { // TODO: ACSDK-1208 investigate Pi failure checkSafeCTimeFunction(TestType::GMTIME); } /// Test to make sure that multithreaded access SafeCTimeAccess::getLocaltimetime is safe. -TEST(SafeCTimeAccessTest, DISABLED_localtimeMultithreadedAccess) { +TEST(SafeCTimeAccessTest, DISABLED_test_localtimeMultithreadedAccess) { // TODO: ACSDK-1208 investigate Pi failure checkSafeCTimeFunction(TestType::LOCALTIME); } diff --git a/AVSCommon/Utils/test/SharedDataStreamTest.cpp b/AVSCommon/Utils/test/SharedDataStreamTest.cpp index 50e0bdfe8b..20fb6e6b09 100644 --- a/AVSCommon/Utils/test/SharedDataStreamTest.cpp +++ b/AVSCommon/Utils/test/SharedDataStreamTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -336,7 +336,7 @@ class SharedDataStreamTest : public ::testing::Test { }; /// This tests @c SharedDataStream::calculateCreateSize() and @c SharedDataStream::create(). -TEST_F(SharedDataStreamTest, sdsCalculateCreateSize) { +TEST_F(SharedDataStreamTest, test_sdsCalculateCreateSize) { static const size_t SDK_MAXREADERS_REQUIRED = 2; static const size_t SDK_WORDSIZE_REQUIRED = sizeof(uint16_t); size_t maxReaders, wordCount, wordSize; @@ -412,7 +412,7 @@ TEST_F(SharedDataStreamTest, sdsCalculateCreateSize) { } /// This tests @c SharedDataStream::open(). -TEST_F(SharedDataStreamTest, sdsOpen) { +TEST_F(SharedDataStreamTest, test_sdsOpen) { static const size_t WORDSIZE = 2; static const size_t WORDCOUNT = 10; static const size_t MAXREADERS = 2; @@ -454,7 +454,7 @@ TEST_F(SharedDataStreamTest, sdsOpen) { } /// This tests @c SharedDataStream::createWriter(). -TEST_F(SharedDataStreamTest, createWriter) { +TEST_F(SharedDataStreamTest, test_createWriter) { static const size_t WORDSIZE = 1; static const size_t WORDCOUNT = 1; static const size_t MAXREADERS = 1; @@ -506,7 +506,7 @@ TEST_F(SharedDataStreamTest, createWriter) { } /// This tests @c SharedDataStream::createReader(). -TEST_F(SharedDataStreamTest, createReader) { +TEST_F(SharedDataStreamTest, test_createReader) { static const size_t WORDSIZE = 1; static const size_t WORDCOUNT = 1; static const size_t MAXREADERS = 2; @@ -571,7 +571,7 @@ TEST_F(SharedDataStreamTest, createReader) { } /// This tests @c SharedDataStream::Reader::read(). -TEST_F(SharedDataStreamTest, readerRead) { +TEST_F(SharedDataStreamTest, test_readerRead) { static const size_t WORDSIZE = 2; static const size_t WORDCOUNT = 2; static const size_t MAXREADERS = 2; @@ -647,7 +647,7 @@ TEST_F(SharedDataStreamTest, readerRead) { } /// This tests @c SharedDataStream::Reader::seek(). -TEST_F(SharedDataStreamTest, readerSeek) { +TEST_F(SharedDataStreamTest, test_readerSeek) { static const size_t WORDSIZE = 2; static const size_t WORDCOUNT = 10; static const size_t MAXREADERS = 2; @@ -794,7 +794,7 @@ TEST_F(SharedDataStreamTest, readerSeek) { } /// This tests @c SharedDataStream::Reader::tell(). -TEST_F(SharedDataStreamTest, readerTell) { +TEST_F(SharedDataStreamTest, test_readerTell) { static const size_t WORDSIZE = 2; static const size_t WORDCOUNT = 10; static const size_t MAXREADERS = 2; @@ -857,7 +857,7 @@ TEST_F(SharedDataStreamTest, readerTell) { } /// This tests @c SharedDataStream::Reader::close(). -TEST_F(SharedDataStreamTest, readerClose) { +TEST_F(SharedDataStreamTest, test_readerClose) { static const size_t WORDSIZE = 2; static const size_t WORDCOUNT = 10; static const size_t MAXREADERS = 2; @@ -894,7 +894,7 @@ TEST_F(SharedDataStreamTest, readerClose) { } /// This tests @c SharedDataStream::Reader::getId(). -TEST_F(SharedDataStreamTest, readerGetId) { +TEST_F(SharedDataStreamTest, test_readerGetId) { static const size_t WORDSIZE = 1; static const size_t WORDCOUNT = 1; static const size_t MAXREADERS = 10; @@ -925,7 +925,7 @@ TEST_F(SharedDataStreamTest, readerGetId) { } /// This tests @c SharedDataStream::Reader::getWordSize(). -TEST_F(SharedDataStreamTest, readerGetWordSize) { +TEST_F(SharedDataStreamTest, test_readerGetWordSize) { static const size_t MINWORDSIZE = 1; static const size_t MAXWORDSIZE = 8; static const size_t WORDCOUNT = 1; @@ -943,7 +943,7 @@ TEST_F(SharedDataStreamTest, readerGetWordSize) { } /// This tests @c SharedDataStream::Writer::write(). -TEST_F(SharedDataStreamTest, writerWrite) { +TEST_F(SharedDataStreamTest, test_writerWrite) { static const size_t WORDSIZE = 2; static const size_t WORDCOUNT = 2; static const size_t MAXREADERS = 1; @@ -1014,7 +1014,7 @@ TEST_F(SharedDataStreamTest, writerWrite) { } /// This tests @c SharedDataStream::Writer::tell(). -TEST_F(SharedDataStreamTest, writerTell) { +TEST_F(SharedDataStreamTest, test_writerTell) { static const size_t WORDSIZE = 1; static const size_t WORDCOUNT = 1; static const size_t MAXREADERS = 1; @@ -1043,7 +1043,7 @@ TEST_F(SharedDataStreamTest, writerTell) { } /// This tests @c SharedDataStream::Writer::close(). -TEST_F(SharedDataStreamTest, writerClose) { +TEST_F(SharedDataStreamTest, test_writerClose) { static const size_t WORDSIZE = 1; static const size_t WORDCOUNT = 1; static const size_t MAXREADERS = 1; @@ -1066,7 +1066,7 @@ TEST_F(SharedDataStreamTest, writerClose) { } /// This tests @c SharedDataStream::Writer::getWordSize(). -TEST_F(SharedDataStreamTest, writerGetWordSize) { +TEST_F(SharedDataStreamTest, test_writerGetWordSize) { static const size_t MINWORDSIZE = 1; static const size_t MAXWORDSIZE = 8; static const size_t WORDCOUNT = 1; @@ -1084,7 +1084,7 @@ TEST_F(SharedDataStreamTest, writerGetWordSize) { } /// This tests a nonblockable, slow @c Writer streaming concurrently to two fast @c Readers (one of each type). -TEST_F(SharedDataStreamTest, concurrencyNonblockableWriterDualReader) { +TEST_F(SharedDataStreamTest, testTimer_concurrencyNonblockableWriterDualReader) { static const size_t WORDSIZE = 2; static const size_t WRITE_FREQUENCY_HZ = 1000; static const size_t READ_FREQUENCY_HZ = 0; @@ -1119,7 +1119,7 @@ TEST_F(SharedDataStreamTest, concurrencyNonblockableWriterDualReader) { } /// This tests an all-or-nothing, fast @c Writer streaming concurrently to a slow non-blocking @c Reader. -TEST_F(SharedDataStreamTest, concurrencyAllOrNothingWriterNonblockingReader) { +TEST_F(SharedDataStreamTest, test_concurrencyAllOrNothingWriterNonblockingReader) { static const size_t WORDSIZE = 1; static const size_t WRITE_FREQUENCY_HZ = 320000; static const size_t READ_FREQUENCY_HZ = 160000; @@ -1148,7 +1148,7 @@ TEST_F(SharedDataStreamTest, concurrencyAllOrNothingWriterNonblockingReader) { } /// This tests a @c Writer from one SDS streaming to a @c Reader from a different SDS, usig a shared @c Buffer. -TEST_F(SharedDataStreamTest, concurrencyMultipleSds) { +TEST_F(SharedDataStreamTest, test_concurrencyMultipleSds) { static const size_t WORDSIZE = 1; static const size_t WRITE_FREQUENCY_HZ = 320000; static const size_t READ_FREQUENCY_HZ = 160000; @@ -1180,7 +1180,7 @@ TEST_F(SharedDataStreamTest, concurrencyMultipleSds) { } /// This tests that a @c Reader closes if a @c Writer is attached and closed before writing anything -TEST_F(SharedDataStreamTest, writerClosedBeforeWriting) { +TEST_F(SharedDataStreamTest, test_writerClosedBeforeWriting) { static const size_t WORDSIZE = 2; static const size_t WORDCOUNT = 2; static const size_t MAXREADERS = 2; @@ -1218,7 +1218,7 @@ TEST_F(SharedDataStreamTest, writerClosedBeforeWriting) { } /// This tests that a @c Reader closes if a @c Writer is attached and closed before the @c Reader is first attached -TEST_F(SharedDataStreamTest, writerClosedBeforeAttachingReader) { +TEST_F(SharedDataStreamTest, test_writerClosedBeforeAttachingReader) { static const size_t WORDSIZE = 2; static const size_t WORDCOUNT = 2; static const size_t MAXREADERS = 2; diff --git a/AVSCommon/Utils/test/StopwatchTest.cpp b/AVSCommon/Utils/test/StopwatchTest.cpp index 4360834d1b..fb6ea7fde0 100644 --- a/AVSCommon/Utils/test/StopwatchTest.cpp +++ b/AVSCommon/Utils/test/StopwatchTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -52,7 +52,7 @@ bool StopwatchTest::checkElapsed(int expectedIncrement) { /** * Test good sequencing of method calls. */ -TEST_F(StopwatchTest, goodSequencing) { +TEST_F(StopwatchTest, test_goodSequencing) { ASSERT_TRUE(m_stopwatch.start()); ASSERT_TRUE(m_stopwatch.pause()); ASSERT_TRUE(m_stopwatch.resume()); @@ -71,7 +71,7 @@ TEST_F(StopwatchTest, goodSequencing) { /** * Test bad sequencing of method calls. */ -TEST_F(StopwatchTest, badSequencing) { +TEST_F(StopwatchTest, test_badSequencing) { // Must be reset to start(). ASSERT_TRUE(m_stopwatch.start()); @@ -140,7 +140,7 @@ TEST_F(StopwatchTest, badSequencing) { /** * Test report of elapsed time. This test is timing sensitive. */ -TEST_F(StopwatchTest, testElapsed) { +TEST_F(StopwatchTest, testSlow_elapsed) { // Expect progression after start(). ASSERT_TRUE(m_stopwatch.start()); std::this_thread::sleep_for(TESTABLE_TIME_INCREMENT * 2); diff --git a/AVSCommon/Utils/test/StreamFunctionsTest.cpp b/AVSCommon/Utils/test/StreamFunctionsTest.cpp index 441d2998a2..bf9b8bca78 100644 --- a/AVSCommon/Utils/test/StreamFunctionsTest.cpp +++ b/AVSCommon/Utils/test/StreamFunctionsTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -46,14 +46,14 @@ class StreamFunctionsTest : public ::testing::Test { /** * Verify that audio bytes passed in are returned exactly the same */ -TEST_F(StreamFunctionsTest, StreamFromData) { +TEST_F(StreamFunctionsTest, test_streamFromData) { ASSERT_TRUE(streamAndDataAreEqual(*m_stream, TEST_DATA, sizeof(TEST_DATA))); } /** * Verify that non-char data streams work correctly */ -TEST_F(StreamFunctionsTest, DataContainsUnprintableChars) { +TEST_F(StreamFunctionsTest, test_dataContainsUnprintableChars) { const std::vector> testData = { {5, 0, 3, 6}, // NULLS in data {0, 0, 6, 6}, // NULLS at beginning @@ -74,7 +74,7 @@ TEST_F(StreamFunctionsTest, DataContainsUnprintableChars) { /** * Verify that empty datasets work */ -TEST_F(StreamFunctionsTest, EmptyVector) { +TEST_F(StreamFunctionsTest, test_emptyVector) { const unsigned char empty[] = {}; auto stream = stream::streamFromData(empty, sizeof(empty)); ASSERT_TRUE(streamAndDataAreEqual(*stream, empty, sizeof(empty))); @@ -83,7 +83,7 @@ TEST_F(StreamFunctionsTest, EmptyVector) { /** * Verify that multiple streams created from the same source can be operated on independently */ -TEST_F(StreamFunctionsTest, MultipleStreams) { +TEST_F(StreamFunctionsTest, test_multipleStreams) { // get two streams to the same data auto stream1 = stream::streamFromData(TEST_DATA, sizeof(TEST_DATA)); auto stream2 = stream::streamFromData(TEST_DATA, sizeof(TEST_DATA)); @@ -101,7 +101,7 @@ TEST_F(StreamFunctionsTest, MultipleStreams) { /** * Verify that seekg works going forward */ -TEST_F(StreamFunctionsTest, seekgBasicForward) { +TEST_F(StreamFunctionsTest, test_seekgBasicForward) { const std::streampos step = 2; m_stream->seekg(step); ASSERT_TRUE(streamAndDataAreEqual(*m_stream, TEST_DATA + step, sizeof(TEST_DATA) - step)); @@ -110,7 +110,7 @@ TEST_F(StreamFunctionsTest, seekgBasicForward) { /** * Verify that seekg can reset */ -TEST_F(StreamFunctionsTest, seekgBasicReset) { +TEST_F(StreamFunctionsTest, test_seekgBasicReset) { // get 4 chars from char from one stream char c; m_stream->get(c); @@ -127,14 +127,14 @@ TEST_F(StreamFunctionsTest, seekgBasicReset) { /** * Verify that tellg works on creation */ -TEST_F(StreamFunctionsTest, tellgBasic) { +TEST_F(StreamFunctionsTest, test_tellgBasic) { ASSERT_EQ(0, m_stream->tellg()); } /** * Verify that the stream will have a bad tellg result when seeking past end */ -TEST_F(StreamFunctionsTest, tellgPastEnd) { +TEST_F(StreamFunctionsTest, test_tellgPastEnd) { m_stream->seekg(sizeof(TEST_DATA) + 1); ASSERT_EQ(-1, m_stream->tellg()); } @@ -142,7 +142,7 @@ TEST_F(StreamFunctionsTest, tellgPastEnd) { /** * Verify that the stream will have a bad tellg result when seeking before beginning */ -TEST_F(StreamFunctionsTest, tellgBeforeBeginning) { +TEST_F(StreamFunctionsTest, test_tellgBeforeBeginning) { m_stream->seekg(-1); ASSERT_EQ(-1, m_stream->tellg()); } @@ -150,7 +150,7 @@ TEST_F(StreamFunctionsTest, tellgBeforeBeginning) { /** * Verify that tellg is set correctly after seeking */ -TEST_F(StreamFunctionsTest, tellgAfterSeeking) { +TEST_F(StreamFunctionsTest, test_tellgAfterSeeking) { const std::streampos step = 2; m_stream->seekg(step); ASSERT_EQ(step, m_stream->tellg()); @@ -160,7 +160,7 @@ TEST_F(StreamFunctionsTest, tellgAfterSeeking) { /** * Verify that tellg is set correctly after reading from stream */ -TEST_F(StreamFunctionsTest, tellgAfterReading) { +TEST_F(StreamFunctionsTest, test_tellgAfterReading) { // get 4 chars from char from one stream const int numberToRead = 4; diff --git a/AVSCommon/Utils/test/StreambufTest.cpp b/AVSCommon/Utils/test/StreambufTest.cpp index 4fc8352146..eb67144e20 100644 --- a/AVSCommon/Utils/test/StreambufTest.cpp +++ b/AVSCommon/Utils/test/StreambufTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -36,14 +36,14 @@ class StreambufTest : public ::testing::Test { /** * Verify that the Streambuf is created correctly */ -TEST_F(StreambufTest, Creation) { +TEST_F(StreambufTest, test_creation) { ASSERT_EQ(testData[0], m_sb.sgetc()); } /** * Verify that the seekoff can be called based from the beginning */ -TEST_F(StreambufTest, seekoffBeginning) { +TEST_F(StreambufTest, test_seekoffBeginning) { const std::vector positions = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; for (const auto& pos : positions) { ASSERT_EQ(pos, m_sb.seekoff(pos, std::ios_base::beg)); @@ -54,7 +54,7 @@ TEST_F(StreambufTest, seekoffBeginning) { /** * Verify that the seekoff can be called based from the current positon */ -TEST_F(StreambufTest, seekoffCurrentForward) { +TEST_F(StreambufTest, test_seekoffCurrentForward) { const std::streampos pos = 3; ASSERT_EQ(pos, m_sb.seekoff(pos, std::ios_base::cur)); ASSERT_EQ(testData[pos], m_sb.sgetc()); @@ -66,7 +66,7 @@ TEST_F(StreambufTest, seekoffCurrentForward) { /** * Verify that you can seek all the way until the end correctly */ -TEST_F(StreambufTest, seekoffFromBeginningUntilEnd) { +TEST_F(StreambufTest, test_seekoffFromBeginningUntilEnd) { const std::streampos step = 1; m_sb.seekoff(0, std::ios_base::beg); for (size_t i = 0; i < testData.size() - 1; ++i) { @@ -80,7 +80,7 @@ TEST_F(StreambufTest, seekoffFromBeginningUntilEnd) { /** * Verify that you can seek all the way from the end to the beginning */ -TEST_F(StreambufTest, seekoffFromEndUntilBeginning) { +TEST_F(StreambufTest, test_seekoffFromEndUntilBeginning) { const std::streampos step = -1; m_sb.seekoff(-1, std::ios_base::end); for (size_t i = 0; i < testData.size() - 1; ++i) { @@ -94,7 +94,7 @@ TEST_F(StreambufTest, seekoffFromEndUntilBeginning) { /** * Verify that you can seek backward from the end */ -TEST_F(StreambufTest, seekoffCurrentBackward) { +TEST_F(StreambufTest, test_seekoffCurrentBackward) { auto end = m_sb.seekoff(-1, std::ios_base::end); const std::streampos pos = 3; @@ -108,21 +108,21 @@ TEST_F(StreambufTest, seekoffCurrentBackward) { /** * Verify that a seek to before the stream results in an error */ -TEST_F(StreambufTest, seekoffBeforeStart) { +TEST_F(StreambufTest, test_seekoffBeforeStart) { ASSERT_EQ(-1, m_sb.seekoff(-1, std::ios_base::beg)); } /** * Verify that a seek to after the stream results in an error */ -TEST_F(StreambufTest, seekoffPastEnd) { +TEST_F(StreambufTest, test_seekoffPastEnd) { ASSERT_EQ(-1, m_sb.seekoff(1, std::ios_base::end)); } /** * Verify that a basic seekpos works */ -TEST_F(StreambufTest, seekpos) { +TEST_F(StreambufTest, test_seekpos) { const std::streampos pos = 3; ASSERT_EQ(pos, m_sb.seekpos(pos)); ASSERT_EQ(testData[pos], m_sb.sgetc()); @@ -131,21 +131,21 @@ TEST_F(StreambufTest, seekpos) { /** * Verify that a basic seekpos before the beginning results in an error */ -TEST_F(StreambufTest, seekposBeforeStart) { +TEST_F(StreambufTest, test_seekposBeforeStart) { ASSERT_EQ(-1, m_sb.seekpos(-1)); } /** * Verify that a basic seekpos after the end results in an error */ -TEST_F(StreambufTest, seekposAfterEnd) { +TEST_F(StreambufTest, test_seekposAfterEnd) { ASSERT_EQ(-1, m_sb.seekpos(sizeof(testData) + 1)); } /** * Verify that a seekpos to the end is correct */ -TEST_F(StreambufTest, seekposToEnd) { +TEST_F(StreambufTest, test_seekposToEnd) { auto end = m_sb.seekoff(0, std::ios_base::end); ASSERT_EQ(end, m_sb.seekpos(end)); } diff --git a/AVSCommon/Utils/test/StringUtilsTest.cpp b/AVSCommon/Utils/test/StringUtilsTest.cpp index 12cf1eb84c..a315cd7134 100644 --- a/AVSCommon/Utils/test/StringUtilsTest.cpp +++ b/AVSCommon/Utils/test/StringUtilsTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ using namespace alexaClientSDK::avsCommon::utils::string; /** * Verify that converting an empty string to an integer fails. */ -TEST(StringUtilsTest, testEmptyStringFails) { +TEST(StringUtilsTest, test_emptyStringFails) { int result = 0; ASSERT_FALSE(stringToInt("", &result)); } @@ -35,7 +35,7 @@ TEST(StringUtilsTest, testEmptyStringFails) { /** * Verify that converting a simple decimal integer string to integer succeeds. */ -TEST(StringUtilsTest, testSimpleDecimalInteger) { +TEST(StringUtilsTest, test_simpleDecimalInteger) { int result = 0; ASSERT_TRUE(stringToInt("123", &result)); ASSERT_EQ(123, result); @@ -44,7 +44,7 @@ TEST(StringUtilsTest, testSimpleDecimalInteger) { /** * Verify that converting a negative decimal integer string to integer succeeds. */ -TEST(StringUtilsTest, testNegativeInt) { +TEST(StringUtilsTest, test_negativeInt) { int result = 0; ASSERT_TRUE(stringToInt("-987654", &result)); ASSERT_EQ(-987654, result); @@ -53,7 +53,7 @@ TEST(StringUtilsTest, testNegativeInt) { /** * Verify that converting a decimal integer string with leading whitespace to integer succeeds. */ -TEST(StringUtilsTest, testInitialWhitespaceSucceeds) { +TEST(StringUtilsTest, test_initialWhitespaceSucceeds) { int result = 0; ASSERT_TRUE(stringToInt("\t 10101", &result)); ASSERT_EQ(10101, result); @@ -62,7 +62,7 @@ TEST(StringUtilsTest, testInitialWhitespaceSucceeds) { /** * Verify that converting a decimal integer string with trailing whitespace to integer succeeds. */ -TEST(StringUtilsTest, testTrailingWhitespaceSucceeds) { +TEST(StringUtilsTest, test_trailingWhitespaceSucceeds) { int result = 0; ASSERT_TRUE(stringToInt("982389\t ", &result)); ASSERT_EQ(982389, result); @@ -71,7 +71,7 @@ TEST(StringUtilsTest, testTrailingWhitespaceSucceeds) { /** * Verify that converting a decimal integer string with leading and trailing whitespace to integer succeeds. */ -TEST(StringUtilsTest, testLeadingAndTrailingWhitespaceSucceeds) { +TEST(StringUtilsTest, test_leadingAndTrailingWhitespaceSucceeds) { int result = 0; ASSERT_TRUE(stringToInt(" 982389 ", &result)); ASSERT_EQ(982389, result); @@ -80,7 +80,7 @@ TEST(StringUtilsTest, testLeadingAndTrailingWhitespaceSucceeds) { /** * Verify that converting a decimal integer with leading non-whitespace and non-decimal digit characters fails. */ -TEST(StringUtilsTest, testNonWhitespacePrefixFails) { +TEST(StringUtilsTest, test_nonWhitespacePrefixFails) { int result = 0; ASSERT_FALSE(stringToInt("a123", &result)); } @@ -88,7 +88,7 @@ TEST(StringUtilsTest, testNonWhitespacePrefixFails) { /** * Verify that converting a decimal integer with trailing non-whitespace and non-decimal digit characters fails. */ -TEST(StringUtilsTest, testNonWhitespaceSuffixFails) { +TEST(StringUtilsTest, test_nonWhitespaceSuffixFails) { int result = 0; ASSERT_FALSE(stringToInt("123a", &result)); } @@ -97,7 +97,7 @@ TEST(StringUtilsTest, testNonWhitespaceSuffixFails) { * Verify that converting a decimal integer with leading and trailing non-whitespace and non-decimal digit * characters fails. */ -TEST(StringUtilsTest, testNonWhitespacePrefixAndSuffixFails) { +TEST(StringUtilsTest, test_nonWhitespacePrefixAndSuffixFails) { int result = 0; ASSERT_FALSE(stringToInt("a123a", &result)); } @@ -105,7 +105,7 @@ TEST(StringUtilsTest, testNonWhitespacePrefixAndSuffixFails) { /** * Verify that converting a decimal integer with both leading whitespace and non-whitespace characters fails. */ -TEST(StringUtilsTest, testNonWhitespaceAndNonWhitespacePrefixFails) { +TEST(StringUtilsTest, test_nonWhitespaceAndNonWhitespacePrefixFails) { int result = 0; ASSERT_FALSE(stringToInt(" e123", &result)); } @@ -113,7 +113,7 @@ TEST(StringUtilsTest, testNonWhitespaceAndNonWhitespacePrefixFails) { /** * Verify that converting a decimal integer with both trailing whitespace and non-whitespace characters fails. */ -TEST(StringUtilsTest, testNonWhitespaceAndNonWhitespaceSuffixFails) { +TEST(StringUtilsTest, test_nonWhitespaceAndNonWhitespaceSuffixFails) { int result = 0; ASSERT_FALSE(stringToInt("123e ", &result)); } @@ -121,7 +121,7 @@ TEST(StringUtilsTest, testNonWhitespaceAndNonWhitespaceSuffixFails) { /** * Verify that converting a decimal integer with leading and trailing whitespace and non-whitespace characters fails. */ -TEST(StringUtilsTest, testNonWhitespaceAndNonWhitespacePrefixAndSuffixFails) { +TEST(StringUtilsTest, test_nonWhitespaceAndNonWhitespacePrefixAndSuffixFails) { int result = 0; ASSERT_FALSE(stringToInt(" e123e ", &result)); } @@ -129,7 +129,7 @@ TEST(StringUtilsTest, testNonWhitespaceAndNonWhitespacePrefixAndSuffixFails) { /** * Verify that converting "0" to integer succeeds. */ -TEST(StringUtilsTest, testZeroSucceeds) { +TEST(StringUtilsTest, test_zeroSucceeds) { int result = -1; ASSERT_TRUE(stringToInt("0", &result)); ASSERT_EQ(0, result); @@ -138,7 +138,7 @@ TEST(StringUtilsTest, testZeroSucceeds) { /** * Verify that converting a floating string to integer fails. */ -TEST(StringUtilsTest, testDecimalFloatFails) { +TEST(StringUtilsTest, test_decimalFloatFails) { int result = 0; ASSERT_FALSE(stringToInt("1.234", &result)); } @@ -146,7 +146,7 @@ TEST(StringUtilsTest, testDecimalFloatFails) { /** * Verify that converting an octal integer string si interpreted as decmal with a leading zero. */ -TEST(StringUtilsTest, testOctalInterpretedAsDecimal) { +TEST(StringUtilsTest, test_octalInterpretedAsDecimal) { int result = 0; ASSERT_TRUE(stringToInt("0567", &result)); ASSERT_EQ(567, result); @@ -155,7 +155,7 @@ TEST(StringUtilsTest, testOctalInterpretedAsDecimal) { /** * Verify that converting a hex integer string to integer fails. */ -TEST(StringUtilsTest, testHexIntFails) { +TEST(StringUtilsTest, test_hexIntFails) { int result = 0; ASSERT_FALSE(stringToInt("0x321", &result)); } @@ -163,7 +163,7 @@ TEST(StringUtilsTest, testHexIntFails) { /** * Verify that converting a too large integer string to int fails. */ -TEST(StringUtilsTest, testTooLargeIntFails) { +TEST(StringUtilsTest, test_tooLargeIntFails) { int result = 0; ASSERT_FALSE(stringToInt("987654321987654321987654321", &result)); } @@ -171,7 +171,7 @@ TEST(StringUtilsTest, testTooLargeIntFails) { /** * Verify that converting a too small integer string to int fails. */ -TEST(StringUtilsTest, testTooSmallIntFails) { +TEST(StringUtilsTest, test_tooSmallIntFails) { int result = 0; ASSERT_FALSE(stringToInt("-11111111111111111111111111", &result)); } @@ -179,7 +179,7 @@ TEST(StringUtilsTest, testTooSmallIntFails) { /** * Verify that converting a string with multiple numbers in it fails. */ -TEST(StringUtilsTest, testMultipleNumbers) { +TEST(StringUtilsTest, test_multipleNumbers) { int result = 0; ASSERT_FALSE(stringToInt("123 123", &result)); ASSERT_FALSE(stringToInt(" 123 123", &result)); @@ -191,28 +191,28 @@ TEST(StringUtilsTest, testMultipleNumbers) { /** * Verify that converting a empty string to lower case works. */ -TEST(StringUtilsTest, testToLowerEmptyString) { +TEST(StringUtilsTest, test_toLowerEmptyString) { ASSERT_EQ(stringToLowerCase(""), ""); } /** * Verify that converting a lower case string to lower case works. */ -TEST(StringUtilsTest, testToLowerCaseString) { +TEST(StringUtilsTest, test_toLowerCaseString) { ASSERT_EQ(stringToLowerCase("abc"), "abc"); } /** * Verify that converting a Upper case string to lower case works. */ -TEST(StringUtilsTest, testToUpperCaseString) { +TEST(StringUtilsTest, test_toUpperCaseString) { ASSERT_EQ(stringToLowerCase("ABC"), "abc"); } /** * Verify that converting a Camel case string to lower case works. */ -TEST(StringUtilsTest, testToCamelCaseString) { +TEST(StringUtilsTest, test_toCamelCaseString) { ASSERT_EQ(stringToLowerCase("AbCd"), "abcd"); } diff --git a/AVSCommon/Utils/test/TaskThreadTest.cpp b/AVSCommon/Utils/test/TaskThreadTest.cpp index 1900af1112..d00d6150c9 100644 --- a/AVSCommon/Utils/test/TaskThreadTest.cpp +++ b/AVSCommon/Utils/test/TaskThreadTest.cpp @@ -33,19 +33,19 @@ using namespace utils::test; using namespace logger; /// Test that wait will return if no job has ever started. -TEST(TaskThreadTest, testWaitForNothing) { +TEST(TaskThreadTest, test_waitForNothing) { TaskThread taskThread; } /// Test that start will fail if function is empty. -TEST(TaskThreadTest, testStartFailsDueToEmptyFunction) { +TEST(TaskThreadTest, test_startFailsDueToEmptyFunction) { TaskThread taskThread; std::function emptyFunction; EXPECT_FALSE(taskThread.start(emptyFunction)); } /// Test that start will trigger the provided job and thread will exit once the job is done and return @c false. -TEST(TaskThreadTest, testSimpleJob) { +TEST(TaskThreadTest, test_simpleJob) { bool finished = false; auto simpleJob = [&finished] { finished = true; @@ -62,7 +62,7 @@ TEST(TaskThreadTest, testSimpleJob) { /// Test that start will trigger the provided job and it will execute the job multiple times until the job returns /// @c false. -TEST(TaskThreadTest, testSequenceJobs) { +TEST(TaskThreadTest, test_sequenceJobs) { int taskCounter = 0; const int runUntil = 10; auto jobSequence = [&taskCounter] { @@ -80,7 +80,7 @@ TEST(TaskThreadTest, testSequenceJobs) { /// Test that start will replace the existing next function. /// - First function increments the counter, while the second will decrement until it reaches 0. -TEST(TaskThreadTest, testStartNewJob) { +TEST(TaskThreadTest, test_startNewJob) { WaitEvent waitEvent; int taskCounter = 0; auto increment = [&taskCounter, &waitEvent] { @@ -102,7 +102,7 @@ TEST(TaskThreadTest, testStartNewJob) { } /// Test that start will fail if called multiple times while waiting for a job. -TEST(TaskThreadTest, testStartFailDueTooManyThreads) { +TEST(TaskThreadTest, test_startFailDueTooManyThreads) { WaitEvent waitEnqueue, waitStart; auto simpleJob = [&waitEnqueue, &waitStart] { waitStart.wakeUp(); // Job has started. @@ -124,7 +124,7 @@ TEST(TaskThreadTest, testStartFailDueTooManyThreads) { } /// Test that threads related to this task thread will always have the same moniker. -TEST(TaskThreadTest, testMoniker) { +TEST(TaskThreadTest, test_moniker) { WaitEvent waitGetMoniker, waitValidateMoniker; std::string moniker; auto getMoniker = [&moniker, &waitGetMoniker] { @@ -148,7 +148,7 @@ TEST(TaskThreadTest, testMoniker) { } /// Test that threads from different @c TaskThreads will have different monikers. -TEST(TaskThreadTest, testMonikerDifferentObjects) { +TEST(TaskThreadTest, test_monikerDifferentObjects) { WaitEvent waitGetMoniker, waitValidateMoniker; std::string moniker; auto getMoniker = [&moniker, &waitGetMoniker] { diff --git a/AVSCommon/Utils/test/TimeUtilsTest.cpp b/AVSCommon/Utils/test/TimeUtilsTest.cpp index be965b53e4..8fbd863fa1 100644 --- a/AVSCommon/Utils/test/TimeUtilsTest.cpp +++ b/AVSCommon/Utils/test/TimeUtilsTest.cpp @@ -27,7 +27,7 @@ namespace utils { namespace timing { namespace test { -TEST(TimeTest, testStringConversion) { +TEST(TimeTest, test_stringConversion) { TimeUtils timeUtils; std::string dateStr{"1986-08-10T21:30:00+0000"}; int64_t date; @@ -45,7 +45,7 @@ TEST(TimeTest, testStringConversion) { ASSERT_EQ(dateTm.tm_min, 30); } -TEST(TimeTest, testStringConversionError) { +TEST(TimeTest, test_stringConversionError) { TimeUtils timeUtils; std::string dateStr{"1986-8-10T21:30:00+0000"}; int64_t date; @@ -53,14 +53,14 @@ TEST(TimeTest, testStringConversionError) { ASSERT_FALSE(success); } -TEST(TimeTest, testStringConversionNullParam) { +TEST(TimeTest, test_stringConversionNullParam) { TimeUtils timeUtils; std::string dateStr{"1986-8-10T21:30:00+0000"}; auto success = timeUtils.convert8601TimeStringToUnix(dateStr, nullptr); ASSERT_FALSE(success); } -TEST(TimeTest, testTimeConversion) { +TEST(TimeTest, test_timeConversion) { TimeUtils timeUtils; std::time_t randomDate = 524089800; std::tm date; @@ -73,7 +73,7 @@ TEST(TimeTest, testTimeConversion) { ASSERT_EQ(randomDate, convertBack); } -TEST(TimeTest, testTimeConversionCurrentTime) { +TEST(TimeTest, test_timeConversionCurrentTime) { TimeUtils timeUtils; int64_t time = -1; ASSERT_TRUE(timeUtils.getCurrentUnixTime(&time)); @@ -90,7 +90,7 @@ TEST(TimeTest, testTimeConversionCurrentTime) { ASSERT_EQ(currentDate, convertBack); } -TEST(TimeTest, testCurrentTime) { +TEST(TimeTest, test_currentTime) { TimeUtils timeUtils; int64_t time = -1; auto success = timeUtils.getCurrentUnixTime(&time); @@ -99,7 +99,7 @@ TEST(TimeTest, testCurrentTime) { ASSERT_GT(time, 0); } -TEST(TimeTest, testCurrentTimeNullParam) { +TEST(TimeTest, test_currentTimeNullParam) { TimeUtils timeUtils; auto success = timeUtils.getCurrentUnixTime(nullptr); ASSERT_FALSE(success); @@ -125,7 +125,7 @@ static void testIso8601ConversionHelper( EXPECT_EQ(expectedString, resultString); } -TEST(TimeTest, testIso8601Conversion) { +TEST(TimeTest, test_iso8601Conversion) { testIso8601ConversionHelper("1970-01-01T00:00:00.000Z", std::chrono::seconds{0}, std::chrono::microseconds{0}); testIso8601ConversionHelper("1970-01-01T00:00:01.000Z", std::chrono::seconds{1}, std::chrono::microseconds{0}); testIso8601ConversionHelper("1970-01-01T00:00:00.001Z", std::chrono::seconds{0}, std::chrono::microseconds{1000}); diff --git a/AVSCommon/Utils/test/TimerTest.cpp b/AVSCommon/Utils/test/TimerTest.cpp index 1f323d59a1..306e42c8f5 100644 --- a/AVSCommon/Utils/test/TimerTest.cpp +++ b/AVSCommon/Utils/test/TimerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -197,7 +197,7 @@ bool TimerTest::waitForInactive() { } /// This test runs a single-shot timer and verifies that the task is called once, at the expected time. -TEST_F(TimerTest, singleShot) { +TEST_F(TimerTest, testTimer_singleShot) { auto t0 = std::chrono::steady_clock::now(); ASSERT_EQ( m_timer->start(SHORT_DELAY, std::bind(&TimerTest::simpleTask, this, NO_DELAY)).wait_for(TIMEOUT), @@ -210,7 +210,7 @@ TEST_F(TimerTest, singleShot) { * This test runs a multi-shot ABSOLUTE timer and verifies that the task is called the expected number of times, * and that each call occurred at the expected time. */ -TEST_F(TimerTest, multiShot) { +TEST_F(TimerTest, testTimer_multiShot) { auto t0 = std::chrono::steady_clock::now(); ASSERT_TRUE(m_timer->start( SHORT_DELAY, Timer::PeriodType::ABSOLUTE, ITERATIONS, std::bind(&TimerTest::simpleTask, this, NO_DELAY))); @@ -223,7 +223,7 @@ TEST_F(TimerTest, multiShot) { * This test runs a multi-shot ABSOLUTE timer with different initial delay and verifies that the task is called * the expected number of times, and that each call occurred at the expected time. */ -TEST_F(TimerTest, multiShotWithDelay) { +TEST_F(TimerTest, testTimer_multiShotWithDelay) { auto t0 = std::chrono::steady_clock::now(); ASSERT_TRUE(m_timer->start( MEDIUM_DELAY, @@ -241,7 +241,7 @@ TEST_F(TimerTest, multiShotWithDelay) { * verifies that it stops when requested, and verifies that the expected number of calls occurred at their expected * times. */ -TEST_F(TimerTest, forever) { +TEST_F(TimerTest, testTimer_forever) { auto t0 = std::chrono::steady_clock::now(); ASSERT_TRUE(m_timer->start( SHORT_DELAY, Timer::PeriodType::ABSOLUTE, Timer::FOREVER, std::bind(&TimerTest::simpleTask, this, NO_DELAY))); @@ -256,7 +256,7 @@ TEST_F(TimerTest, forever) { * This test runs a slow task with an ABSOLUTE timer, but one which completes in less than a period, and verifies * that the slow task does not change the number of calls or their period. */ -TEST_F(TimerTest, slowTaskLessThanPeriod) { +TEST_F(TimerTest, testTimer_slowTaskLessThanPeriod) { auto t0 = std::chrono::steady_clock::now(); ASSERT_TRUE(m_timer->start( MEDIUM_DELAY, Timer::PeriodType::ABSOLUTE, ITERATIONS, std::bind(&TimerTest::simpleTask, this, SHORT_DELAY))); @@ -268,7 +268,7 @@ TEST_F(TimerTest, slowTaskLessThanPeriod) { * This test runs a slow task with an ABSOLUTE timer which does not complete within a period, and verifies that * the slow task results in skipped calls, but on a consistent period. */ -TEST_F(TimerTest, slowTaskGreaterThanPeriod) { +TEST_F(TimerTest, testTimer_slowTaskGreaterThanPeriod) { auto t0 = std::chrono::steady_clock::now(); ASSERT_TRUE(m_timer->start( SHORT_DELAY, Timer::PeriodType::ABSOLUTE, ITERATIONS, std::bind(&TimerTest::simpleTask, this, MEDIUM_DELAY))); @@ -280,7 +280,7 @@ TEST_F(TimerTest, slowTaskGreaterThanPeriod) { * This test runs a slow task with an ABSOLUTE timer which does not complete within multiple periods, and verifies * that the slow task results in skipped calls, but on a consistent period. */ -TEST_F(TimerTest, slowTaskGreaterThanTwoPeriods) { +TEST_F(TimerTest, testTimer_slowTaskGreaterThanTwoPeriods) { auto t0 = std::chrono::steady_clock::now(); ASSERT_TRUE(m_timer->start( SHORT_DELAY, Timer::PeriodType::ABSOLUTE, ITERATIONS, std::bind(&TimerTest::simpleTask, this, LONG_DELAY))); @@ -292,7 +292,7 @@ TEST_F(TimerTest, slowTaskGreaterThanTwoPeriods) { * This test runs a slow task with a RELATIVE timer which does not complete within a period, and verifies that * the slow task does not result in skipped calls, but calls have a consistent between-task delay. */ -TEST_F(TimerTest, endToStartPeriod) { +TEST_F(TimerTest, testTimer_endToStartPeriod) { auto t0 = std::chrono::steady_clock::now(); ASSERT_TRUE(m_timer->start( SHORT_DELAY, Timer::PeriodType::RELATIVE, ITERATIONS, std::bind(&TimerTest::simpleTask, this, MEDIUM_DELAY))); @@ -304,7 +304,7 @@ TEST_F(TimerTest, endToStartPeriod) { * This test verifies that a call to stop() before the task is called results in an inactive timer which does not * execute the task. */ -TEST_F(TimerTest, stopSingleShotBeforeTask) { +TEST_F(TimerTest, testTimer_stopSingleShotBeforeTask) { ASSERT_TRUE(m_timer->start(MEDIUM_DELAY, std::bind(&TimerTest::simpleTask, this, NO_DELAY)).valid()); ASSERT_TRUE(m_timer->isActive()); std::this_thread::sleep_for(SHORT_DELAY); @@ -321,7 +321,7 @@ TEST_F(TimerTest, stopSingleShotBeforeTask) { * This test verifies that a call to stop() while a task is executing results in an inactive timer after that task * finishes executing. */ -TEST_F(TimerTest, stopSingleShotDuringTask) { +TEST_F(TimerTest, testTimer_stopSingleShotDuringTask) { auto t0 = std::chrono::steady_clock::now(); ASSERT_TRUE(m_timer->start(SHORT_DELAY, std::bind(&TimerTest::simpleTask, this, SHORT_DELAY)).valid()); ASSERT_TRUE(m_timer->isActive()); @@ -335,7 +335,7 @@ TEST_F(TimerTest, stopSingleShotDuringTask) { * This test verifies that a call to stop() after a task has finished executing leaves the timer inactive and * unchanged. */ -TEST_F(TimerTest, stopSingleShotAfterTask) { +TEST_F(TimerTest, testTimer_stopSingleShotAfterTask) { auto t0 = std::chrono::steady_clock::now(); ASSERT_TRUE(m_timer->start(SHORT_DELAY, std::bind(&TimerTest::simpleTask, this, SHORT_DELAY)).valid()); ASSERT_TRUE(m_timer->isActive()); @@ -350,7 +350,7 @@ TEST_F(TimerTest, stopSingleShotAfterTask) { * This test verifies that a call to stop() on a multi-shot timer results in an inactive timer with the expected * number of calls. */ -TEST_F(TimerTest, stopMultiShot) { +TEST_F(TimerTest, testTimer_stopMultiShot) { auto t0 = std::chrono::steady_clock::now(); ASSERT_TRUE(m_timer->start( SHORT_DELAY, Timer::PeriodType::ABSOLUTE, ITERATIONS, std::bind(&TimerTest::simpleTask, this, NO_DELAY))); @@ -365,7 +365,7 @@ TEST_F(TimerTest, stopMultiShot) { * This test verifies that a call to start() fails on a timer which is active but has not called a task yet, but does * not interfere with the previously scheduled task. */ -TEST_F(TimerTest, startRunningBeforeTask) { +TEST_F(TimerTest, testTimer_startRunningBeforeTask) { auto t0 = std::chrono::steady_clock::now(); ASSERT_TRUE(m_timer->start(SHORT_DELAY, std::bind(&TimerTest::simpleTask, this, NO_DELAY)).valid()); ASSERT_TRUE(m_timer->isActive()); @@ -383,7 +383,7 @@ TEST_F(TimerTest, startRunningBeforeTask) { * This test verifies that a call to start() fails on a timer which is currently executing a task, but does * not interfere with that task. */ -TEST_F(TimerTest, startRunningDuringTask) { +TEST_F(TimerTest, testTimer_startRunningDuringTask) { auto t0 = std::chrono::steady_clock::now(); ASSERT_TRUE(m_timer->start(SHORT_DELAY, std::bind(&TimerTest::simpleTask, this, SHORT_DELAY)).valid()); ASSERT_TRUE(m_timer->isActive()); @@ -399,7 +399,7 @@ TEST_F(TimerTest, startRunningDuringTask) { * This test verifies that a call to start() succeeds on a timer which was previously used to run a task, but which is * inactive at the time the new start() is called. */ -TEST_F(TimerTest, startRunningAfterTask) { +TEST_F(TimerTest, testTimer_startRunningAfterTask) { auto t0 = std::chrono::steady_clock::now(); ASSERT_TRUE(m_timer->start(SHORT_DELAY, std::bind(&TimerTest::simpleTask, this, NO_DELAY)).valid()); ASSERT_TRUE(m_timer->isActive()); @@ -415,7 +415,7 @@ TEST_F(TimerTest, startRunningAfterTask) { } /// This test verifies that a timer which is deleted while active, but before running its task, does not run the task. -TEST_F(TimerTest, deleteBeforeTask) { +TEST_F(TimerTest, test_deleteBeforeTask) { ASSERT_TRUE(m_timer->start(SHORT_DELAY, std::bind(&TimerTest::simpleTask, this, SHORT_DELAY)).valid()); ASSERT_TRUE(m_timer->isActive()); m_timer.reset(); @@ -426,7 +426,7 @@ TEST_F(TimerTest, deleteBeforeTask) { } /// This test verifies that a timer which is deleted while running a task completes the task. -TEST_F(TimerTest, deleteDuringTask) { +TEST_F(TimerTest, testTimer_deleteDuringTask) { auto t0 = std::chrono::steady_clock::now(); ASSERT_TRUE(m_timer->start( SHORT_DELAY, @@ -445,7 +445,7 @@ TEST_F(TimerTest, deleteDuringTask) { * This test verifies that a call to start() succeeds on a timer which was previously stopped while running a task, but * which is inactive at the time the new start() is called. */ -TEST_F(TimerTest, startRunningAfterStopDuringTask) { +TEST_F(TimerTest, testTimer_startRunningAfterStopDuringTask) { ASSERT_TRUE(m_timer->start(NO_DELAY, std::bind(&TimerTest::simpleTask, this, MEDIUM_DELAY)).valid()); ASSERT_TRUE(m_timer->isActive()); std::this_thread::sleep_for(SHORT_DELAY); diff --git a/AVSCommon/Utils/test/UUIDGenerationTest.cpp b/AVSCommon/Utils/test/UUIDGenerationTest.cpp index 60d80e67d7..83db26a9d6 100644 --- a/AVSCommon/Utils/test/UUIDGenerationTest.cpp +++ b/AVSCommon/Utils/test/UUIDGenerationTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -76,7 +76,7 @@ class UUIDGenerationTest : public ::testing::Test {}; /** * Call @c generateUUID and expect a string of length @c UUID_LENGTH. */ -TEST_F(UUIDGenerationTest, testUUIDStringLength) { +TEST_F(UUIDGenerationTest, test_uUIDStringLength) { ASSERT_EQ(UUID_LENGTH, generateUUID().length()); } @@ -84,7 +84,7 @@ TEST_F(UUIDGenerationTest, testUUIDStringLength) { * Call @c generateUUID and expect a string of length @c UUID_LENGTH. Check that each character in the string * is a hexedecimal number except for the hyphens. */ -TEST_F(UUIDGenerationTest, testUUIDContainsOnlyHexCharacters) { +TEST_F(UUIDGenerationTest, test_uUIDContainsOnlyHexCharacters) { auto uuid = generateUUID(); ASSERT_EQ(UUID_LENGTH, uuid.length()); for (unsigned int i = 0; i < uuid.length(); i++) { @@ -99,21 +99,21 @@ TEST_F(UUIDGenerationTest, testUUIDContainsOnlyHexCharacters) { /** * Call @c generateUUID and check that the version is set correctly. */ -TEST_F(UUIDGenerationTest, testUUIDVersion) { +TEST_F(UUIDGenerationTest, test_uUIDVersion) { ASSERT_EQ(UUID_VERSION, generateUUID().substr(UUID_VERSION_OFFSET, 1)); } /** * Call @c generateUUID and check the variant is set correctly. */ -TEST_F(UUIDGenerationTest, testUUIDVariant) { +TEST_F(UUIDGenerationTest, test_uUIDVariant) { ASSERT_EQ(UUID_VARIANT, strtoul(generateUUID().substr(UUID_VARIANT_OFFSET, 1).c_str(), nullptr, 16) & UUID_VARIANT); } /** * Call @c generateUUID and check that the hyphens are in the right positions. */ -TEST_F(UUIDGenerationTest, testUUIDHyphens) { +TEST_F(UUIDGenerationTest, test_uUIDHyphens) { std::string uuid = generateUUID(); ASSERT_EQ(HYPHEN, uuid.substr(HYPHEN1_POSITION, 1)); ASSERT_EQ(HYPHEN, uuid.substr(HYPHEN2_POSITION, 1)); @@ -125,7 +125,7 @@ TEST_F(UUIDGenerationTest, testUUIDHyphens) { * Call @c generateUUID multiple times and check the version and variant are set correctly. * Check for uniqueness of the UUIDs generated. */ -TEST_F(UUIDGenerationTest, testMultipleRequests) { +TEST_F(UUIDGenerationTest, test_multipleRequests) { std::unordered_set uuidsGenerated; for (unsigned int i = 0; i < MAX_UUIDS_TO_GENERATE; ++i) { @@ -143,7 +143,7 @@ TEST_F(UUIDGenerationTest, testMultipleRequests) { * Call @c generateUUID from multiple threads and check the version and variant are set correctly. * Check for uniqueness of the UUIDs generated. */ -TEST_F(UUIDGenerationTest, testMultipleConcurrentRequests) { +TEST_F(UUIDGenerationTest, test_multipleConcurrentRequests) { int no_of_threads = MAX_TEST_THREADS; std::vector> uuidRequesters; std::unordered_set uuidsGenerated; @@ -167,7 +167,7 @@ TEST_F(UUIDGenerationTest, testMultipleConcurrentRequests) { /** * Call @c generateUUID and ensure all hex values are generated. Will retry @c MAX_RETRIES times. */ -TEST_F(UUIDGenerationTest, testAllHexValuesGenerated) { +TEST_F(UUIDGenerationTest, test_allHexValuesGenerated) { std::unordered_set hexCharacters = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; for (unsigned int retry = 0; retry < MAX_RETRIES && !hexCharacters.empty(); retry++) { diff --git a/ApplicationUtilities/AndroidUtilities/test/AndroidLoggerTest.cpp b/ApplicationUtilities/AndroidUtilities/test/AndroidLoggerTest.cpp index ea4099f4c7..b36940727b 100644 --- a/ApplicationUtilities/AndroidUtilities/test/AndroidLoggerTest.cpp +++ b/ApplicationUtilities/AndroidUtilities/test/AndroidLoggerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -26,25 +26,25 @@ namespace test { using namespace avsCommon::utils::logger; /// Test a valid log entry. -TEST(AndroidLoggerTest, sanityTestOk) { +TEST(AndroidLoggerTest, test_sanityTestOk) { AndroidLogger logger{Level::DEBUG9}; logger.emit(Level::ERROR, std::chrono::system_clock::now(), "A", "Hello"); } /// Test a log entry with null threadMoniker. -TEST(AndroidLoggerTest, sanityTestNullThreadMoniker) { +TEST(AndroidLoggerTest, test_sanityTestNullThreadMoniker) { AndroidLogger logger{Level::DEBUG9}; logger.emit(Level::INFO, std::chrono::system_clock::now(), nullptr, "log message"); } /// Test a log entry with null text. -TEST(AndroidLoggerTest, sanityTestNullText) { +TEST(AndroidLoggerTest, test_sanityTestNullText) { AndroidLogger logger{Level::DEBUG9}; logger.emit(Level::DEBUG0, std::chrono::system_clock::now(), "A", nullptr); } /// Test all levels. -TEST(AndroidLoggerTest, sanityTestLevels) { +TEST(AndroidLoggerTest, test_sanityTestLevels) { AndroidLogger logger{Level::DEBUG9}; auto levels = {Level::UNKNOWN, Level::NONE, diff --git a/ApplicationUtilities/AndroidUtilities/test/AndroidSLESBufferQueueTest.cpp b/ApplicationUtilities/AndroidUtilities/test/AndroidSLESBufferQueueTest.cpp index 1da3077b06..0086765ad0 100644 --- a/ApplicationUtilities/AndroidUtilities/test/AndroidSLESBufferQueueTest.cpp +++ b/ApplicationUtilities/AndroidUtilities/test/AndroidSLESBufferQueueTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -178,7 +178,7 @@ std::unique_ptr AndroidSLESBufferQueueTest::createBuffer /** * Test successful creation. */ -TEST_F(AndroidSLESBufferQueueTest, TestRegisterCallbackSucceeded) { +TEST_F(AndroidSLESBufferQueueTest, test_registerCallbackSucceeded) { auto buffer = createBuffer(); EXPECT_NE(buffer, nullptr); } @@ -186,7 +186,7 @@ TEST_F(AndroidSLESBufferQueueTest, TestRegisterCallbackSucceeded) { /** * Test the callback register failure. */ -TEST_F(AndroidSLESBufferQueueTest, TestRegisterCallbackFailed) { +TEST_F(AndroidSLESBufferQueueTest, test_registerCallbackFailed) { m_queueMock->get().RegisterCallback = mockRegisterCallbackFailure; std::shared_ptr slObject = AndroidSLESObject::create(m_recorderMock->getObject()); auto buffer = AndroidSLESBufferQueue::create( @@ -197,7 +197,7 @@ TEST_F(AndroidSLESBufferQueueTest, TestRegisterCallbackFailed) { /** * Test enqueue succeeded. */ -TEST_F(AndroidSLESBufferQueueTest, TestEnqueueOK) { +TEST_F(AndroidSLESBufferQueueTest, test_enqueueOK) { m_queueMock->get().Enqueue = mockEnqueue; m_queueMock->get().GetState = mockGetState; auto buffer = createBuffer(); @@ -210,7 +210,7 @@ TEST_F(AndroidSLESBufferQueueTest, TestEnqueueOK) { /** * Test enqueue failed. */ -TEST_F(AndroidSLESBufferQueueTest, TestEnqueueFailed) { +TEST_F(AndroidSLESBufferQueueTest, test_enqueueFailed) { m_queueMock->get().Enqueue = mockEnqueueFailed; m_queueMock->get().GetState = mockGetState; auto buffer = createBuffer(); @@ -222,7 +222,7 @@ TEST_F(AndroidSLESBufferQueueTest, TestEnqueueFailed) { /** * Test enqueue succeeded to enqueue a few buffers. */ -TEST_F(AndroidSLESBufferQueueTest, TestEnqueuePartial) { +TEST_F(AndroidSLESBufferQueueTest, test_enqueuePartial) { m_queueMock->get().Enqueue = mockEnqueueHalf; m_queueMock->get().GetState = mockGetState; auto buffer = createBuffer(); @@ -235,7 +235,7 @@ TEST_F(AndroidSLESBufferQueueTest, TestEnqueuePartial) { /** * Test onBufferCompleted. */ -TEST_F(AndroidSLESBufferQueueTest, TestOnBufferCompleted) { +TEST_F(AndroidSLESBufferQueueTest, test_onBufferCompleted) { AndroidSLESBufferQueueTest::m_count = NUMBER_OF_BUFFERS - 1; m_queueMock->get().Enqueue = mockEnqueue; auto buffer = createBuffer(); diff --git a/ApplicationUtilities/AndroidUtilities/test/AndroidSLESMicrophoneTest.cpp b/ApplicationUtilities/AndroidUtilities/test/AndroidSLESMicrophoneTest.cpp index ef8a52768f..4a8b105aaa 100644 --- a/ApplicationUtilities/AndroidUtilities/test/AndroidSLESMicrophoneTest.cpp +++ b/ApplicationUtilities/AndroidUtilities/test/AndroidSLESMicrophoneTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -84,7 +84,7 @@ class AndroidSLESMicrophoneTest : public Test { /** * Test if recording works. */ -TEST_F(AndroidSLESMicrophoneTest, TestStartRecording) { +TEST_F(AndroidSLESMicrophoneTest, test_startRecording) { EXPECT_TRUE(m_mic->startStreamingMicrophoneData()); auto read = m_reader->read(m_testBuffer.data(), TEST_BUFFER_SIZE, TIMEOUT); EXPECT_EQ(read, static_cast(TEST_BUFFER_SIZE)); @@ -93,7 +93,7 @@ TEST_F(AndroidSLESMicrophoneTest, TestStartRecording) { /** * Test if the stopStreamingMicrophoneData will stop writing to the buffer. */ -TEST_F(AndroidSLESMicrophoneTest, TestPauseRecording) { +TEST_F(AndroidSLESMicrophoneTest, test_pauseRecording) { EXPECT_TRUE(m_mic->startStreamingMicrophoneData()); EXPECT_TRUE(m_mic->stopStreamingMicrophoneData()); auto read = m_reader->read(m_testBuffer.data(), TEST_BUFFER_SIZE, TIMEOUT); @@ -103,7 +103,7 @@ TEST_F(AndroidSLESMicrophoneTest, TestPauseRecording) { /** * Test if recording works after mute / unmute. */ -TEST_F(AndroidSLESMicrophoneTest, TestUnPauseRecording) { +TEST_F(AndroidSLESMicrophoneTest, test_unPauseRecording) { EXPECT_TRUE(m_mic->startStreamingMicrophoneData()); EXPECT_TRUE(m_mic->stopStreamingMicrophoneData()); EXPECT_TRUE(m_mic->startStreamingMicrophoneData()); @@ -114,7 +114,7 @@ TEST_F(AndroidSLESMicrophoneTest, TestUnPauseRecording) { /** * Test recording for a full iteration on the buffer circular queue. */ -TEST_F(AndroidSLESMicrophoneTest, TestLongRecording) { +TEST_F(AndroidSLESMicrophoneTest, test_longRecording) { EXPECT_TRUE(m_mic->startStreamingMicrophoneData()); constexpr size_t iterations = AndroidSLESBufferQueue::NUMBER_OF_BUFFERS + 1; for (size_t i = 0; i < iterations; i++) { diff --git a/ApplicationUtilities/AndroidUtilities/test/AndroidSLESObjectTest.cpp b/ApplicationUtilities/AndroidUtilities/test/AndroidSLESObjectTest.cpp index 3f907d2a2a..ac91f053eb 100644 --- a/ApplicationUtilities/AndroidUtilities/test/AndroidSLESObjectTest.cpp +++ b/ApplicationUtilities/AndroidUtilities/test/AndroidSLESObjectTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -75,7 +75,7 @@ SLresult mockGetInterface(SLObjectItf self, const SLInterfaceID iid, void* pInte /** * Test create method when the provided object can be realized. */ -TEST_F(AndroidSLESObjectTest, testCreateDestroySucceed) { +TEST_F(AndroidSLESObjectTest, test_createDestroySucceed) { { SLObjectItf_ mockObj; SLObjectItf_* mockSinglePtr = &mockObj; @@ -94,7 +94,7 @@ TEST_F(AndroidSLESObjectTest, testCreateDestroySucceed) { /** * Test create method when the provided object cannot be realized. */ -TEST_F(AndroidSLESObjectTest, testCreateFailed) { +TEST_F(AndroidSLESObjectTest, test_createFailed) { SLObjectItf_ mockObj; SLObjectItf_* mockSinglePtr = &mockObj; SLObjectItf mockDoublePtr = &mockSinglePtr; @@ -109,7 +109,7 @@ TEST_F(AndroidSLESObjectTest, testCreateFailed) { /** * Test get interface when method succeeds. */ -TEST_F(AndroidSLESObjectTest, testGetInterface) { +TEST_F(AndroidSLESObjectTest, test_getInterface) { SLObjectItf_ mockObj; SLObjectItf_* mockSinglePtr = &mockObj; SLObjectItf mockDoublePtr = &mockSinglePtr; @@ -130,7 +130,7 @@ TEST_F(AndroidSLESObjectTest, testGetInterface) { /** * Test get interface when method fails. */ -TEST_F(AndroidSLESObjectTest, testGetInterfaceFailed) { +TEST_F(AndroidSLESObjectTest, test_getInterfaceFailed) { SLObjectItf_ mockObj; SLObjectItf_* mockSinglePtr = &mockObj; SLObjectItf mockDoublePtr = &mockSinglePtr; diff --git a/ApplicationUtilities/DefaultClient/include/DefaultClient/DefaultClient.h b/ApplicationUtilities/DefaultClient/include/DefaultClient/DefaultClient.h index 64f84d1da4..3e6c8a1a56 100644 --- a/ApplicationUtilities/DefaultClient/include/DefaultClient/DefaultClient.h +++ b/ApplicationUtilities/DefaultClient/include/DefaultClient/DefaultClient.h @@ -43,12 +43,12 @@ #include #include #include +#include #include #include #include #include #include -#include #include #include #include @@ -67,6 +67,10 @@ #include #endif +#ifdef ENABLE_COMMS_AUDIO_PROXY +#include +#endif + #include #include #include @@ -125,6 +129,11 @@ class DefaultClient : public avsCommon::sdkInterfaces::CapabilitiesObserverInter * @param bluetoothSpeaker The speaker to control volume of bluetooth. * @param ringtoneSpeaker The speaker to control volume of Comms ringtones. * @param additionalSpeakers A list of additional speakers to receive volume changes. +#ifdef ENABLE_COMMS_AUDIO_PROXY + * @param commsMediaPlayer The media player to play Comms calling audio. + * @param commsSpeaker The speaker to control volume of Comms calling audio. + * @param sharedDataStream The stream to use which has the audio from microphone. +#endif * @param equalizerRuntimeSetup Equalizer component runtime setup * @param audioFactory The audioFactory is a component that provides unique audio streams. * @param authDelegate The component that provides the client with valid LWA authorization. @@ -174,6 +183,11 @@ class DefaultClient : public avsCommon::sdkInterfaces::CapabilitiesObserverInter #ifdef ENABLE_PCC std::shared_ptr phoneSpeaker, std::shared_ptr phoneCaller, +#endif +#ifdef ENABLE_COMMS_AUDIO_PROXY + std::shared_ptr commsMediaPlayer, + std::shared_ptr commsSpeaker, + std::shared_ptr sharedDataStream, #endif std::shared_ptr equalizerRuntimeSetup, std::shared_ptr audioFactory, @@ -188,7 +202,7 @@ class DefaultClient : public avsCommon::sdkInterfaces::CapabilitiesObserverInter alexaDialogStateObservers, std::unordered_set> connectionObservers, - std::shared_ptr internetConnectionMonitor, + std::shared_ptr internetConnectionMonitor, bool isGuiSupported, std::shared_ptr capabilitiesDelegate, std::shared_ptr contextManager, @@ -686,6 +700,11 @@ class DefaultClient : public avsCommon::sdkInterfaces::CapabilitiesObserverInter #ifdef ENABLE_PCC std::shared_ptr phoneSpeaker, std::shared_ptr phoneCaller, +#endif +#ifdef ENABLE_COMMS_AUDIO_PROXY + std::shared_ptr commsMediaPlayer, + std::shared_ptr commsSpeaker, + std::shared_ptr sharedDataStream, #endif std::shared_ptr equalizerRuntimeSetup, std::shared_ptr audioFactory, @@ -700,7 +719,7 @@ class DefaultClient : public avsCommon::sdkInterfaces::CapabilitiesObserverInter alexaDialogStateObservers, std::unordered_set> connectionObservers, - std::shared_ptr internetConnectionMonitor, + std::shared_ptr internetConnectionMonitor, bool isGuiSupported, std::shared_ptr capabilitiesDelegate, std::shared_ptr contextManager, @@ -731,7 +750,7 @@ class DefaultClient : public avsCommon::sdkInterfaces::CapabilitiesObserverInter /// The connection manager. std::shared_ptr m_connectionManager; - std::shared_ptr m_internetConnectionMonitor; + std::shared_ptr m_internetConnectionMonitor; /// The exception sender. std::shared_ptr m_exceptionSender; @@ -760,6 +779,9 @@ class DefaultClient : public avsCommon::sdkInterfaces::CapabilitiesObserverInter /// The interaction model capability agent. std::shared_ptr m_interactionCapabilityAgent; + /// The notifications renderer. + std::shared_ptr m_notificationsRenderer; + /// The notifications capability agent. std::shared_ptr m_notificationsCapabilityAgent; @@ -826,6 +848,11 @@ class DefaultClient : public avsCommon::sdkInterfaces::CapabilitiesObserverInter /// Settings storage. This storage needs to be closed during default client destruction. std::shared_ptr m_deviceSettingStorage; + +#ifdef ENABLE_COMMS_AUDIO_PROXY + /// The CallAudioDeviceProxy used to work with audio proxy audio driver of CommsLib. + std::shared_ptr m_callAudioDeviceProxy; +#endif }; } // namespace defaultClient diff --git a/ApplicationUtilities/DefaultClient/src/DefaultClient.cpp b/ApplicationUtilities/DefaultClient/src/DefaultClient.cpp index 714cce1448..336a767cbf 100644 --- a/ApplicationUtilities/DefaultClient/src/DefaultClient.cpp +++ b/ApplicationUtilities/DefaultClient/src/DefaultClient.cpp @@ -17,7 +17,9 @@ #include #include #include +#include #include +#include #ifdef ENABLE_OPUS #include @@ -28,6 +30,10 @@ #include #endif +#ifdef ENABLE_COMMS_AUDIO_PROXY +#include +#endif + #ifdef ENABLE_PCC #include #include @@ -52,9 +58,6 @@ namespace defaultClient { using namespace alexaClientSDK::avsCommon::sdkInterfaces; -/// String identifier for 'Alexa Stop' return by wake word engine -static const std::string ALEXA_STOP_KEYWORD = "STOP"; - /// String to identify log entries originating from this file. static const std::string TAG("DefaultClient"); @@ -89,6 +92,11 @@ std::unique_ptr DefaultClient::create( #ifdef ENABLE_PCC std::shared_ptr phoneSpeaker, std::shared_ptr phoneCaller, +#endif +#ifdef ENABLE_COMMS_AUDIO_PROXY + std::shared_ptr commsMediaPlayer, + std::shared_ptr commsSpeaker, + std::shared_ptr sharedDataStream, #endif std::shared_ptr equalizerRuntimeSetup, std::shared_ptr audioFactory, @@ -103,7 +111,7 @@ std::unique_ptr DefaultClient::create( alexaDialogStateObservers, std::unordered_set> connectionObservers, - std::shared_ptr internetConnectionMonitor, + std::shared_ptr internetConnectionMonitor, bool isGuiSupported, std::shared_ptr capabilitiesDelegate, std::shared_ptr contextManager, @@ -135,6 +143,11 @@ std::unique_ptr DefaultClient::create( #ifdef ENABLE_PCC phoneSpeaker, phoneCaller, +#endif +#ifdef ENABLE_COMMS_AUDIO_PROXY + commsMediaPlayer, + commsSpeaker, + sharedDataStream, #endif equalizerRuntimeSetup, audioFactory, @@ -186,6 +199,11 @@ bool DefaultClient::initialize( #ifdef ENABLE_PCC std::shared_ptr phoneSpeaker, std::shared_ptr phoneCaller, +#endif +#ifdef ENABLE_COMMS_AUDIO_PROXY + std::shared_ptr commsMediaPlayer, + std::shared_ptr commsSpeaker, + std::shared_ptr sharedDataStream, #endif std::shared_ptr equalizerRuntimeSetup, std::shared_ptr audioFactory, @@ -200,7 +218,7 @@ bool DefaultClient::initialize( alexaDialogStateObservers, std::unordered_set> connectionObservers, - std::shared_ptr internetConnectionMonitor, + std::shared_ptr internetConnectionMonitor, bool isGuiSupported, std::shared_ptr capabilitiesDelegate, std::shared_ptr contextManager, @@ -301,23 +319,23 @@ bool DefaultClient::initialize( */ m_messageRouter = std::make_shared(authDelegate, attachmentManager, transportFactory); + if (!internetConnectionMonitor) { + ACSDK_CRITICAL(LX("initializeFailed").d("reason", "internetConnectionMonitor was nullptr")); + return false; + } + m_internetConnectionMonitor = internetConnectionMonitor; + /* * Creating the connection manager - This component is the overarching connection manager that glues together all * the other networking components into one easy-to-use component. */ - m_connectionManager = - acl::AVSConnectionManager::create(m_messageRouter, false, connectionObservers, {m_dialogUXStateAggregator}); + m_connectionManager = acl::AVSConnectionManager::create( + m_messageRouter, false, connectionObservers, {m_dialogUXStateAggregator}, internetConnectionMonitor); if (!m_connectionManager) { ACSDK_ERROR(LX("initializeFailed").d("reason", "unableToCreateConnectionManager")); return false; } - if (!internetConnectionMonitor) { - ACSDK_CRITICAL(LX("initializeFailed").d("reason", "internetConnectionMonitor was nullptr")); - return false; - } - m_internetConnectionMonitor = internetConnectionMonitor; - /* * Creating our certified sender - this component guarantees that messages given to it (expected to be JSON * formatted AVS Events) will be sent to AVS. This nicely decouples strict message sending from components which @@ -488,6 +506,10 @@ bool DefaultClient::initialize( allSpeakers.push_back(phoneSpeaker); #endif +#ifdef ENABLE_COMMS_AUDIO_PROXY + allSpeakers.push_back(commsSpeaker); +#endif + allSpeakers.insert(allSpeakers.end(), additionalSpeakers.begin(), additionalSpeakers.end()); /* @@ -524,13 +546,19 @@ bool DefaultClient::initialize( addConnectionObserver(m_dialogUXStateAggregator); + m_notificationsRenderer = capabilityAgents::notifications::NotificationRenderer::create(notificationsMediaPlayer); + if (!m_notificationsRenderer) { + ACSDK_ERROR(LX("initializeFailed").d("reason", "unableToCreateNotificationsRenderer")); + return false; + } + /* * Creating the Notifications Capability Agent - This component is the Capability Agent that implements the * Notifications interface of AVS. */ m_notificationsCapabilityAgent = capabilityAgents::notifications::NotificationsCapabilityAgent::create( notificationsStorage, - capabilityAgents::notifications::NotificationRenderer::create(notificationsMediaPlayer), + m_notificationsRenderer, contextManager, m_exceptionSender, audioFactory->notifications(), @@ -575,7 +603,9 @@ bool DefaultClient::initialize( contextManager, m_audioFocusManager, m_exceptionSender, - audioFactory->communications())) { + audioFactory->communications(), + nullptr, + m_speakerManager)) { ACSDK_ERROR(LX("initializeFailed").d("reason", "unableToCreateCallManager")); return false; } @@ -584,6 +614,18 @@ bool DefaultClient::initialize( addConnectionObserver(m_callManager); #endif +#ifdef ENABLE_COMMS_AUDIO_PROXY + auto acquireAudioInputStream = [sharedDataStream]() -> std::shared_ptr { + return sharedDataStream; + }; + auto relinquishAudioInputStream = [](std::shared_ptr stream) { + // Nothing to release + }; + m_callAudioDeviceProxy = capabilityAgents::callManager::CallAudioDeviceProxy::create( + commsMediaPlayer, commsSpeaker, acquireAudioInputStream, relinquishAudioInputStream); + m_callManager->addObserver(m_callAudioDeviceProxy); +#endif + std::shared_ptr settingsUpdatedEventSender = alexaClientSDK::capabilityAgents::settings::SettingsUpdatedEventSender::create(m_certifiedSender); if (!settingsUpdatedEventSender) { @@ -1353,9 +1395,11 @@ std::future DefaultClient::notifyOfWakeWord( std::chrono::steady_clock::time_point startOfSpeechTimestamp, const capabilityAgents::aip::ESPData espData, std::shared_ptr> KWDMetadata) { + ACSDK_DEBUG5(LX(__func__).d("keyword", keyword).d("connected", m_connectionManager->isConnected())); + if (!m_connectionManager->isConnected()) { std::promise ret; - if (ALEXA_STOP_KEYWORD == keyword) { + if (capabilityAgents::aip::AudioInputProcessor::KEYWORD_TEXT_STOP == keyword) { // Alexa Stop uttered while offline ACSDK_INFO(LX("notifyOfWakeWord").d("action", "localStop").d("reason", "stopUtteredWhileNotConnected")); stopForegroundActivity(); @@ -1506,6 +1550,10 @@ DefaultClient::~DefaultClient() { ACSDK_DEBUG5(LX("NotificationsShutdown.")); m_notificationsCapabilityAgent->shutdown(); } + if (m_notificationsRenderer) { + ACSDK_DEBUG5(LX("NotificationsRendererShutdown.")); + m_notificationsRenderer->shutdown(); + } if (m_bluetooth) { ACSDK_DEBUG5(LX("BluetoothShutdown.")); m_bluetooth->shutdown(); @@ -1548,6 +1596,12 @@ DefaultClient::~DefaultClient() { ACSDK_DEBUG5(LX("CloseSettingStorage")); m_deviceSettingStorage->close(); } + +#ifdef ENABLE_COMMS_AUDIO_PROXY + if (m_callManager) { + m_callManager->removeObserver(m_callAudioDeviceProxy); + } +#endif } } // namespace defaultClient diff --git a/BluetoothImplementations/BlueZ/include/BlueZ/BlueZBluetoothDevice.h b/BluetoothImplementations/BlueZ/include/BlueZ/BlueZBluetoothDevice.h index 7977bb02c3..6c9655052c 100644 --- a/BluetoothImplementations/BlueZ/include/BlueZ/BlueZBluetoothDevice.h +++ b/BluetoothImplementations/BlueZ/include/BlueZ/BlueZBluetoothDevice.h @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -228,6 +228,25 @@ class BlueZBluetoothDevice */ void transitionToState(BlueZDeviceState newState, bool sendEvent); + /* + * Querying BlueZ for whether the Connect property is set to true does not guarantee + * that a device has established a connection with its services. + * The Connect property can be set to true when pairing: + * + * 1) Pairing (BlueZ sends Connect = true). + * 2) Pair Successful. + * 3) Connect multimedia services. + * 4) Connect multimedia services successful (BlueZ sends Paired = true, UUIDs = [array of + * uuids]). + * + * Use a combination of Connect, Paired, and the availability of certain UUIDs to + * determine if a service has been connected to. A relevant service currently encompasses the set of + * A2DP services that AVS uses to understand connectedness. This should be done in the executor. + * + * @return Whether the device has established a connection with at least one service of interest. + */ + bool executeIsConnectedToRelevantServices(); + /** * Helper function to check if a service exists in the @c m_servicesMap. * diff --git a/BluetoothImplementations/BlueZ/src/BlueZBluetoothDevice.cpp b/BluetoothImplementations/BlueZ/src/BlueZBluetoothDevice.cpp index f83d3c9055..6974f27f01 100644 --- a/BluetoothImplementations/BlueZ/src/BlueZBluetoothDevice.cpp +++ b/BluetoothImplementations/BlueZ/src/BlueZBluetoothDevice.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -401,6 +401,8 @@ bool BlueZBluetoothDevice::executeConnect() { } ManagedGError error; + // Calling org.bluez.Device1::Connect will attempt to connect as many services as possible, and return when at least + // one service is connected. m_deviceProxy->callMethod(BLUEZ_DEVICE_METHOD_CONNECT, nullptr, error.toOutputParameter()); if (error.hasError()) { @@ -602,6 +604,17 @@ void BlueZBluetoothDevice::transitionToState(BlueZDeviceState newState, bool sen } } +bool BlueZBluetoothDevice::executeIsConnectedToRelevantServices() { + ACSDK_DEBUG5(LX(__func__)); + + bool isPaired = false; + bool isConnected = false; + bool relevantServiceDiscovered = getA2DPSink() != nullptr || getA2DPSource() != nullptr; + + return relevantServiceDiscovered && queryDeviceProperty(BLUEZ_DEVICE_PROPERTY_PAIRED, &isPaired) && isPaired && + queryDeviceProperty(BLUEZ_DEVICE_PROPERTY_CONNECTED, &isConnected) && isConnected; +} + // TODO ACSDK-1398: Refactor this with a proper state machine. void BlueZBluetoothDevice::onPropertyChanged(const GVariantMapReader& changesMap) { ACSDK_DEBUG5(LX(__func__).d("values", g_variant_print(changesMap.get(), true))); @@ -627,10 +640,6 @@ void BlueZBluetoothDevice::onPropertyChanged(const GVariantMapReader& changesMap } } - // This is used for checking connectedness. - bool a2dpSourceAvailable = false; - bool a2dpSinkAvailable = false; - /* * It's not guaranteed all services will be available at construction time. * If any become available at a later time, initialize them. @@ -641,21 +650,9 @@ void BlueZBluetoothDevice::onPropertyChanged(const GVariantMapReader& changesMap if (uuidsVariant.hasValue()) { auto uuids = getServiceUuids(uuidsVariant.get()); initializeServices(uuids); - - a2dpSourceAvailable = (uuids.count(A2DPSourceInterface::UUID) > 0); - a2dpSinkAvailable = (uuids.count(A2DPSinkInterface::UUID) > 0); } - m_executor.submit([this, - pairedChanged, - paired, - connectedChanged, - connected, - a2dpSourceAvailable, - a2dpSinkAvailable, - aliasChanged, - aliasStr] { - + m_executor.submit([this, pairedChanged, paired, connectedChanged, connected, aliasChanged, aliasStr] { if (aliasChanged) { ACSDK_DEBUG5(LX("nameChanged").d("oldName", m_friendlyName).d("newName", aliasStr)); m_friendlyName = aliasStr; @@ -667,29 +664,14 @@ void BlueZBluetoothDevice::onPropertyChanged(const GVariantMapReader& changesMap transitionToState(BlueZDeviceState::PAIRED, true); transitionToState(BlueZDeviceState::IDLE, true); - /* - * A connect signal doesn't always mean a device is connected by the BluetoothDeviceInterface - * definition. This sequence has been observed: - * - * 1) Pairing (BlueZ sends Connect = true). - * 2) Pair Successful. - * 3) Connect multimedia services. - * 4) Connect multimedia services successful (BlueZ sends Paired = true, UUIDs = [array of - * uuids]). - * - * Thus we will use the combination of Connect, Paired, and the availability of certain UUIDs to - * determine connectedness. - */ - bool isConnected = false; - if (queryDeviceProperty(BLUEZ_DEVICE_PROPERTY_CONNECTED, &isConnected) && isConnected && - (a2dpSourceAvailable || a2dpSinkAvailable)) { + if (executeIsConnectedToRelevantServices()) { transitionToState(BlueZDeviceState::CONNECTED, true); } } break; } case BlueZDeviceState::IDLE: { - if (connectedChanged && connected) { + if (executeIsConnectedToRelevantServices()) { transitionToState(BlueZDeviceState::CONNECTED, true); } else if (pairedChanged && !paired) { transitionToState(BlueZDeviceState::UNPAIRED, true); diff --git a/BluetoothImplementations/BlueZ/src/BlueZDeviceManager.cpp b/BluetoothImplementations/BlueZ/src/BlueZDeviceManager.cpp index 95fa1e6c68..dde8eca84f 100644 --- a/BluetoothImplementations/BlueZ/src/BlueZDeviceManager.cpp +++ b/BluetoothImplementations/BlueZ/src/BlueZDeviceManager.cpp @@ -236,6 +236,7 @@ std::shared_ptr BlueZDeviceManager::getDeviceByPath(const } void BlueZDeviceManager::onMediaStreamPropertyChanged(const std::string& path, const GVariantMapReader& changesMap) { + ACSDK_DEBUG7(LX(__func__).d("path", path)); const std::string FD_KEY = "/fd"; // Get device path without the /fd @@ -269,20 +270,23 @@ void BlueZDeviceManager::onMediaStreamPropertyChanged(const std::string& path, c ACSDK_DEBUG5(LX(__func__).d("mediaStreamUuid", uuid)); char* newStateStr; - avsCommon::utils::bluetooth::MediaStreamingState newState; - if (changesMap.getCString(MEDIATRANSPORT_PROPERTY_STATE, &newStateStr)) { - ACSDK_DEBUG5(LX("Media transport state changed").d("newState", newStateStr)); - - if (STATE_ACTIVE == newStateStr) { - newState = avsCommon::utils::bluetooth::MediaStreamingState::ACTIVE; - } else if (STATE_PENDING == newStateStr) { - newState = avsCommon::utils::bluetooth::MediaStreamingState::PENDING; - } else if (STATE_IDLE == newStateStr) { - newState = avsCommon::utils::bluetooth::MediaStreamingState::IDLE; - } else { - ACSDK_ERROR(LX("onMediaStreamPropertyChangedFailed").d("Unknown state", newStateStr)); - return; - } + if (!changesMap.getCString(MEDIATRANSPORT_PROPERTY_STATE, &newStateStr)) { + ACSDK_DEBUG5(LX("mediaTransportStateUnchanged").d("action", "ignoringCallback")); + return; + } + + ACSDK_DEBUG5(LX("mediaTransportStateChanged").d("newState", newStateStr)); + + MediaStreamingState newState = MediaStreamingState::IDLE; + if (STATE_ACTIVE == newStateStr) { + newState = MediaStreamingState::ACTIVE; + } else if (STATE_PENDING == newStateStr) { + newState = MediaStreamingState::PENDING; + } else if (STATE_IDLE == newStateStr) { + newState = MediaStreamingState::IDLE; + } else { + ACSDK_ERROR(LX("onMediaStreamPropertyChangedFailed").d("unknownState", newStateStr)); + return; } if (A2DPSourceInterface::UUID == uuid) { diff --git a/BluetoothImplementations/BlueZ/test/BlueZA2DPSinkTest.cpp b/BluetoothImplementations/BlueZ/test/BlueZA2DPSinkTest.cpp index 88da5b83f5..17e1b522b3 100644 --- a/BluetoothImplementations/BlueZ/test/BlueZA2DPSinkTest.cpp +++ b/BluetoothImplementations/BlueZ/test/BlueZA2DPSinkTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -26,12 +26,12 @@ namespace test { using namespace ::testing; /// Test that a valid object is returned. -TEST(BlueZA2DPSinkTest, createSucceeds) { +TEST(BlueZA2DPSinkTest, test_createSucceeds) { ASSERT_THAT(BlueZA2DPSink::create(), NotNull()); } /// Test the correct SDP record is returned. -TEST(BlueZA2DPSinkTest, checkSDPRecord) { +TEST(BlueZA2DPSinkTest, test_checkSDPRecord) { auto sdp = BlueZA2DPSink::create()->getRecord(); ASSERT_EQ(sdp->getUuid(), std::string(avsCommon::sdkInterfaces::bluetooth::services::A2DPSinkInterface::UUID)); ASSERT_EQ(sdp->getName(), std::string(avsCommon::sdkInterfaces::bluetooth::services::A2DPSinkInterface::NAME)); diff --git a/BluetoothImplementations/BlueZ/test/BlueZAVRCPControllerTest.cpp b/BluetoothImplementations/BlueZ/test/BlueZAVRCPControllerTest.cpp index 789fd5ab69..cc586478a7 100644 --- a/BluetoothImplementations/BlueZ/test/BlueZAVRCPControllerTest.cpp +++ b/BluetoothImplementations/BlueZ/test/BlueZAVRCPControllerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -26,12 +26,12 @@ namespace test { using namespace ::testing; /// Test that a valid object is returned. -TEST(BlueZAVRCPControllerTest, createSucceeds) { +TEST(BlueZAVRCPControllerTest, test_createSucceeds) { ASSERT_THAT(BlueZAVRCPController::create(), NotNull()); } /// Test the correct SDP record is returned. -TEST(BlueZAVRCPControllerTest, checkSDPRecord) { +TEST(BlueZAVRCPControllerTest, test_checkSDPRecord) { auto sdp = BlueZAVRCPController::create()->getRecord(); ASSERT_EQ( sdp->getUuid(), std::string(avsCommon::sdkInterfaces::bluetooth::services::AVRCPControllerInterface::UUID)); diff --git a/BluetoothImplementations/BlueZ/test/BlueZAVRCPTargetTest.cpp b/BluetoothImplementations/BlueZ/test/BlueZAVRCPTargetTest.cpp index 71730aa69c..9e6993d917 100644 --- a/BluetoothImplementations/BlueZ/test/BlueZAVRCPTargetTest.cpp +++ b/BluetoothImplementations/BlueZ/test/BlueZAVRCPTargetTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -47,36 +47,36 @@ void BlueZAVRCPTargetTest::SetUp() { } /// Test create() with a null proxy. Should return nullptr. -TEST_F(BlueZAVRCPTargetTest, createNullFails) { +TEST_F(BlueZAVRCPTargetTest, test_createNullFails) { ASSERT_THAT(BlueZAVRCPTarget::create(nullptr), IsNull()); } /// Test create() and expect success. -TEST_F(BlueZAVRCPTargetTest, createSucceeds) { +TEST_F(BlueZAVRCPTargetTest, test_createSucceeds) { auto proxy = std::make_shared(); ASSERT_THAT(BlueZAVRCPTarget::create(proxy), NotNull()); } /// Test that play() calls the correct method. -TEST_F(BlueZAVRCPTargetTest, playSuceeds) { +TEST_F(BlueZAVRCPTargetTest, test_playSuceeds) { EXPECT_CALL(*m_mockProxy, callMethod("Play", _, _)).Times(1); m_avrcpTarget->play(); } /// Test that pause() calls the correct method. -TEST_F(BlueZAVRCPTargetTest, pauseSuceeds) { +TEST_F(BlueZAVRCPTargetTest, test_pauseSuceeds) { EXPECT_CALL(*m_mockProxy, callMethod("Pause", _, _)).Times(1); m_avrcpTarget->pause(); } /// Test that next() calls the correct method. -TEST_F(BlueZAVRCPTargetTest, nextSuceeds) { +TEST_F(BlueZAVRCPTargetTest, test_nextSuceeds) { EXPECT_CALL(*m_mockProxy, callMethod("Next", _, _)).Times(1); m_avrcpTarget->next(); } /// Test that previous() calls the correct method. -TEST_F(BlueZAVRCPTargetTest, previousSuceeds) { +TEST_F(BlueZAVRCPTargetTest, test_previousSuceeds) { EXPECT_CALL(*m_mockProxy, callMethod("Previous", _, _)).Times(1); m_avrcpTarget->previous(); } diff --git a/BluetoothImplementations/BlueZ/test/MPRISPlayerTest.cpp b/BluetoothImplementations/BlueZ/test/MPRISPlayerTest.cpp index 3f69c5da91..e515916c33 100644 --- a/BluetoothImplementations/BlueZ/test/MPRISPlayerTest.cpp +++ b/BluetoothImplementations/BlueZ/test/MPRISPlayerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -137,20 +137,20 @@ void MPRISPlayerTest::gMainLoop() { } /// Test that the happy create() case succeeds. -TEST_F(MPRISPlayerTest, createSucceeds) { +TEST_F(MPRISPlayerTest, test_createSucceeds) { init(); ASSERT_THAT(m_player, NotNull()); } /// Tests that missing parameters result in a nullptr. -TEST_F(MPRISPlayerTest, createWithNullFails) { +TEST_F(MPRISPlayerTest, test_createWithNullFails) { ASSERT_THAT(MPRISPlayer::create(nullptr, m_mockMedia, m_eventBus), IsNull()); ASSERT_THAT(MPRISPlayer::create(g_connection, nullptr, m_eventBus), IsNull()); ASSERT_THAT(MPRISPlayer::create(g_connection, m_mockMedia, nullptr), IsNull()); } /// Tests that the MPRISPlayer properly registers and unregisters throughout its life time. -TEST_F(MPRISPlayerTest, playerRegistration) { +TEST_F(MPRISPlayerTest, test_playerRegistration) { Expectation registerPlayer = EXPECT_CALL(*m_mockMedia, callMethod("RegisterPlayer", _, _)).Times(1); EXPECT_CALL(*m_mockMedia, callMethod("UnregisterPlayer", _, _)).Times(1).After(registerPlayer); init(); @@ -191,7 +191,7 @@ MATCHER_P(ContainsAVRCPCommand, /* AVRCPCommand */ cmd, "") { } /// Test that a supported DBus method sends the correct corresponding AVRCPCommand. -TEST_P(MPRISPlayerSupportedAVRCPTest, avrcpCommand) { +TEST_P(MPRISPlayerSupportedAVRCPTest, test_avrcpCommand) { std::string dbusMethodName; AVRCPCommand command; @@ -235,7 +235,7 @@ INSTANTIATE_TEST_CASE_P( [](testing::TestParamInfo info) { return info.param; }); /// Test that unsupported DBus methods do not send any Bluetooth events. -TEST_P(MPRISPlayerUnsupportedTest, unsupportedMethod) { +TEST_P(MPRISPlayerUnsupportedTest, test_unsupportedMethod) { std::string dbusMethodName = GetParam(); EXPECT_CALL(*m_mockListener, onEventFired(_)).Times(0); diff --git a/CHANGELOG.md b/CHANGELOG.md index 045247e43c..880d4c1477 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,49 @@ ## ChangeLog +### v1.13.0 released 05/22/2019: + +**Enhancements** + +* When an active Alert moves to the background, the alert now begins after a 10-second delay. Alert loop iteration delays can now no longer last longer than a maximum of 10 seconds, rather than depending on the length of the audio asset. +* Changed NotificationsSpeaker to use Alerts Volume instead of using the speaker volume. +* Allow customers to pass in an implementation of InternetConnectionMonitorInterface which will force AVSConnectionManager to reconnect on internet connectivity loss. +* Added an exponential wait time for retrying transmitting a message via CertifiedSender. +* When Volume is set to 0 and device is unmuted, volume is bumped up to a non-zero value. When Volume is set to 0 and Alexa talks back to you, volume is bumped up to a non-zero value. +* Deprecated HttpResponseCodes.h, which is now present only to ensure backward compatibility. +* The default endpoint for AVS connections has changed. + +**Bug Fixes** + +* Fixed bug where receiving a Connected = true Property change from BlueZ without UUID information resulted in BlueZBluetoothDevice transitioning to CONNECTED state. +* Fixed bug where MediaStreamingStateChangedEvent may be sent on non-state related property changes. +* Added null check to SQLiteStatement::getColumnText. +* Fixed an issue where database values with unescaped single quotes passed to miscStorage database will fail to be stored. Added a note on the interface that only non-escaped values should be passed. +* Fixed a loop in audio in live stations based on playlists. +* Fixed a race condition in TemplateRuntime that may result in a crash. +* Fixed a race condition where a recognize event due to a EXPECT_SPEECH may end prematurely. +* Changed the name of Alerts channel to Alert channel within AudioActivityTracker. +* Prevented STOP Wakeword detections from generating Recognize events. +* The SQLiteDeviceSettingsStorageTest no longer fails for Android. + +**Known Issues** + +* Music playback history isn't being displayed in the Alexa app for certain account and device types. +* On GCC 8+, issues related to `-Wclass-memaccess` will trigger warnings. However, this won't cause the build to fail and these warnings can be ignored. +* Android error ("libDefaultClient.so" not found) can be resolved by upgrading to ADB version 1.0.40 +* When network connection is lost, lost connection status is not returned via local TTS. +* `ACL` may encounter issues if audio attachments are received but not consumed. +* `SpeechSynthesizerState` currently uses `GAINING_FOCUS` and `LOSING_FOCUS` as a workaround for handling intermediate state. These states may be removed in a future release. +* The Alexa app doesn't always indicate when a device is successfully connected via Bluetooth. +* Connecting a product to streaming media via Bluetooth will sometimes stop media playback within the source application. Resuming playback through the source application or toggling next/previous will correct playback. +* When a source device is streaming silence via Bluetooth, the Alexa app indicates that audio content is streaming. +* The Bluetooth agent assumes that the Bluetooth adapter is always connected to a power source. Disconnecting from a power source during operation is not yet supported. +* On some products, interrupted Bluetooth playback may not resume if other content is locally streamed. +* `make integration` is currently not available for Android. In order to run integration tests on Android, you'll need to manually upload the test binary file along with any input file. At that point, the adb can be used to run the integration tests. +* On Raspberry Pi running Android Things with HDMI output audio, beginning of speech is truncated when Alexa responds to user text-to-speech (TTS). +* When the sample app is restarted and the network connection is lost, the Reminder TTS message does not play. Instead, the default alarm tone will play twice. +* ServerDisconnectIntegratonTest tests have been disabled until they can be updated to reflect new service behavior. +* Devices connected before the Bluetooth CA is initialized are ignored. + ### v1.12.1 released 04/02/2019: **Bug Fixes** @@ -36,6 +80,7 @@ * The `BluetoothDeviceManagerInterface` instantiation was moved from `DefaultClient` to `SampleApp` to allow applications to override it. * The `MediaPlayerInterface` now supports repeating playback of URL sources. * The Kitt.AI wake word engine (WWE) is now compatible with GCC5+. +* Stop of ongoing alerts, management of MessageObservers, and management of CallStateObservers have been exposed through DefaultClient. **Bug Fixes** @@ -48,7 +93,6 @@ * Added missing shutdown handling for ContentDecrypter to prevent the `Stop` command from triggering a crash when SAMPLE-AES encrypted content was streaming. * Fixed a bug where if the Notifications database is empty, due to a crash or corruption, the SDK initialization process enters an infinite loop when it retries to get context from the Notifications capability agent. * Fixed a race condition that caused `AlertsRenderer` observers to miss notification that an alert has been completed. -* Fixed logging for adding/removing `BluetoothDeviceObserver` in the `DefaultClient`. **Known Issues** @@ -73,7 +117,7 @@ **Enhancements** * Added support for the new Alexa [DoNotDisturb](https://developer.amazon.com/docs/alexa-voice-service/donotdisturb.html) interface, which enables users to toggle the do not disturb (DND) function on their Alexa built-in products. -* The SDK now supports [Opus](https://opus-codec.org/license/) encoding, which is optional. To enable Opus, you must [set the CMake flag to `-DOPUS=ON`](https://github.com/alexa/avs-device-sdk/wiki/cmake-options#Opus-encoding), and include the [libopus library](https://github.com/alexa/avs-device-sdk/wiki/Dependencies#core-dependencies) dependency in your build. +* The SDK now supports [Opus](https://opus-codec.org/license/) encoding, which is optional. To enable Opus, you must [set the CMake flag to `-DOPUS=ON`](https://github.com/alexa/avs-device-sdk/wiki/Build-Options#Opus-encoding), and include the [libopus library](https://github.com/alexa/avs-device-sdk/wiki/Dependencies#core-dependencies) dependency in your build. * The MediaPlayer reference implementation has been expanded to support the SAMPLE-AES and AES-128 encryption methods for HLS streaming. * AES-128 encryption is dependent on libcrypto, which is part of the required openSSL library, and is enabled by default. * To enable [SAMPLE-AES](https://github.com/alexa/avs-device-sdk/wiki/Dependencies#core-dependencies/Enable-SAMPLE-AES-decryption) encryption, you must set the `-DSAMPLE_AES=ON` in your CMake command, and include the [FFMPEG](https://github.com/alexa/avs-device-sdk/wiki/Dependencies#core-dependencies/Enable-SAMPLE-AES-decryption) library dependency in your build. @@ -159,7 +203,7 @@ * Added Android SDK support, which includes new implementations of the MediaPlayer, audio recorder, and logger. * Added the [InteractionModel](https://developer.amazon.com/docs/alexa-voice-service/interaction-model.html) interface, which enables Alexa Routines. * Optional configuration changes have been introduced. Now a [network interface can be specified](https://github.com/alexa/avs-device-sdk/blob/v1.9/Integration/AlexaClientSDKConfig.json#L129) to connect to the SDK via curl. -* [Cmake parameters can be configured](https://github.com/alexa/avs-device-sdk/wiki/cmake-options#build-for-Android) to support Android. +* [Build options can be configured](https://github.com/alexa/avs-device-sdk/wiki/Build-Options#build-for-Android) to support Android. * Added GUI 1.1 support. The `PlaybackController` has been extended to support new control functionality, and the `System` interface has been updated to support `SoftwareInfo`. **Bug Fixes** diff --git a/CMakeLists.txt b/CMakeLists.txt index 308f74f484..4c16aaeb81 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.1 FATAL_ERROR) # Set project information -project(AlexaClientSDK VERSION 1.12.1 LANGUAGES CXX) +project(AlexaClientSDK VERSION 1.13.0 LANGUAGES CXX) set(PROJECT_BRIEF "A cross-platform, modular SDK for interacting with the Alexa Voice Service") if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/CapabilityAgents/ExternalMediaPlayer/src/ExternalMediaPlayerAdapters") set(HAS_EXTERNAL_MEDIA_PLAYER_ADAPTERS ON) diff --git a/CapabilitiesDelegate/test/CapabilitiesDelegateTest.cpp b/CapabilitiesDelegate/test/CapabilitiesDelegateTest.cpp index 5be42ca011..52cfc6072a 100644 --- a/CapabilitiesDelegate/test/CapabilitiesDelegateTest.cpp +++ b/CapabilitiesDelegate/test/CapabilitiesDelegateTest.cpp @@ -341,7 +341,7 @@ std::unordered_map> Capabi } /// Test publishing no capabilities -TEST_F(CapabilitiesDelegateTest, noCapability) { +TEST_F(CapabilitiesDelegateTest, test_noCapability) { ASSERT_EQ( m_capabilitiesDelegate->publishCapabilities(), CapabilitiesDelegate::CapabilitiesPublishReturnCode::FATAL_ERROR); @@ -350,7 +350,7 @@ TEST_F(CapabilitiesDelegateTest, noCapability) { } /// Test publishing capabilities with no errors -TEST_F(CapabilitiesDelegateTest, withCapabilitiesHappyCase) { +TEST_F(CapabilitiesDelegateTest, test_withCapabilitiesHappyCase) { std::shared_ptr capabilityProviderOne = std::make_shared(); capabilityProviderOne->addCapabilityConfiguration(INTERFACE_TYPE, INTERFACE_NAME_ONE, INTERFACE_VERSION); capabilityProviderOne->addCapabilityConfiguration(INTERFACE_TYPE, INTERFACE_NAME_THREE, INTERFACE_VERSION); @@ -427,7 +427,7 @@ TEST_F(CapabilitiesDelegateTest, withCapabilitiesHappyCase) { } /// Test publishing capabilities that returns a fatal error -TEST_F(CapabilitiesDelegateTest, publishFatalError) { +TEST_F(CapabilitiesDelegateTest, test_publishFatalError) { std::shared_ptr capabilityProvider = std::make_shared(); capabilityProvider->addCapabilityConfiguration(INTERFACE_TYPE, INTERFACE_NAME_ONE, INTERFACE_VERSION); @@ -441,7 +441,7 @@ TEST_F(CapabilitiesDelegateTest, publishFatalError) { } /// Test publishing capabilities that returns a retriable error -TEST_F(CapabilitiesDelegateTest, publishRetriableError) { +TEST_F(CapabilitiesDelegateTest, test_publishRetriableError) { std::shared_ptr capabilityProvider = std::make_shared(); capabilityProvider->addCapabilityConfiguration(INTERFACE_TYPE, INTERFACE_NAME_ONE, INTERFACE_VERSION); @@ -455,7 +455,7 @@ TEST_F(CapabilitiesDelegateTest, publishRetriableError) { } /// Test republishing capabilities -TEST_F(CapabilitiesDelegateTest, republish) { +TEST_F(CapabilitiesDelegateTest, test_republish) { std::shared_ptr capabilityProvider = std::make_shared(); capabilityProvider->addCapabilityConfiguration( INTERFACE_TYPE, INTERFACE_NAME_ONE, INTERFACE_VERSION, INTERFACE_CONFIG); @@ -525,7 +525,7 @@ TEST_F(CapabilitiesDelegateTest, republish) { } /// Tests with registering capabilities -TEST_F(CapabilitiesDelegateTest, registerTests) { +TEST_F(CapabilitiesDelegateTest, test_registerTests) { std::shared_ptr capabilityProvider = std::make_shared(); std::unordered_map capabilityConfigurationMap; @@ -608,7 +608,7 @@ TEST_F(CapabilitiesDelegateTest, registerTests) { } /// Test after clearData() is called, that the databse is deleted. -TEST_F(CapabilitiesDelegateTest, testClearData) { +TEST_F(CapabilitiesDelegateTest, test_clearData) { std::shared_ptr capabilityProvider = std::make_shared(); capabilityProvider->addCapabilityConfiguration( INTERFACE_TYPE, INTERFACE_NAME_ONE, INTERFACE_VERSION, INTERFACE_CONFIG); diff --git a/CapabilitiesDelegate/test/Common/TestableHttpPut.cpp b/CapabilitiesDelegate/test/Common/TestableHttpPut.cpp index e4c60bf6ce..e9871e40a1 100644 --- a/CapabilitiesDelegate/test/Common/TestableHttpPut.cpp +++ b/CapabilitiesDelegate/test/Common/TestableHttpPut.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. diff --git a/CapabilityAgents/AIP/include/AIP/AudioInputProcessor.h b/CapabilityAgents/AIP/include/AIP/AudioInputProcessor.h index 0dafcae707..2093615898 100644 --- a/CapabilityAgents/AIP/include/AIP/AudioInputProcessor.h +++ b/CapabilityAgents/AIP/include/AIP/AudioInputProcessor.h @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -73,6 +73,9 @@ class AudioInputProcessor /// Alias to the @c AudioInputProcessorObserverInterface for brevity. using ObserverInterface = avsCommon::sdkInterfaces::AudioInputProcessorObserverInterface; + /// A special keyword sent by supported wakeword engines for "Alexa, Stop". + static constexpr const char* KEYWORD_TEXT_STOP = "STOP"; + /// A reserved @c Index value which is considered invalid. static const auto INVALID_INDEX = std::numeric_limits::max(); @@ -129,6 +132,9 @@ class AudioInputProcessor * allowed to override an ongoing Recognize Event. If the flags do not allow an override, no event will be sent, no * state change will occur, and the function will fail. * + * A special case is that the function will also fail if the keyword passed in is equal + * to @c KEYWORD_TEXT_STOP. This check is case insensitive. + * * @note This function will not pass the audio stream to @c MessageSenderInterface to start streaming if the the * start index or any subsequent data has already expired from the buffer. In addition, it is assumed that * @c MessageSenderInterface will stop streaming immediately if it detects an overrun, and notify AIP of this @@ -565,6 +571,9 @@ class AudioInputProcessor */ std::shared_ptr m_recognizeRequest; + /// The @c MessageRequest for the most recent Recognize event sent with the @c MessageSender. + std::shared_ptr m_recognizeRequestSent; + /// The current state of the @c AudioInputProcessor. ObserverInterface::State m_state; diff --git a/CapabilityAgents/AIP/src/AudioInputProcessor.cpp b/CapabilityAgents/AIP/src/AudioInputProcessor.cpp index 00407fce40..04dc84df94 100644 --- a/CapabilityAgents/AIP/src/AudioInputProcessor.cpp +++ b/CapabilityAgents/AIP/src/AudioInputProcessor.cpp @@ -13,6 +13,8 @@ * permissions and limitations under the License. */ +#include +#include #include #include @@ -211,6 +213,15 @@ std::future AudioInputProcessor::recognize( std::shared_ptr> KWDMetadata) { ACSDK_METRIC_IDS(TAG, "Recognize", "", "", Metrics::Location::AIP_RECEIVE); + std::string upperCaseKeyword = keyword; + std::transform(upperCaseKeyword.begin(), upperCaseKeyword.end(), upperCaseKeyword.begin(), ::toupper); + if (KEYWORD_TEXT_STOP == upperCaseKeyword) { + ACSDK_DEBUG(LX("skippingRecognizeEvent").d("reason", "invalidKeyword").d("keyword", keyword)); + std::promise ret; + ret.set_value(false); + return ret.get_future(); + } + // If no begin index was provided, grab the current index ASAP so that we can start streaming from the time this // call was made. if (audioProvider.stream && INVALID_INDEX == begin) { @@ -730,8 +741,6 @@ void AudioInputProcessor::executeOnContextAvailable(const std::string jsonContex // Release ownership of the metadata so it can be released once ACL will finish sending the message. m_KWDMetadataReader.reset(); - m_recognizeRequest->addObserver(shared_from_this()); - // If we already have focus, there won't be a callback to send the message, so send it now. if (avsCommon::avs::FocusState::FOREGROUND == m_focusState) { sendRequestNow(); @@ -843,6 +852,7 @@ bool AudioInputProcessor::executeStopCapture(bool stopImmediately, std::shared_p void AudioInputProcessor::executeResetState() { // Irrespective of current state, clean up and go back to idle. + ACSDK_DEBUG(LX(__func__)); m_expectingSpeechTimer.stop(); m_precedingExpectSpeechInitiator.reset(); if (m_reader) { @@ -853,6 +863,10 @@ void AudioInputProcessor::executeResetState() { } m_reader.reset(); m_KWDMetadataReader.reset(); + if (m_recognizeRequestSent) { + m_recognizeRequestSent->removeObserver(shared_from_this()); + m_recognizeRequestSent.reset(); + } m_recognizeRequest.reset(); m_espRequest.reset(); m_preparingToSend = false; @@ -979,6 +993,7 @@ void AudioInputProcessor::removeDirective(std::shared_ptr info) { } void AudioInputProcessor::sendRequestNow() { + ACSDK_DEBUG(LX(__func__)); if (m_espRequest) { m_messageSender->sendMessage(m_espRequest); m_espRequest.reset(); @@ -986,7 +1001,12 @@ void AudioInputProcessor::sendRequestNow() { if (m_recognizeRequest) { ACSDK_METRIC_IDS(TAG, "Recognize", "", "", Metrics::Location::AIP_SEND); - m_messageSender->sendMessage(m_recognizeRequest); + if (m_recognizeRequestSent && (m_recognizeRequestSent != m_recognizeRequest)) { + m_recognizeRequestSent->removeObserver(shared_from_this()); + } + m_recognizeRequestSent = m_recognizeRequest; + m_recognizeRequestSent->addObserver(shared_from_this()); + m_messageSender->sendMessage(m_recognizeRequestSent); m_recognizeRequest.reset(); m_preparingToSend = false; if (m_deferredStopCapture) { diff --git a/CapabilityAgents/AIP/test/AudioInputProcessorTest.cpp b/CapabilityAgents/AIP/test/AudioInputProcessorTest.cpp index 0056fc46ff..b7a6ded0f6 100644 --- a/CapabilityAgents/AIP/test/AudioInputProcessorTest.cpp +++ b/CapabilityAgents/AIP/test/AudioInputProcessorTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -1456,7 +1456,7 @@ void AudioInputProcessorTest::testAIPStateTransitionOnEventFinish( } /// Function to verify that @c AudioInputProcessor::create() errors out with an invalid @c DirectiveSequencerInterface. -TEST_F(AudioInputProcessorTest, createWithoutDirectiveSequencer) { +TEST_F(AudioInputProcessorTest, test_createWithoutDirectiveSequencer) { m_audioInputProcessor->removeObserver(m_dialogUXStateAggregator); m_audioInputProcessor = AudioInputProcessor::create( nullptr, @@ -1472,7 +1472,7 @@ TEST_F(AudioInputProcessorTest, createWithoutDirectiveSequencer) { } /// Function to verify that @c AudioInputProcessor::create() errors out with an invalid @c MessageSenderInterface. -TEST_F(AudioInputProcessorTest, createWithoutMessageSender) { +TEST_F(AudioInputProcessorTest, test_createWithoutMessageSender) { m_audioInputProcessor->removeObserver(m_dialogUXStateAggregator); m_audioInputProcessor = AudioInputProcessor::create( m_mockDirectiveSequencer, @@ -1488,7 +1488,7 @@ TEST_F(AudioInputProcessorTest, createWithoutMessageSender) { } /// Function to verify that @c AudioInputProcessor::create() errors out with an invalid @c ContextManagerInterface. -TEST_F(AudioInputProcessorTest, createWithoutContextManager) { +TEST_F(AudioInputProcessorTest, test_createWithoutContextManager) { m_audioInputProcessor->removeObserver(m_dialogUXStateAggregator); m_audioInputProcessor = AudioInputProcessor::create( m_mockDirectiveSequencer, @@ -1504,7 +1504,7 @@ TEST_F(AudioInputProcessorTest, createWithoutContextManager) { } /// Function to verify that @c AudioInputProcessor::create() errors out with an invalid @c FocusManagerInterface. -TEST_F(AudioInputProcessorTest, createWithoutFocusManager) { +TEST_F(AudioInputProcessorTest, test_createWithoutFocusManager) { m_audioInputProcessor->removeObserver(m_dialogUXStateAggregator); m_audioInputProcessor = AudioInputProcessor::create( m_mockDirectiveSequencer, @@ -1520,7 +1520,7 @@ TEST_F(AudioInputProcessorTest, createWithoutFocusManager) { } /// Function to verify that @c AudioInputProcessor::create() errors out with an invalid @c DialogUXStateAggregator. -TEST_F(AudioInputProcessorTest, createWithoutStateAggregator) { +TEST_F(AudioInputProcessorTest, test_createWithoutStateAggregator) { m_audioInputProcessor->removeObserver(m_dialogUXStateAggregator); m_audioInputProcessor = AudioInputProcessor::create( m_mockDirectiveSequencer, @@ -1539,7 +1539,7 @@ TEST_F(AudioInputProcessorTest, createWithoutStateAggregator) { * Function to verify that @c AudioInputProcessor::create() errors out with an invalid * @c ExceptionEncounteredSenderInterface. */ -TEST_F(AudioInputProcessorTest, createWithoutExceptionSender) { +TEST_F(AudioInputProcessorTest, test_createWithoutExceptionSender) { m_audioInputProcessor->removeObserver(m_dialogUXStateAggregator); m_audioInputProcessor = AudioInputProcessor::create( m_mockDirectiveSequencer, @@ -1558,7 +1558,7 @@ TEST_F(AudioInputProcessorTest, createWithoutExceptionSender) { * Function to verify that @c AudioInputProcessor::create() errors out with an invalid * @c UserInactivityMonitorInterface. */ -TEST_F(AudioInputProcessorTest, createWithoutUserInactivityMonitor) { +TEST_F(AudioInputProcessorTest, test_createWithoutUserInactivityMonitor) { m_audioInputProcessor->removeObserver(m_dialogUXStateAggregator); m_audioInputProcessor = AudioInputProcessor::create( m_mockDirectiveSequencer, @@ -1574,7 +1574,7 @@ TEST_F(AudioInputProcessorTest, createWithoutUserInactivityMonitor) { } /// Function to verify that @c AudioInputProcessor::create() succeeds with a null @c AudioProvider. -TEST_F(AudioInputProcessorTest, createWithoutAudioProvider) { +TEST_F(AudioInputProcessorTest, test_createWithoutAudioProvider) { m_audioInputProcessor->removeObserver(m_dialogUXStateAggregator); m_audioInputProcessor = AudioInputProcessor::create( m_mockDirectiveSequencer, @@ -1588,7 +1588,7 @@ TEST_F(AudioInputProcessorTest, createWithoutAudioProvider) { } /// Function to verify that @c AudioInputProcessor::getconfiguration() returns the expected configuration data. -TEST_F(AudioInputProcessorTest, getConfiguration) { +TEST_F(AudioInputProcessorTest, test_getConfiguration) { DirectiveHandlerConfiguration expectedConfiguration{ {STOP_CAPTURE, BlockingPolicy(BlockingPolicy::MEDIUMS_NONE, false)}, {EXPECT_SPEECH, BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, true)}, @@ -1602,7 +1602,7 @@ TEST_F(AudioInputProcessorTest, getConfiguration) { * Function to verify that observers can be added/removed. Nothing is directly asserted here, but this test verifies * that these functions work without crashing. */ -TEST_F(AudioInputProcessorTest, addRemoveObserver) { +TEST_F(AudioInputProcessorTest, test_addRemoveObserver) { // Null pointer detection. m_audioInputProcessor->addObserver(nullptr); m_audioInputProcessor->removeObserver(nullptr); @@ -1626,14 +1626,14 @@ TEST_F(AudioInputProcessorTest, addRemoveObserver) { } /// This function verifies that @c AudioInputProcessor::recognize() fails when given a null @c AudioProvider. -TEST_F(AudioInputProcessorTest, recognizeNullStream) { +TEST_F(AudioInputProcessorTest, test_recognizeNullStream) { auto result = m_audioInputProcessor->recognize(AudioProvider::null(), Initiator::PRESS_AND_HOLD); ASSERT_TRUE(result.valid()); ASSERT_FALSE(result.get()); } /// This function verifies that @c AudioInputProcessor::recognize() fails when given invalid @c AudioFormats. -TEST_F(AudioInputProcessorTest, recognizeInvalidAudioFormat) { +TEST_F(AudioInputProcessorTest, test_recognizeInvalidAudioFormat) { AudioProvider audioProvider = *m_audioProvider; audioProvider.format.endianness = avsCommon::utils::AudioFormat::Endianness::BIG; EXPECT_FALSE(m_audioInputProcessor->recognize(audioProvider, Initiator::PRESS_AND_HOLD).get()); @@ -1652,17 +1652,17 @@ TEST_F(AudioInputProcessorTest, recognizeInvalidAudioFormat) { } /// This function verifies that @c AudioInputProcessor::recognize() works with @c Initiator::PRESS_AND_HOLD. -TEST_F(AudioInputProcessorTest, recognizePressAndHold) { +TEST_F(AudioInputProcessorTest, test_recognizePressAndHold) { ASSERT_TRUE(testRecognizeSucceeds(*m_audioProvider, Initiator::PRESS_AND_HOLD)); } /// This function verifies that @c AudioInputProcessor::recognize() works with @c Initiator::TAP. -TEST_F(AudioInputProcessorTest, recognizeTap) { +TEST_F(AudioInputProcessorTest, test_recognizeTap) { ASSERT_TRUE(testRecognizeSucceeds(*m_audioProvider, Initiator::TAP)); } /// This function verifies that @c AudioInputProcessor::recognize() fails with @c Initiator::WAKEWORD and no keyword. -TEST_F(AudioInputProcessorTest, recognizeWakewordWithoutKeyword) { +TEST_F(AudioInputProcessorTest, test_recognizeWakewordWithoutKeyword) { EXPECT_TRUE(testRecognizeFails(*m_audioProvider, Initiator::WAKEWORD)); } @@ -1670,7 +1670,7 @@ TEST_F(AudioInputProcessorTest, recognizeWakewordWithoutKeyword) { * This function verifies that @c AudioInputProcessor::recognize() fails with @c Initiator::WAKEWORD and invalid begin * index. */ -TEST_F(AudioInputProcessorTest, recognizeWakewordWithBadBegin) { +TEST_F(AudioInputProcessorTest, test_recognizeWakewordWithBadBegin) { // Write data until the sds wraps, which will make 0 an invalid index. for (size_t written = 0; written <= SDS_WORDS; written += PATTERN_WORDS) { EXPECT_EQ(m_writer->write(m_pattern.data(), m_pattern.size()), static_cast(m_pattern.size())); @@ -1681,14 +1681,14 @@ TEST_F(AudioInputProcessorTest, recognizeWakewordWithBadBegin) { } /// This function verifies that @c AudioInputProcessor::recognize() works with @c Initiator::WAKEWORD and keyword. -TEST_F(AudioInputProcessorTest, recognizeWakewordWithKeyword) { +TEST_F(AudioInputProcessorTest, test_recognizeWakewordWithKeyword) { auto begin = AudioInputProcessor::INVALID_INDEX; auto end = AudioInputProcessor::INVALID_INDEX; EXPECT_TRUE(testRecognizeSucceeds(*m_audioProvider, Initiator::WAKEWORD, begin, end, KEYWORD_TEXT)); } /// This function verifies that @c AudioInputProcessor::recognize() works with @c Initiator::WAKEWORD valid begin. -TEST_F(AudioInputProcessorTest, recognizeWakewordWithGoodBegin) { +TEST_F(AudioInputProcessorTest, test_recognizeWakewordWithGoodBegin) { avsCommon::avs::AudioInputStream::Index begin = 0; auto end = AudioInputProcessor::INVALID_INDEX; EXPECT_TRUE(testRecognizeSucceeds(*m_audioProvider, Initiator::WAKEWORD, begin, end, KEYWORD_TEXT)); @@ -1698,35 +1698,35 @@ TEST_F(AudioInputProcessorTest, recognizeWakewordWithGoodBegin) { * This function verifies that @c AudioInputProcessor::recognize() works with @c Initiator::WAKEWORD valid begin and * end indices. */ -TEST_F(AudioInputProcessorTest, recognizeWakewordWithGoodBeginAndEnd) { +TEST_F(AudioInputProcessorTest, test_recognizeWakewordWithGoodBeginAndEnd) { avsCommon::avs::AudioInputStream::Index begin = PREROLL_WORDS; avsCommon::avs::AudioInputStream::Index end = PREROLL_WORDS + WAKEWORD_WORDS; EXPECT_TRUE(testRecognizeSucceeds(*m_audioProvider, Initiator::WAKEWORD, begin, end, KEYWORD_TEXT)); } /// This function verifies that @c AudioInputProcessor::recognize() works with @c ASRProfile::CLOSE_TALK. -TEST_F(AudioInputProcessorTest, recognizeCloseTalk) { +TEST_F(AudioInputProcessorTest, test_recognizeCloseTalk) { auto audioProvider = *m_audioProvider; audioProvider.profile = ASRProfile::CLOSE_TALK; ASSERT_TRUE(testRecognizeSucceeds(audioProvider, Initiator::PRESS_AND_HOLD)); } /// This function verifies that @c AudioInputProcessor::recognize() works with @c ASRProfile::NEAR_FIELD. -TEST_F(AudioInputProcessorTest, recognizeNearField) { +TEST_F(AudioInputProcessorTest, test_recognizeNearField) { auto audioProvider = *m_audioProvider; audioProvider.profile = ASRProfile::NEAR_FIELD; ASSERT_TRUE(testRecognizeSucceeds(audioProvider, Initiator::TAP)); } /// This function verifies that @c AudioInputProcessor::recognize() works with @c ASRProfile::FAR_FIELD. -TEST_F(AudioInputProcessorTest, recognizeFarField) { +TEST_F(AudioInputProcessorTest, test_recognizeFarField) { auto audioProvider = *m_audioProvider; audioProvider.profile = ASRProfile::FAR_FIELD; ASSERT_TRUE(testRecognizeSucceeds(audioProvider, Initiator::TAP)); } /// This function verifies that @c AudioInputProcessor::recognize() works in @c State::EXPECTING_SPEECH. -TEST_F(AudioInputProcessorTest, recognizeWhileExpectingSpeech) { +TEST_F(AudioInputProcessorTest, test_recognizeWhileExpectingSpeech) { removeDefaultAudioProvider(); ASSERT_TRUE(testExpectSpeechWaits(WITH_DIALOG_REQUEST_ID, !VERIFY_TIMEOUT)); // Recognize event after an ExpectSpeech results in the ExpectSpeech's initiator being passed back to AVS. @@ -1744,7 +1744,7 @@ TEST_F(AudioInputProcessorTest, recognizeWhileExpectingSpeech) { * This function verifies that @c AudioInputProcessor::recognize() works with a call to @c stopCapture() immediately * after the @c recognize() call. */ -TEST_F(AudioInputProcessorTest, recognizeStopAfterRecognize) { +TEST_F(AudioInputProcessorTest, test_recognizeStopAfterRecognize) { auto audioProvider = *m_audioProvider; audioProvider.profile = ASRProfile::CLOSE_TALK; ASSERT_TRUE(testRecognizeSucceeds( @@ -1760,7 +1760,7 @@ TEST_F(AudioInputProcessorTest, recognizeStopAfterRecognize) { * This function verifies that @c AudioInputProcessor::recognize() works with a call to @c stopCapture() immediately * after the @c onContextAvailable() call. */ -TEST_F(AudioInputProcessorTest, recognizeStopAfterContext) { +TEST_F(AudioInputProcessorTest, test_recognizeStopAfterContext) { auto audioProvider = *m_audioProvider; audioProvider.profile = ASRProfile::CLOSE_TALK; ASSERT_TRUE(testRecognizeSucceeds( @@ -1776,7 +1776,7 @@ TEST_F(AudioInputProcessorTest, recognizeStopAfterContext) { * This function verifies that @c AudioInputProcessor::recognize() works with a call to @c stopCapture() immediately * after the @c onFocusChanged() call. */ -TEST_F(AudioInputProcessorTest, recognizeStopAfterFocus) { +TEST_F(AudioInputProcessorTest, test_recognizeStopAfterFocus) { auto audioProvider = *m_audioProvider; audioProvider.profile = ASRProfile::CLOSE_TALK; ASSERT_TRUE(testRecognizeSucceeds( @@ -1792,7 +1792,7 @@ TEST_F(AudioInputProcessorTest, recognizeStopAfterFocus) { * This function verifies that @c AudioInputProcessor::recognize() works with a call to @c stopCapture() immediately * after the message is sent. */ -TEST_F(AudioInputProcessorTest, recognizeStopAfterSend) { +TEST_F(AudioInputProcessorTest, test_recognizeStopAfterSend) { auto audioProvider = *m_audioProvider; audioProvider.profile = ASRProfile::CLOSE_TALK; ASSERT_TRUE(testRecognizeSucceeds( @@ -1808,7 +1808,7 @@ TEST_F(AudioInputProcessorTest, recognizeStopAfterSend) { * This function verifies that @c AudioInputProcessor::recognize() works in @c State::RECOGNIZING when the previous * recognize used the CLOSE_TALK profile. */ -TEST_F(AudioInputProcessorTest, recognizeBargeInWhileRecognizingCloseTalk) { +TEST_F(AudioInputProcessorTest, test_recognizeBargeInWhileRecognizingCloseTalk) { auto audioProvider = *m_audioProvider; audioProvider.profile = ASRProfile::CLOSE_TALK; ASSERT_TRUE(testRecognizeSucceeds(audioProvider, Initiator::TAP)); @@ -1819,7 +1819,7 @@ TEST_F(AudioInputProcessorTest, recognizeBargeInWhileRecognizingCloseTalk) { * This function verifies that @c AudioInputProcessor::recognize() works in @c State::RECOGNIZING when the previous * recognize used the NEAR_FIELD profile. */ -TEST_F(AudioInputProcessorTest, recognizeBargeInWhileRecognizingNearField) { +TEST_F(AudioInputProcessorTest, test_recognizeBargeInWhileRecognizingNearField) { auto audioProvider = *m_audioProvider; audioProvider.profile = ASRProfile::NEAR_FIELD; ASSERT_TRUE(testRecognizeSucceeds(audioProvider, Initiator::TAP)); @@ -1830,7 +1830,7 @@ TEST_F(AudioInputProcessorTest, recognizeBargeInWhileRecognizingNearField) { * This function verifies that @c AudioInputProcessor::recognize() works in @c State::RECOGNIZING when the previous * recognize used the FAR_FIELD profile. */ -TEST_F(AudioInputProcessorTest, recognizeBargeInWhileRecognizingFarField) { +TEST_F(AudioInputProcessorTest, test_recognizeBargeInWhileRecognizingFarField) { auto audioProvider = *m_audioProvider; audioProvider.profile = ASRProfile::FAR_FIELD; ASSERT_TRUE(testRecognizeSucceeds(audioProvider, Initiator::TAP)); @@ -1841,7 +1841,7 @@ TEST_F(AudioInputProcessorTest, recognizeBargeInWhileRecognizingFarField) { * This function verifies that @c AudioInputProcessor::recognize() fails in @c State::RECOGNIZING when the second * @c AudioProvider can't override. */ -TEST_F(AudioInputProcessorTest, recognizeBargeInWhileRecognizingCantOverride) { +TEST_F(AudioInputProcessorTest, test_recognizeBargeInWhileRecognizingCantOverride) { ASSERT_TRUE(testRecognizeSucceeds(*m_audioProvider, Initiator::TAP)); auto audioProvider = *m_audioProvider; audioProvider.canOverride = false; @@ -1852,7 +1852,7 @@ TEST_F(AudioInputProcessorTest, recognizeBargeInWhileRecognizingCantOverride) { * This function verifies that @c AudioInputProcessor::recognize() fails in @c State::RECOGNIZING when the * first @c AudioProvider can't be overridden. */ -TEST_F(AudioInputProcessorTest, recognizeBargeInWhileRecognizingCantBeOverridden) { +TEST_F(AudioInputProcessorTest, test_recognizeBargeInWhileRecognizingCantBeOverridden) { auto audioProvider = *m_audioProvider; audioProvider.canBeOverridden = false; ASSERT_TRUE(testRecognizeSucceeds(audioProvider, Initiator::TAP)); @@ -1860,19 +1860,19 @@ TEST_F(AudioInputProcessorTest, recognizeBargeInWhileRecognizingCantBeOverridden } /// This function verifies that @c AudioInputProcessor::stopCapture() fails in @c State::IDLE. -TEST_F(AudioInputProcessorTest, stopCaptureWhenIdle) { +TEST_F(AudioInputProcessorTest, test_stopCaptureWhenIdle) { ASSERT_FALSE(m_audioInputProcessor->stopCapture().get()); } /// This function verifies that @c AudioInputProcessor::stopCapture() fails in @c State::EXPECTING_SPEECH. -TEST_F(AudioInputProcessorTest, stopCaptureWhenExpectingSpeech) { +TEST_F(AudioInputProcessorTest, test_stopCaptureWhenExpectingSpeech) { removeDefaultAudioProvider(); ASSERT_TRUE(testExpectSpeechWaits(WITH_DIALOG_REQUEST_ID, !VERIFY_TIMEOUT)); ASSERT_FALSE(m_audioInputProcessor->stopCapture().get()); } /// This function verifies that @c AudioInputProcessor::stopCapture() works in @c State::RECOGNIZING. -TEST_F(AudioInputProcessorTest, stopCaptureWhenRecognizing) { +TEST_F(AudioInputProcessorTest, test_stopCaptureWhenRecognizing) { ASSERT_TRUE(testRecognizeSucceeds(*m_audioProvider, Initiator::TAP, 0)); ASSERT_TRUE(testStopCaptureSucceeds()); @@ -1886,7 +1886,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureWhenRecognizing) { * This function verifies that @c AudioInputProcessor::stopCapture() works in @c State::RECOGNIZING and check if * subsequent StopCapture directive will be ignored. */ -TEST_F(AudioInputProcessorTest, stopCaptureWhenRecognizingFollowByStopCaptureDirective) { +TEST_F(AudioInputProcessorTest, test_stopCaptureWhenRecognizingFollowByStopCaptureDirective) { ASSERT_TRUE(testRecognizeSucceeds(*m_audioProvider, Initiator::TAP, 0)); ASSERT_TRUE(testStopCaptureSucceeds()); @@ -1917,12 +1917,12 @@ TEST_F(AudioInputProcessorTest, stopCaptureWhenRecognizingFollowByStopCaptureDir } /// This function verifies that @c AudioInputProcessor::resetState() works in @c State::IDLE. -TEST_F(AudioInputProcessorTest, resetStateWhenIdle) { +TEST_F(AudioInputProcessorTest, test_resetStateWhenIdle) { m_audioInputProcessor->resetState().get(); } /// This function verifies that @c AudioInputProcessor::resetState() works in @c State::EXPECTING_SPEECH. -TEST_F(AudioInputProcessorTest, resetStateWhenExpectingSpeech) { +TEST_F(AudioInputProcessorTest, test_resetStateWhenExpectingSpeech) { removeDefaultAudioProvider(); ASSERT_TRUE(testExpectSpeechWaits(WITH_DIALOG_REQUEST_ID, !VERIFY_TIMEOUT)); EXPECT_CALL(*m_mockObserver, onStateChanged(AudioInputProcessorObserverInterface::State::IDLE)); @@ -1930,7 +1930,7 @@ TEST_F(AudioInputProcessorTest, resetStateWhenExpectingSpeech) { } /// This function verifies that @c AudioInputProcessor::resetState() works in @c State::RECOGNIZING. -TEST_F(AudioInputProcessorTest, resetStateWhenRecognizing) { +TEST_F(AudioInputProcessorTest, test_resetStateWhenRecognizing) { ASSERT_TRUE(testRecognizeSucceeds(*m_audioProvider, Initiator::TAP, 0)); EXPECT_CALL(*m_mockFocusManager, releaseChannel(CHANNEL_NAME, _)); @@ -1942,7 +1942,7 @@ TEST_F(AudioInputProcessorTest, resetStateWhenRecognizing) { * This function verifies that @c AudioInputProcessor responds correctly to * @c ContextRequestError::STATE_PROVIDER_TIMEDOUT. */ -TEST_F(AudioInputProcessorTest, contextFailureStateProviderTimedout) { +TEST_F(AudioInputProcessorTest, test_contextFailureStateProviderTimedout) { ASSERT_TRUE(testContextFailure(avsCommon::sdkInterfaces::ContextRequestError::STATE_PROVIDER_TIMEDOUT)); } @@ -1950,65 +1950,65 @@ TEST_F(AudioInputProcessorTest, contextFailureStateProviderTimedout) { * This function verifies that @c AudioInputProcessor responds correctly to * @c ContextRequestError::BUILD_CONTEXT_ERROR. */ -TEST_F(AudioInputProcessorTest, contextFailureBuildContextError) { +TEST_F(AudioInputProcessorTest, test_contextFailureBuildContextError) { ASSERT_TRUE(testContextFailure(avsCommon::sdkInterfaces::ContextRequestError::BUILD_CONTEXT_ERROR)); } /// This function verifies that StopCapture directives fail in @c State::IDLE. -TEST_F(AudioInputProcessorTest, preHandleAndHandleDirectiveStopCaptureWhenIdle) { +TEST_F(AudioInputProcessorTest, test_preHandleAndHandleDirectiveStopCaptureWhenIdle) { ASSERT_TRUE(testStopCaptureDirectiveFails(WITH_DIALOG_REQUEST_ID)); } /// This function verifies that StopCapture directives with dialog request ID work in @c State::RECOGNIZING. -TEST_F(AudioInputProcessorTest, preHandleAndHandleDirectiveStopCaptureWhenRecognizing) { +TEST_F(AudioInputProcessorTest, test_preHandleAndHandleDirectiveStopCaptureWhenRecognizing) { ASSERT_TRUE(testRecognizeSucceeds(*m_audioProvider, Initiator::TAP, 0)); ASSERT_TRUE(testStopCaptureDirectiveSucceeds(WITH_DIALOG_REQUEST_ID)); } /// This function verifies that StopCapture directives fail in @c State::EXPECTING_SPEECH. -TEST_F(AudioInputProcessorTest, preHandleAndHandleDirectiveStopCaptureWhenExpectingSpeech) { +TEST_F(AudioInputProcessorTest, test_preHandleAndHandleDirectiveStopCaptureWhenExpectingSpeech) { removeDefaultAudioProvider(); ASSERT_TRUE(testExpectSpeechWaits(WITH_DIALOG_REQUEST_ID, !VERIFY_TIMEOUT)); ASSERT_TRUE(testStopCaptureDirectiveFails(WITH_DIALOG_REQUEST_ID)); } /// This function verifies that StopCapture directives without dialog request ID work in @c State::RECOGNIZING. -TEST_F(AudioInputProcessorTest, handleDirectiveImmediatelyStopCaptureWhenRecognizing) { +TEST_F(AudioInputProcessorTest, test_handleDirectiveImmediatelyStopCaptureWhenRecognizing) { ASSERT_TRUE(testRecognizeSucceeds(*m_audioProvider, Initiator::TAP, 0)); ASSERT_TRUE(testStopCaptureDirectiveSucceeds(!WITH_DIALOG_REQUEST_ID)); } /// This function verifies that ExpectSpeech directives with dialog request ID work in @c State::IDLE. -TEST_F(AudioInputProcessorTest, preHandleAndHandleDirectiveExpectSpeechWhenIdle) { +TEST_F(AudioInputProcessorTest, test_preHandleAndHandleDirectiveExpectSpeechWhenIdle) { ASSERT_TRUE(testExpectSpeechSucceeds(WITH_DIALOG_REQUEST_ID)); } /// This function verifies that ExpectSpeech directives without dialog request ID work in @c State::IDLE. -TEST_F(AudioInputProcessorTest, handleDirectiveImmediatelyExpectSpeechWhenIdle) { +TEST_F(AudioInputProcessorTest, test_handleDirectiveImmediatelyExpectSpeechWhenIdle) { ASSERT_TRUE(testExpectSpeechSucceeds(!WITH_DIALOG_REQUEST_ID)); } /// This function verifies that ExpectSpeech directives fail in @c State::RECOGNIZING. -TEST_F(AudioInputProcessorTest, preHandleAndHandleDirectiveExpectSpeechWhenRecognizing) { +TEST_F(AudioInputProcessorTest, test_preHandleAndHandleDirectiveExpectSpeechWhenRecognizing) { ASSERT_TRUE(testRecognizeSucceeds(*m_audioProvider, Initiator::TAP, 0)); ASSERT_TRUE(testExpectSpeechFails(WITH_DIALOG_REQUEST_ID)); } /// This function verifies that ExpectSpeech directives fail in @c State::EXPECTING_SPEECH. -TEST_F(AudioInputProcessorTest, preHandleAndHandleDirectiveExpectSpeechWhenExpectingSpeech) { +TEST_F(AudioInputProcessorTest, test_preHandleAndHandleDirectiveExpectSpeechWhenExpectingSpeech) { removeDefaultAudioProvider(); ASSERT_TRUE(testExpectSpeechWaits(WITH_DIALOG_REQUEST_ID, !VERIFY_TIMEOUT)); ASSERT_TRUE(testExpectSpeechFails(WITH_DIALOG_REQUEST_ID)); } /// This function verifies that ExpectSpeech directives wait with no default and no previous @c AudioProvider. -TEST_F(AudioInputProcessorTest, expectSpeechNoDefaultNoPrevious) { +TEST_F(AudioInputProcessorTest, test_expectSpeechNoDefaultNoPrevious) { removeDefaultAudioProvider(); ASSERT_TRUE(testExpectSpeechWaits(WITH_DIALOG_REQUEST_ID, VERIFY_TIMEOUT)); } /// This function verifies that ExpectSpeech directives wait with unreadable default and no previous @c AudioProvider. -TEST_F(AudioInputProcessorTest, expectSpeechUnreadableDefaultNoPrevious) { +TEST_F(AudioInputProcessorTest, test_expectSpeechUnreadableDefaultNoPrevious) { makeDefaultAudioProviderNotAlwaysReadable(); ASSERT_TRUE(testExpectSpeechWaits(WITH_DIALOG_REQUEST_ID, VERIFY_TIMEOUT)); } @@ -2017,7 +2017,7 @@ TEST_F(AudioInputProcessorTest, expectSpeechUnreadableDefaultNoPrevious) { * This function verifies that ExpectSpeech directives wait with unreadable default and unreadable previous * @c AudioProvider. */ -TEST_F(AudioInputProcessorTest, expectSpeechUnreadableDefaultUnreadablePrevious) { +TEST_F(AudioInputProcessorTest, test_expectSpeechUnreadableDefaultUnreadablePrevious) { makeDefaultAudioProviderNotAlwaysReadable(); ASSERT_TRUE(testRecognizeSucceeds(*m_audioProvider, Initiator::PRESS_AND_HOLD, 0)); ASSERT_TRUE(testStopCaptureSucceeds()); @@ -2025,7 +2025,7 @@ TEST_F(AudioInputProcessorTest, expectSpeechUnreadableDefaultUnreadablePrevious) } /// This function verifies that ExpectSpeech directives work with no default and readable previous @c AudioProvider. -TEST_F(AudioInputProcessorTest, expectSpeechNoDefaultReadablePrevious) { +TEST_F(AudioInputProcessorTest, test_expectSpeechNoDefaultReadablePrevious) { removeDefaultAudioProvider(); ASSERT_TRUE(testRecognizeSucceeds(*m_audioProvider, Initiator::PRESS_AND_HOLD, 0)); ASSERT_TRUE(testStopCaptureSucceeds()); @@ -2033,7 +2033,7 @@ TEST_F(AudioInputProcessorTest, expectSpeechNoDefaultReadablePrevious) { } /// This function verifies that the initiator from an ExpectSpeech is passed to a subsequent Recognize. -TEST_F(AudioInputProcessorTest, expectSpeechWithInitiator) { +TEST_F(AudioInputProcessorTest, test_expectSpeechWithInitiator) { ASSERT_TRUE(testRecognizeWithExpectSpeechInitiator(true)); } @@ -2041,7 +2041,7 @@ TEST_F(AudioInputProcessorTest, expectSpeechWithInitiator) { * This function verifies that if the ExpectSpeech does not have an initiator, no initiator is present in the * subsequent Recognize. */ -TEST_F(AudioInputProcessorTest, expectSpeechWithNoInitiator) { +TEST_F(AudioInputProcessorTest, test_expectSpeechWithNoInitiator) { ASSERT_TRUE(testRecognizeWithExpectSpeechInitiator(false)); } @@ -2049,7 +2049,7 @@ TEST_F(AudioInputProcessorTest, expectSpeechWithNoInitiator) { * This function verifies that if the ExpectSpeech times out, the next user initiated Recognize will send the standard * initiator and not the one passed from AVS. */ -TEST_F(AudioInputProcessorTest, expectSpeechWithInitiatorTimedOut) { +TEST_F(AudioInputProcessorTest, test_expectSpeechWithInitiatorTimedOut) { removeDefaultAudioProvider(); ASSERT_TRUE(testExpectSpeechWaits(WITH_DIALOG_REQUEST_ID, VERIFY_TIMEOUT)); ASSERT_TRUE(testRecognizeSucceeds(*m_audioProvider, Initiator::TAP)); @@ -2057,19 +2057,19 @@ TEST_F(AudioInputProcessorTest, expectSpeechWithInitiatorTimedOut) { /// This function verifies that a focus change to @c FocusState::BACKGROUND causes the @c AudioInputProcessor to /// release the channel and go back to @c State::IDLE. -TEST_F(AudioInputProcessorTest, focusChangedBackground) { +TEST_F(AudioInputProcessorTest, test_focusChangedBackground) { ASSERT_TRUE(testFocusChange(avsCommon::avs::FocusState::BACKGROUND)); } /// This function verifies that a focus change to @c FocusState::NONE causes the @c AudioInputProcessor to /// release the channel and go back to @c State::IDLE. -TEST_F(AudioInputProcessorTest, focusChangedNone) { +TEST_F(AudioInputProcessorTest, test_focusChangedNone) { ASSERT_TRUE(testFocusChange(avsCommon::avs::FocusState::NONE)); } /// Test that the @c AudioInputProcessor correctly transitions to @c State::IDLE /// if @c Status::TIMEDOUT is received -TEST_F(AudioInputProcessorTest, resetStateOnTimeOut) { +TEST_F(AudioInputProcessorTest, test_resetStateOnTimeOut) { ASSERT_TRUE(testRecognizeSucceeds(*m_audioProvider, Initiator::TAP, 0)); EXPECT_CALL(*m_mockFocusManager, releaseChannel(CHANNEL_NAME, _)); @@ -2081,7 +2081,7 @@ TEST_F(AudioInputProcessorTest, resetStateOnTimeOut) { * This function verifies that @c AudioInputProcessor::recognize() works with @c Initiator::WAKEWORD, keyword and * valid espData. */ -TEST_F(AudioInputProcessorTest, recognizeWakewordWithESPWithKeyword) { +TEST_F(AudioInputProcessorTest, test_recognizeWakewordWithESPWithKeyword) { auto begin = AudioInputProcessor::INVALID_INDEX; auto end = AudioInputProcessor::INVALID_INDEX; // note that we are just using a integer instead of a float number, this is to help with JSON verification. @@ -2095,7 +2095,7 @@ TEST_F(AudioInputProcessorTest, recognizeWakewordWithESPWithKeyword) { * invalid espData. The ReportEchoSpatialPerceptionData event will not be sent but the Recognize event should still be * sent. */ -TEST_F(AudioInputProcessorTest, recognizeWakewordWithInvalidESPWithKeyword) { +TEST_F(AudioInputProcessorTest, test_recognizeWakewordWithInvalidESPWithKeyword) { auto begin = AudioInputProcessor::INVALID_INDEX; auto end = AudioInputProcessor::INVALID_INDEX; ESPData espData("@#\"", "@#\""); @@ -2107,7 +2107,7 @@ TEST_F(AudioInputProcessorTest, recognizeWakewordWithInvalidESPWithKeyword) { * This function verifies that @c AudioInputProcessor::recognize() works with OPUS encoding used with * @c Initiator::TAP. */ -TEST_F(AudioInputProcessorTest, recognizeOPUSWithTap) { +TEST_F(AudioInputProcessorTest, test_recognizeOPUSWithTap) { m_audioProvider->format.encoding = avsCommon::utils::AudioFormat::Encoding::OPUS; m_audioProvider->format.sampleRateHz = 32000; ASSERT_TRUE(testRecognizeSucceeds(*m_audioProvider, Initiator::TAP)); @@ -2117,7 +2117,7 @@ TEST_F(AudioInputProcessorTest, recognizeOPUSWithTap) { * This function verifies that @c AudioInputProcessor::recognize() works with OPUS encoding used with * @c Initiator::PRESS_AND_HOLD. */ -TEST_F(AudioInputProcessorTest, recognizeOPUSWithPressAndHold) { +TEST_F(AudioInputProcessorTest, test_recognizeOPUSWithPressAndHold) { m_audioProvider->format.encoding = avsCommon::utils::AudioFormat::Encoding::OPUS; m_audioProvider->format.sampleRateHz = 32000; ASSERT_TRUE(testRecognizeSucceeds(*m_audioProvider, Initiator::PRESS_AND_HOLD)); @@ -2127,7 +2127,7 @@ TEST_F(AudioInputProcessorTest, recognizeOPUSWithPressAndHold) { * This function verifies that @c AudioInputProcessor::recognize() works with OPUS encoding used with * @c Initiator::WAKEWORD valid begin and end indices. */ -TEST_F(AudioInputProcessorTest, recognizeOPUSWithWakeWord) { +TEST_F(AudioInputProcessorTest, test_recognizeOPUSWithWakeWord) { avsCommon::avs::AudioInputStream::Index begin = 0; avsCommon::avs::AudioInputStream::Index end = AudioInputProcessor::INVALID_INDEX; m_audioProvider->format.encoding = avsCommon::utils::AudioFormat::Encoding::OPUS; @@ -2139,7 +2139,7 @@ TEST_F(AudioInputProcessorTest, recognizeOPUSWithWakeWord) { * This function verifies that @c AudioInputProcessor::recognize() creates a @c MessageRequest with KWDMetadata * When metadata has been received */ -TEST_F(AudioInputProcessorTest, recognizeWakewordWithKWDMetadata) { +TEST_F(AudioInputProcessorTest, test_recognizeWakewordWithKWDMetadata) { auto begin = AudioInputProcessor::INVALID_INDEX; auto end = AudioInputProcessor::INVALID_INDEX; @@ -2158,11 +2158,22 @@ TEST_F(AudioInputProcessorTest, recognizeWakewordWithKWDMetadata) { metadata)); } +/** + * This function verifies that @c AudioInputProcessor::recognize() does not generate an event for invalid keyword + * detections (ex. "STOP") + */ +TEST_F(AudioInputProcessorTest, test_recognizeInvalidWakeWord) { + avsCommon::avs::AudioInputStream::Index begin = PREROLL_WORDS; + avsCommon::avs::AudioInputStream::Index end = PREROLL_WORDS + WAKEWORD_WORDS; + EXPECT_TRUE( + testRecognizeFails(*m_audioProvider, Initiator::WAKEWORD, begin, end, AudioInputProcessor::KEYWORD_TEXT_STOP)); +} + /** * This function verifies that @c AudioInputProcessor state will stop listening when the recognize event stream has been * successfully sent. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamSuccess) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamSuccess) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::SUCCESS, StopCaptureDirectiveSchedule::NONE, @@ -2174,7 +2185,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamSuccess) { * This function verifies that @c AudioInputProcessor state will stop listening when the recognize event stream has been * successfully sent but received no HTTP/2 content. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamSuccessNoContent) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamSuccessNoContent) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::SUCCESS_NO_CONTENT, StopCaptureDirectiveSchedule::NONE, @@ -2186,7 +2197,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamSuccessNoContent) { * This function verifies that @c AudioInputProcessor state will stop listening when the recognize event stream has not * been sent due to connection to AVS has been severed. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamSuccessNotConnected) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamSuccessNotConnected) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::NOT_CONNECTED, StopCaptureDirectiveSchedule::NONE, @@ -2198,7 +2209,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamSuccessNotConnected) { * This function verifies that @c AudioInputProcessor state will stop listening when the recognize event stream has not * been sent due to AVS is not synchronized. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamNotSynchronized) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamNotSynchronized) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::NOT_SYNCHRONIZED, StopCaptureDirectiveSchedule::NONE, @@ -2210,7 +2221,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamNotSynchronized) { * This function verifies that @c AudioInputProcessor state will stop listening when the recognize event stream has not * been sent due to an internal error within ACL. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamInternalrror) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamInternalrror) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::INTERNAL_ERROR, StopCaptureDirectiveSchedule::NONE, @@ -2222,7 +2233,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamInternalrror) { * This function verifies that @c AudioInputProcessor state will stop listening when the recognize event stream has not * been sent due to an underlying protocol error. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamProtocolError) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamProtocolError) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::PROTOCOL_ERROR, StopCaptureDirectiveSchedule::NONE, @@ -2234,7 +2245,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamProtocolError) { * This function verifies that @c AudioInputProcessor state will stop listening when the recognize event stream has not * been sent due to an internal error on the server which sends code 500. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamServerInternalError) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamServerInternalError) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::SERVER_INTERNAL_ERROR_V2, StopCaptureDirectiveSchedule::NONE, @@ -2246,7 +2257,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamServerInternalError) { * This function verifies that @c AudioInputProcessor state will stop listening when the recognize event stream has not * been sent due to server refusing the request. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamRefused) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamRefused) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::REFUSED, StopCaptureDirectiveSchedule::NONE, @@ -2258,7 +2269,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamRefused) { * This function verifies that @c AudioInputProcessor state will stop listening when the recognize event stream has not * been sent due to server canceling it before the transmission completed. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamCanceled) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamCanceled) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::CANCELED, StopCaptureDirectiveSchedule::NONE, @@ -2270,7 +2281,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamCanceled) { * This function verifies that @c AudioInputProcessor state will stop listening when the recognize event stream has not * been sent due to excessive load on the server. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamThrottled) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamThrottled) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::THROTTLED, StopCaptureDirectiveSchedule::NONE, @@ -2282,7 +2293,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamThrottled) { * This function verifies that @c AudioInputProcessor state will stop listening when the recognize event stream has not * been sent due to the access credentials provided to ACL were invalid. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamInvalidAuth) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamInvalidAuth) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::INVALID_AUTH, StopCaptureDirectiveSchedule::NONE, @@ -2294,7 +2305,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamInvalidAuth) { * This function verifies that @c AudioInputProcessor state will stop listening when the recognize event stream has not * been sent due to invalid request sent by the user. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamBadRequest) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamBadRequest) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::BAD_REQUEST, StopCaptureDirectiveSchedule::NONE, @@ -2306,7 +2317,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamBadRequest) { * This function verifies that @c AudioInputProcessor state will stop listening when the recognize event stream has not * been sent due to unknown server error. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamUnknownServerError) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamUnknownServerError) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::SERVER_OTHER_ERROR, StopCaptureDirectiveSchedule::NONE, @@ -2318,7 +2329,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamUnknownServerError) { * This function verifies that @c AudioInputProcessor state is correct after receiving a stop capture directive and the * recognize event stream has been successfully sent. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamSuccess) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnDirectiveAndStreamSuccess) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::SUCCESS, StopCaptureDirectiveSchedule::BEFORE_EVENT_STREAM_CLOSE, @@ -2330,7 +2341,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamSuccess) { * This function verifies that @c AudioInputProcessor state is correct after receiving a stop capture directive and the * recognize event stream has been successfully sent but received no HTTP/2 content. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamSuccessNoContent) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnDirectiveAndStreamSuccessNoContent) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::SUCCESS_NO_CONTENT, StopCaptureDirectiveSchedule::BEFORE_EVENT_STREAM_CLOSE, @@ -2342,7 +2353,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamSuccessNoContent) * This function verifies that @c AudioInputProcessor state is correct after receiving a stop capture directive and the * recognize event stream has not been sent due to connection to AVS has been severed. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamSuccessNotConnected) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnDirectiveAndStreamSuccessNotConnected) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::NOT_CONNECTED, StopCaptureDirectiveSchedule::BEFORE_EVENT_STREAM_CLOSE, @@ -2354,7 +2365,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamSuccessNotConnect * This function verifies that @c AudioInputProcessor state is correct after receiving a stop capture directive and the * recognize event stream has not been sent due to AVS is not synchronized. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamNotSynchronized) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnDirectiveAndStreamNotSynchronized) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::NOT_SYNCHRONIZED, StopCaptureDirectiveSchedule::BEFORE_EVENT_STREAM_CLOSE, @@ -2366,7 +2377,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamNotSynchronized) * This function verifies that @c AudioInputProcessor state is correct after receiving a stop capture directive and the * recognize event stream has not been sent due to an internal error within ACL. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamInternalrror) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnDirectiveAndStreamInternalrror) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::INTERNAL_ERROR, StopCaptureDirectiveSchedule::BEFORE_EVENT_STREAM_CLOSE, @@ -2378,7 +2389,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamInternalrror) { * This function verifies that @c AudioInputProcessor state is correct after receiving a stop capture directive and the * recognize event stream has not been sent due to an underlying protocol error. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamProtocolError) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnDirectiveAndStreamProtocolError) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::PROTOCOL_ERROR, StopCaptureDirectiveSchedule::BEFORE_EVENT_STREAM_CLOSE, @@ -2390,7 +2401,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamProtocolError) { * This function verifies that @c AudioInputProcessor state is correct after receiving a stop capture directive and the * recognize event stream has not been sent due to an internal error on the server which sends code 500. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamServerInternalError) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnDirectiveAndStreamServerInternalError) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::SERVER_INTERNAL_ERROR_V2, StopCaptureDirectiveSchedule::BEFORE_EVENT_STREAM_CLOSE, @@ -2402,7 +2413,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamServerInternalErr * This function verifies that @c AudioInputProcessor state is correct after receiving a stop capture directive and the * recognize event stream has not been sent due to server refusing the request. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamRefused) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnDirectiveAndStreamRefused) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::REFUSED, StopCaptureDirectiveSchedule::BEFORE_EVENT_STREAM_CLOSE, @@ -2414,7 +2425,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamRefused) { * This function verifies that @c AudioInputProcessor state is correct after receiving a stop capture directive and the * recognize event stream has not been sent due to server canceling it before the transmission completed. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamCanceled) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnDirectiveAndStreamCanceled) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::CANCELED, StopCaptureDirectiveSchedule::BEFORE_EVENT_STREAM_CLOSE, @@ -2426,7 +2437,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamCanceled) { * This function verifies that @c AudioInputProcessor state is correct after receiving a stop capture directive and the * recognize event stream has not been sent due to excessive load on the server. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamThrottled) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnDirectiveAndStreamThrottled) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::THROTTLED, StopCaptureDirectiveSchedule::BEFORE_EVENT_STREAM_CLOSE, @@ -2438,7 +2449,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamThrottled) { * This function verifies that @c AudioInputProcessor state is correct after receiving a stop capture directive and the * recognize event stream has not been sent due to the access credentials provided to ACL were invalid. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamInvalidAuth) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnDirectiveAndStreamInvalidAuth) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::INVALID_AUTH, StopCaptureDirectiveSchedule::BEFORE_EVENT_STREAM_CLOSE, @@ -2450,7 +2461,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamInvalidAuth) { * This function verifies that @c AudioInputProcessor state is correct after receiving a stop capture directive and the * recognize event stream has not been sent due to invalid request sent by the user. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamBadRequest) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnDirectiveAndStreamBadRequest) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::BAD_REQUEST, StopCaptureDirectiveSchedule::BEFORE_EVENT_STREAM_CLOSE, @@ -2462,7 +2473,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamBadRequest) { * This function verifies that @c AudioInputProcessor state is correct after receiving a stop capture directive and the * recognize event stream has not been sent due to unknown server error. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamUnknownServerError) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnDirectiveAndStreamUnknownServerError) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::SERVER_OTHER_ERROR, StopCaptureDirectiveSchedule::BEFORE_EVENT_STREAM_CLOSE, @@ -2474,7 +2485,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnDirectiveAndStreamUnknownServerErro * This function verifies that @c AudioInputProcessor state is correct after the recognize event stream has been * successfully sent and a stop capture directive is received. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamSuccessAndDirective) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamSuccessAndDirective) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::SUCCESS, StopCaptureDirectiveSchedule::AFTER_EVENT_STREAM_CLOSE, @@ -2486,7 +2497,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamSuccessAndDirective) { * This function verifies that @c AudioInputProcessor state is correct after the recognize event stream has been * successfully sent but received no HTTP/2 content and a stop capture directive is received. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamSuccessNoContentAndDirective) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamSuccessNoContentAndDirective) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::SUCCESS_NO_CONTENT, StopCaptureDirectiveSchedule::AFTER_EVENT_STREAM_CLOSE, @@ -2498,7 +2509,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamSuccessNoContentAndDirective) * This function verifies that @c AudioInputProcessor state is correct after the recognize event stream has not * been sent due to connection to AVS has been severed and a stop capture directive is received. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamSuccessNotConnectedAndDirective) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamSuccessNotConnectedAndDirective) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::NOT_CONNECTED, StopCaptureDirectiveSchedule::AFTER_EVENT_STREAM_CLOSE, @@ -2510,7 +2521,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamSuccessNotConnectedAndDirecti * This function verifies that @c AudioInputProcessor state is correct after the recognize event stream has not * been sent due to AVS is not synchronized and a stop capture directive is received. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamNotSynchronizedAndDirective) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamNotSynchronizedAndDirective) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::NOT_SYNCHRONIZED, StopCaptureDirectiveSchedule::AFTER_EVENT_STREAM_CLOSE, @@ -2522,7 +2533,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamNotSynchronizedAndDirective) * This function verifies that @c AudioInputProcessor state is correct after the recognize event stream has not * been sent due to an internal error within ACL and a stop capture directive is received. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamInternalrrorAndDirective) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamInternalrrorAndDirective) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::INTERNAL_ERROR, StopCaptureDirectiveSchedule::AFTER_EVENT_STREAM_CLOSE, @@ -2534,7 +2545,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamInternalrrorAndDirective) { * This function verifies that @c AudioInputProcessor state is correct after the recognize event stream has not * been sent due to an underlying protocol error and a stop capture directive is received. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamProtocolErrorAndDirective) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamProtocolErrorAndDirective) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::PROTOCOL_ERROR, StopCaptureDirectiveSchedule::AFTER_EVENT_STREAM_CLOSE, @@ -2546,7 +2557,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamProtocolErrorAndDirective) { * This function verifies that @c AudioInputProcessor state is correct after the recognize event stream has not * been sent due to an internal error on the server which sends code 500 and a stop capture directive is received. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamServerInternalErrorAndDirective) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamServerInternalErrorAndDirective) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::SERVER_INTERNAL_ERROR_V2, StopCaptureDirectiveSchedule::AFTER_EVENT_STREAM_CLOSE, @@ -2558,7 +2569,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamServerInternalErrorAndDirecti * This function verifies that @c AudioInputProcessor state is correct after the recognize event stream has not * been sent due to server refusing the request and a stop capture directive is received. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamRefusedAndDirective) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamRefusedAndDirective) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::REFUSED, StopCaptureDirectiveSchedule::AFTER_EVENT_STREAM_CLOSE, @@ -2570,7 +2581,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamRefusedAndDirective) { * This function verifies that @c AudioInputProcessor state is correct after the recognize event stream has not * been sent due to server canceling it before the transmission completed and a stop capture directive is received. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamCanceledAndDirective) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamCanceledAndDirective) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::CANCELED, StopCaptureDirectiveSchedule::AFTER_EVENT_STREAM_CLOSE, @@ -2582,7 +2593,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamCanceledAndDirective) { * This function verifies that @c AudioInputProcessor state is correct after the recognize event stream has not * been sent due to excessive load on the server and a stop capture directive is received. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamThrottledAndDirective) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamThrottledAndDirective) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::THROTTLED, StopCaptureDirectiveSchedule::AFTER_EVENT_STREAM_CLOSE, @@ -2594,7 +2605,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamThrottledAndDirective) { * This function verifies that @c AudioInputProcessor state is correct after the recognize event stream has not * been sent due to the access credentials provided to ACL were invalid and a stop capture directive is received. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamInvalidAuthAndDirective) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamInvalidAuthAndDirective) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::INVALID_AUTH, StopCaptureDirectiveSchedule::AFTER_EVENT_STREAM_CLOSE, @@ -2606,7 +2617,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamInvalidAuthAndDirective) { * This function verifies that @c AudioInputProcessor state is correct after the recognize event stream has not * been sent due to invalid request sent by the user and a stop capture directive is received. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamBadRequestAndDirective) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamBadRequestAndDirective) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::BAD_REQUEST, StopCaptureDirectiveSchedule::AFTER_EVENT_STREAM_CLOSE, @@ -2618,7 +2629,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamBadRequestAndDirective) { * This function verifies that @c AudioInputProcessor state is correct after the recognize event stream has not * been sent due to unknown server error and a stop capture directive is received. */ -TEST_F(AudioInputProcessorTest, stopCaptureOnStreamUnknownServerErrorAndDirective) { +TEST_F(AudioInputProcessorTest, test_stopCaptureOnStreamUnknownServerErrorAndDirective) { testAIPStateTransitionOnEventFinish( avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::SERVER_OTHER_ERROR, StopCaptureDirectiveSchedule::AFTER_EVENT_STREAM_CLOSE, @@ -2629,7 +2640,7 @@ TEST_F(AudioInputProcessorTest, stopCaptureOnStreamUnknownServerErrorAndDirectiv /* * This function verifies that the SET_END_OF_SPEECH_OFFSET directive is handled properly in the successful case */ -TEST_F(AudioInputProcessorTest, handleSetEndOfSpeechOffsetSuccess) { +TEST_F(AudioInputProcessorTest, test_handleSetEndOfSpeechOffsetSuccess) { rapidjson::Document document(rapidjson::kObjectType); rapidjson::Value payloadJson(rapidjson::kObjectType); rapidjson::Value endOfSpeechOffsetMilliseconds(END_OF_SPEECH_OFFSET_IN_MILLISECONDS); @@ -2649,7 +2660,7 @@ TEST_F(AudioInputProcessorTest, handleSetEndOfSpeechOffsetSuccess) { /** * This function verifies that the SET_END_OF_SPEECH_OFFSET directive gracefully handles invalid offset values */ -TEST_F(AudioInputProcessorTest, handleSetEndOfSpeechOffsetFailureInvalid) { +TEST_F(AudioInputProcessorTest, test_handleSetEndOfSpeechOffsetFailureInvalid) { rapidjson::Document document(rapidjson::kObjectType); rapidjson::Value payloadJson(rapidjson::kObjectType); rapidjson::Value badValue("foobar"); @@ -2665,7 +2676,7 @@ TEST_F(AudioInputProcessorTest, handleSetEndOfSpeechOffsetFailureInvalid) { /** * This function verifies that the SET_END_OF_SPEECH_OFFSET directive gracefully handles missing offset values */ -TEST_F(AudioInputProcessorTest, handleSetEndOfSpeechOffsetFailureMissing) { +TEST_F(AudioInputProcessorTest, test_handleSetEndOfSpeechOffsetFailureMissing) { rapidjson::Document document(rapidjson::kObjectType); rapidjson::Value payloadJson(rapidjson::kObjectType); auto avsDirective = createAVSDirective(SET_END_OF_SPEECH_OFFSET, true, true, document, payloadJson); diff --git a/CapabilityAgents/AIP/test/ESPDataTest.cpp b/CapabilityAgents/AIP/test/ESPDataTest.cpp index 141b2c05cb..655c7e6a9c 100644 --- a/CapabilityAgents/AIP/test/ESPDataTest.cpp +++ b/CapabilityAgents/AIP/test/ESPDataTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -29,43 +29,43 @@ namespace test { class ESPDataTest : public ::testing::Test {}; /// Test for a normal positive number (with sign), expect verify() to return true. -TEST_F(ESPDataTest, NormalPositiveNumber) { +TEST_F(ESPDataTest, test_normalPositiveNumber) { ESPData data{"+0.123f", "+123.123"}; EXPECT_TRUE(data.verify()); } /// Test for a normal positive number (without sign), expect verify() to return true. -TEST_F(ESPDataTest, NormalPositiveNumberWithoutSign) { +TEST_F(ESPDataTest, test_normalPositiveNumberWithoutSign) { ESPData data{"0.123f", "123.123"}; EXPECT_TRUE(data.verify()); } /// Test for a normal negative number, expect verify() to return true. -TEST_F(ESPDataTest, NormalNegativeNumber) { +TEST_F(ESPDataTest, test_normalNegativeNumber) { ESPData data{"-0.123F", "-123.123"}; EXPECT_TRUE(data.verify()); } /// Test for a normal positive exponential number, expect verify() to return true. -TEST_F(ESPDataTest, NormalPositiveExponentialNumber) { +TEST_F(ESPDataTest, test_normalPositiveExponentialNumber) { ESPData data{"100e+9", ".6e19f"}; EXPECT_TRUE(data.verify()); } /// Test for a normal negative exponential number, expect verify() to return true. -TEST_F(ESPDataTest, NormalNegativeExponentialNumber) { +TEST_F(ESPDataTest, test_normalNegativeExponentialNumber) { ESPData data{"-100e-9", "-1.6e-19f"}; EXPECT_TRUE(data.verify()); } /// Test for a empty number, expect verify() to return false. -TEST_F(ESPDataTest, emptyNumber) { +TEST_F(ESPDataTest, test_emptyNumber) { ESPData data{"", ""}; EXPECT_FALSE(data.verify()); } /// Test for a number with quotation mark, expect verify() to return false. -TEST_F(ESPDataTest, noDigitInNumber) { +TEST_F(ESPDataTest, test_noDigitInNumber) { ESPData data{"\"", "\""}; EXPECT_FALSE(data.verify()); } diff --git a/CapabilityAgents/Alerts/include/Alerts/Renderer/Renderer.h b/CapabilityAgents/Alerts/include/Alerts/Renderer/Renderer.h index 603bc09ff5..af95fe1505 100644 --- a/CapabilityAgents/Alerts/include/Alerts/Renderer/Renderer.h +++ b/CapabilityAgents/Alerts/include/Alerts/Renderer/Renderer.h @@ -54,7 +54,8 @@ class Renderer std::function()> audioFactory, const std::vector& urls = std::vector(), int loopCount = 0, - std::chrono::milliseconds loopPause = std::chrono::milliseconds{0}) override; + std::chrono::milliseconds loopPause = std::chrono::milliseconds{0}, + bool startWithPause = false) override; void stop() override; @@ -95,14 +96,20 @@ class Renderer * else is available. * @param urls A container of urls to be rendered per the above description. * @param loopCount The number of times the urls should be rendered. - * @param loopPauseInMilliseconds The number of milliseconds to pause between rendering url sequences. + * @param loopPause The duration which must expire between the beginning of rendering of any loop of audio. + * Therefore if the audio (either urls or local audio file) finishes before this duration, then the renderer will + * wait for the remainder of this time before starting the next loop. + * @param startWithPause Indicates if the renderer should begin with an initial pause before rendering audio. + * This initial pause will be for the same duration as @c loopPause, and will not be considered part of the + * @c loopCount. */ void executeStart( std::shared_ptr observer, std::function()> audioFactory, const std::vector& urls, int loopCount, - std::chrono::milliseconds loopPause); + std::chrono::milliseconds loopPause, + bool startWithPause); /** * This function will stop rendering the currently active alert audio. @@ -199,8 +206,10 @@ class Renderer /** * Implements the pause between playback loops + * + * @param duration The duration the pause should be for. Must be a positive value. */ - void pause(); + void pause(std::chrono::milliseconds duration); /** * Implements the playback of the audio source @@ -257,6 +266,12 @@ class Renderer /// The time to pause between the rendering of the @c m_urls sequence. std::chrono::milliseconds m_loopPause; + /// A variable to capture if the renderer should perform an initial pause before rendering audio. + bool m_shouldPauseBeforeRender; + + /// The timestamp when the current loop began rendering. + std::chrono::time_point m_loopStartTime; + /// A pointer to a stream factory to use as the default audio to use when the audio assets aren't available. std::function()> m_defaultAudioFactory; diff --git a/CapabilityAgents/Alerts/include/Alerts/Renderer/RendererInterface.h b/CapabilityAgents/Alerts/include/Alerts/Renderer/RendererInterface.h index d55ea3bd0b..9addac0735 100644 --- a/CapabilityAgents/Alerts/include/Alerts/Renderer/RendererInterface.h +++ b/CapabilityAgents/Alerts/include/Alerts/Renderer/RendererInterface.h @@ -57,14 +57,20 @@ class RendererInterface { * else is available. * @param urls A container of urls to be rendered per the above description. * @param loopCount The number of times the urls should be rendered. - * @param loopPauseInMilliseconds The number of milliseconds to pause between rendering url sequences. + * @param loopPause The duration which must expire between the beginning of rendering of any loop of audio. + * Therefore if the audio (either urls or local audio file) finishes before this duration, then the renderer will + * wait for the remainder of this time before starting the next loop. + * @param startWithPause Indicates if the renderer should begin with an initial pause before rendering audio. + * This initial pause will be for the same duration as @c loopPause, and will not be considered part of the + * @c loopCount. */ virtual void start( std::shared_ptr observer, std::function()> audioFactory, const std::vector& urls = std::vector(), int loopCount = 0, - std::chrono::milliseconds loopPause = std::chrono::milliseconds{0}) = 0; + std::chrono::milliseconds loopPause = std::chrono::milliseconds{0}, + bool startWithPause = false) = 0; /** * Stop rendering. diff --git a/CapabilityAgents/Alerts/src/Alert.cpp b/CapabilityAgents/Alerts/src/Alert.cpp index cd71181182..834a940c47 100644 --- a/CapabilityAgents/Alerts/src/Alert.cpp +++ b/CapabilityAgents/Alerts/src/Alert.cpp @@ -577,6 +577,7 @@ void Alert::startRenderer() { auto rendererCopy = m_renderer; auto loopCount = m_dynamicData.loopCount; auto loopPause = m_staticData.assetConfiguration.loopPause; + bool startWithPause = false; // If there are no assets to play (due to the alert not providing any assets), or there was a previous error // (indicated by m_staticData.assetConfiguration.hasRenderingFailed), we call rendererCopy->start(..) with an @@ -589,6 +590,9 @@ void Alert::startRenderer() { m_staticData.assetConfiguration.assets[m_staticData.assetConfiguration.backgroundAssetId].url); } loopPause = BACKGROUND_ALERT_SOUND_PAUSE_TIME; + if (State::ACTIVATING != m_dynamicData.state) { + startWithPause = true; + } } else if (!m_staticData.assetConfiguration.assets.empty() && !m_dynamicData.hasRenderingFailed) { // Only play the named timer urls when it's in foreground. for (auto item : m_staticData.assetConfiguration.assetPlayOrderItems) { @@ -598,7 +602,7 @@ void Alert::startRenderer() { lock.unlock(); - rendererCopy->start(shared_from_this(), audioFactory, urls, loopCount, loopPause); + rendererCopy->start(shared_from_this(), audioFactory, urls, loopCount, loopPause, startWithPause); } void Alert::onMaxTimerExpiration() { diff --git a/CapabilityAgents/Alerts/src/AlertsCapabilityAgent.cpp b/CapabilityAgents/Alerts/src/AlertsCapabilityAgent.cpp index 214e413ce1..43b8b17175 100644 --- a/CapabilityAgents/Alerts/src/AlertsCapabilityAgent.cpp +++ b/CapabilityAgents/Alerts/src/AlertsCapabilityAgent.cpp @@ -553,7 +553,10 @@ bool AlertsCapabilityAgent::handleAdjustVolume( } SpeakerInterface::SpeakerSettings speakerSettings; - m_speakerManager->getSpeakerSettings(SpeakerInterface::Type::AVS_ALERTS_VOLUME, &speakerSettings); + if (!m_speakerManager->getSpeakerSettings(SpeakerInterface::Type::AVS_ALERTS_VOLUME, &speakerSettings).get()) { + ACSDK_ERROR(LX("handleAdjustVolumeFailed").m("Could not retrieve speaker volume.")); + return false; + } int64_t volume = adjustValue + speakerSettings.volume; setNextAlertVolume(volume); @@ -666,13 +669,13 @@ void AlertsCapabilityAgent::sendProcessingDirectiveException( void AlertsCapabilityAgent::acquireChannel() { ACSDK_DEBUG9(LX("acquireChannel")); - m_focusManager->acquireChannel(FocusManagerInterface::ALERTS_CHANNEL_NAME, shared_from_this(), NAMESPACE); + m_focusManager->acquireChannel(FocusManagerInterface::ALERT_CHANNEL_NAME, shared_from_this(), NAMESPACE); } void AlertsCapabilityAgent::releaseChannel() { ACSDK_DEBUG9(LX("releaseChannel")); if (m_alertScheduler.getFocusState() != FocusState::NONE) { - m_focusManager->releaseChannel(FocusManagerInterface::ALERTS_CHANNEL_NAME, shared_from_this()); + m_focusManager->releaseChannel(FocusManagerInterface::ALERT_CHANNEL_NAME, shared_from_this()); } } diff --git a/CapabilityAgents/Alerts/src/Renderer/Renderer.cpp b/CapabilityAgents/Alerts/src/Renderer/Renderer.cpp index 1fe84b70fe..6b8f35dd96 100644 --- a/CapabilityAgents/Alerts/src/Renderer/Renderer.cpp +++ b/CapabilityAgents/Alerts/src/Renderer/Renderer.cpp @@ -63,7 +63,8 @@ void Renderer::start( std::function()> audioFactory, const std::vector& urls, int loopCount, - std::chrono::milliseconds loopPause) { + std::chrono::milliseconds loopPause, + bool startWithPause) { ACSDK_DEBUG5(LX(__func__)); std::unique_ptr defaultAudio = audioFactory(); @@ -82,8 +83,8 @@ void Renderer::start( loopPause = std::chrono::milliseconds{0}; } - m_executor.submit([this, observer, audioFactory, urls, loopCount, loopPause]() { - executeStart(observer, audioFactory, urls, loopCount, loopPause); + m_executor.submit([this, observer, audioFactory, urls, loopCount, loopPause, startWithPause]() { + executeStart(observer, audioFactory, urls, loopCount, loopPause, startWithPause); }); } @@ -122,6 +123,7 @@ Renderer::Renderer(std::shared_ptr mediaPlayer) : m_remainingLoopCount{0}, m_directiveLoopCount{0}, m_loopPause{std::chrono::milliseconds{0}}, + m_shouldPauseBeforeRender{false}, m_isStopping{false}, m_pauseWasInterrupted{false}, m_isStartPending{false} { @@ -182,11 +184,17 @@ bool Renderer::shouldPause() { return false; } -void Renderer::pause() { - ACSDK_DEBUG9(LX("pause")); +void Renderer::pause(std::chrono::milliseconds duration) { + ACSDK_DEBUG9(LX(__func__).d("duration", duration.count())); + + if (duration.count() <= 0) { + ACSDK_WARN(LX(__func__).m("duration is a non-positive value. Returning.")); + return; + } + std::unique_lock lock(m_waitMutex); // Wait for stop() or m_loopPause to elapse. - m_pauseWasInterrupted = m_waitCondition.wait_for(lock, m_loopPause, [this]() { return m_isStopping; }); + m_pauseWasInterrupted = m_waitCondition.wait_for(lock, duration, [this]() { return m_isStopping; }); } void Renderer::play() { @@ -205,6 +213,16 @@ void Renderer::play() { return; } + if (m_shouldPauseBeforeRender) { + ACSDK_DEBUG5(LX(__func__).m("Performing initial pause before beginning loop rendering.")); + m_shouldPauseBeforeRender = false; + pause(m_loopPause); + } + + if (0 == m_numberOfStreamsRenderedThisLoop) { + m_loopStartTime = std::chrono::steady_clock::now(); + } + if (!m_mediaPlayer->play(m_currentSourceId)) { const std::string errorMessage{"MediaPlayer play request failed."}; ACSDK_ERROR(LX("executeStartFailed").d("m_currentSourceId", m_currentSourceId).m(errorMessage)); @@ -217,11 +235,13 @@ void Renderer::executeStart( std::function()> audioFactory, const std::vector& urls, int loopCount, - std::chrono::milliseconds loopPause) { - ACSDK_DEBUG1(LX("executeStart") + std::chrono::milliseconds loopPause, + bool startWithPause) { + ACSDK_DEBUG1(LX(__func__) .d("urls.size", urls.size()) .d("loopCount", loopCount) - .d("loopPause (ms)", std::chrono::duration_cast(loopPause).count())); + .d("loopPause (ms)", std::chrono::duration_cast(loopPause).count()) + .d("startWithPause", startWithPause)); m_observer = observer; @@ -229,6 +249,7 @@ void Renderer::executeStart( m_remainingLoopCount = loopCount; m_directiveLoopCount = loopCount; m_loopPause = loopPause; + m_shouldPauseBeforeRender = startWithPause; m_defaultAudioFactory = audioFactory; m_numberOfStreamsRenderedThisLoop = 0; @@ -356,10 +377,18 @@ bool Renderer::renderNextAudioAsset() { .m("Preparing the audio loop counters.")); if (shouldPause()) { - pause(); - if (m_pauseWasInterrupted) { - ACSDK_DEBUG5(LX(__func__).m("Pause has been interrupted, not proceeding with the loop.")); - return false; + auto loopRenderDuration = std::chrono::duration_cast( + std::chrono::steady_clock::now() - m_loopStartTime); + // let's ensure we only pause for the remainder of the loopPause duration. + auto pauseDuration = m_loopPause - loopRenderDuration; + + // only pause if there is a positive remainder duration. + if (pauseDuration.count() > 0) { + pause(pauseDuration); + if (m_pauseWasInterrupted) { + ACSDK_DEBUG5(LX(__func__).m("Pause has been interrupted, not proceeding with the loop.")); + return false; + } } } } diff --git a/CapabilityAgents/Alerts/test/AlarmAlertTest.cpp b/CapabilityAgents/Alerts/test/AlarmAlertTest.cpp index 4d689ec8bf..ff72b3ec4e 100644 --- a/CapabilityAgents/Alerts/test/AlarmAlertTest.cpp +++ b/CapabilityAgents/Alerts/test/AlarmAlertTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -43,21 +43,21 @@ class AlarmAlertTest : public ::testing::Test { AlarmAlertTest::AlarmAlertTest() : m_alarm{std::make_shared(alarmDefaultFactory, alarmShortFactory)} { } -TEST_F(AlarmAlertTest, defaultAudio) { +TEST_F(AlarmAlertTest, test_defaultAudio) { std::ostringstream oss; oss << m_alarm->getDefaultAudioFactory()()->rdbuf(); ASSERT_EQ(ALARM_DEFAULT_DATA, oss.str()); } -TEST_F(AlarmAlertTest, shortAudio) { +TEST_F(AlarmAlertTest, test_shortAudio) { std::ostringstream oss; oss << m_alarm->getShortAudioFactory()()->rdbuf(); ASSERT_EQ(ALARM_SHORT_DATA, oss.str()); } -TEST_F(AlarmAlertTest, testGetTypeName) { +TEST_F(AlarmAlertTest, test_getTypeName) { ASSERT_EQ(m_alarm->getTypeName(), Alarm::TYPE_NAME); } diff --git a/CapabilityAgents/Alerts/test/AlertSchedulerTest.cpp b/CapabilityAgents/Alerts/test/AlertSchedulerTest.cpp index b6f39f0729..057bd0dea0 100644 --- a/CapabilityAgents/Alerts/test/AlertSchedulerTest.cpp +++ b/CapabilityAgents/Alerts/test/AlertSchedulerTest.cpp @@ -51,14 +51,15 @@ static const std::chrono::seconds ALERT_PAST_DUE_TIME_LIMIT{10}; class MockRenderer : public renderer::RendererInterface { public: - MOCK_METHOD5( + MOCK_METHOD6( start, void( std::shared_ptr observer, std::function()> audioFactory, const std::vector& urls, int loopCount, - std::chrono::milliseconds loopPause)); + std::chrono::milliseconds loopPause, + bool startWithPause)); MOCK_METHOD0(stop, void()); }; @@ -293,7 +294,7 @@ std::shared_ptr AlertSchedulerTest::doSimpleTestSetup(bool activateAl /** * Test initializing AlertScheduler */ -TEST_F(AlertSchedulerTest, initialize) { +TEST_F(AlertSchedulerTest, test_initialize) { /// check if init fails if scheduler is not available ASSERT_FALSE(m_alertScheduler->initialize(nullptr)); @@ -340,7 +341,7 @@ TEST_F(AlertSchedulerTest, initialize) { /** * Test AlertScheduler getting focus */ -TEST_F(AlertSchedulerTest, updateGetFocus) { +TEST_F(AlertSchedulerTest, test_updateGetFocus) { std::shared_ptr alert = doSimpleTestSetup(); // check if focus changes to foreground @@ -359,7 +360,7 @@ TEST_F(AlertSchedulerTest, updateGetFocus) { /** * Test scheduling alerts */ -TEST_F(AlertSchedulerTest, scheduleAlert) { +TEST_F(AlertSchedulerTest, test_scheduleAlert) { // check that a future alert is scheduled std::shared_ptr alert1 = doSimpleTestSetup(true); ASSERT_TRUE(m_alertScheduler->scheduleAlert(alert1)); @@ -379,7 +380,7 @@ TEST_F(AlertSchedulerTest, scheduleAlert) { /** * Test update alert scheduled time. */ -TEST_F(AlertSchedulerTest, rescheduleAlert) { +TEST_F(AlertSchedulerTest, test_rescheduleAlert) { // Schedule an alert and create an updated version with the same token. auto oldAlert = doSimpleTestSetup(); auto newAlert = std::make_shared(oldAlert->getToken(), getFutureInstant(2)); @@ -396,7 +397,7 @@ TEST_F(AlertSchedulerTest, rescheduleAlert) { /** * Test update alert scheduled time to now will start rendering the alert. */ -TEST_F(AlertSchedulerTest, rescheduleAlertNow) { +TEST_F(AlertSchedulerTest, test_rescheduleAlertNow) { // Schedule an alert and create an updated version with the same token. auto oldAlert = doSimpleTestSetup(/*activeAlert*/ false, /*initWithAlertObserver*/ true); auto newAlert = std::make_shared(oldAlert->getToken(), getTimeNow()); @@ -416,7 +417,7 @@ TEST_F(AlertSchedulerTest, rescheduleAlertNow) { /** * Test update alert scheduled time fails. */ -TEST_F(AlertSchedulerTest, rescheduleAlertFails) { +TEST_F(AlertSchedulerTest, test_rescheduleAlertFails) { // Schedule an alert and create an updated version with the same token. auto oldAlert = doSimpleTestSetup(); auto newAlert = std::make_shared(oldAlert->getToken(), getFutureInstant(2)); @@ -434,7 +435,7 @@ TEST_F(AlertSchedulerTest, rescheduleAlertFails) { /** * Test snoozing alerts */ -TEST_F(AlertSchedulerTest, snoozeAlert) { +TEST_F(AlertSchedulerTest, test_snoozeAlert) { doSimpleTestSetup(true); // check that a random alert token is ignored @@ -447,7 +448,7 @@ TEST_F(AlertSchedulerTest, snoozeAlert) { /** * Test deleting single alert */ -TEST_F(AlertSchedulerTest, deleteAlertSingle) { +TEST_F(AlertSchedulerTest, test_deleteAlertSingle) { std::shared_ptr alertSchedulerObs{ std::make_shared(m_alertStorage, m_alertRenderer, m_alertPastDueTimeLimit)}; std::vector> alertsToAdd; @@ -476,7 +477,7 @@ TEST_F(AlertSchedulerTest, deleteAlertSingle) { /** * Test deleting multiple alerts - one at a time */ -TEST_F(AlertSchedulerTest, bulkDeleteAlertsSingle) { +TEST_F(AlertSchedulerTest, test_bulkDeleteAlertsSingle) { std::shared_ptr alertSchedulerObs{ std::make_shared(m_alertStorage, m_alertRenderer, m_alertPastDueTimeLimit)}; std::vector> alertsToAdd; @@ -507,7 +508,7 @@ TEST_F(AlertSchedulerTest, bulkDeleteAlertsSingle) { /** * Test deleting multiple existing alerts */ -TEST_F(AlertSchedulerTest, bulkDeleteAlertsMultipleExisting) { +TEST_F(AlertSchedulerTest, test_bulkDeleteAlertsMultipleExisting) { std::shared_ptr alertSchedulerObs{ std::make_shared(m_alertStorage, m_alertRenderer, m_alertPastDueTimeLimit)}; std::vector> alertsToAdd; @@ -529,7 +530,7 @@ TEST_F(AlertSchedulerTest, bulkDeleteAlertsMultipleExisting) { /** * Test deleting multiple alerts, both existing and not */ -TEST_F(AlertSchedulerTest, bulkDeleteAlertsMultipleMixed) { +TEST_F(AlertSchedulerTest, test_bulkDeleteAlertsMultipleMixed) { std::shared_ptr alertSchedulerObs{ std::make_shared(m_alertStorage, m_alertRenderer, m_alertPastDueTimeLimit)}; std::vector> alertsToAdd; @@ -551,7 +552,7 @@ TEST_F(AlertSchedulerTest, bulkDeleteAlertsMultipleMixed) { /** * Test deleting multiple non-existing alerts */ -TEST_F(AlertSchedulerTest, bulkDeleteAlertsMultipleMissing) { +TEST_F(AlertSchedulerTest, test_bulkDeleteAlertsMultipleMissing) { std::shared_ptr alertSchedulerObs{ std::make_shared(m_alertStorage, m_alertRenderer, m_alertPastDueTimeLimit)}; std::vector> alertsToAdd; @@ -573,7 +574,7 @@ TEST_F(AlertSchedulerTest, bulkDeleteAlertsMultipleMissing) { /** * Test deleting same alerts multiple times */ -TEST_F(AlertSchedulerTest, bulkDeleteAlertsMultipleSame) { +TEST_F(AlertSchedulerTest, test_bulkDeleteAlertsMultipleSame) { std::shared_ptr alertSchedulerObs{ std::make_shared(m_alertStorage, m_alertRenderer, m_alertPastDueTimeLimit)}; std::vector> alertsToAdd; @@ -595,7 +596,7 @@ TEST_F(AlertSchedulerTest, bulkDeleteAlertsMultipleSame) { /** * Test bulk deleting with empty list */ -TEST_F(AlertSchedulerTest, bulkDeleteAlertsMultipleEmpty) { +TEST_F(AlertSchedulerTest, test_bulkDeleteAlertsMultipleEmpty) { std::shared_ptr alertSchedulerObs{ std::make_shared(m_alertStorage, m_alertRenderer, m_alertPastDueTimeLimit)}; std::vector> alertsToAdd; @@ -617,7 +618,7 @@ TEST_F(AlertSchedulerTest, bulkDeleteAlertsMultipleEmpty) { /** * Test method that checks if an alert is active */ -TEST_F(AlertSchedulerTest, isAlertActive) { +TEST_F(AlertSchedulerTest, test_isAlertActive) { std::shared_ptr alertSchedulerObs{ std::make_shared(m_alertStorage, m_alertRenderer, m_alertPastDueTimeLimit)}; std::vector> alertsToAdd; @@ -644,7 +645,7 @@ TEST_F(AlertSchedulerTest, isAlertActive) { /** * Test to see if the correct context about the scheduler is obtained */ -TEST_F(AlertSchedulerTest, getContextInfo) { +TEST_F(AlertSchedulerTest, test_getContextInfo) { std::shared_ptr alertSchedulerObs{ std::make_shared(m_alertStorage, m_alertRenderer, m_alertPastDueTimeLimit)}; std::vector> alertsToAdd; @@ -671,7 +672,7 @@ TEST_F(AlertSchedulerTest, getContextInfo) { /** * Test local stop on AlertScheduler */ -TEST_F(AlertSchedulerTest, onLocalStop) { +TEST_F(AlertSchedulerTest, test_onLocalStop) { std::shared_ptr alert = doSimpleTestSetup(true); m_alertScheduler->onLocalStop(); @@ -683,7 +684,7 @@ TEST_F(AlertSchedulerTest, onLocalStop) { /** * Test if AlertScheduler clears data */ -TEST_F(AlertSchedulerTest, clearData) { +TEST_F(AlertSchedulerTest, test_clearData) { std::shared_ptr alert = doSimpleTestSetup(true); EXPECT_CALL(*(m_alertStorage.get()), clearDatabase()).Times(1); @@ -696,7 +697,7 @@ TEST_F(AlertSchedulerTest, clearData) { /** * Test if AlertScheduler clears data */ -TEST_F(AlertSchedulerTest, clearDataLogout) { +TEST_F(AlertSchedulerTest, test_clearDataLogout) { std::shared_ptr alert = doSimpleTestSetup(true); EXPECT_CALL(*(m_alertStorage.get()), clearDatabase()).Times(1); @@ -709,7 +710,7 @@ TEST_F(AlertSchedulerTest, clearDataLogout) { /** * Test if AlertScheduler shuts down appropriately */ -TEST_F(AlertSchedulerTest, shutdown) { +TEST_F(AlertSchedulerTest, test_shutdown) { doSimpleTestSetup(true); m_alertScheduler->shutdown(); @@ -722,7 +723,7 @@ TEST_F(AlertSchedulerTest, shutdown) { /** * Test Alert state change to Active on an inactive alert */ -TEST_F(AlertSchedulerTest, onAlertStateChangeStartedInactiveAlert) { +TEST_F(AlertSchedulerTest, test_onAlertStateChangeStartedInactiveAlert) { const std::string testReason = "stateStarted"; auto testState = AlertScheduler::State::STARTED; @@ -736,7 +737,7 @@ TEST_F(AlertSchedulerTest, onAlertStateChangeStartedInactiveAlert) { /** * Test Alert state change to Active on an active alert */ -TEST_F(AlertSchedulerTest, onAlertStateChangeStartedActiveAlert) { +TEST_F(AlertSchedulerTest, test_onAlertStateChangeStartedActiveAlert) { const std::string testReason = "stateStarted"; auto testState = AlertScheduler::State::STARTED; @@ -751,7 +752,7 @@ TEST_F(AlertSchedulerTest, onAlertStateChangeStartedActiveAlert) { /** * Test Alert state change to Stopped */ -TEST_F(AlertSchedulerTest, onAlertStateChangeStopped) { +TEST_F(AlertSchedulerTest, test_onAlertStateChangeStopped) { const std::string testReason = "stateStopped"; auto testState = AlertScheduler::State::STOPPED; @@ -765,7 +766,7 @@ TEST_F(AlertSchedulerTest, onAlertStateChangeStopped) { /** * Test Alert state change to Completed */ -TEST_F(AlertSchedulerTest, onAlertStateChangeCompleted) { +TEST_F(AlertSchedulerTest, test_onAlertStateChangeCompleted) { const std::string testReason = "stateCompleted"; auto testState = AlertScheduler::State::COMPLETED; @@ -779,7 +780,7 @@ TEST_F(AlertSchedulerTest, onAlertStateChangeCompleted) { /** * Test Alert state change to Snoozed */ -TEST_F(AlertSchedulerTest, onAlertStateChangeSnoozed) { +TEST_F(AlertSchedulerTest, test_onAlertStateChangeSnoozed) { const std::string testReason = "stateSnoozed"; auto testState = AlertScheduler::State::SNOOZED; @@ -793,7 +794,7 @@ TEST_F(AlertSchedulerTest, onAlertStateChangeSnoozed) { /** * Test Alert state change to Error on an active alert */ -TEST_F(AlertSchedulerTest, onAlertStateChangeErrorActiveAlert) { +TEST_F(AlertSchedulerTest, test_onAlertStateChangeErrorActiveAlert) { const std::string testReason = "stateError"; auto testState = AlertScheduler::State::ERROR; @@ -807,7 +808,7 @@ TEST_F(AlertSchedulerTest, onAlertStateChangeErrorActiveAlert) { /** * Test Alert state change to Error on an inactive alert */ -TEST_F(AlertSchedulerTest, onAlertStateChangeErrorInactiveAlert) { +TEST_F(AlertSchedulerTest, test_onAlertStateChangeErrorInactiveAlert) { const std::string testReason = "stateError"; auto testState = AlertScheduler::State::ERROR; diff --git a/CapabilityAgents/Alerts/test/AlertTest.cpp b/CapabilityAgents/Alerts/test/AlertTest.cpp index 433c5d09e8..72136a7df8 100644 --- a/CapabilityAgents/Alerts/test/AlertTest.cpp +++ b/CapabilityAgents/Alerts/test/AlertTest.cpp @@ -82,7 +82,8 @@ class MockRenderer : public renderer::RendererInterface { std::function()> audioFactory, const std::vector& urls = std::vector(), int loopCount = 0, - std::chrono::milliseconds loopPause = std::chrono::milliseconds{0}){}; + std::chrono::milliseconds loopPause = std::chrono::milliseconds{0}, + bool startWithPause = false){}; void stop(){}; }; @@ -136,21 +137,21 @@ const std::string getPayloadJson(bool inclToken, bool inclSchedTime, const std:: return payloadJson; } -TEST_F(AlertTest, defaultAudio) { +TEST_F(AlertTest, test_defaultAudio) { std::ostringstream oss; oss << m_alert->getDefaultAudioFactory()()->rdbuf(); ASSERT_EQ(DEFAULT_AUDIO, oss.str()); } -TEST_F(AlertTest, defaultShortAudio) { +TEST_F(AlertTest, test_defaultShortAudio) { std::ostringstream oss; oss << m_alert->getShortAudioFactory()()->rdbuf(); ASSERT_EQ(SHORT_AUDIO, oss.str()); } -TEST_F(AlertTest, testParseFromJsonHappyCase) { +TEST_F(AlertTest, test_parseFromJsonHappyCase) { std::string errorMessage; const std::string payloadJson = getPayloadJson(true, true, SCHED_TIME); rapidjson::Document payload; @@ -179,7 +180,7 @@ TEST_F(AlertTest, testParseFromJsonHappyCase) { ASSERT_EQ(assetsMap[ASSET_ID2].url, ASSET_URL2); } -TEST_F(AlertTest, testParseFromJsonMissingToken) { +TEST_F(AlertTest, test_parseFromJsonMissingToken) { std::string errorMessage; const std::string payloadJson = getPayloadJson(false, true, SCHED_TIME); rapidjson::Document payload; @@ -190,7 +191,7 @@ TEST_F(AlertTest, testParseFromJsonMissingToken) { ASSERT_EQ(resultStatus, Alert::ParseFromJsonStatus::MISSING_REQUIRED_PROPERTY); } -TEST_F(AlertTest, testParseFromJsonMissingSchedTime) { +TEST_F(AlertTest, test_parseFromJsonMissingSchedTime) { std::string errorMessage; const std::string payloadJson = getPayloadJson(true, false, SCHED_TIME); rapidjson::Document payload; @@ -201,7 +202,7 @@ TEST_F(AlertTest, testParseFromJsonMissingSchedTime) { ASSERT_EQ(resultStatus, Alert::ParseFromJsonStatus::MISSING_REQUIRED_PROPERTY); } -TEST_F(AlertTest, testParseFromJsonBadSchedTimeFormat) { +TEST_F(AlertTest, test_parseFromJsonBadSchedTimeFormat) { const std::string schedTime{INVALID_FORMAT_SCHED_TIME}; std::string errorMessage; const std::string payloadJson = getPayloadJson(true, true, schedTime); @@ -213,7 +214,7 @@ TEST_F(AlertTest, testParseFromJsonBadSchedTimeFormat) { ASSERT_EQ(resultStatus, Alert::ParseFromJsonStatus::INVALID_VALUE); } -TEST_F(AlertTest, testSetStateActive) { +TEST_F(AlertTest, test_setStateActive) { m_alert->reset(); ASSERT_EQ(m_alert->getState(), Alert::State::SET); m_alert->setStateActive(); @@ -225,14 +226,14 @@ TEST_F(AlertTest, testSetStateActive) { ASSERT_EQ(m_alert->getState(), Alert::State::ACTIVE); } -TEST_F(AlertTest, testDeactivate) { +TEST_F(AlertTest, test_deactivate) { Alert::StopReason stopReason = Alert::StopReason::AVS_STOP; m_alert->deactivate(stopReason); ASSERT_EQ(m_alert->getState(), Alert::State::STOPPING); ASSERT_EQ(m_alert->getStopReason(), stopReason); } -TEST_F(AlertTest, testSetTimeISO8601) { +TEST_F(AlertTest, test_setTimeISO8601) { avsCommon::utils::timing::TimeUtils timeUtils; std::string schedTime{"2030-02-02T12:56:34+0000"}; Alert::DynamicData dynamicData; @@ -246,7 +247,7 @@ TEST_F(AlertTest, testSetTimeISO8601) { ASSERT_EQ(m_alert->getScheduledTime_Unix(), unixTime); } -TEST_F(AlertTest, testUpdateScheduleActiveFailed) { +TEST_F(AlertTest, test_updateScheduleActiveFailed) { m_alert->activate(); m_alert->setStateActive(); ASSERT_EQ(m_alert->getState(), Alert::State::ACTIVE); @@ -257,31 +258,31 @@ TEST_F(AlertTest, testUpdateScheduleActiveFailed) { ASSERT_EQ(m_alert->getScheduledTime_ISO_8601(), oldScheduledTime); } -TEST_F(AlertTest, testUpdateScheduleBadTime) { +TEST_F(AlertTest, test_updateScheduleBadTime) { auto oldScheduledTime = m_alert->getScheduledTime_ISO_8601(); ASSERT_FALSE(m_alert->updateScheduledTime(INVALID_FORMAT_SCHED_TIME)); ASSERT_EQ(m_alert->getScheduledTime_ISO_8601(), oldScheduledTime); } -TEST_F(AlertTest, testUpdateScheduleHappyCase) { +TEST_F(AlertTest, test_updateScheduleHappyCase) { m_alert->reset(); ASSERT_TRUE(m_alert->updateScheduledTime("2030-02-02T12:56:34+0000")); ASSERT_EQ(m_alert->getState(), Alert::State::SET); } -TEST_F(AlertTest, testSnoozeBadTime) { +TEST_F(AlertTest, test_snoozeBadTime) { m_alert->reset(); ASSERT_FALSE(m_alert->snooze(INVALID_FORMAT_SCHED_TIME)); ASSERT_NE(m_alert->getState(), Alert::State::SNOOZING); } -TEST_F(AlertTest, testSnoozeHappyCase) { +TEST_F(AlertTest, test_snoozeHappyCase) { m_alert->reset(); ASSERT_TRUE(m_alert->snooze("2030-02-02T12:56:34+0000")); ASSERT_EQ(m_alert->getState(), Alert::State::SNOOZING); } -TEST_F(AlertTest, testSetLoopCountNegative) { +TEST_F(AlertTest, test_setLoopCountNegative) { int loopCount = -1; Alert::DynamicData dynamicData; m_alert->getAlertData(nullptr, &dynamicData); @@ -290,7 +291,7 @@ TEST_F(AlertTest, testSetLoopCountNegative) { ASSERT_NE(m_alert->getLoopCount(), loopCount); } -TEST_F(AlertTest, testSetLoopCountHappyCase) { +TEST_F(AlertTest, test_setLoopCountHappyCase) { int loopCount = 3; Alert::DynamicData dynamicData; m_alert->getAlertData(nullptr, &dynamicData); @@ -299,7 +300,7 @@ TEST_F(AlertTest, testSetLoopCountHappyCase) { ASSERT_EQ(m_alert->getLoopCount(), loopCount); } -TEST_F(AlertTest, testSetLoopPause) { +TEST_F(AlertTest, test_setLoopPause) { std::chrono::milliseconds loopPause{900}; Alert::StaticData staticData; m_alert->getAlertData(&staticData, nullptr); @@ -308,7 +309,7 @@ TEST_F(AlertTest, testSetLoopPause) { ASSERT_EQ(m_alert->getLoopPause(), loopPause); } -TEST_F(AlertTest, testSetBackgroundAssetId) { +TEST_F(AlertTest, test_setBackgroundAssetId) { std::unordered_map assets; assets["testAssetId"] = Alert::Asset("testAssetId", "http://test.com/a"); @@ -321,7 +322,7 @@ TEST_F(AlertTest, testSetBackgroundAssetId) { ASSERT_EQ(m_alert->getBackgroundAssetId(), backgroundAssetId); } -TEST_F(AlertTest, testIsPastDue) { +TEST_F(AlertTest, test_isPastDue) { Alert::DynamicData dynamicData; avsCommon::utils::timing::TimeUtils timeUtils; int64_t currentUnixTime = 0; @@ -338,7 +339,7 @@ TEST_F(AlertTest, testIsPastDue) { ASSERT_TRUE(m_alert->isPastDue(currentUnixTime, std::chrono::seconds{1})); } -TEST_F(AlertTest, testStateToString) { +TEST_F(AlertTest, test_stateToString) { ASSERT_EQ(m_alert->stateToString(Alert::State::UNSET), "UNSET"); ASSERT_EQ(m_alert->stateToString(Alert::State::SET), "SET"); ASSERT_EQ(m_alert->stateToString(Alert::State::READY), "READY"); @@ -351,14 +352,14 @@ TEST_F(AlertTest, testStateToString) { ASSERT_EQ(m_alert->stateToString(Alert::State::COMPLETED), "COMPLETED"); } -TEST_F(AlertTest, testStopReasonToString) { +TEST_F(AlertTest, test_stopReasonToString) { ASSERT_EQ(m_alert->stopReasonToString(Alert::StopReason::UNSET), "UNSET"); ASSERT_EQ(m_alert->stopReasonToString(Alert::StopReason::AVS_STOP), "AVS_STOP"); ASSERT_EQ(m_alert->stopReasonToString(Alert::StopReason::LOCAL_STOP), "LOCAL_STOP"); ASSERT_EQ(m_alert->stopReasonToString(Alert::StopReason::SHUTDOWN), "SHUTDOWN"); } -TEST_F(AlertTest, testParseFromJsonStatusToString) { +TEST_F(AlertTest, test_parseFromJsonStatusToString) { ASSERT_EQ(m_alert->parseFromJsonStatusToString(Alert::ParseFromJsonStatus::OK), "OK"); ASSERT_EQ( m_alert->parseFromJsonStatusToString(Alert::ParseFromJsonStatus::MISSING_REQUIRED_PROPERTY), @@ -366,7 +367,7 @@ TEST_F(AlertTest, testParseFromJsonStatusToString) { ASSERT_EQ(m_alert->parseFromJsonStatusToString(Alert::ParseFromJsonStatus::INVALID_VALUE), "INVALID_VALUE"); } -TEST_F(AlertTest, testHasAssetHappy) { +TEST_F(AlertTest, test_hasAssetHappy) { std::unordered_map assets; assets["A"] = Alert::Asset("A", "http://test.com/a"); assets["B"] = Alert::Asset("B", "http://test.com/a"); @@ -389,7 +390,7 @@ TEST_F(AlertTest, testHasAssetHappy) { ASSERT_TRUE(m_alert->setAlertData(&d, nullptr)); } -TEST_F(AlertTest, testHasAssetBgAssetIdNotFoundOnAssets) { +TEST_F(AlertTest, test_hasAssetBgAssetIdNotFoundOnAssets) { std::unordered_map assets; assets["A"] = Alert::Asset("A", "http://test.com/a"); assets["B"] = Alert::Asset("B", "http://test.com/a"); @@ -412,7 +413,7 @@ TEST_F(AlertTest, testHasAssetBgAssetIdNotFoundOnAssets) { ASSERT_FALSE(m_alert->setAlertData(&d, nullptr)); } -TEST_F(AlertTest, testHasAssetOrderItemNotFoundOnAssets) { +TEST_F(AlertTest, test_hasAssetOrderItemNotFoundOnAssets) { std::unordered_map assets; assets["A"] = Alert::Asset("A", "http://test.com/a"); assets["B"] = Alert::Asset("B", "http://test.com/a"); diff --git a/CapabilityAgents/Alerts/test/AlertsCapabilityAgentTest.cpp b/CapabilityAgents/Alerts/test/AlertsCapabilityAgentTest.cpp index 4e6e3e42f9..6e1b77e0c9 100644 --- a/CapabilityAgents/Alerts/test/AlertsCapabilityAgentTest.cpp +++ b/CapabilityAgents/Alerts/test/AlertsCapabilityAgentTest.cpp @@ -149,7 +149,8 @@ class StubRenderer : public RendererInterface { std::function()> audioFactory, const std::vector& urls, int loopCount, - std::chrono::milliseconds loopPause) override { + std::chrono::milliseconds loopPause, + bool startWithPause) override { } void stop() override { @@ -370,7 +371,7 @@ void AlertsCapabilityAgentTest::testStartAlertWithContentVolume( /** * Test local alert volume changes. Without alert sounding. Must send event. */ -TEST_F(AlertsCapabilityAgentTest, localAlertVolumeChangeNoAlert) { +TEST_F(AlertsCapabilityAgentTest, test_localAlertVolumeChangeNoAlert) { SpeakerInterface::SpeakerSettings speakerSettings; speakerSettings.volume = TEST_VOLUME_VALUE; speakerSettings.mute = false; @@ -388,7 +389,7 @@ TEST_F(AlertsCapabilityAgentTest, localAlertVolumeChangeNoAlert) { /** * Test local alert volume changes. With alert sounding. Must not send event, volume is treated as local. */ -TEST_F(AlertsCapabilityAgentTest, localAlertVolumeChangeAlertPlaying) { +TEST_F(AlertsCapabilityAgentTest, test_localAlertVolumeChangeAlertPlaying) { m_alertsCA->onAlertStateChange("", "", AlertObserverInterface::State::STARTED, ""); // We have to wait for the alert state to be processed before updating speaker settings. @@ -411,7 +412,7 @@ TEST_F(AlertsCapabilityAgentTest, localAlertVolumeChangeAlertPlaying) { /** * Test volume changes originated from AVS */ -TEST_F(AlertsCapabilityAgentTest, avsAlertVolumeChangeNoAlert) { +TEST_F(AlertsCapabilityAgentTest, test_avsAlertVolumeChangeNoAlert) { // Create Directive. auto attachmentManager = std::make_shared>(); auto avsMessageHeader = @@ -437,7 +438,7 @@ TEST_F(AlertsCapabilityAgentTest, avsAlertVolumeChangeNoAlert) { /** * Test if AVS alerts volume directive results in a proper event when alert is already playing. */ -TEST_F(AlertsCapabilityAgentTest, avsAlertVolumeChangeAlertPlaying) { +TEST_F(AlertsCapabilityAgentTest, test_avsAlertVolumeChangeAlertPlaying) { // Create Directive. auto attachmentManager = std::make_shared>(); auto avsMessageHeader = @@ -470,7 +471,7 @@ TEST_F(AlertsCapabilityAgentTest, avsAlertVolumeChangeAlertPlaying) { /** * Test use cases when alert is going to start when content is being played on Content channel with lower volume. */ -TEST_F(AlertsCapabilityAgentTest, startAlertWithContentChannelLowerVolume) { +TEST_F(AlertsCapabilityAgentTest, test_startAlertWithContentChannelLowerVolume) { testStartAlertWithContentVolume( LOWER_VOLUME_VALUE, HIGHER_VOLUME_VALUE, FocusManagerInterface::CONTENT_CHANNEL_NAME, false); } @@ -478,7 +479,7 @@ TEST_F(AlertsCapabilityAgentTest, startAlertWithContentChannelLowerVolume) { /** * Test use cases when alert is going to start when content is being played on Content channel with higher volume. */ -TEST_F(AlertsCapabilityAgentTest, startAlertWithContentChannelHigherVolume) { +TEST_F(AlertsCapabilityAgentTest, test_startAlertWithContentChannelHigherVolume) { testStartAlertWithContentVolume( HIGHER_VOLUME_VALUE, LOWER_VOLUME_VALUE, FocusManagerInterface::CONTENT_CHANNEL_NAME, true); } @@ -486,7 +487,7 @@ TEST_F(AlertsCapabilityAgentTest, startAlertWithContentChannelHigherVolume) { /** * Test use cases when alert is going to start when content is being played on Comms channel with lower volume. */ -TEST_F(AlertsCapabilityAgentTest, startAlertWithCommsChannelLowerVolume) { +TEST_F(AlertsCapabilityAgentTest, test_startAlertWithCommsChannelLowerVolume) { testStartAlertWithContentVolume( LOWER_VOLUME_VALUE, HIGHER_VOLUME_VALUE, FocusManagerInterface::COMMUNICATIONS_CHANNEL_NAME, false); } @@ -494,7 +495,7 @@ TEST_F(AlertsCapabilityAgentTest, startAlertWithCommsChannelLowerVolume) { /** * Test use cases when alert is going to start when content is being played on Comms channel with higher volume. */ -TEST_F(AlertsCapabilityAgentTest, startAlertWithCommsChannelHigherVolume) { +TEST_F(AlertsCapabilityAgentTest, test_startAlertWithCommsChannelHigherVolume) { testStartAlertWithContentVolume( HIGHER_VOLUME_VALUE, LOWER_VOLUME_VALUE, FocusManagerInterface::COMMUNICATIONS_CHANNEL_NAME, true); } @@ -502,7 +503,7 @@ TEST_F(AlertsCapabilityAgentTest, startAlertWithCommsChannelHigherVolume) { /** * Test use cases when alert is going to start when content is being played on Dialog channel with lower volume. */ -TEST_F(AlertsCapabilityAgentTest, startAlertWithDialogChannelLowerVolume) { +TEST_F(AlertsCapabilityAgentTest, test_startAlertWithDialogChannelLowerVolume) { testStartAlertWithContentVolume( LOWER_VOLUME_VALUE, HIGHER_VOLUME_VALUE, FocusManagerInterface::DIALOG_CHANNEL_NAME, false); } @@ -510,7 +511,7 @@ TEST_F(AlertsCapabilityAgentTest, startAlertWithDialogChannelLowerVolume) { /** * Test use cases when alert is going to start when content is being played on Dialog channel with higher volume. */ -TEST_F(AlertsCapabilityAgentTest, startAlertWithDialogChannelHigherVolume) { +TEST_F(AlertsCapabilityAgentTest, test_startAlertWithDialogChannelHigherVolume) { testStartAlertWithContentVolume( HIGHER_VOLUME_VALUE, LOWER_VOLUME_VALUE, FocusManagerInterface::DIALOG_CHANNEL_NAME, false); } @@ -518,7 +519,7 @@ TEST_F(AlertsCapabilityAgentTest, startAlertWithDialogChannelHigherVolume) { /** * Test invalid volume value handling. */ -TEST_F(AlertsCapabilityAgentTest, invalidVolumeValuesMax) { +TEST_F(AlertsCapabilityAgentTest, test_invalidVolumeValuesMax) { EXPECT_CALL(*(m_speakerManager.get()), setVolume(SpeakerInterface::Type::AVS_ALERTS_VOLUME, AVS_SET_VOLUME_MAX, _)) .Times(1); @@ -548,7 +549,7 @@ TEST_F(AlertsCapabilityAgentTest, invalidVolumeValuesMax) { /** * Test invalid volume value handling. */ -TEST_F(AlertsCapabilityAgentTest, invalidVolumeValuesMin) { +TEST_F(AlertsCapabilityAgentTest, test_invalidVolumeValuesMin) { EXPECT_CALL(*(m_speakerManager.get()), setVolume(SpeakerInterface::Type::AVS_ALERTS_VOLUME, AVS_SET_VOLUME_MIN, _)) .Times(1); diff --git a/CapabilityAgents/Alerts/test/ReminderAlertTest.cpp b/CapabilityAgents/Alerts/test/ReminderAlertTest.cpp index bd29ca761a..dea8885fd0 100644 --- a/CapabilityAgents/Alerts/test/ReminderAlertTest.cpp +++ b/CapabilityAgents/Alerts/test/ReminderAlertTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -43,21 +43,21 @@ ReminderAlertTest::ReminderAlertTest() : m_reminder{std::make_shared(reminderDefaultFactory, reminderShortFactory)} { } -TEST_F(ReminderAlertTest, defaultAudio) { +TEST_F(ReminderAlertTest, test_defaultAudio) { std::ostringstream oss; oss << m_reminder->getDefaultAudioFactory()()->rdbuf(); ASSERT_EQ(REMINDER_DEFAULT_DATA, oss.str()); } -TEST_F(ReminderAlertTest, shortAudio) { +TEST_F(ReminderAlertTest, test_shortAudio) { std::ostringstream oss; oss << m_reminder->getShortAudioFactory()()->rdbuf(); ASSERT_EQ(REMINDER_SHORT_DATA, oss.str()); } -TEST_F(ReminderAlertTest, testGetTypeName) { +TEST_F(ReminderAlertTest, test_getTypeName) { ASSERT_EQ(m_reminder->getTypeName(), Reminder::TYPE_NAME); } diff --git a/CapabilityAgents/Alerts/test/Renderer/RendererTest.cpp b/CapabilityAgents/Alerts/test/Renderer/RendererTest.cpp index 1a63da7a08..28a95b2e0b 100644 --- a/CapabilityAgents/Alerts/test/Renderer/RendererTest.cpp +++ b/CapabilityAgents/Alerts/test/Renderer/RendererTest.cpp @@ -168,7 +168,7 @@ void RendererTest::TearDown() { /** * Test if the Renderer class creates an object appropriately and fails when it must */ -TEST_F(RendererTest, create) { +TEST_F(RendererTest, test_create) { /// m_renderer was created using create() in the constructor. Check if not null ASSERT_NE(m_renderer, nullptr); @@ -179,7 +179,7 @@ TEST_F(RendererTest, create) { /** * Test if the Renderer starts */ -TEST_F(RendererTest, start) { +TEST_F(RendererTest, test_start) { SetUpTest(); ASSERT_TRUE(m_observer->waitFor(RendererObserverInterface::State::UNSET)); @@ -188,7 +188,7 @@ TEST_F(RendererTest, start) { /** * Test if the Renderer stops */ -TEST_F(RendererTest, stop) { +TEST_F(RendererTest, test_stop) { SetUpTest(); m_renderer->stop(); @@ -199,7 +199,7 @@ TEST_F(RendererTest, stop) { /** * Test if the Renderer errors out when it cant stop */ -TEST_F(RendererTest, stopError) { +TEST_F(RendererTest, test_stopError) { SetUpTest(); m_renderer->onPlaybackStarted(TEST_SOURCE_ID_GOOD); ASSERT_TRUE(m_observer->waitFor(RendererObserverInterface::State::STARTED)); @@ -214,7 +214,7 @@ TEST_F(RendererTest, stopError) { /** * Test if the Renderer correctly handles Playback starting */ -TEST_F(RendererTest, onPlaybackStarted) { +TEST_F(RendererTest, test_onPlaybackStarted) { SetUpTest(); /// shouldn't start if the source is bad @@ -229,7 +229,7 @@ TEST_F(RendererTest, onPlaybackStarted) { /** * Test if the Renderer correctly handles Playback stopping */ -TEST_F(RendererTest, onPlaybackStopped) { +TEST_F(RendererTest, test_onPlaybackStopped) { SetUpTest(); /// shouldn't stop if the source is bad @@ -244,7 +244,7 @@ TEST_F(RendererTest, onPlaybackStopped) { /** * Test if the Renderer gracefully handles errors when Playback finishing */ -TEST_F(RendererTest, onPlaybackFinishedError) { +TEST_F(RendererTest, test_onPlaybackFinishedError) { SetUpTest(); /// shouldn't finish even if the source is good, if the media player is errored out @@ -262,7 +262,7 @@ TEST_F(RendererTest, onPlaybackFinishedError) { /** * Test if the Renderer correctly handles Playback erroring out */ -TEST_F(RendererTest, onPlaybackError) { +TEST_F(RendererTest, test_onPlaybackError) { const avsCommon::utils::mediaPlayer::ErrorType& errorType = avsCommon::utils::mediaPlayer::ErrorType::MEDIA_ERROR_INVALID_REQUEST; std::string errorMsg = "testError"; @@ -281,7 +281,7 @@ TEST_F(RendererTest, onPlaybackError) { /** * Test empty URL with non-zero loop pause, simulating playing a default alarm audio on background */ -TEST_F(RendererTest, emptyURLNonZeroLoopPause) { +TEST_F(RendererTest, testTimer_emptyURLNonZeroLoopPause) { std::function()> audioFactory = RendererTest::audioFactoryFunc; std::vector urls; diff --git a/CapabilityAgents/Alerts/test/TimerAlertTest.cpp b/CapabilityAgents/Alerts/test/TimerAlertTest.cpp index 8ef12aa792..896c7e9de4 100644 --- a/CapabilityAgents/Alerts/test/TimerAlertTest.cpp +++ b/CapabilityAgents/Alerts/test/TimerAlertTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -43,21 +43,21 @@ class TimerAlertTest : public ::testing::Test { TimerAlertTest::TimerAlertTest() : m_timer{std::make_shared(timerDefaultFactory, timerShortFactory)} { } -TEST_F(TimerAlertTest, defaultAudio) { +TEST_F(TimerAlertTest, test_defaultAudio) { std::ostringstream oss; oss << m_timer->getDefaultAudioFactory()()->rdbuf(); ASSERT_EQ(TIMER_DEFAULT_DATA, oss.str()); } -TEST_F(TimerAlertTest, shortAudio) { +TEST_F(TimerAlertTest, test_shortAudio) { std::ostringstream oss; oss << m_timer->getShortAudioFactory()()->rdbuf(); ASSERT_EQ(TIMER_SHORT_DATA, oss.str()); } -TEST_F(TimerAlertTest, testGetTypeName) { +TEST_F(TimerAlertTest, test_getTypeName) { ASSERT_EQ(m_timer->getTypeName(), Timer::TYPE_NAME); } } // namespace test diff --git a/CapabilityAgents/AudioPlayer/test/AudioPlayerTest.cpp b/CapabilityAgents/AudioPlayer/test/AudioPlayerTest.cpp index 691c7f6615..ae2b04b68f 100644 --- a/CapabilityAgents/AudioPlayer/test/AudioPlayerTest.cpp +++ b/CapabilityAgents/AudioPlayer/test/AudioPlayerTest.cpp @@ -727,7 +727,7 @@ void AudioPlayerTest::verifyTags( * Test create() with nullptrs */ -TEST_F(AudioPlayerTest, testCreateWithNullPointers) { +TEST_F(AudioPlayerTest, test_createWithNullPointers) { std::shared_ptr testAudioPlayer; testAudioPlayer = AudioPlayer::create( @@ -789,7 +789,7 @@ TEST_F(AudioPlayerTest, testCreateWithNullPointers) { * Test transition from Idle to Playing */ -TEST_F(AudioPlayerTest, testTransitionFromIdleToPlaying) { +TEST_F(AudioPlayerTest, test_transitionFromIdleToPlaying) { EXPECT_CALL(*(m_mockMediaPlayer.get()), play(_)).Times(AtLeast(1)); sendPlayDirective(); } @@ -798,7 +798,7 @@ TEST_F(AudioPlayerTest, testTransitionFromIdleToPlaying) { * Test transition from Playing to Stopped with Stop Directive */ -TEST_F(AudioPlayerTest, testTransitionFromPlayingToStopped) { +TEST_F(AudioPlayerTest, test_transitionFromPlayingToStopped) { sendPlayDirective(); EXPECT_CALL(*(m_mockMediaPlayer.get()), stop(_)).Times(AtLeast(1)); @@ -819,7 +819,7 @@ TEST_F(AudioPlayerTest, testTransitionFromPlayingToStopped) { * Test transition from Playing to Stopped with ClearQueue.CLEAR_ALL Directive */ -TEST_F(AudioPlayerTest, testTransitionFromPlayingToStoppedWithClear) { +TEST_F(AudioPlayerTest, test_transitionFromPlayingToStoppedWithClear) { sendPlayDirective(); EXPECT_CALL(*(m_mockMediaPlayer.get()), stop(_)).Times(AtLeast(1)); @@ -833,7 +833,7 @@ TEST_F(AudioPlayerTest, testTransitionFromPlayingToStoppedWithClear) { * Test transition from Stopped to Playing after issuing second Play directive */ -TEST_F(AudioPlayerTest, testTransitionFromStoppedToPlaying) { +TEST_F(AudioPlayerTest, test_transitionFromStoppedToPlaying) { sendPlayDirective(); EXPECT_CALL(*(m_mockMediaPlayer.get()), stop(_)).Times(AtLeast(1)); @@ -872,7 +872,7 @@ TEST_F(AudioPlayerTest, testTransitionFromStoppedToPlaying) { * Test transition from Playing to Paused when focus changes to Dialog channel */ -TEST_F(AudioPlayerTest, testTransitionFromPlayingToPaused) { +TEST_F(AudioPlayerTest, test_transitionFromPlayingToPaused) { sendPlayDirective(); EXPECT_CALL(*(m_mockMediaPlayer.get()), pause(_)).Times(AtLeast(1)); @@ -886,7 +886,7 @@ TEST_F(AudioPlayerTest, testTransitionFromPlayingToPaused) { /** * Test transition from Paused to Stopped on ClearQueue.CLEAR_ALL directive */ -TEST_F(AudioPlayerTest, testTransitionFromPausedToStopped) { +TEST_F(AudioPlayerTest, test_transitionFromPausedToStopped) { sendPlayDirective(); EXPECT_CALL(*(m_mockMediaPlayer.get()), stop(_)).Times(AtLeast(1)); @@ -905,7 +905,7 @@ TEST_F(AudioPlayerTest, testTransitionFromPausedToStopped) { * Test transition from Paused to Playing after resume */ -TEST_F(AudioPlayerTest, testResumeAfterPaused) { +TEST_F(AudioPlayerTest, test_resumeAfterPaused) { sendPlayDirective(); EXPECT_CALL(*(m_mockMediaPlayer.get()), stop(_)).Times(AtLeast(1)); @@ -926,7 +926,7 @@ TEST_F(AudioPlayerTest, testResumeAfterPaused) { * Test @c provideState while IDLE */ -TEST_F(AudioPlayerTest, testCallingProvideStateWhenIdle) { +TEST_F(AudioPlayerTest, test_callingProvideStateWhenIdle) { EXPECT_CALL( *(m_mockContextManager.get()), setState(NAMESPACE_AND_NAME_PLAYBACK_STATE, _, StateRefreshPolicy::NEVER, PROVIDE_STATE_TOKEN_TEST)) @@ -948,7 +948,7 @@ TEST_F(AudioPlayerTest, testCallingProvideStateWhenIdle) { * Test @c onPlaybackError and expect a PlaybackFailed message */ -TEST_F(AudioPlayerTest, testOnPlaybackError) { +TEST_F(AudioPlayerTest, test_onPlaybackError) { m_expectedMessages.insert({PLAYBACK_STARTED_NAME, 0}); m_expectedMessages.insert({PLAYBACK_FAILED_NAME, 0}); m_expectedMessages.insert({PLAYBACK_STOPPED_NAME, 0}); @@ -986,7 +986,7 @@ TEST_F(AudioPlayerTest, testOnPlaybackError) { * Test @c onPlaybackPaused and expect a PlaybackPaused message */ -TEST_F(AudioPlayerTest, testOnPlaybackPaused) { +TEST_F(AudioPlayerTest, test_onPlaybackPaused) { m_expectedMessages.insert({PLAYBACK_STARTED_NAME, 0}); m_expectedMessages.insert({PLAYBACK_PAUSED_NAME, 0}); @@ -1024,7 +1024,7 @@ TEST_F(AudioPlayerTest, testOnPlaybackPaused) { * Test @c onPlaybackResumed and expect a PlaybackResumed message */ -TEST_F(AudioPlayerTest, testOnPlaybackResumed) { +TEST_F(AudioPlayerTest, test_onPlaybackResumed) { m_expectedMessages.insert({PLAYBACK_STARTED_NAME, 0}); m_expectedMessages.insert({PLAYBACK_RESUMED_NAME, 0}); @@ -1060,7 +1060,7 @@ TEST_F(AudioPlayerTest, testOnPlaybackResumed) { * Test @c onPlaybackFinished and expect a PLAYBACK_NEARLY_FINISHED_NAME and a PLAYBACK_FINISHED_NAME message */ -TEST_F(AudioPlayerTest, testOnPlaybackFinished) { +TEST_F(AudioPlayerTest, test_onPlaybackFinished) { m_expectedMessages.insert({PLAYBACK_STARTED_NAME, 0}); m_expectedMessages.insert({PLAYBACK_NEARLY_FINISHED_NAME, 0}); m_expectedMessages.insert({PLAYBACK_FINISHED_NAME, 0}); @@ -1097,7 +1097,7 @@ TEST_F(AudioPlayerTest, testOnPlaybackFinished) { * Test @c onBufferUnderrun and expect a PlaybackStutterStarted message */ -TEST_F(AudioPlayerTest, testOnBufferUnderrun) { +TEST_F(AudioPlayerTest, test_onBufferUnderrun) { m_expectedMessages.insert({PLAYBACK_STARTED_NAME, 0}); m_expectedMessages.insert({PLAYBACK_STUTTER_STARTED_NAME, 0}); @@ -1133,7 +1133,7 @@ TEST_F(AudioPlayerTest, testOnBufferUnderrun) { * Test @c onBufferRefilled and expect a PlaybackStutterFinished message */ -TEST_F(AudioPlayerTest, testOnBufferRefilled) { +TEST_F(AudioPlayerTest, testTimer_onBufferRefilled) { m_expectedMessages.insert({PLAYBACK_STARTED_NAME, 0}); m_expectedMessages.insert({PLAYBACK_STUTTER_FINISHED_NAME, 0}); @@ -1172,7 +1172,7 @@ TEST_F(AudioPlayerTest, testOnBufferRefilled) { * "StreamMetadataExtracted Event". This JSON object is verified in verifyTags. */ -TEST_F(AudioPlayerTest, testOnTags) { +TEST_F(AudioPlayerTest, test_onTags) { m_expectedMessages.insert({STREAM_METADATA_EXTRACTED_NAME, 0}); m_expectedMessages.insert({MESSAGE_METADATA_STRING_VALUE, 0}); m_expectedMessages.insert({MESSAGE_METADATA_UINT_VALUE, 0}); @@ -1238,7 +1238,7 @@ TEST_F(AudioPlayerTest, testOnTags) { * Expect the @c handleDirective call to the cancelled directive returns false */ -TEST_F(AudioPlayerTest, testCancelDirective) { +TEST_F(AudioPlayerTest, test_cancelDirective) { sendPlayDirective(); m_audioPlayer->CapabilityAgent::cancelDirective(MESSAGE_ID_TEST); @@ -1251,7 +1251,7 @@ TEST_F(AudioPlayerTest, testCancelDirective) { * Expect nothing to happen */ -TEST_F(AudioPlayerTest, testFocusChangeToNoneInIdleState) { +TEST_F(AudioPlayerTest, test_focusChangeToNoneInIdleState) { // switching to FocusState::NONE should cause no change m_audioPlayer->onFocusChanged(FocusState::NONE); ASSERT_TRUE(m_testAudioPlayerObserver->waitFor(PlayerActivity::IDLE, WAIT_TIMEOUT)); @@ -1263,7 +1263,7 @@ TEST_F(AudioPlayerTest, testFocusChangeToNoneInIdleState) { * due to a lack of a queued AudioItem. */ -TEST_F(AudioPlayerTest, testFocusChangeFromForegroundToBackgroundInIdleState) { +TEST_F(AudioPlayerTest, test_focusChangeFromForegroundToBackgroundInIdleState) { bool pauseCalled = false; EXPECT_CALL(*(m_mockMediaPlayer.get()), pause(_)) @@ -1291,7 +1291,7 @@ TEST_F(AudioPlayerTest, testFocusChangeFromForegroundToBackgroundInIdleState) { * Expect a call to pause. This isn't an expected state during normal execution. */ -TEST_F(AudioPlayerTest, testFocusChangeFromNoneToBackgroundInIdleState) { +TEST_F(AudioPlayerTest, test_focusChangeFromNoneToBackgroundInIdleState) { bool pauseCalled = false; EXPECT_CALL(*(m_mockMediaPlayer.get()), pause(_)) @@ -1313,7 +1313,7 @@ TEST_F(AudioPlayerTest, testFocusChangeFromNoneToBackgroundInIdleState) { * Expect to pause when switching to BACKGROUND and to stop when switching to NONE */ -TEST_F(AudioPlayerTest, testFocusChangesInPlayingState) { +TEST_F(AudioPlayerTest, test_focusChangesInPlayingState) { sendPlayDirective(); // already in FOREGROUND, expect no change @@ -1342,7 +1342,7 @@ TEST_F(AudioPlayerTest, testFocusChangesInPlayingState) { * to transition to PAUSED when switching to BACKGROUND. */ -TEST_F(AudioPlayerTest, testFocusChangesInStoppedState) { +TEST_F(AudioPlayerTest, test_focusChangesInStoppedState) { sendPlayDirective(); // push AudioPlayer into stopped state @@ -1363,7 +1363,7 @@ TEST_F(AudioPlayerTest, testFocusChangesInStoppedState) { * Expect to resume when switching to FOREGROUND, expect nothing when switching to BACKGROUND, expect stop when * switching to NONE */ -TEST_F(AudioPlayerTest, testFocusChangesInPausedState) { +TEST_F(AudioPlayerTest, test_focusChangesInPausedState) { sendPlayDirective(); // push AudioPlayer into paused state @@ -1397,7 +1397,7 @@ TEST_F(AudioPlayerTest, testFocusChangesInPausedState) { * when switching to NONE */ -TEST_F(AudioPlayerTest, testFocusChangesInBufferUnderrunState) { +TEST_F(AudioPlayerTest, test_focusChangesInBufferUnderrunState) { sendPlayDirective(); // push AudioPlayer into buffer underrun state @@ -1431,7 +1431,7 @@ TEST_F(AudioPlayerTest, testFocusChangesInBufferUnderrunState) { * Expect that pause() is called when @c AudioPlayer is pushed into background */ -TEST_F(AudioPlayerTest, testFocusChangeToBackgroundBeforeOnPlaybackStarted) { +TEST_F(AudioPlayerTest, test_focusChangeToBackgroundBeforeOnPlaybackStarted) { EXPECT_CALL(*(m_mockMediaPlayer.get()), play(_)).Times(1); sendPlayDirective(); @@ -1474,7 +1474,7 @@ TEST_F(AudioPlayerTest, testFocusChangeToBackgroundBeforeOnPlaybackStarted) { * when a new REPLACE_ALL Play directive comes in. */ -TEST_F(AudioPlayerTest, testPlayAfterOnPlaybackError) { +TEST_F(AudioPlayerTest, test_playAfterOnPlaybackError) { EXPECT_CALL(*(m_mockMediaPlayer.get()), getOffset(_)) .WillRepeatedly(Return(m_mockMediaPlayer->getOffset(m_mockMediaPlayer->getCurrentSourceId()))); sendPlayDirective(); @@ -1510,7 +1510,7 @@ TEST_F(AudioPlayerTest, testPlayAfterOnPlaybackError) { /** * Test @c onPlaybackStarted calls the @c PlaybackRouter */ -TEST_F(AudioPlayerTest, testPlaybackStartedSwitchesHandler) { +TEST_F(AudioPlayerTest, test_playbackStartedSwitchesHandler) { EXPECT_CALL(*m_mockPlaybackRouter, switchToDefaultHandler()); sendPlayDirective(); } @@ -1518,7 +1518,7 @@ TEST_F(AudioPlayerTest, testPlaybackStartedSwitchesHandler) { /** * Test to verify that ProgressReportDelayElapsed Event is sent correctly. This test is timing sensitive. */ -TEST_F(AudioPlayerTest, testProgressReportDelayElapsed) { +TEST_F(AudioPlayerTest, test_progressReportDelayElapsed) { m_expectedMessages.insert({PROGRESS_REPORT_DELAY_ELAPSED_NAME, 0}); EXPECT_CALL(*(m_mockMessageSender.get()), sendMessage(_)) @@ -1549,7 +1549,7 @@ TEST_F(AudioPlayerTest, testProgressReportDelayElapsed) { * Test to verify that ProgressReportDelayElapsed Event is not sent when the delay is less than the offset. This test * is timing sensitive. */ -TEST_F(AudioPlayerTest, testProgressReportDelayElapsedDelayLessThanOffset) { +TEST_F(AudioPlayerTest, test_progressReportDelayElapsedDelayLessThanOffset) { m_expectedMessages.insert({PROGRESS_REPORT_DELAY_ELAPSED_NAME, 0}); EXPECT_CALL(*(m_mockMessageSender.get()), sendMessage(_)) @@ -1580,7 +1580,7 @@ TEST_F(AudioPlayerTest, testProgressReportDelayElapsedDelayLessThanOffset) { * Test to verify that ProgressReportIntervalElapsed Event is sent when the interval is less than the offset. There * will be a ProgressReportIntervalElapsed Event at 100, 200 and 300 ms. This test is timing sensitive. */ -TEST_F(AudioPlayerTest, testProgressReportIntervalElapsed) { +TEST_F(AudioPlayerTest, testTimer_progressReportIntervalElapsed) { m_expectedMessages.insert({PROGRESS_REPORT_INTERVAL_ELAPSED_NAME, 0}); EXPECT_CALL(*(m_mockMessageSender.get()), sendMessage(_)) @@ -1611,7 +1611,7 @@ TEST_F(AudioPlayerTest, testProgressReportIntervalElapsed) { * Test to verify that ProgressReportIntervalElapsed Event is sent when the interval is less than the offset. There * will be a ProgressReportIntervalElapsed Event at 200 and 300 ms. This test is timing sensitive. */ -TEST_F(AudioPlayerTest, testProgressReportIntervalElapsedIntervalLessThanOffset) { +TEST_F(AudioPlayerTest, test_progressReportIntervalElapsedIntervalLessThanOffset) { m_expectedMessages.insert({PROGRESS_REPORT_INTERVAL_ELAPSED_NAME, 0}); EXPECT_CALL(*(m_mockMessageSender.get()), sendMessage(_)) @@ -1644,7 +1644,7 @@ TEST_F(AudioPlayerTest, testProgressReportIntervalElapsedIntervalLessThanOffset) * focus goes back to FOREGROUND. */ -TEST_F(AudioPlayerTest, testPlayOnlyAfterForegroundFocus) { +TEST_F(AudioPlayerTest, testSlow_playOnlyAfterForegroundFocus) { EXPECT_CALL(*(m_mockMediaPlayer.get()), getOffset(_)) .WillRepeatedly(Return(m_mockMediaPlayer->getOffset(m_mockMediaPlayer->getCurrentSourceId()))); sendPlayDirective(); @@ -1683,7 +1683,7 @@ TEST_F(AudioPlayerTest, testPlayOnlyAfterForegroundFocus) { * Test when @c AudioPlayer starts to play but loses focus before the onPlaybackStarted callback is received. * After onPlaybackStarted is received, playback should stop. */ -TEST_F(AudioPlayerTest, testPlaybackStartedCallbackAfterFocusLost) { +TEST_F(AudioPlayerTest, testTimer_playbackStartedCallbackAfterFocusLost) { EXPECT_CALL(*(m_mockMediaPlayer.get()), getOffset(_)) .WillRepeatedly(Return(m_mockMediaPlayer->getOffset(m_mockMediaPlayer->getCurrentSourceId()))); diff --git a/CapabilityAgents/AudioPlayer/test/ProgressTimerTest.cpp b/CapabilityAgents/AudioPlayer/test/ProgressTimerTest.cpp index a2c7ecf9fe..1ad5e9f87b 100644 --- a/CapabilityAgents/AudioPlayer/test/ProgressTimerTest.cpp +++ b/CapabilityAgents/AudioPlayer/test/ProgressTimerTest.cpp @@ -153,7 +153,7 @@ void ProgressTimerTest::callOnProgress() { } // Verify that with invalid delay and interval, no progress is reported. -TEST_F(ProgressTimerTest, testNoDelayOrInterval) { +TEST_F(ProgressTimerTest, test_noDelayOrInterval) { EXPECT_CALL(*(m_mockContext.get()), onProgressReportDelayElapsed()).Times(0); EXPECT_CALL(*(m_mockContext.get()), onProgressReportIntervalElapsed()).Times(0); @@ -165,7 +165,7 @@ TEST_F(ProgressTimerTest, testNoDelayOrInterval) { } // Verify that an interval of zero does not trigger progress reports or a crash. -TEST_F(ProgressTimerTest, testZeroInterval) { +TEST_F(ProgressTimerTest, test_zeroInterval) { EXPECT_CALL(*(m_mockContext.get()), onProgressReportDelayElapsed()).Times(0); EXPECT_CALL(*(m_mockContext.get()), onProgressReportIntervalElapsed()).Times(0); @@ -177,7 +177,7 @@ TEST_F(ProgressTimerTest, testZeroInterval) { } // Verify that with a valid delay and invalid interval, a delay notification is generated. -TEST_F(ProgressTimerTest, testJustDelay) { +TEST_F(ProgressTimerTest, test_justDelay) { auto requestProgress = [this] { callOnProgress(); }; EXPECT_CALL(*(m_mockContext.get()), requestProgress()).WillRepeatedly(Invoke(requestProgress)); @@ -192,7 +192,7 @@ TEST_F(ProgressTimerTest, testJustDelay) { } // Verify that with a invalid delay and a valid interval, interval notifications are generated. -TEST_F(ProgressTimerTest, testJustInterval) { +TEST_F(ProgressTimerTest, test_justInterval) { auto requestProgress = [this] { callOnProgress(); }; int reportCounter = 0; @@ -215,7 +215,7 @@ TEST_F(ProgressTimerTest, testJustInterval) { } // Verify that with both a valid delay and interval, both types of notifications are generated. -TEST_F(ProgressTimerTest, testDelayAndInterval) { +TEST_F(ProgressTimerTest, test_delayAndInterval) { auto requestProgress = [this] { callOnProgress(); }; int reportCounter = 0; @@ -254,7 +254,7 @@ TEST_F(ProgressTimerTest, testDelayAndInterval) { } // Verify that when paused, a ProgressTimer will not generate notifications. -TEST_F(ProgressTimerTest, testPause) { +TEST_F(ProgressTimerTest, test_pause) { auto requestProgress = [this] { callOnProgress(); }; std::mutex counterMutex; @@ -301,7 +301,7 @@ TEST_F(ProgressTimerTest, testPause) { } // Verify that when resumed, a ProgressTimer will not repeat delay progress reports. -TEST_F(ProgressTimerTest, testResumeDoesNotRepeat) { +TEST_F(ProgressTimerTest, test_resumeDoesNotRepeat) { auto requestProgress = [this] { callOnProgress(); }; EXPECT_CALL(*(m_mockContext.get()), requestProgress()).WillRepeatedly(Invoke(requestProgress)); @@ -320,7 +320,7 @@ TEST_F(ProgressTimerTest, testResumeDoesNotRepeat) { } // Verify that the generated offsets are approximately correct. -TEST_F(ProgressTimerTest, testOffsets) { +TEST_F(ProgressTimerTest, testTimer_offsets) { auto requestProgress = [this] { callOnProgress(); }; auto verifyDelayOffset = [this]() { verifyOffset(OFFSET_TEST_DELAY, m_stopwatch.getElapsed()); }; @@ -348,7 +348,7 @@ TEST_F(ProgressTimerTest, testOffsets) { } // Verify that when delay and interval coincide, both types of notifications are generated. -TEST_F(ProgressTimerTest, testDelayAndIntervalCoincide) { +TEST_F(ProgressTimerTest, test_delayAndIntervalCoincide) { auto requestProgress = [this] { callOnProgress(); }; PromiseFuturePair gotReport; diff --git a/CapabilityAgents/Bluetooth/src/Bluetooth.cpp b/CapabilityAgents/Bluetooth/src/Bluetooth.cpp index 6b8a66457b..5a8264737e 100644 --- a/CapabilityAgents/Bluetooth/src/Bluetooth.cpp +++ b/CapabilityAgents/Bluetooth/src/Bluetooth.cpp @@ -1988,7 +1988,7 @@ void Bluetooth::executeSendMediaControlNextSucceeded() { } void Bluetooth::executeSendMediaControlNextFailed() { - executeQueueEventAndRequestContext(MEDIA_CONTROL_NEXT_SUCCEEDED.name, EMPTY_PAYLOAD); + executeQueueEventAndRequestContext(MEDIA_CONTROL_NEXT_FAILED.name, EMPTY_PAYLOAD); } void Bluetooth::executeSendMediaControlPreviousSucceeded() { diff --git a/CapabilityAgents/Bluetooth/test/BluetoothAVRCPTransformerTest.cpp b/CapabilityAgents/Bluetooth/test/BluetoothAVRCPTransformerTest.cpp index ccf8a5d75b..1ee7a556e8 100644 --- a/CapabilityAgents/Bluetooth/test/BluetoothAVRCPTransformerTest.cpp +++ b/CapabilityAgents/Bluetooth/test/BluetoothAVRCPTransformerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -63,13 +63,13 @@ void BluetoothAVRCPTransformerTest::SetUp() { } /// Test that create() returns a nullptr if called with invalid arguments. -TEST_F(BluetoothAVRCPTransformerTest, createWithNullParams) { +TEST_F(BluetoothAVRCPTransformerTest, test_createWithNullParams) { ASSERT_THAT(BluetoothAVRCPTransformer::create(m_eventBus, nullptr), IsNull()); ASSERT_THAT(BluetoothAVRCPTransformer::create(nullptr, m_mockRouter), IsNull()); } /// Test that a Play AVRCP command is transformed to playButtonPressed(). -TEST_F(BluetoothAVRCPTransformerTest, handlePlayCommand) { +TEST_F(BluetoothAVRCPTransformerTest, test_handlePlayCommand) { EXPECT_CALL(*m_mockRouter, buttonPressed(PlaybackButton::PLAY)).Times(1); AVRCPCommandReceivedEvent event(AVRCPCommand::PLAY); @@ -77,7 +77,7 @@ TEST_F(BluetoothAVRCPTransformerTest, handlePlayCommand) { } /// Test that a Pause AVRCP command is transformed to pauseButtonPressed(). -TEST_F(BluetoothAVRCPTransformerTest, handlePauseCommand) { +TEST_F(BluetoothAVRCPTransformerTest, test_handlePauseCommand) { EXPECT_CALL(*m_mockRouter, buttonPressed(PlaybackButton::PAUSE)).Times(1); AVRCPCommandReceivedEvent event(AVRCPCommand::PAUSE); @@ -85,7 +85,7 @@ TEST_F(BluetoothAVRCPTransformerTest, handlePauseCommand) { } /// Test that a Next AVRCP command is transformed to nextButtonPressed(). -TEST_F(BluetoothAVRCPTransformerTest, handleNextCommand) { +TEST_F(BluetoothAVRCPTransformerTest, test_handleNextCommand) { EXPECT_CALL(*m_mockRouter, buttonPressed(PlaybackButton::NEXT)).Times(1); AVRCPCommandReceivedEvent event(AVRCPCommand::NEXT); @@ -93,7 +93,7 @@ TEST_F(BluetoothAVRCPTransformerTest, handleNextCommand) { } /// Test that a Previous AVRCP command is transformed to previousButtonPressed(). -TEST_F(BluetoothAVRCPTransformerTest, handlePreviousCommand) { +TEST_F(BluetoothAVRCPTransformerTest, test_handlePreviousCommand) { EXPECT_CALL(*m_mockRouter, buttonPressed(PlaybackButton::PREVIOUS)).Times(1); AVRCPCommandReceivedEvent event(AVRCPCommand::PREVIOUS); @@ -101,7 +101,7 @@ TEST_F(BluetoothAVRCPTransformerTest, handlePreviousCommand) { } /// Test that an unrelated event does not trigger any calls to the PlaybackRouter. -TEST_F(BluetoothAVRCPTransformerTest, unrelatedEvent) { +TEST_F(BluetoothAVRCPTransformerTest, test_unrelatedEvent) { auto strictPlaybackRouter = std::shared_ptr(new StrictMock()); auto avrcpTransformer = BluetoothAVRCPTransformer::create(m_eventBus, strictPlaybackRouter); diff --git a/CapabilityAgents/Bluetooth/test/SQLiteBluetoothStorageTest.cpp b/CapabilityAgents/Bluetooth/test/SQLiteBluetoothStorageTest.cpp index f81bdb955f..23fce8457a 100644 --- a/CapabilityAgents/Bluetooth/test/SQLiteBluetoothStorageTest.cpp +++ b/CapabilityAgents/Bluetooth/test/SQLiteBluetoothStorageTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -205,7 +205,7 @@ void SQLiteBluetoothStorageTest::getMacOrUuidHelper( } /// Tests the create function with an invalid root. -TEST_F(SQLiteBluetoothStorageTest, createInvalidConfigurationRoot) { +TEST_F(SQLiteBluetoothStorageTest, test_createInvalidConfigurationRoot) { ConfigurationNode::uninitialize(); std::vector> empty; ConfigurationNode::initialize(empty); @@ -214,13 +214,13 @@ TEST_F(SQLiteBluetoothStorageTest, createInvalidConfigurationRoot) { } /// Tests creating a database object. -TEST_F(SQLiteBluetoothStorageTest, createValidConfigurationRoot) { +TEST_F(SQLiteBluetoothStorageTest, test_createValidConfigurationRoot) { // SQLite allows simultaneous access to the database. ASSERT_THAT(SQLiteBluetoothStorage::create(ConfigurationNode::getRoot()), NotNull()); } /// Test creating a valid DB. This is implicitly tested in the SetUp() function, but we formally test it here. -TEST_F(SQLiteBluetoothStorageTest, createDatabaseSucceeds) { +TEST_F(SQLiteBluetoothStorageTest, test_createDatabaseSucceeds) { closeAndDeleteDB(); m_db = SQLiteBluetoothStorage::create(ConfigurationNode::getRoot()); @@ -229,18 +229,18 @@ TEST_F(SQLiteBluetoothStorageTest, createDatabaseSucceeds) { } /// Test that creating an existing DB fails. -TEST_F(SQLiteBluetoothStorageTest, createExistingDatabaseFails) { +TEST_F(SQLiteBluetoothStorageTest, test_createExistingDatabaseFails) { ASSERT_FALSE(m_db->createDatabase()); } /// Test opening an existing database. -TEST_F(SQLiteBluetoothStorageTest, openExistingDatabaseSucceeds) { +TEST_F(SQLiteBluetoothStorageTest, test_openExistingDatabaseSucceeds) { m_db->close(); ASSERT_TRUE(m_db->open()); } /// Test clearing the table with one row. -TEST_F(SQLiteBluetoothStorageTest, clearOnOneRowSucceeds) { +TEST_F(SQLiteBluetoothStorageTest, test_clearOnOneRowSucceeds) { ASSERT_TRUE(m_db->insertByMac(TEST_MAC, TEST_UUID)); ASSERT_TRUE(m_db->clear()); std::unordered_map rows; @@ -249,7 +249,7 @@ TEST_F(SQLiteBluetoothStorageTest, clearOnOneRowSucceeds) { } /// Test clearing the table with multiple rows. -TEST_F(SQLiteBluetoothStorageTest, clearOnMultipleRowsSucceeds) { +TEST_F(SQLiteBluetoothStorageTest, test_clearOnMultipleRowsSucceeds) { ASSERT_TRUE(m_db->insertByMac(TEST_MAC, TEST_UUID)); ASSERT_TRUE(m_db->insertByMac(TEST_MAC_2, TEST_UUID_2)); ASSERT_TRUE(m_db->clear()); @@ -259,7 +259,7 @@ TEST_F(SQLiteBluetoothStorageTest, clearOnMultipleRowsSucceeds) { } /// Test clearing the table when it's already empty. -TEST_F(SQLiteBluetoothStorageTest, clearOnEmptySucceeds) { +TEST_F(SQLiteBluetoothStorageTest, test_clearOnEmptySucceeds) { ASSERT_TRUE(m_db->clear()); std::unordered_map rows; ASSERT_TRUE(m_db->getUuidToMac(&rows)); @@ -267,67 +267,67 @@ TEST_F(SQLiteBluetoothStorageTest, clearOnEmptySucceeds) { } /// Test getUuid with one row containing UUID. -TEST_F(SQLiteBluetoothStorageTest, getUuidWithOneSucceeds) { +TEST_F(SQLiteBluetoothStorageTest, test_getUuidWithOneSucceeds) { const std::unordered_map data{{TEST_MAC, TEST_UUID}}; getMacOrUuidHelper(&SQLiteBluetoothStorage::getUuid, TEST_MAC, TEST_UUID, data); } /// Test getUuid with multiple rows, one of which contains the UUID. -TEST_F(SQLiteBluetoothStorageTest, getUuidWithMultipleSucceeds) { +TEST_F(SQLiteBluetoothStorageTest, test_getUuidWithMultipleSucceeds) { const std::unordered_map data{{TEST_MAC, TEST_UUID}, {TEST_MAC_2, TEST_UUID_2}}; getMacOrUuidHelper(&SQLiteBluetoothStorage::getUuid, TEST_MAC, TEST_UUID, data); } /// Test getUuid with no matching UUID. -TEST_F(SQLiteBluetoothStorageTest, getUuidNoMatchingFails) { +TEST_F(SQLiteBluetoothStorageTest, test_getUuidNoMatchingFails) { std::string uuid; ASSERT_FALSE(m_db->getUuid(TEST_MAC, &uuid)); } /// Test getMac with one row containing MAC. -TEST_F(SQLiteBluetoothStorageTest, getMacWithOneSucceeds) { +TEST_F(SQLiteBluetoothStorageTest, test_getMacWithOneSucceeds) { const std::unordered_map data{{TEST_MAC, TEST_UUID}}; getMacOrUuidHelper(&SQLiteBluetoothStorage::getMac, TEST_UUID, TEST_MAC, data); } /// Test getMac with multiple rows, one of which contains the MAC. -TEST_F(SQLiteBluetoothStorageTest, getMacWithMultipleSucceeds) { +TEST_F(SQLiteBluetoothStorageTest, test_getMacWithMultipleSucceeds) { const std::unordered_map data{{TEST_MAC, TEST_UUID}, {TEST_MAC_2, TEST_UUID_2}}; getMacOrUuidHelper(&SQLiteBluetoothStorage::getMac, TEST_UUID, TEST_MAC, data); } /// Test getMac with no matching MAC. -TEST_F(SQLiteBluetoothStorageTest, getMacNoMatchingFails) { +TEST_F(SQLiteBluetoothStorageTest, test_getMacNoMatchingFails) { std::string mac; ASSERT_FALSE(m_db->getMac(TEST_UUID, &mac)); } /// Test getMacToUuid with one row. -TEST_F(SQLiteBluetoothStorageTest, getMacToUuidWithOneRowSucceeds) { +TEST_F(SQLiteBluetoothStorageTest, test_getMacToUuidWithOneRowSucceeds) { const std::unordered_map data{{TEST_MAC, TEST_UUID}}; getRowsHelper(&SQLiteBluetoothStorage::getMacToUuid, data, data); } /// Test getMacToUuid with multiple expected. -TEST_F(SQLiteBluetoothStorageTest, getMacToUuidWithMultipleRowsSucceeds) { +TEST_F(SQLiteBluetoothStorageTest, test_getMacToUuidWithMultipleRowsSucceeds) { const std::unordered_map data{{TEST_MAC, TEST_UUID}, {TEST_MAC_2, TEST_UUID_2}}; getRowsHelper(&SQLiteBluetoothStorage::getMacToUuid, data, data); } /// Test getMacToUuid when empty. -TEST_F(SQLiteBluetoothStorageTest, getMacToUuidWithEmptySucceeds) { +TEST_F(SQLiteBluetoothStorageTest, test_getMacToUuidWithEmptySucceeds) { std::unordered_map data; getRowsHelper(&SQLiteBluetoothStorage::getMacToUuid, data, data); } /// Test getUuidToMac with one row. -TEST_F(SQLiteBluetoothStorageTest, getUuidToMacWithOneRowSucceeds) { +TEST_F(SQLiteBluetoothStorageTest, test_getUuidToMacWithOneRowSucceeds) { const std::unordered_map data{{TEST_MAC, TEST_UUID}}; const std::unordered_map expected{{TEST_UUID, TEST_MAC}}; @@ -336,7 +336,7 @@ TEST_F(SQLiteBluetoothStorageTest, getUuidToMacWithOneRowSucceeds) { } /// Test getUuidToMac with multiple expected. -TEST_F(SQLiteBluetoothStorageTest, getUuidToMacWithMultipleRowsSucceeds) { +TEST_F(SQLiteBluetoothStorageTest, test_getUuidToMacWithMultipleRowsSucceeds) { const std::unordered_map data{{TEST_MAC, TEST_UUID}, {TEST_MAC_2, TEST_UUID_2}}; const std::unordered_map expected{{TEST_UUID, TEST_MAC}, {TEST_UUID_2, TEST_MAC_2}}; @@ -344,23 +344,23 @@ TEST_F(SQLiteBluetoothStorageTest, getUuidToMacWithMultipleRowsSucceeds) { } /// Test getUuidToMac when empty. -TEST_F(SQLiteBluetoothStorageTest, getUuidToMacWithEmptySucceeds) { +TEST_F(SQLiteBluetoothStorageTest, test_getUuidToMacWithEmptySucceeds) { std::unordered_map data; getRowsHelper(&SQLiteBluetoothStorage::getUuidToMac, data, data); } /// Test getOrderedMac and retrieve the macs in ascending insertion order (oldest first). -TEST_F(SQLiteBluetoothStorageTest, getOrderedMacAscending) { +TEST_F(SQLiteBluetoothStorageTest, test_getOrderedMacAscending) { getOrderedMacHelper(true); } /// Test getOrderedMac and retrieve the macs in descending insertion order (newest first). -TEST_F(SQLiteBluetoothStorageTest, getOrderedMacDescending) { +TEST_F(SQLiteBluetoothStorageTest, test_getOrderedMacDescending) { getOrderedMacHelper(false); } /// Test insertByMac succeeds. -TEST_F(SQLiteBluetoothStorageTest, insertByMacSucceeds) { +TEST_F(SQLiteBluetoothStorageTest, test_insertByMacSucceeds) { const std::unordered_map expected{{TEST_MAC, TEST_UUID}}; ASSERT_TRUE(m_db->insertByMac(TEST_MAC, TEST_UUID)); @@ -371,13 +371,13 @@ TEST_F(SQLiteBluetoothStorageTest, insertByMacSucceeds) { } /// Test insertByMac existing fails. -TEST_F(SQLiteBluetoothStorageTest, insertByMacDuplicateFails) { +TEST_F(SQLiteBluetoothStorageTest, test_insertByMacDuplicateFails) { ASSERT_TRUE(m_db->insertByMac(TEST_MAC, TEST_UUID)); ASSERT_FALSE(m_db->insertByMac(TEST_MAC, TEST_UUID, false)); } /// Test insertByMac with overwrite succeeds. -TEST_F(SQLiteBluetoothStorageTest, insertByMacOverwriteSucceeds) { +TEST_F(SQLiteBluetoothStorageTest, test_insertByMacOverwriteSucceeds) { const std::unordered_map expected{{TEST_MAC, TEST_UUID}}; ASSERT_TRUE(m_db->insertByMac(TEST_MAC, TEST_UUID_2)); @@ -389,7 +389,7 @@ TEST_F(SQLiteBluetoothStorageTest, insertByMacOverwriteSucceeds) { } /// Test remove succeeds. -TEST_F(SQLiteBluetoothStorageTest, removeExistingSucceeds) { +TEST_F(SQLiteBluetoothStorageTest, test_removeExistingSucceeds) { ASSERT_TRUE(m_db->insertByMac(TEST_MAC, TEST_UUID)); ASSERT_TRUE(m_db->remove(TEST_MAC)); @@ -400,7 +400,7 @@ TEST_F(SQLiteBluetoothStorageTest, removeExistingSucceeds) { } /// Test remove on non-existing record succeeds. -TEST_F(SQLiteBluetoothStorageTest, removeNonExistingSucceeds) { +TEST_F(SQLiteBluetoothStorageTest, test_removeNonExistingSucceeds) { ASSERT_TRUE(m_db->remove(TEST_MAC)); std::unordered_map rows; diff --git a/CapabilityAgents/DoNotDisturb/test/DoNotDisturbCapabilityAgentTest.cpp b/CapabilityAgents/DoNotDisturb/test/DoNotDisturbCapabilityAgentTest.cpp index 7a36d7aa41..ad5f87f088 100644 --- a/CapabilityAgents/DoNotDisturb/test/DoNotDisturbCapabilityAgentTest.cpp +++ b/CapabilityAgents/DoNotDisturb/test/DoNotDisturbCapabilityAgentTest.cpp @@ -157,37 +157,37 @@ void DoNotDisturbCapabilityAgentTest::TearDown() { } } -TEST_F(DoNotDisturbCapabilityAgentTest, givenNullCustomerDataManager_create_shouldFail) { +TEST_F(DoNotDisturbCapabilityAgentTest, test_givenNullCustomerDataManager_create_shouldFail) { auto dndCA = DoNotDisturbCapabilityAgent::create( nullptr, m_mockExceptionEncounteredSender, m_messageSender, m_settingsManager, m_settingsStorage); EXPECT_THAT(dndCA, IsNull()); } -TEST_F(DoNotDisturbCapabilityAgentTest, givenNullExceptionSender_create_shouldFail) { +TEST_F(DoNotDisturbCapabilityAgentTest, test_givenNullExceptionSender_create_shouldFail) { auto dndCA = DoNotDisturbCapabilityAgent::create( m_customerDataManager, nullptr, m_messageSender, m_settingsManager, m_settingsStorage); EXPECT_THAT(dndCA, IsNull()); } -TEST_F(DoNotDisturbCapabilityAgentTest, givenNullMessageSender_create_shouldFail) { +TEST_F(DoNotDisturbCapabilityAgentTest, test_givenNullMessageSender_create_shouldFail) { auto dndCA = DoNotDisturbCapabilityAgent::create( m_customerDataManager, m_mockExceptionEncounteredSender, nullptr, m_settingsManager, m_settingsStorage); EXPECT_THAT(dndCA, IsNull()); } -TEST_F(DoNotDisturbCapabilityAgentTest, givenNullSettingsManager_create_shouldFail) { +TEST_F(DoNotDisturbCapabilityAgentTest, test_givenNullSettingsManager_create_shouldFail) { auto dndCA = DoNotDisturbCapabilityAgent::create( m_customerDataManager, m_mockExceptionEncounteredSender, m_messageSender, nullptr, m_settingsStorage); EXPECT_THAT(dndCA, IsNull()); } -TEST_F(DoNotDisturbCapabilityAgentTest, givenNullSettingsStorage_create_shouldFail) { +TEST_F(DoNotDisturbCapabilityAgentTest, test_givenNullSettingsStorage_create_shouldFail) { auto dndCA = DoNotDisturbCapabilityAgent::create( m_customerDataManager, m_mockExceptionEncounteredSender, m_messageSender, m_settingsManager, nullptr); EXPECT_THAT(dndCA, IsNull()); } -TEST_F(DoNotDisturbCapabilityAgentTest, givenValidSetDNDDirective_handleDirective_shouldSucceed) { +TEST_F(DoNotDisturbCapabilityAgentTest, test_givenValidSetDNDDirective_handleDirective_shouldSucceed) { // Become online bool initialReportSent = expectEventSend(DND_REPORT_EVENT, MessageRequestObserverInterface::Status::SUCCESS, [this]() { @@ -209,7 +209,7 @@ TEST_F(DoNotDisturbCapabilityAgentTest, givenValidSetDNDDirective_handleDirectiv ASSERT_TRUE(directiveResponseEventSent); } -TEST_F(DoNotDisturbCapabilityAgentTest, beingOnline_applyLocalChange_shouldSendReport) { +TEST_F(DoNotDisturbCapabilityAgentTest, test_beingOnline_applyLocalChange_shouldSendReport) { bool initialReportSent = expectEventSend(DND_REPORT_EVENT, MessageRequestObserverInterface::Status::SUCCESS, [this]() { m_dndCA->onConnectionStatusChanged( @@ -227,7 +227,7 @@ TEST_F(DoNotDisturbCapabilityAgentTest, beingOnline_applyLocalChange_shouldSendR ASSERT_TRUE(changeEventSent); } -TEST_F(DoNotDisturbCapabilityAgentTest, beingOffline_applyLocalChangeAndBecomeOnline_shouldSendChanged) { +TEST_F(DoNotDisturbCapabilityAgentTest, test_beingOffline_applyLocalChangeAndBecomeOnline_shouldSendChanged) { // Apply change while offline m_dndCA->sendChangedEvent("true"); @@ -241,7 +241,7 @@ TEST_F(DoNotDisturbCapabilityAgentTest, beingOffline_applyLocalChangeAndBecomeOn ASSERT_TRUE(changeEventSent); } -TEST_F(DoNotDisturbCapabilityAgentTest, whileSendingChangedEvent_sendChangedFail_shouldSendReport) { +TEST_F(DoNotDisturbCapabilityAgentTest, test_whileSendingChangedEvent_sendChangedFail_shouldSendReport) { // Become online and ignore the first "report" event. bool initialReportSent = diff --git a/CapabilityAgents/ExternalMediaPlayer/src/ExternalMediaPlayer.cpp b/CapabilityAgents/ExternalMediaPlayer/src/ExternalMediaPlayer.cpp index 7e6c43abd8..937300dd93 100644 --- a/CapabilityAgents/ExternalMediaPlayer/src/ExternalMediaPlayer.cpp +++ b/CapabilityAgents/ExternalMediaPlayer/src/ExternalMediaPlayer.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -110,6 +110,7 @@ static const NamespaceAndName LOGOUT_DIRECTIVE{EXTERNALMEDIAPLAYER_NAMESPACE, "L // The @c Transport control directive signatures. static const NamespaceAndName RESUME_DIRECTIVE{PLAYBACKCONTROLLER_NAMESPACE, "Play"}; static const NamespaceAndName PAUSE_DIRECTIVE{PLAYBACKCONTROLLER_NAMESPACE, "Pause"}; +static const NamespaceAndName STOP_DIRECTIVE{PLAYBACKCONTROLLER_NAMESPACE, "Stop"}; static const NamespaceAndName NEXT_DIRECTIVE{PLAYBACKCONTROLLER_NAMESPACE, "Next"}; static const NamespaceAndName PREVIOUS_DIRECTIVE{PLAYBACKCONTROLLER_NAMESPACE, "Previous"}; static const NamespaceAndName STARTOVER_DIRECTIVE{PLAYBACKCONTROLLER_NAMESPACE, "StartOver"}; @@ -161,6 +162,7 @@ std::unordered_mapgetConfiguration(); auto audioNonBlockingPolicy = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, false); auto neitherNonBlockingPolicy = BlockingPolicy(BlockingPolicy::MEDIUMS_NONE, false); @@ -817,6 +818,7 @@ TEST_F(ExternalMediaPlayerTest, testGetConfiguration) { ASSERT_EQ(configuration[LOGOUT_DIRECTIVE], neitherNonBlockingPolicy); ASSERT_EQ(configuration[RESUME_DIRECTIVE], audioNonBlockingPolicy); ASSERT_EQ(configuration[PAUSE_DIRECTIVE], audioNonBlockingPolicy); + ASSERT_EQ(configuration[STOP_DIRECTIVE], audioNonBlockingPolicy); ASSERT_EQ(configuration[NEXT_DIRECTIVE], audioNonBlockingPolicy); ASSERT_EQ(configuration[PREVIOUS_DIRECTIVE], audioNonBlockingPolicy); ASSERT_EQ(configuration[STARTOVER_DIRECTIVE], audioNonBlockingPolicy); @@ -836,7 +838,7 @@ TEST_F(ExternalMediaPlayerTest, testGetConfiguration) { /** * Test session state information on an ExternalMediaPlayer . */ -TEST_F(ExternalMediaPlayerTest, testCallingProvideSessionState) { +TEST_F(ExternalMediaPlayerTest, test_callingProvideSessionState) { EXPECT_CALL( *(m_mockContextManager.get()), setState(SESSION_STATE, _, StateRefreshPolicy::ALWAYS, PROVIDE_STATE_TOKEN_TEST)) .Times(1) @@ -858,7 +860,7 @@ TEST_F(ExternalMediaPlayerTest, testCallingProvideSessionState) { /** * Test playback state information on an ExternalMediaPlayer. */ -TEST_F(ExternalMediaPlayerTest, testCallingProvidePlaybackState) { +TEST_F(ExternalMediaPlayerTest, test_callingProvidePlaybackState) { EXPECT_CALL( *(m_mockContextManager.get()), setState(PLAYBACK_STATE, _, StateRefreshPolicy::ALWAYS, PROVIDE_STATE_TOKEN_TEST)) @@ -881,7 +883,7 @@ TEST_F(ExternalMediaPlayerTest, testCallingProvidePlaybackState) { /** * Test payload with parse error in ExternalMediaPlayer. This should fail. */ -TEST_F(ExternalMediaPlayerTest, testPlayParserError) { +TEST_F(ExternalMediaPlayerTest, test_playParserError) { auto avsMessageHeader = std::make_shared( PLAY_DIRECTIVE.nameSpace, PLAY_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -898,7 +900,7 @@ TEST_F(ExternalMediaPlayerTest, testPlayParserError) { /** * Test PLAY payload without an adapter in ExternalMediaPlayer. This should fail. */ -TEST_F(ExternalMediaPlayerTest, testPlayNoAdapter) { +TEST_F(ExternalMediaPlayerTest, test_playNoAdapter) { auto avsMessageHeader = std::make_shared( PLAY_DIRECTIVE.nameSpace, PLAY_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -915,7 +917,7 @@ TEST_F(ExternalMediaPlayerTest, testPlayNoAdapter) { /** * Test PLAY payload without play context in ExternalMediaPlayer. This should fail. */ -TEST_F(ExternalMediaPlayerTest, testPlayNoPlayContext) { +TEST_F(ExternalMediaPlayerTest, test_playNoPlayContext) { auto avsMessageHeader = std::make_shared( PLAY_DIRECTIVE.nameSpace, PLAY_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -932,7 +934,7 @@ TEST_F(ExternalMediaPlayerTest, testPlayNoPlayContext) { /** * Test PLAY payload without playerId in ExternalMediaPlayer. This should fail. */ -TEST_F(ExternalMediaPlayerTest, testPlayNoPlayerId) { +TEST_F(ExternalMediaPlayerTest, test_playNoPlayerId) { auto avsMessageHeader = std::make_shared( PLAY_DIRECTIVE.nameSpace, PLAY_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -949,7 +951,7 @@ TEST_F(ExternalMediaPlayerTest, testPlayNoPlayerId) { /** * Test PLAY payload without offsetin ExternalMediaPlayer. This should succeed. */ -TEST_F(ExternalMediaPlayerTest, testPlayNoOffset) { +TEST_F(ExternalMediaPlayerTest, test_playNoOffset) { auto avsMessageHeader = std::make_shared( PLAY_DIRECTIVE.nameSpace, PLAY_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -966,7 +968,7 @@ TEST_F(ExternalMediaPlayerTest, testPlayNoOffset) { /** * Test PLAY payload without index in ExternalMediaPlayer. This should succeed. */ -TEST_F(ExternalMediaPlayerTest, testPlayNoIndex) { +TEST_F(ExternalMediaPlayerTest, test_playNoIndex) { auto avsMessageHeader = std::make_shared( PLAY_DIRECTIVE.nameSpace, PLAY_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -983,7 +985,7 @@ TEST_F(ExternalMediaPlayerTest, testPlayNoIndex) { /** * Test successful logout. */ -TEST_F(ExternalMediaPlayerTest, testLogout) { +TEST_F(ExternalMediaPlayerTest, test_logout) { auto avsMessageHeader = std::make_shared( LOGOUT_DIRECTIVE.nameSpace, LOGOUT_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1000,7 +1002,7 @@ TEST_F(ExternalMediaPlayerTest, testLogout) { /** * Test successful login. */ -TEST_F(ExternalMediaPlayerTest, testLogin) { +TEST_F(ExternalMediaPlayerTest, test_login) { auto avsMessageHeader = std::make_shared( LOGIN_DIRECTIVE.nameSpace, LOGIN_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1021,7 +1023,7 @@ TEST_F(ExternalMediaPlayerTest, testLogin) { /** * Test observers of session state are correctly notified */ -TEST_F(ExternalMediaPlayerTest, testLoginStateChangeObserverIsNotified) { +TEST_F(ExternalMediaPlayerTest, test_loginStateChangeObserverIsNotified) { // add a mock observer auto observer = MockExternalMediaPlayerObserver::getInstance(); m_externalMediaPlayer->addObserver(observer); @@ -1044,7 +1046,7 @@ TEST_F(ExternalMediaPlayerTest, testLoginStateChangeObserverIsNotified) { /** * Test observers of playback state are correctly notified */ -TEST_F(ExternalMediaPlayerTest, testPlaybackStateChangeObserverIsNotified) { +TEST_F(ExternalMediaPlayerTest, test_playbackStateChangeObserverIsNotified) { // add a mock observer auto observer = MockExternalMediaPlayerObserver::getInstance(); m_externalMediaPlayer->addObserver(observer); @@ -1068,7 +1070,7 @@ TEST_F(ExternalMediaPlayerTest, testPlaybackStateChangeObserverIsNotified) { /** * Test that after removal login observers are not called anymore */ -TEST_F(ExternalMediaPlayerTest, testLoginStateChangeObserverRemoval) { +TEST_F(ExternalMediaPlayerTest, test_loginStateChangeObserverRemoval) { // add a mock observer auto observer = MockExternalMediaPlayerObserver::getInstance(); m_externalMediaPlayer->addObserver(observer); @@ -1095,7 +1097,7 @@ TEST_F(ExternalMediaPlayerTest, testLoginStateChangeObserverRemoval) { /** * Test that after removal playback state observers are not called anymore */ -TEST_F(ExternalMediaPlayerTest, testPlaybackStateChangeObserverRemoval) { +TEST_F(ExternalMediaPlayerTest, test_playbackStateChangeObserverRemoval) { // add a mock observer auto observer = MockExternalMediaPlayerObserver::getInstance(); m_externalMediaPlayer->addObserver(observer); @@ -1123,7 +1125,7 @@ TEST_F(ExternalMediaPlayerTest, testPlaybackStateChangeObserverRemoval) { /** * Test successful resume. */ -TEST_F(ExternalMediaPlayerTest, testPlay) { +TEST_F(ExternalMediaPlayerTest, test_play) { auto avsMessageHeader = std::make_shared( RESUME_DIRECTIVE.nameSpace, RESUME_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1140,7 +1142,7 @@ TEST_F(ExternalMediaPlayerTest, testPlay) { /** * Test successful pause. */ -TEST_F(ExternalMediaPlayerTest, testPause) { +TEST_F(ExternalMediaPlayerTest, test_pause) { auto avsMessageHeader = std::make_shared( PAUSE_DIRECTIVE.nameSpace, PAUSE_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1154,10 +1156,27 @@ TEST_F(ExternalMediaPlayerTest, testPause) { m_externalMediaPlayer->CapabilityAgent::handleDirective(MESSAGE_ID_TEST); } +/** + * Test successful stop. + */ +TEST_F(ExternalMediaPlayerTest, test_stop) { + auto avsMessageHeader = std::make_shared( + STOP_DIRECTIVE.nameSpace, STOP_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); + + std::shared_ptr directive = + AVSDirective::create("", avsMessageHeader, createPayloadWithPlayerId(MSP_NAME1), m_attachmentManager, ""); + + EXPECT_CALL(*(MockExternalMediaPlayerAdapter::m_currentActiveMediaPlayerAdapter), handlePlayControl(_)); + EXPECT_CALL(*m_mockDirectiveHandlerResult, setCompleted()); + + m_externalMediaPlayer->CapabilityAgent::preHandleDirective(directive, std::move(m_mockDirectiveHandlerResult)); + m_externalMediaPlayer->CapabilityAgent::handleDirective(MESSAGE_ID_TEST); +} + /** * Test successful next. */ -TEST_F(ExternalMediaPlayerTest, testNext) { +TEST_F(ExternalMediaPlayerTest, test_next) { auto avsMessageHeader = std::make_shared( NEXT_DIRECTIVE.nameSpace, NEXT_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1174,7 +1193,7 @@ TEST_F(ExternalMediaPlayerTest, testNext) { /** * Test successful previous. */ -TEST_F(ExternalMediaPlayerTest, testPrevious) { +TEST_F(ExternalMediaPlayerTest, test_previous) { auto avsMessageHeader = std::make_shared( PREVIOUS_DIRECTIVE.nameSpace, PREVIOUS_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1191,7 +1210,7 @@ TEST_F(ExternalMediaPlayerTest, testPrevious) { /** * Test successful StarOver. */ -TEST_F(ExternalMediaPlayerTest, testStartOver) { +TEST_F(ExternalMediaPlayerTest, test_startOver) { auto avsMessageHeader = std::make_shared( STARTOVER_DIRECTIVE.nameSpace, STARTOVER_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1208,7 +1227,7 @@ TEST_F(ExternalMediaPlayerTest, testStartOver) { /** * Test successful rewind. */ -TEST_F(ExternalMediaPlayerTest, testRewind) { +TEST_F(ExternalMediaPlayerTest, test_rewind) { auto avsMessageHeader = std::make_shared( REWIND_DIRECTIVE.nameSpace, REWIND_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1225,7 +1244,7 @@ TEST_F(ExternalMediaPlayerTest, testRewind) { /** * Test successful fast-forward. */ -TEST_F(ExternalMediaPlayerTest, testFastForward) { +TEST_F(ExternalMediaPlayerTest, test_fastForward) { auto avsMessageHeader = std::make_shared( FASTFORWARD_DIRECTIVE.nameSpace, FASTFORWARD_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1242,7 +1261,7 @@ TEST_F(ExternalMediaPlayerTest, testFastForward) { /** * Test successful EnableRepeatOne. */ -TEST_F(ExternalMediaPlayerTest, testEnableRepeatOne) { +TEST_F(ExternalMediaPlayerTest, test_enableRepeatOne) { auto avsMessageHeader = std::make_shared( ENABLEREPEATONE_DIRECTIVE.nameSpace, ENABLEREPEATONE_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1259,7 +1278,7 @@ TEST_F(ExternalMediaPlayerTest, testEnableRepeatOne) { /** * Test successful EnableRepeat. */ -TEST_F(ExternalMediaPlayerTest, testEnableRepeat) { +TEST_F(ExternalMediaPlayerTest, test_enableRepeat) { auto avsMessageHeader = std::make_shared( ENABLEREPEAT_DIRECTIVE.nameSpace, ENABLEREPEAT_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1276,7 +1295,7 @@ TEST_F(ExternalMediaPlayerTest, testEnableRepeat) { /** * Test successful DisableRepeat. */ -TEST_F(ExternalMediaPlayerTest, testDisableRepeat) { +TEST_F(ExternalMediaPlayerTest, test_disableRepeat) { auto avsMessageHeader = std::make_shared( DISABLEREPEAT_DIRECTIVE.nameSpace, DISABLEREPEAT_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1293,7 +1312,7 @@ TEST_F(ExternalMediaPlayerTest, testDisableRepeat) { /** * Test successful EnableShuffle. */ -TEST_F(ExternalMediaPlayerTest, testEnableShuffle) { +TEST_F(ExternalMediaPlayerTest, test_enableShuffle) { auto avsMessageHeader = std::make_shared( ENABLESHUFFLE_DIRECTIVE.nameSpace, ENABLESHUFFLE_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1310,7 +1329,7 @@ TEST_F(ExternalMediaPlayerTest, testEnableShuffle) { /** * Test successful DisableRepeat. */ -TEST_F(ExternalMediaPlayerTest, testDisableShuffle) { +TEST_F(ExternalMediaPlayerTest, test_disableShuffle) { auto avsMessageHeader = std::make_shared( DISABLESHUFFLE_DIRECTIVE.nameSpace, DISABLESHUFFLE_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1327,7 +1346,7 @@ TEST_F(ExternalMediaPlayerTest, testDisableShuffle) { /** * Test successful Favorite. */ -TEST_F(ExternalMediaPlayerTest, testFavorite) { +TEST_F(ExternalMediaPlayerTest, test_favorite) { auto avsMessageHeader = std::make_shared( FAVORITE_DIRECTIVE.nameSpace, FAVORITE_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1344,7 +1363,7 @@ TEST_F(ExternalMediaPlayerTest, testFavorite) { /** * Test successful UnFavorite. */ -TEST_F(ExternalMediaPlayerTest, testUnfavorite) { +TEST_F(ExternalMediaPlayerTest, test_unfavorite) { auto avsMessageHeader = std::make_shared( UNFAVORITE_DIRECTIVE.nameSpace, UNFAVORITE_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1361,7 +1380,7 @@ TEST_F(ExternalMediaPlayerTest, testUnfavorite) { /** * Test incorrect directive. */ -TEST_F(ExternalMediaPlayerTest, testIncorrectDirective) { +TEST_F(ExternalMediaPlayerTest, test_incorrectDirective) { auto avsMessageHeader = std::make_shared( FAVORITE_DIRECTIVE.nameSpace, PREVIOUS_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1378,7 +1397,7 @@ TEST_F(ExternalMediaPlayerTest, testIncorrectDirective) { /** * Test Seek failure passing incorrect field in payload. */ -TEST_F(ExternalMediaPlayerTest, testSeekFailure) { +TEST_F(ExternalMediaPlayerTest, test_seekFailure) { auto avsMessageHeader = std::make_shared( SEEK_DIRECTIVE.nameSpace, SEEK_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1395,7 +1414,7 @@ TEST_F(ExternalMediaPlayerTest, testSeekFailure) { /** * Test successful Seek. */ -TEST_F(ExternalMediaPlayerTest, testSeekSuccess) { +TEST_F(ExternalMediaPlayerTest, test_seekSuccess) { auto avsMessageHeader = std::make_shared( SEEK_DIRECTIVE.nameSpace, SEEK_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1412,7 +1431,7 @@ TEST_F(ExternalMediaPlayerTest, testSeekSuccess) { /** * Test AdjustSeek failure incorrect field in payload. */ -TEST_F(ExternalMediaPlayerTest, testAdjustSeekFailure) { +TEST_F(ExternalMediaPlayerTest, test_adjustSeekFailure) { auto avsMessageHeader = std::make_shared( ADJUSTSEEK_DIRECTIVE.nameSpace, ADJUSTSEEK_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1429,7 +1448,7 @@ TEST_F(ExternalMediaPlayerTest, testAdjustSeekFailure) { /** * Test AdjustSeek failure passing in an incorrect offset. */ -TEST_F(ExternalMediaPlayerTest, testAdjustSeekFailure2) { +TEST_F(ExternalMediaPlayerTest, test_adjustSeekFailure2) { auto avsMessageHeader = std::make_shared( ADJUSTSEEK_DIRECTIVE.nameSpace, ADJUSTSEEK_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); @@ -1446,7 +1465,7 @@ TEST_F(ExternalMediaPlayerTest, testAdjustSeekFailure2) { /** * Test AdjustSeek successful passing in correct payload and offset. */ -TEST_F(ExternalMediaPlayerTest, testAdjustSeekSuccess) { +TEST_F(ExternalMediaPlayerTest, test_adjustSeekSuccess) { auto avsMessageHeader = std::make_shared( ADJUSTSEEK_DIRECTIVE.nameSpace, ADJUSTSEEK_DIRECTIVE.name, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); diff --git a/CapabilityAgents/InteractionModel/test/InteractionModelCapabilityAgentTest.cpp b/CapabilityAgents/InteractionModel/test/InteractionModelCapabilityAgentTest.cpp index 1ae817226e..23b4f2c5cc 100644 --- a/CapabilityAgents/InteractionModel/test/InteractionModelCapabilityAgentTest.cpp +++ b/CapabilityAgents/InteractionModel/test/InteractionModelCapabilityAgentTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -129,7 +129,7 @@ void InteractionModelCapabilityAgentTest::SetUp() { /** * Test to verify the @c InteractionModelCapabilityAgent can not be created if directiveSequencer param is null. */ -TEST_F(InteractionModelCapabilityAgentTest, createNoDirectiveSequencer) { +TEST_F(InteractionModelCapabilityAgentTest, test_createNoDirectiveSequencer) { m_interactionModelCA = InteractionModelCapabilityAgent::create(nullptr, m_mockExceptionEncounteredSender); ASSERT_EQ(m_interactionModelCA, nullptr); @@ -137,7 +137,7 @@ TEST_F(InteractionModelCapabilityAgentTest, createNoDirectiveSequencer) { /** * Test to verify the @c InteractionModelCapabilityAgent can not be created if exceptionHandler param is null. */ -TEST_F(InteractionModelCapabilityAgentTest, createNoExceptionHanlder) { +TEST_F(InteractionModelCapabilityAgentTest, test_createNoExceptionHanlder) { m_interactionModelCA = InteractionModelCapabilityAgent::create(m_mockDirectiveSequencer, nullptr); ASSERT_EQ(m_interactionModelCA, nullptr); @@ -146,7 +146,7 @@ TEST_F(InteractionModelCapabilityAgentTest, createNoExceptionHanlder) { /** * Test to verify if a valid NewDialogRequest directive will set the dialogRequestID in the directive sequencer. */ -TEST_F(InteractionModelCapabilityAgentTest, processNewDialogRequestID) { +TEST_F(InteractionModelCapabilityAgentTest, test_processNewDialogRequestID) { // Create a dummy AVSDirective. auto directivePair = AVSDirective::create(CORRECT_NEW_DIALOG_REQUEST_DIRECTIVE_JSON_STRING, nullptr, ""); std::shared_ptr directive = std::move(directivePair.first); @@ -158,7 +158,7 @@ TEST_F(InteractionModelCapabilityAgentTest, processNewDialogRequestID) { /** * Test to verify if interface will ignore null directives */ -TEST_F(InteractionModelCapabilityAgentTest, processNullDirective) { +TEST_F(InteractionModelCapabilityAgentTest, test_processNullDirective) { EXPECT_CALL(*m_mockDirectiveSequencer, setDialogRequestId(_)).Times(0); m_interactionModelCA->handleDirectiveImmediately(nullptr); } @@ -166,7 +166,7 @@ TEST_F(InteractionModelCapabilityAgentTest, processNullDirective) { /** * Test to verify if interface will send exceptions when the directive received is invalid */ -TEST_F(InteractionModelCapabilityAgentTest, processInvalidDirective) { +TEST_F(InteractionModelCapabilityAgentTest, test_processInvalidDirective) { std::shared_ptr directive1 = AVSDirective::create(INCORRECT_NEW_DIALOG_REQUEST_DIRECTIVE_JSON_STRING_1, nullptr, "").first; std::shared_ptr directive2 = diff --git a/CapabilityAgents/MRM/test/MRMCapabilityAgentTest.cpp b/CapabilityAgents/MRM/test/MRMCapabilityAgentTest.cpp index d81fc69ebc..68076f94b6 100644 --- a/CapabilityAgents/MRM/test/MRMCapabilityAgentTest.cpp +++ b/CapabilityAgents/MRM/test/MRMCapabilityAgentTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -252,7 +252,7 @@ void MRMCapabilityAgentTest::TearDown() { /** * Test to verify the @c create function of @c MRMCapabilityAgent class. */ -TEST_F(MRMCapabilityAgentTest, createTest) { +TEST_F(MRMCapabilityAgentTest, test_create) { /// A dummy MRMHandler. auto mrmHandler = std::unique_ptr(new MockMRMHandler()); @@ -273,7 +273,7 @@ TEST_F(MRMCapabilityAgentTest, createTest) { /** * Test to verify the @c getConfiguration function of @c MRMCapabilityAgent class. */ -TEST_F(MRMCapabilityAgentTest, getConfigurationTest) { +TEST_F(MRMCapabilityAgentTest, test_getConfiguration) { auto config = m_mrmCA->getConfiguration(); ASSERT_NE(true, config.empty()); } @@ -281,7 +281,7 @@ TEST_F(MRMCapabilityAgentTest, getConfigurationTest) { /** * Test to verify the @c getVersionString function of @c MRMCapabilityAgent class. */ -TEST_F(MRMCapabilityAgentTest, getVersionStringTest) { +TEST_F(MRMCapabilityAgentTest, test_getVersionString) { EXPECT_CALL(*m_mockMRMHandlerPtr, getVersionString()).WillOnce(Return(TEST_MRM_HANDLER_VERSION_STRING)); std::string versionString = m_mrmCA->getVersionString(); ASSERT_NE(true, versionString.empty()); @@ -290,7 +290,7 @@ TEST_F(MRMCapabilityAgentTest, getVersionStringTest) { /** * Test to verify the @c handleDirective function of @c MRMHandler class, invoked by the @c MRMCapabilityAgent class. */ -TEST_F(MRMCapabilityAgentTest, handleMRMDirectiveTest) { +TEST_F(MRMCapabilityAgentTest, test_handleMRMDirective) { // Create a dummy AVSDirective. auto directivePair = AVSDirective::create(TEST_DIRECTIVE_JSON_STRING, nullptr, ""); std::shared_ptr directive = std::move(directivePair.first); @@ -310,7 +310,7 @@ TEST_F(MRMCapabilityAgentTest, handleMRMDirectiveTest) { * Test to verify the @c onSpeakerSettingsChanged function of @c MRMHandler class, invoked by the @c MRMCapabilityAgent * class. */ -TEST_F(MRMCapabilityAgentTest, onSpeakerSettingsChangedTest) { +TEST_F(MRMCapabilityAgentTest, test_onSpeakerSettingsChanged) { SpeakerInterface::SpeakerSettings dummySpeakerSettings; // Test that the AVS_ALERTS_VOLUME option works. @@ -334,7 +334,7 @@ TEST_F(MRMCapabilityAgentTest, onSpeakerSettingsChangedTest) { * Test to verify the @c waitForUserInactivityReport function of @c MRMHandler class, invoked by the * @c MRMCapabilityAgent class. */ -TEST_F(MRMCapabilityAgentTest, onUserInactivityReportTest) { +TEST_F(MRMCapabilityAgentTest, test_onUserInactivityReport) { // Verify that our Inactivity Report is sent by MRMHandler when invoked by the MRM CA. m_mrmCA->onUserInactivityReportSent(); ASSERT_TRUE(m_mockMRMHandlerPtr->waitForUserInactivityReport(WAIT_FOR_INVOCATION_LONG_TIMEOUT)); diff --git a/CapabilityAgents/Notifications/include/Notifications/NotificationRenderer.h b/CapabilityAgents/Notifications/include/Notifications/NotificationRenderer.h index 3bbc808877..5b16cb895e 100644 --- a/CapabilityAgents/Notifications/include/Notifications/NotificationRenderer.h +++ b/CapabilityAgents/Notifications/include/Notifications/NotificationRenderer.h @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ #include #include +#include #include "NotificationRendererInterface.h" @@ -34,6 +35,7 @@ namespace notifications { class NotificationRenderer : public NotificationRendererInterface , public avsCommon::utils::mediaPlayer::MediaPlayerObserverInterface + , public avsCommon::utils::RequiresShutdown , public std::enable_shared_from_this { public: /// A type that identifies which source is currently being operated on. @@ -67,6 +69,11 @@ class NotificationRenderer override; /// @} + /// @name RequiresShutdown methods + /// @{ + void doShutdown() override; + /// @} + private: /** * The different states that a NotificationRenderer may be in. The normal flow of states is: diff --git a/CapabilityAgents/Notifications/src/NotificationRenderer.cpp b/CapabilityAgents/Notifications/src/NotificationRenderer.cpp index 25f913fd0b..140a6d6b81 100644 --- a/CapabilityAgents/Notifications/src/NotificationRenderer.cpp +++ b/CapabilityAgents/Notifications/src/NotificationRenderer.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -64,6 +64,16 @@ std::ostream& operator<<(std::ostream& stream, const NotificationRenderer::State return stream; } +void NotificationRenderer::doShutdown() { + ACSDK_DEBUG5(LX(__func__)); + if (m_mediaPlayer) { + m_mediaPlayer->setObserver(nullptr); + } + + std::lock_guard lock(m_mutex); + m_observers.clear(); +} + std::shared_ptr NotificationRenderer::create(std::shared_ptr mediaPlayer) { ACSDK_DEBUG5(LX("create")); if (!mediaPlayer) { @@ -220,6 +230,7 @@ void NotificationRenderer::onPlaybackError(SourceId sourceId, const ErrorType& t } NotificationRenderer::NotificationRenderer(std::shared_ptr mediaPlayer) : + RequiresShutdown{"NotificationRenderer"}, m_mediaPlayer{mediaPlayer}, m_state{State::IDLE}, m_sourceId{MediaPlayerInterface::ERROR} { diff --git a/CapabilityAgents/Notifications/test/NotificationRendererTest.cpp b/CapabilityAgents/Notifications/test/NotificationRendererTest.cpp index ab0dc8c329..c5ea7b7657 100644 --- a/CapabilityAgents/Notifications/test/NotificationRendererTest.cpp +++ b/CapabilityAgents/Notifications/test/NotificationRendererTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -143,7 +143,7 @@ void NotificationRendererTest::TearDown() { /** * Test that create fails with a null MediaPlayer */ -TEST_F(NotificationRendererTest, testCreateWithNullMediaPlayer) { +TEST_F(NotificationRendererTest, test_createWithNullMediaPlayer) { auto renderer = NotificationRenderer::create(nullptr); ASSERT_FALSE(renderer); } @@ -153,7 +153,7 @@ TEST_F(NotificationRendererTest, testCreateWithNullMediaPlayer) { * methods get called (once each) and that the NotificationRenderer's observer gets called * back to indicate that playback had completed. */ -TEST_F(NotificationRendererTest, testPlayPreferredStream) { +TEST_F(NotificationRendererTest, test_playPreferredStream) { EXPECT_CALL(*(m_player.get()), urlSetSource(_)).Times(1); EXPECT_CALL(*(m_player.get()), streamSetSource(_, _)).Times(0); EXPECT_CALL(*(m_player.get()), play(_)).Times(1); @@ -170,7 +170,7 @@ TEST_F(NotificationRendererTest, testPlayPreferredStream) { * methods get called (once each) and that the NotificationRenderer's observer gets called * back to indicate that playback had completed. */ -TEST_F(NotificationRendererTest, testPlayDefaultStream) { +TEST_F(NotificationRendererTest, test_playDefaultStream) { EXPECT_CALL(*(m_player.get()), urlSetSource(_)).Times(1); EXPECT_CALL(*(m_player.get()), streamSetSource(_, _)).Times(1); EXPECT_CALL(*(m_player.get()), play(_)).Times(2); @@ -193,7 +193,7 @@ TEST_F(NotificationRendererTest, testPlayDefaultStream) { * Exercise making a second @c renderNotification() call while a previous * one is still outstanding. Verify that it is rejected. */ -TEST_F(NotificationRendererTest, testSecondPlayRejected) { +TEST_F(NotificationRendererTest, test_secondPlayRejected) { EXPECT_CALL(*(m_player.get()), urlSetSource(_)).Times(1); EXPECT_CALL(*(m_player.get()), streamSetSource(_, _)).Times(0); EXPECT_CALL(*(m_player.get()), play(_)).Times(1); @@ -210,7 +210,7 @@ TEST_F(NotificationRendererTest, testSecondPlayRejected) { * Exercise rendering the default stream. Verify that a call to @c renderNotification() * while the default stream is playing is rejected. */ -TEST_F(NotificationRendererTest, testSecondPlayWhilePlayingDefaultStream) { +TEST_F(NotificationRendererTest, test_secondPlayWhilePlayingDefaultStream) { EXPECT_CALL(*(m_player.get()), urlSetSource(_)).Times(1); EXPECT_CALL(*(m_player.get()), streamSetSource(_, _)).Times(1); EXPECT_CALL(*(m_player.get()), play(_)).Times(2); @@ -236,7 +236,7 @@ TEST_F(NotificationRendererTest, testSecondPlayWhilePlayingDefaultStream) { /** * Exercise cancelNotificationRendering(). Verify that it causes rendering to complete. */ -TEST_F(NotificationRendererTest, testCancelNotificationRendering) { +TEST_F(NotificationRendererTest, test_cancelNotificationRendering) { EXPECT_CALL(*(m_player.get()), urlSetSource(_)).Times(1); EXPECT_CALL(*(m_player.get()), streamSetSource(_, _)).Times(0); EXPECT_CALL(*(m_player.get()), play(_)).Times(1); @@ -255,7 +255,7 @@ TEST_F(NotificationRendererTest, testCancelNotificationRendering) { * This verifies the use case where onNotificationRenderingFinished() is * used as a trigger to render the next notification. */ -TEST_F(NotificationRendererTest, testRenderNotificationWhileNotifying) { +TEST_F(NotificationRendererTest, test_renderNotificationWhileNotifying) { FuturePromisePair signal; EXPECT_CALL(*(m_player.get()), urlSetSource(_)).Times(2); EXPECT_CALL(*(m_player.get()), streamSetSource(_, _)).Times(0); @@ -283,6 +283,15 @@ TEST_F(NotificationRendererTest, testRenderNotificationWhileNotifying) { m_player->waitUntilPlaybackFinished(); } +/** + * Test that shutdown does the correct cleanup. + */ +TEST_F(NotificationRendererTest, testShutdown) { + m_renderer->shutdown(); + m_renderer.reset(); + ASSERT_THAT(m_player->getObserver(), IsNull()); +} + } // namespace test } // namespace notifications } // namespace capabilityAgents diff --git a/CapabilityAgents/Notifications/test/NotificationsCapabilityAgentTest.cpp b/CapabilityAgents/Notifications/test/NotificationsCapabilityAgentTest.cpp index 40ac28ce18..8a89dcbedf 100644 --- a/CapabilityAgents/Notifications/test/NotificationsCapabilityAgentTest.cpp +++ b/CapabilityAgents/Notifications/test/NotificationsCapabilityAgentTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -657,7 +657,7 @@ const std::string NotificationsCapabilityAgentTest::generatePayload( /** * Test create() with nullptrs */ -TEST_F(NotificationsCapabilityAgentTest, testCreate) { +TEST_F(NotificationsCapabilityAgentTest, test_create) { std::shared_ptr testNotificationsCapabilityAgent; testNotificationsCapabilityAgent = NotificationsCapabilityAgent::create( @@ -705,7 +705,7 @@ TEST_F(NotificationsCapabilityAgentTest, testCreate) { * Test starting up the capability agent with a non-empty queue. * Expect that the next item in the queue will be played. */ -TEST_F(NotificationsCapabilityAgentTest, testNonEmptyStartupQueue) { +TEST_F(NotificationsCapabilityAgentTest, test_nonEmptyStartupQueue) { NotificationIndicator ni(true, true, ASSET_ID1, ASSET_URL1); ASSERT_TRUE(m_notificationsStorage->enqueue(ni)); @@ -720,7 +720,7 @@ TEST_F(NotificationsCapabilityAgentTest, testNonEmptyStartupQueue) { * Expect that the NotificationsObserver is notified of the indicator's state remaining OFF. * Expect no calls to render notifications since playAudioIndicator is false. */ -TEST_F(NotificationsCapabilityAgentTest, testSendSetIndicator) { +TEST_F(NotificationsCapabilityAgentTest, test_sendSetIndicator) { EXPECT_CALL(*(m_renderer.get()), renderNotificationShim(_, _)).Times(0); initializeCapabilityAgent(); ASSERT_TRUE(m_testNotificationsObserver->waitFor(IndicatorState::OFF, WAIT_TIMEOUT)); @@ -737,7 +737,7 @@ TEST_F(NotificationsCapabilityAgentTest, testSendSetIndicator) { * Expect the renderer to start playback of the Notification. * Expect that the NotificationsObserver is notified of the indicator's state being OFF. */ -TEST_F(NotificationsCapabilityAgentTest, testSendSetIndicatorWithAudio) { +TEST_F(NotificationsCapabilityAgentTest, test_sendSetIndicatorWithAudio) { EXPECT_CALL(*(m_renderer.get()), renderNotificationShim(_, ASSET_URL1)); initializeCapabilityAgent(); @@ -751,7 +751,7 @@ TEST_F(NotificationsCapabilityAgentTest, testSendSetIndicatorWithAudio) { * Test a single SetIndicator directive with with persistVisualIndicator set to true. * Expect that the NotificationsObserver is notified of the indicator's state being ON. */ -TEST_F(NotificationsCapabilityAgentTest, testSendSetIndicatorWithVisualIndicator) { +TEST_F(NotificationsCapabilityAgentTest, test_sendSetIndicatorWithVisualIndicator) { EXPECT_CALL(*(m_renderer.get()), renderNotificationShim(_, _)).Times(0); initializeCapabilityAgent(); @@ -763,7 +763,7 @@ TEST_F(NotificationsCapabilityAgentTest, testSendSetIndicatorWithVisualIndicator * Test sending two SetIndicator directives where the second has the same assetId as the first. * Expect that the renderer only gets one call to renderNotification(). */ -TEST_F(NotificationsCapabilityAgentTest, testSameAssetId) { +TEST_F(NotificationsCapabilityAgentTest, test_sameAssetId) { EXPECT_CALL(*(m_renderer.get()), renderNotificationShim(_, ASSET_URL1)) .Times(1) .WillOnce(Invoke([this](std::function()> audioFactory, const std::string& url) { @@ -793,7 +793,7 @@ TEST_F(NotificationsCapabilityAgentTest, testSameAssetId) { /** * Test that the persistVisualIndicator setting is preserved and used across shutdown. */ -TEST_F(NotificationsCapabilityAgentTest, testPersistVisualIndicatorPreserved) { +TEST_F(NotificationsCapabilityAgentTest, test_persistVisualIndicatorPreserved) { initializeCapabilityAgent(); // set IndicatorState to ON @@ -819,7 +819,7 @@ TEST_F(NotificationsCapabilityAgentTest, testPersistVisualIndicatorPreserved) { /** * Test sending a ClearIndicator directive with an empty queue, expecting nothing to happen. */ -TEST_F(NotificationsCapabilityAgentTest, testClearIndicatorWithEmptyQueue) { +TEST_F(NotificationsCapabilityAgentTest, test_clearIndicatorWithEmptyQueue) { initializeCapabilityAgent(); sendClearIndicatorDirective(MESSAGE_ID_TEST); ASSERT_TRUE(m_testNotificationsObserver->waitFor(IndicatorState::OFF, WAIT_TIMEOUT)); @@ -829,7 +829,7 @@ TEST_F(NotificationsCapabilityAgentTest, testClearIndicatorWithEmptyQueue) { * Test sending a ClearIndicator directive with an empty queue and the indicator state set to ON. * Expect that the indicator is set to OFF. */ -TEST_F(NotificationsCapabilityAgentTest, testClearIndicatorWithEmptyQueueAndIndicatorOn) { +TEST_F(NotificationsCapabilityAgentTest, test_clearIndicatorWithEmptyQueueAndIndicatorOn) { EXPECT_CALL(*(m_renderer.get()), renderNotificationShim(_, ASSET_URL1)).Times(1); initializeCapabilityAgent(); @@ -848,7 +848,7 @@ TEST_F(NotificationsCapabilityAgentTest, testClearIndicatorWithEmptyQueueAndIndi * Test sending a ClearIndicator directive after multiple SetIndicator directives. * Expect that the indicator is set to OFF. */ -TEST_F(NotificationsCapabilityAgentTest, testClearIndicatorAfterMultipleSetIndicators) { +TEST_F(NotificationsCapabilityAgentTest, testSlow_clearIndicatorAfterMultipleSetIndicators) { EXPECT_CALL(*(m_renderer.get()), renderNotificationShim(_, ASSET_URL1)).Times(1); EXPECT_CALL(*(m_renderer.get()), cancelNotificationRenderingShim()).Times(1); initializeCapabilityAgent(); @@ -870,7 +870,7 @@ TEST_F(NotificationsCapabilityAgentTest, testClearIndicatorAfterMultipleSetIndic * Test sending multiple SetIndicators and letting them all render. * Expect multiple calls to renderNotification(). */ -TEST_F(NotificationsCapabilityAgentTest, testMultipleSetIndicators) { +TEST_F(NotificationsCapabilityAgentTest, test_multipleSetIndicators) { EXPECT_CALL(*(m_renderer.get()), renderNotificationShim(_, ASSET_URL1)).Times(3); initializeCapabilityAgent(); @@ -891,7 +891,7 @@ TEST_F(NotificationsCapabilityAgentTest, testMultipleSetIndicators) { /** * Test that @c clearData() removes all notifications and sets the indicator to OFF. */ -TEST_F(NotificationsCapabilityAgentTest, testClearData) { +TEST_F(NotificationsCapabilityAgentTest, test_clearData) { initializeCapabilityAgent(); sendSetIndicatorDirective(generatePayload(true, true, "assetId1"), "firstIndicatorMessageId"); ASSERT_TRUE(m_renderer->waitUntilRenderingStarted()); @@ -926,4 +926,4 @@ int main(int argc, char** argv) { ::testing::GTEST_FLAG(filter) = "-NotificationsCapabilityAgentTest.testSameAssetId"; #endif return RUN_ALL_TESTS(); -} \ No newline at end of file +} diff --git a/CapabilityAgents/Notifications/test/NotificationsStorageTest.cpp b/CapabilityAgents/Notifications/test/NotificationsStorageTest.cpp index 9b89b8662a..7710038a4b 100644 --- a/CapabilityAgents/Notifications/test/NotificationsStorageTest.cpp +++ b/CapabilityAgents/Notifications/test/NotificationsStorageTest.cpp @@ -131,14 +131,14 @@ void NotificationsStorageTest::checkNotificationIndicatorsEquality( /** * Test basic construction. Database should not be open. */ -TEST_F(NotificationsStorageTest, testConstructionAndDestruction) { +TEST_F(NotificationsStorageTest, test_constructionAndDestruction) { ASSERT_FALSE(isOpen(m_storage)); } /** * Test database creation. */ -TEST_F(NotificationsStorageTest, testDatabaseCreation) { +TEST_F(NotificationsStorageTest, test_databaseCreation) { ASSERT_FALSE(isOpen(m_storage)); createDatabase(); ASSERT_TRUE(isOpen(m_storage)); @@ -147,7 +147,7 @@ TEST_F(NotificationsStorageTest, testDatabaseCreation) { /** * Test opening and closing a database. */ -TEST_F(NotificationsStorageTest, testOpenAndCloseDatabase) { +TEST_F(NotificationsStorageTest, test_openAndCloseDatabase) { ASSERT_FALSE(isOpen(m_storage)); createDatabase(); ASSERT_TRUE(isOpen(m_storage)); @@ -162,7 +162,7 @@ TEST_F(NotificationsStorageTest, testOpenAndCloseDatabase) { /** * Test enqueueing and dequeueing records in the database. */ -TEST_F(NotificationsStorageTest, testDatabaseEnqueueAndDequeue) { +TEST_F(NotificationsStorageTest, test_databaseEnqueueAndDequeue) { NotificationIndicator firstIndicator(true, false, TEST_ASSET_ID1, TEST_ASSET_URL1); NotificationIndicator secondIndicator(false, true, TEST_ASSET_ID2, TEST_ASSET_URL2); @@ -196,7 +196,7 @@ TEST_F(NotificationsStorageTest, testDatabaseEnqueueAndDequeue) { /** * Test setting and getting the IndicatorState */ -TEST_F(NotificationsStorageTest, testSettingAndGettingIndicatorState) { +TEST_F(NotificationsStorageTest, test_settingAndGettingIndicatorState) { IndicatorState state; // should fail to set/get if database is not open for business @@ -220,7 +220,7 @@ TEST_F(NotificationsStorageTest, testSettingAndGettingIndicatorState) { /** * Test just clearing the notification indicators table. */ -TEST_F(NotificationsStorageTest, testClearingNotificationIndicators) { +TEST_F(NotificationsStorageTest, test_clearingNotificationIndicators) { createDatabase(); ASSERT_TRUE(isOpen(m_storage)); @@ -238,7 +238,7 @@ TEST_F(NotificationsStorageTest, testClearingNotificationIndicators) { * Test that empty database (due to a corruption or crash) results in default indicator state being used * (non-undefined). */ -TEST_F(NotificationsStorageTest, testDefaultValueForEmptyStorage) { +TEST_F(NotificationsStorageTest, test_defaultValueForEmptyStorage) { createDatabase(); ASSERT_TRUE(isOpen(m_storage)); @@ -256,7 +256,7 @@ TEST_F(NotificationsStorageTest, testDefaultValueForEmptyStorage) { * Test that invalid database value (due to a corruption or crash) results in default indicator state being used * (non-undefined). */ -TEST_F(NotificationsStorageTest, testDefaultValueForInvalidDBContents) { +TEST_F(NotificationsStorageTest, test_defaultValueForInvalidDBContents) { createDatabase(); ASSERT_TRUE(isOpen(m_storage)); @@ -288,7 +288,7 @@ TEST_F(NotificationsStorageTest, testDefaultValueForInvalidDBContents) { /** * Test checking for an empty queue. */ -TEST_F(NotificationsStorageTest, testCheckingEmptyQueue) { +TEST_F(NotificationsStorageTest, test_checkingEmptyQueue) { createDatabase(); ASSERT_TRUE(isOpen(m_storage)); @@ -324,7 +324,7 @@ TEST_F(NotificationsStorageTest, testCheckingEmptyQueue) { /** * Test persistence across closing and reopening database. */ -TEST_F(NotificationsStorageTest, testDatabasePersistence) { +TEST_F(NotificationsStorageTest, test_databasePersistence) { createDatabase(); ASSERT_TRUE(isOpen(m_storage)); @@ -363,7 +363,7 @@ TEST_F(NotificationsStorageTest, testDatabasePersistence) { /** * Test that ordering is maintained with multiple queueing/dequeueing. */ -TEST_F(NotificationsStorageTest, testQueueOrder) { +TEST_F(NotificationsStorageTest, test_queueOrder) { createDatabase(); ASSERT_TRUE(isOpen(m_storage)); @@ -401,7 +401,7 @@ TEST_F(NotificationsStorageTest, testQueueOrder) { /** * Test that peek() functionality works. */ -TEST_F(NotificationsStorageTest, testPeek) { +TEST_F(NotificationsStorageTest, test_peek) { createDatabase(); ASSERT_TRUE(isOpen(m_storage)); @@ -428,7 +428,7 @@ TEST_F(NotificationsStorageTest, testPeek) { * Test that queueSize() works correctly. */ -TEST_F(NotificationsStorageTest, testSize) { +TEST_F(NotificationsStorageTest, test_size) { createDatabase(); ASSERT_TRUE(isOpen(m_storage)); diff --git a/CapabilityAgents/PlaybackController/test/PlaybackControllerTest.cpp b/CapabilityAgents/PlaybackController/test/PlaybackControllerTest.cpp index 93419a23a2..02e0d4f048 100644 --- a/CapabilityAgents/PlaybackController/test/PlaybackControllerTest.cpp +++ b/CapabilityAgents/PlaybackController/test/PlaybackControllerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -332,14 +332,14 @@ void PlaybackControllerTest::checkMessageRequestAndReleaseTrigger( /** * This case tests if @c StateSynchronizer basic create function works properly */ -TEST_F(PlaybackControllerTest, createSuccessfully) { +TEST_F(PlaybackControllerTest, test_createSuccessfully) { ASSERT_NE(nullptr, PlaybackController::create(m_mockContextManager, m_mockMessageSender)); } /** * This case tests if possible @c nullptr parameters passed to @c StateSynchronizer::create are handled properly. */ -TEST_F(PlaybackControllerTest, createWithError) { +TEST_F(PlaybackControllerTest, test_createWithError) { ASSERT_EQ(nullptr, PlaybackController::create(m_mockContextManager, nullptr)); ASSERT_EQ(nullptr, PlaybackController::create(nullptr, m_mockMessageSender)); ASSERT_EQ(nullptr, PlaybackController::create(nullptr, nullptr)); @@ -348,7 +348,7 @@ TEST_F(PlaybackControllerTest, createWithError) { /** * This case tests if buttonPressed will send the correct PlaybackButton::PLAY event message. */ -TEST_F(PlaybackControllerTest, playButtonPressed) { +TEST_F(PlaybackControllerTest, test_playButtonPressed) { PlaybackControllerTest::verifyButtonPressed( [this]() { m_playbackController->onButtonPressed(PlaybackButton::PLAY); }, PLAYBACK_PLAY_NAME); } @@ -356,7 +356,7 @@ TEST_F(PlaybackControllerTest, playButtonPressed) { /** * This case tests if buttonPressed will send the correct PlaybackButton::PAUSE event message. */ -TEST_F(PlaybackControllerTest, pauseButtonPressed) { +TEST_F(PlaybackControllerTest, test_pauseButtonPressed) { ASSERT_NE(nullptr, m_playbackController); PlaybackControllerTest::verifyButtonPressed( @@ -366,7 +366,7 @@ TEST_F(PlaybackControllerTest, pauseButtonPressed) { /** * This case tests if buttonPressed will send the correct PlaybackButton::NEXT event message. */ -TEST_F(PlaybackControllerTest, nextButtonPressed) { +TEST_F(PlaybackControllerTest, test_nextButtonPressed) { PlaybackControllerTest::verifyButtonPressed( [this]() { m_playbackController->onButtonPressed(PlaybackButton::NEXT); }, PLAYBACK_NEXT_NAME); } @@ -374,7 +374,7 @@ TEST_F(PlaybackControllerTest, nextButtonPressed) { /** * This case tests if buttonPressed will send the correct PlaybackButton::PREVIOUS event message. */ -TEST_F(PlaybackControllerTest, previousButtonPressed) { +TEST_F(PlaybackControllerTest, test_previousButtonPressed) { PlaybackControllerTest::verifyButtonPressed( [this]() { m_playbackController->onButtonPressed(PlaybackButton::PREVIOUS); }, PLAYBACK_PREVIOUS_NAME); } @@ -382,7 +382,7 @@ TEST_F(PlaybackControllerTest, previousButtonPressed) { /** * This case tests if buttonPressed will send the correct PlaybackButton::SKIP_FORWARD event message. */ -TEST_F(PlaybackControllerTest, skipForwardButtonPressed) { +TEST_F(PlaybackControllerTest, test_skipForwardButtonPressed) { PlaybackControllerTest::verifyButtonPressed( [this]() { m_playbackController->onButtonPressed(PlaybackButton::SKIP_FORWARD); }, PLAYBACK_BUTTON_NAME, @@ -392,7 +392,7 @@ TEST_F(PlaybackControllerTest, skipForwardButtonPressed) { /** * This case tests if buttonPressed will send the correct PlaybackButton::SKIP_BACKWARD event message. */ -TEST_F(PlaybackControllerTest, skipBackwardButtonPressed) { +TEST_F(PlaybackControllerTest, test_skipBackwardButtonPressed) { PlaybackControllerTest::verifyButtonPressed( [this]() { m_playbackController->onButtonPressed(PlaybackButton::SKIP_BACKWARD); }, PLAYBACK_BUTTON_NAME, @@ -402,7 +402,7 @@ TEST_F(PlaybackControllerTest, skipBackwardButtonPressed) { /** * This case tests if togglePressed will send the correct PlaybackToggle::SHUFFLE event message. */ -TEST_F(PlaybackControllerTest, shuffleTogglePressed) { +TEST_F(PlaybackControllerTest, test_shuffleTogglePressed) { PlaybackControllerTest::verifyTogglePressed( [this]() { m_playbackController->onTogglePressed(PlaybackToggle::SHUFFLE, true); }, PLAYBACK_TOGGLE_NAME, @@ -418,7 +418,7 @@ TEST_F(PlaybackControllerTest, shuffleTogglePressed) { /** * This case tests if togglePressed will send the correct PlaybackToggle::LOOP event message. */ -TEST_F(PlaybackControllerTest, loopTogglePressed) { +TEST_F(PlaybackControllerTest, test_loopTogglePressed) { PlaybackControllerTest::verifyTogglePressed( [this]() { m_playbackController->onTogglePressed(PlaybackToggle::LOOP, true); }, PLAYBACK_TOGGLE_NAME, @@ -434,7 +434,7 @@ TEST_F(PlaybackControllerTest, loopTogglePressed) { /** * This case tests if togglePressed will send the correct PlaybackToggle::REPEAT event message. */ -TEST_F(PlaybackControllerTest, repeatTogglePressed) { +TEST_F(PlaybackControllerTest, test_repeatTogglePressed) { PlaybackControllerTest::verifyTogglePressed( [this]() { m_playbackController->onTogglePressed(PlaybackToggle::REPEAT, true); }, PLAYBACK_TOGGLE_NAME, @@ -450,7 +450,7 @@ TEST_F(PlaybackControllerTest, repeatTogglePressed) { /** * This case tests if togglePressed will send the correct PlaybackToggle::THUMBS_UP event message. */ -TEST_F(PlaybackControllerTest, thumbsUpTogglePressed) { +TEST_F(PlaybackControllerTest, test_thumbsUpTogglePressed) { PlaybackControllerTest::verifyTogglePressed( [this]() { m_playbackController->onTogglePressed(PlaybackToggle::THUMBS_UP, true); }, PLAYBACK_TOGGLE_NAME, @@ -466,7 +466,7 @@ TEST_F(PlaybackControllerTest, thumbsUpTogglePressed) { /** * This case tests if togglePressed will send the correct PlaybackToggle::THUMBS_DOWN event message. */ -TEST_F(PlaybackControllerTest, thumbsDownTogglePressed) { +TEST_F(PlaybackControllerTest, test_thumbsDownTogglePressed) { PlaybackControllerTest::verifyTogglePressed( [this]() { m_playbackController->onTogglePressed(PlaybackToggle::THUMBS_DOWN, true); }, PLAYBACK_TOGGLE_NAME, @@ -483,7 +483,7 @@ TEST_F(PlaybackControllerTest, thumbsDownTogglePressed) { * This case tests if getContext() returns failure, the button on the top of the queue will be dropped and getContext * will be called for the next button on the queue. */ -TEST_F(PlaybackControllerTest, getContextFailure) { +TEST_F(PlaybackControllerTest, test_getContextFailure) { std::unique_lock exitLock(m_mutex); EXPECT_CALL(*m_mockContextManager, getContext(_)) @@ -520,7 +520,7 @@ TEST_F(PlaybackControllerTest, getContextFailure) { * This case tests if sendMessage() returns failure, an error log should be logged with the button pressed and reason * for failure. */ -TEST_F(PlaybackControllerTest, sendMessageFailure) { +TEST_F(PlaybackControllerTest, test_sendMessageFailure) { std::unique_lock exitLock(m_mutex); m_messageStatus = avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::INTERNAL_ERROR; @@ -543,7 +543,7 @@ TEST_F(PlaybackControllerTest, sendMessageFailure) { * This case tests if exceptionReceived() is received, an error log should be logged with with the exception * description. */ -TEST_F(PlaybackControllerTest, sendMessageException) { +TEST_F(PlaybackControllerTest, test_sendMessageException) { std::unique_lock exitLock(m_mutex); m_messageStatus = avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::INTERNAL_ERROR; diff --git a/CapabilityAgents/PlaybackController/test/PlaybackRouterTest.cpp b/CapabilityAgents/PlaybackController/test/PlaybackRouterTest.cpp index 23ad232348..a1ab59382b 100644 --- a/CapabilityAgents/PlaybackController/test/PlaybackRouterTest.cpp +++ b/CapabilityAgents/PlaybackController/test/PlaybackRouterTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ void PlaybackRouterTest::TearDown() { /** * Test default handler is called. */ -TEST_F(PlaybackRouterTest, defaultHandler) { +TEST_F(PlaybackRouterTest, test_defaultHandler) { EXPECT_CALL(*m_defaultPlaybackHandler, onButtonPressed(PlaybackButton::PLAY)); m_playbackRouter->buttonPressed(PlaybackButton::PLAY); @@ -91,7 +91,7 @@ TEST_F(PlaybackRouterTest, defaultHandler) { /** * Test 2nd handler is called after registration. */ -TEST_F(PlaybackRouterTest, secondHandler) { +TEST_F(PlaybackRouterTest, test_secondHandler) { m_playbackRouter->setHandler(m_defaultPlaybackHandler); EXPECT_CALL(*m_defaultPlaybackHandler, onButtonPressed(PlaybackButton::PLAY)); m_playbackRouter->buttonPressed(PlaybackButton::PLAY); @@ -138,7 +138,7 @@ TEST_F(PlaybackRouterTest, secondHandler) { /** * Test default handler is called again after @c switchToDefaultHandler has been called. */ -TEST_F(PlaybackRouterTest, switchToDefaultHandler) { +TEST_F(PlaybackRouterTest, test_switchToDefaultHandler) { EXPECT_CALL(*m_defaultPlaybackHandler, onButtonPressed(PlaybackButton::PLAY)); m_playbackRouter->buttonPressed(PlaybackButton::PLAY); diff --git a/CapabilityAgents/Settings/test/SettingsTest.cpp b/CapabilityAgents/Settings/test/SettingsTest.cpp index 57c4d5cd76..91e821b682 100644 --- a/CapabilityAgents/Settings/test/SettingsTest.cpp +++ b/CapabilityAgents/Settings/test/SettingsTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -345,7 +345,7 @@ bool SettingsTest::testChangeSettingSucceeds(const std::string& key, const std:: /** * Test to verify the @c create function of @c Settings class. */ -TEST_F(SettingsTest, createTest) { +TEST_F(SettingsTest, test_create) { ASSERT_EQ( nullptr, m_settingsObject->create( @@ -358,7 +358,7 @@ TEST_F(SettingsTest, createTest) { * Test to verify if by adding a global observer and changing the setting, * the global observer is notified of the change. It also verifies that event is being sent in correct JSON format. */ -TEST_F(SettingsTest, addGlobalSettingsObserverTest) { +TEST_F(SettingsTest, test_addGlobalSettingsObserver) { std::shared_ptr mockGlobalSettingObserver; mockGlobalSettingObserver = std::make_shared(); m_settingsObject->addGlobalSettingsObserver(mockGlobalSettingObserver); @@ -370,7 +370,7 @@ TEST_F(SettingsTest, addGlobalSettingsObserverTest) { * Test to verify if by removing a global observer and changing the setting, * the global observer is not notified of the change. It also verifies that event is being sent in correct JSON format. */ -TEST_F(SettingsTest, removeGlobalSettingsObserverTest) { +TEST_F(SettingsTest, test_removeGlobalSettingsObserver) { std::shared_ptr mockGlobalSettingObserver; mockGlobalSettingObserver = std::make_shared(); m_settingsObject->removeGlobalSettingsObserver(mockGlobalSettingObserver); @@ -383,7 +383,7 @@ TEST_F(SettingsTest, removeGlobalSettingsObserverTest) { * i.e. it doesn't exist in the list of @c SETTINGS_ACCEPTED_KEYS, the observer corresponding to it * will not be added. */ -TEST_F(SettingsTest, addSingleSettingObserverWithInvalidKeyTest) { +TEST_F(SettingsTest, testSlow_addSingleSettingObserverWithInvalidKeyTest) { std::shared_ptr wakewordObserver; wakewordObserver = std::make_shared(); m_settingsObject->addSingleSettingObserver("wakeword", wakewordObserver); @@ -401,7 +401,7 @@ TEST_F(SettingsTest, addSingleSettingObserverWithInvalidKeyTest) { * an invalid key even if it is a typo, the observer will not be removed. * It also verifies that event is being sent in correct JSON format. */ -TEST_F(SettingsTest, removeSingleSettingObserverWithInvalidKeyTest) { +TEST_F(SettingsTest, test_removeSingleSettingObserverWithInvalidKey) { std::shared_ptr localeObserver; localeObserver = std::make_shared(); m_settingsObject->addSingleSettingObserver("locale", localeObserver); @@ -414,7 +414,7 @@ TEST_F(SettingsTest, removeSingleSettingObserverWithInvalidKeyTest) { * Test verifies that if an observer is removed with a valid key, the observer gets removed * and is not notified when the setting changes. It also verifies that event is being sent in correct JSON format. */ -TEST_F(SettingsTest, removeSingleSettingObserverWithCorrectKeyTest) { +TEST_F(SettingsTest, test_removeSingleSettingObserverWithCorrectKey) { std::shared_ptr localeObserver; localeObserver = std::make_shared(); m_settingsObject->addSingleSettingObserver("locale", localeObserver); @@ -426,7 +426,7 @@ TEST_F(SettingsTest, removeSingleSettingObserverWithCorrectKeyTest) { /** * Test to check if the settings loaded from the database are same as the default settings. */ -TEST_F(SettingsTest, defaultSettingsCorrect) { +TEST_F(SettingsTest, test_defaultSettingsCorrect) { std::string DEFAULT_SETTINGS = "defaultAVSClientSettings"; std::string settings_json = ""; retrieveValue(SETTINGS_CONFIG_JSON, MESSAGE_SETTINGS_KEY, &settings_json); @@ -446,7 +446,7 @@ TEST_F(SettingsTest, defaultSettingsCorrect) { /** * Test to check that @c clearData() removes any setting stored in the database. */ -TEST_F(SettingsTest, clearDataTest) { +TEST_F(SettingsTest, test_clearData) { ASSERT_TRUE(testChangeSettingSucceeds("locale", "en-CA")); m_settingsObject->clearData(); @@ -458,7 +458,7 @@ TEST_F(SettingsTest, clearDataTest) { /** * Test to check clear database works as expected. */ -TEST_F(SettingsTest, clearDatabaseTest) { +TEST_F(SettingsTest, test_clearDatabase) { std::unordered_map tempMap; ASSERT_TRUE(m_storage->clearDatabase()); ASSERT_TRUE(m_storage->load(&tempMap)); @@ -468,7 +468,7 @@ TEST_F(SettingsTest, clearDatabaseTest) { /** * Test to check the store function of SQLiteSettingStorage class. */ -TEST_F(SettingsTest, storeDatabaseTest) { +TEST_F(SettingsTest, test_storeDatabase) { ASSERT_TRUE(m_storage->clearDatabase()); std::map MapToStore = {{"wakeword", "Alexa"}, {"locale", "en-US"}}; for (auto& it : MapToStore) { @@ -483,7 +483,7 @@ TEST_F(SettingsTest, storeDatabaseTest) { /** * Test to check the modify function of SQLiteSettingStorage class. */ -TEST_F(SettingsTest, modifyDatabaseTest) { +TEST_F(SettingsTest, test_modifyDatabase) { ASSERT_TRUE(m_storage->modify("locale", "en-US")); ASSERT_FALSE(m_storage->modify("local", "en-GB")); ASSERT_TRUE(m_storage->clearDatabase()); @@ -492,7 +492,7 @@ TEST_F(SettingsTest, modifyDatabaseTest) { /** * Test to check the erase function of SQLiteSettingStorage class. */ -TEST_F(SettingsTest, eraseTest) { +TEST_F(SettingsTest, test_erase) { ASSERT_TRUE(m_storage->erase("locale")); ASSERT_FALSE(m_storage->settingExists("locale")); ASSERT_FALSE(m_storage->erase("local")); @@ -501,7 +501,7 @@ TEST_F(SettingsTest, eraseTest) { /** * Test to check the createDatabase function of SQLiteSettingStorage class. */ -TEST_F(SettingsTest, createDatabaseTest) { +TEST_F(SettingsTest, test_createDatabase) { m_storage->close(); ASSERT_FALSE(m_storage->createDatabase()); } @@ -509,7 +509,7 @@ TEST_F(SettingsTest, createDatabaseTest) { /** * Test to check the open and close functions of SQLiteSettingStorage class. */ -TEST_F(SettingsTest, openAndCloseDatabaseTest) { +TEST_F(SettingsTest, test_openAndCloseDatabase) { ASSERT_FALSE(m_storage->open()); ASSERT_TRUE(isOpen(m_storage)); m_storage->close(); diff --git a/CapabilityAgents/SpeakerManager/include/SpeakerManager/SpeakerManager.h b/CapabilityAgents/SpeakerManager/include/SpeakerManager/SpeakerManager.h index 96875aac5d..e070e53a02 100644 --- a/CapabilityAgents/SpeakerManager/include/SpeakerManager/SpeakerManager.h +++ b/CapabilityAgents/SpeakerManager/include/SpeakerManager/SpeakerManager.h @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -128,14 +128,16 @@ class SpeakerManager * @param speakers The @c Speakers to register. * @param contextManager A @c ContextManagerInterface to manage the context. * @param messageSender A @c MessageSenderInterface to send messages to AVS. - * @param exceptionEncounteredSender An @c ExceptionEncounteredSenderInterface to send + * @param exceptionEncounteredSender An @c ExceptionEncounteredSenderInterface to send. + * @param minUnmuteVolume The volume level to increase to when unmuting. * directive processing exceptions to AVS. */ SpeakerManager( const std::vector>& speakerInterfaces, std::shared_ptr contextManager, std::shared_ptr messageSender, - std::shared_ptr exceptionEncounteredSender); + std::shared_ptr exceptionEncounteredSender, + const int minUnmuteVolume); /** * Parses the payload from a string into a rapidjson document. @@ -173,7 +175,7 @@ class SpeakerManager avsCommon::avs::ExceptionErrorType type); /** - * Internal function to update the state of the ContextManager. + * Function to update the state of the ContextManager. * * @param type The Speaker Type that is being updated. * @param settings The SpeakerSettings to update the ContextManager with. @@ -194,7 +196,7 @@ class SpeakerManager avsCommon::sdkInterfaces::SpeakerInterface::SpeakerSettings settings); /** - * Internal function to set the volume for a specific @c Type. This runs on a worker thread. + * Function to set the volume for a specific @c Type. This runs on a worker thread. * Upon success, a VolumeChanged event will be sent to AVS. * * @param type The type of speaker to modify volume for. @@ -210,7 +212,19 @@ class SpeakerManager bool forceNoNotifications = false); /** - * Internal function to adjust the volume for a specific @c Type. This runs on a worker thread. + * Function to restore the volume from a mute state. This runs on a worker thread and will not send an event or + * notify an observer. Upon success, a VolumeChanged event will be sent to AVS. + * + * @param type The type of speaker to modify volume for. + * @param source Whether the call is from AVS or locally. + * @return A bool indicating success. + */ + bool executeRestoreVolume( + avsCommon::sdkInterfaces::SpeakerInterface::Type type, + avsCommon::sdkInterfaces::SpeakerManagerObserverInterface::Source source); + + /** + * Function to adjust the volume for a specific @c Type. This runs on a worker thread. * Upon success, a VolumeChanged event will be sent to AVS. * * @param type The type of speaker to modify volume for. @@ -226,7 +240,7 @@ class SpeakerManager bool forceNoNotifications = false); /** - * Internal function to set the mute for a specific @c Type. This runs on a worker thread. + * Function to set the mute for a specific @c Type. This runs on a worker thread. * Upon success, a MuteChanged event will be sent to AVS. * * @param type The type of speaker to modify mute for. @@ -242,7 +256,7 @@ class SpeakerManager bool forceNoNotifications = false); /** - * Internal function to get the speaker settings for a specific @c Type. + * Function to get the speaker settings for a specific @c Type. * This runs on a worker thread. * * @param type The type of speaker to modify mute for. @@ -254,7 +268,7 @@ class SpeakerManager avsCommon::sdkInterfaces::SpeakerInterface::SpeakerSettings* settings); /** - * Internal function to send events and notify observers when settings have changed. + * Function to send events and notify observers when settings have changed. * This runs on a worker thread. * * @param settings The new settings. @@ -269,7 +283,7 @@ class SpeakerManager const avsCommon::sdkInterfaces::SpeakerInterface::Type& type); /** - * Internal function to notify the observer when a @c SpeakerSettings change has occurred. + * Function to notify the observer when a @c SpeakerSettings change has occurred. * * @param source. This indicates the origin of the call. * @param type. This indicates the type of speaker that was modified. @@ -297,6 +311,9 @@ class SpeakerManager /// The @c MessageSenderInterface used to send event messages. std::shared_ptr m_messageSender; + /// the @c volume to restore to when unmuting at 0 volume + const int m_minUnmuteVolume; + /// A multimap contain speakers keyed by @c Type. std::multimap< avsCommon::sdkInterfaces::SpeakerInterface::Type, @@ -317,4 +334,4 @@ class SpeakerManager } // namespace capabilityAgents } // namespace alexaClientSDK -#endif // ALEXA_CLIENT_SDK_CAPABILITYAGENTS_SPEAKERMANAGER_INCLUDE_SPEAKERMANAGER_SPEAKERMANAGER_H_ +#endif // ALEXA_CLIENT_SDK_CAPABILITYAGENTS_SPEAKERMANAGER_INCLUDE_SPEAKERMANAGER_SPEAKERMANAGER_H_ \ No newline at end of file diff --git a/CapabilityAgents/SpeakerManager/src/SpeakerManager.cpp b/CapabilityAgents/SpeakerManager/src/SpeakerManager.cpp index f72f49ef7e..ca1efda9cf 100644 --- a/CapabilityAgents/SpeakerManager/src/SpeakerManager.cpp +++ b/CapabilityAgents/SpeakerManager/src/SpeakerManager.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -34,6 +34,7 @@ using namespace avsCommon::avs; using namespace avsCommon::avs::speakerConstants; using namespace avsCommon::sdkInterfaces; using namespace avsCommon::utils::json; +using namespace avsCommon::utils::configuration; using namespace rapidjson; /// Speaker capability constants @@ -46,6 +47,10 @@ static const std::string SPEAKER_CAPABILITY_INTERFACE_VERSION = "1.0"; /// String to identify log entries originating from this file. static const std::string TAG{"SpeakerManager"}; +/// The key in our config file to find the root of speaker manager configuration. +static const std::string SPEAKERMANAGER_CONFIGURATION_ROOT_KEY = "speakerManagerCapabilityAgent"; +/// The key in our config file to find the minUnmuteVolume value. +static const std::string SPEAKERMANAGER_MIN_UNMUTE_VOLUME_KEY = "minUnmuteVolume"; /** * Create a LogEntry using this file's TAG and the specified event string. @@ -93,8 +98,14 @@ std::shared_ptr SpeakerManager::create( return nullptr; } + int minUnmuteVolume = MIN_UNMUTE_VOLUME; + + auto configurationRoot = ConfigurationNode::getRoot()[SPEAKERMANAGER_CONFIGURATION_ROOT_KEY]; + // If key is present, then read and initilize the value from config or set to default. + configurationRoot.getInt(SPEAKERMANAGER_MIN_UNMUTE_VOLUME_KEY, &minUnmuteVolume, MIN_UNMUTE_VOLUME); + auto speakerManager = std::shared_ptr( - new SpeakerManager(speakers, contextManager, messageSender, exceptionEncounteredSender)); + new SpeakerManager(speakers, contextManager, messageSender, exceptionEncounteredSender, minUnmuteVolume)); return speakerManager; } @@ -103,11 +114,13 @@ SpeakerManager::SpeakerManager( const std::vector>& speakers, std::shared_ptr contextManager, std::shared_ptr messageSender, - std::shared_ptr exceptionEncounteredSender) : + std::shared_ptr exceptionEncounteredSender, + const int minUnmuteVolume) : CapabilityAgent{NAMESPACE, exceptionEncounteredSender}, RequiresShutdown{"SpeakerManager"}, m_contextManager{contextManager}, - m_messageSender{messageSender} { + m_messageSender{messageSender}, + m_minUnmuteVolume{minUnmuteVolume} { for (auto speaker : speakers) { m_speakerMap.insert( std::pair>(speaker->getSpeakerType(), speaker)); @@ -329,7 +342,13 @@ void SpeakerManager::handleDirective(std::shared_ptr 0) { + return true; + } + + return executeSetVolume(type, m_minUnmuteVolume, source, true); +} + std::future SpeakerManager::adjustVolume(SpeakerInterface::Type type, int8_t delta, bool forceNoNotifications) { ACSDK_DEBUG9(LX("adjustVolumeCalled").d("delta", static_cast(delta))); return m_executor.submit([this, type, delta, forceNoNotifications] { @@ -693,4 +728,4 @@ std::unordered_set> Spe } // namespace speakerManager } // namespace capabilityAgents -} // namespace alexaClientSDK +} // namespace alexaClientSDK \ No newline at end of file diff --git a/CapabilityAgents/SpeakerManager/test/SpeakerManagerTest.cpp b/CapabilityAgents/SpeakerManager/test/SpeakerManagerTest.cpp index 93046289bd..272cde00bc 100644 --- a/CapabilityAgents/SpeakerManager/test/SpeakerManagerTest.cpp +++ b/CapabilityAgents/SpeakerManager/test/SpeakerManagerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -73,6 +73,14 @@ static const std::string MUTE_PAYLOAD = "" "}"; +/// A @c SetMute payload to unmute. +static const std::string UNMUTE_PAYLOAD = + "{" + "\"mute\":" + + UNMUTE_STRING + + "" + "}"; + /** * A mock object to test that the observer is being correctly notified. */ @@ -184,7 +192,7 @@ std::string generateVolumeStateJson(SpeakerInterface::SpeakerSettings settings) /** * Tests creating the SpeakerManager with a null contextManager. */ -TEST_F(SpeakerManagerTest, testNullContextManager) { +TEST_F(SpeakerManagerTest, test_nullContextManager) { std::vector> speakers{ std::make_shared(SpeakerInterface::Type::AVS_SPEAKER_VOLUME)}; @@ -196,7 +204,7 @@ TEST_F(SpeakerManagerTest, testNullContextManager) { /** * Tests creating the SpeakerManager with a null messageSender. */ -TEST_F(SpeakerManagerTest, testNullMessageSender) { +TEST_F(SpeakerManagerTest, test_nullMessageSender) { std::vector> speakers{ std::make_shared(SpeakerInterface::Type::AVS_SPEAKER_VOLUME)}; @@ -208,7 +216,7 @@ TEST_F(SpeakerManagerTest, testNullMessageSender) { /** * Tests creating the SpeakerManager with a null exceptionSender. */ -TEST_F(SpeakerManagerTest, testNullExceptionSender) { +TEST_F(SpeakerManagerTest, test_nullExceptionSender) { std::vector> speakers{ std::make_shared(SpeakerInterface::Type::AVS_SPEAKER_VOLUME)}; @@ -220,7 +228,7 @@ TEST_F(SpeakerManagerTest, testNullExceptionSender) { /** * Tests creating the SpeakerManager with no speakers. */ -TEST_F(SpeakerManagerTest, testNoSpeakers) { +TEST_F(SpeakerManagerTest, test_noSpeakers) { m_speakerManager = SpeakerManager::create({}, m_mockContextManager, m_mockMessageSender, m_mockExceptionSender); ASSERT_NE(m_speakerManager, nullptr); @@ -229,7 +237,7 @@ TEST_F(SpeakerManagerTest, testNoSpeakers) { /** * Tests that the SpeakerManager initially provides the state at constructor time. */ -TEST_F(SpeakerManagerTest, testContextManagerSetStateConstructor) { +TEST_F(SpeakerManagerTest, test_contextManagerSetStateConstructor) { EXPECT_CALL( *m_mockContextManager, setState(VOLUME_STATE, generateVolumeStateJson(DEFAULT_SETTINGS), StateRefreshPolicy::NEVER, _)) @@ -245,7 +253,7 @@ TEST_F(SpeakerManagerTest, testContextManagerSetStateConstructor) { /* * Test setVolume with a value that's under the bounds. The operation should fail. */ -TEST_F(SpeakerManagerTest, testSetVolumeUnderBounds) { +TEST_F(SpeakerManagerTest, test_setVolumeUnderBounds) { auto speaker = std::make_shared>(SpeakerInterface::Type::AVS_SPEAKER_VOLUME); speaker->DelegateToReal(); EXPECT_CALL(*speaker, setVolume(_)).Times(Exactly(0)); @@ -266,7 +274,7 @@ TEST_F(SpeakerManagerTest, testSetVolumeUnderBounds) { /* * Test setVolume with a value that's over the bounds. The operation should fail. */ -TEST_F(SpeakerManagerTest, testSetVolumeOverBounds) { +TEST_F(SpeakerManagerTest, test_setVolumeOverBounds) { auto speaker = std::make_shared>(SpeakerInterface::Type::AVS_SPEAKER_VOLUME); speaker->DelegateToReal(); EXPECT_CALL(*speaker, setVolume(_)).Times(Exactly(0)); @@ -286,7 +294,7 @@ TEST_F(SpeakerManagerTest, testSetVolumeOverBounds) { /* * Test adjustVolume with a value that's under the bounds. The operation should fail. */ -TEST_F(SpeakerManagerTest, testAdjustVolumeUnderBounds) { +TEST_F(SpeakerManagerTest, test_adjustVolumeUnderBounds) { auto speaker = std::make_shared>(SpeakerInterface::Type::AVS_SPEAKER_VOLUME); speaker->DelegateToReal(); EXPECT_CALL(*speaker, adjustVolume(_)).Times(Exactly(0)); @@ -306,7 +314,7 @@ TEST_F(SpeakerManagerTest, testAdjustVolumeUnderBounds) { /* * Test adjustVolume with a value that's over the bounds. The operation should fail. */ -TEST_F(SpeakerManagerTest, testAdjustVolumeOverBounds) { +TEST_F(SpeakerManagerTest, test_adjustVolumeOverBounds) { auto speaker = std::make_shared>(SpeakerInterface::Type::AVS_SPEAKER_VOLUME); speaker->DelegateToReal(); EXPECT_CALL(*speaker, adjustVolume(_)).Times(Exactly(0)); @@ -326,7 +334,7 @@ TEST_F(SpeakerManagerTest, testAdjustVolumeOverBounds) { /* * Test setVolume when the speaker interfaces are out of sync. The operation should fail. */ -TEST_F(SpeakerManagerTest, testSetVolumeOutOfSync) { +TEST_F(SpeakerManagerTest, test_setVolumeOutOfSync) { auto speaker = std::make_shared>(SpeakerInterface::Type::AVS_SPEAKER_VOLUME); speaker->DelegateToReal(); @@ -352,7 +360,7 @@ TEST_F(SpeakerManagerTest, testSetVolumeOutOfSync) { /* * Test adjustVolume when the speaker interfaces are out of sync. The operation should fail. */ -TEST_F(SpeakerManagerTest, testAdjustVolumeOutOfSync) { +TEST_F(SpeakerManagerTest, test_adjustVolumeOutOfSync) { auto speaker = std::make_shared>(SpeakerInterface::Type::AVS_SPEAKER_VOLUME); speaker->DelegateToReal(); @@ -378,7 +386,7 @@ TEST_F(SpeakerManagerTest, testAdjustVolumeOutOfSync) { /* * Test setMute when the speaker interfaces are out of sync. The operation should fail. */ -TEST_F(SpeakerManagerTest, testSetMuteOutOfSync) { +TEST_F(SpeakerManagerTest, test_setMuteOutOfSync) { auto speaker = std::make_shared>(SpeakerInterface::Type::AVS_SPEAKER_VOLUME); speaker->DelegateToReal(); @@ -403,7 +411,7 @@ TEST_F(SpeakerManagerTest, testSetMuteOutOfSync) { /** * Test getSpeakerSettings when speakers are out of sync. The operation should fail. */ -TEST_F(SpeakerManagerTest, testGetSpeakerSettingsSpeakersOutOfSync) { +TEST_F(SpeakerManagerTest, test_getSpeakerSettingsSpeakersOutOfSync) { auto speaker = std::make_shared>(SpeakerInterface::Type::AVS_SPEAKER_VOLUME); speaker->DelegateToReal(); @@ -429,7 +437,7 @@ TEST_F(SpeakerManagerTest, testGetSpeakerSettingsSpeakersOutOfSync) { /** * Test getConfiguration and ensure that all directives are handled. */ -TEST_F(SpeakerManagerTest, testGetConfiguration) { +TEST_F(SpeakerManagerTest, test_getConfiguration) { std::shared_ptr speaker = std::make_shared>(SpeakerInterface::Type::AVS_SPEAKER_VOLUME); @@ -446,7 +454,7 @@ TEST_F(SpeakerManagerTest, testGetConfiguration) { /** * Test that adding a null observer does not cause any errors in the SpeakerManager. */ -TEST_F(SpeakerManagerTest, testAddNullObserver) { +TEST_F(SpeakerManagerTest, test_addNullObserver) { auto speaker = std::make_shared>(SpeakerInterface::Type::AVS_SPEAKER_VOLUME); speaker->DelegateToReal(); @@ -463,7 +471,7 @@ TEST_F(SpeakerManagerTest, testAddNullObserver) { /** * Test that removing an observer works correctly. */ -TEST_F(SpeakerManagerTest, testRemoveSpeakerManagerObserver) { +TEST_F(SpeakerManagerTest, test_removeSpeakerManagerObserver) { auto speaker = std::make_shared>(SpeakerInterface::Type::AVS_SPEAKER_VOLUME); speaker->DelegateToReal(); @@ -483,7 +491,7 @@ TEST_F(SpeakerManagerTest, testRemoveSpeakerManagerObserver) { /** * Test that removing a null observer does not cause any errors in the SpeakerManager. */ -TEST_F(SpeakerManagerTest, testRemoveNullObserver) { +TEST_F(SpeakerManagerTest, test_removeNullObserver) { auto speaker = std::make_shared>(SpeakerInterface::Type::AVS_SPEAKER_VOLUME); speaker->DelegateToReal(); @@ -531,7 +539,7 @@ INSTANTIATE_TEST_CASE_P( /** * Parameterized test for setVolume. One event should be sent if an AVS_SPEAKER_VOLUME typed speaker is modified. */ -TEST_P(SpeakerManagerTest, testSetVolume) { +TEST_P(SpeakerManagerTest, test_setVolume) { std::vector> speakers; for (auto& typeOfSpeaker : GetParam()) { @@ -563,7 +571,7 @@ TEST_P(SpeakerManagerTest, testSetVolume) { /** * Parameterized test for adjustVolume. One event should be sent if an AVS_SPEAKER_VOLUME typed speaker is modified. */ -TEST_P(SpeakerManagerTest, testAdjustVolume) { +TEST_P(SpeakerManagerTest, test_adjustVolume) { std::vector> speakers; for (auto& typeOfSpeaker : GetParam()) { @@ -596,7 +604,7 @@ TEST_P(SpeakerManagerTest, testAdjustVolume) { /** * Parameterized test for setMute. One event should be sent if an AVS_SPEAKER_VOLUME typed speaker is modified. */ -TEST_P(SpeakerManagerTest, testSetMute) { +TEST_P(SpeakerManagerTest, test_setMute) { std::vector> speakers; for (auto& typeOfSpeaker : GetParam()) { @@ -628,7 +636,7 @@ TEST_P(SpeakerManagerTest, testSetMute) { /** * Parameterized test for getSpeakerSettings. Operation should succeed with default speaker settings. */ -TEST_P(SpeakerManagerTest, testGetSpeakerSettings) { +TEST_P(SpeakerManagerTest, test_getSpeakerSettings) { std::vector> speakers; for (auto& typeOfSpeaker : GetParam()) { @@ -661,7 +669,7 @@ TEST_P(SpeakerManagerTest, testGetSpeakerSettings) { * event is sent. In the event there are no AVS_SPEAKER_VOLUME speakers registered, no event will be sent. * In addition, only AVS_SPEAKER_VOLUME speakers should be affected. */ -TEST_P(SpeakerManagerTest, testSetVolumeDirective) { +TEST_P(SpeakerManagerTest, test_setVolumeDirective) { std::vector> speakers; int eventsSent = 0; SpeakerInterface::SpeakerSettings expectedSettings{AVS_SET_VOLUME_MAX, UNMUTE}; @@ -719,7 +727,7 @@ TEST_P(SpeakerManagerTest, testSetVolumeDirective) { * event is sent. In the event there are no AVS_SPEAKER_VOLUME speakers registered, no event will be sent. * In addition, only AVS_SPEAKER_VOLUME speakers should be affected. */ -TEST_P(SpeakerManagerTest, testAdjustVolumeDirective) { +TEST_P(SpeakerManagerTest, test_adjustVolumeDirective) { std::vector> speakers; int eventsSent = 0; SpeakerInterface::SpeakerSettings expectedSettings{AVS_SET_VOLUME_MAX, UNMUTE}; @@ -777,7 +785,7 @@ TEST_P(SpeakerManagerTest, testAdjustVolumeDirective) { * event is sent. In the event there are no AVS_SPEAKER_VOLUME speakers registered, no event will be sent. * In addition, only AVS_SPEAKER_VOLUME speakers should be affected. */ -TEST_P(SpeakerManagerTest, testSetMuteDirective) { +TEST_P(SpeakerManagerTest, test_setMuteDirective) { std::vector> speakers; int eventsSent = 0; SpeakerInterface::SpeakerSettings expectedSettings{DEFAULT_SETTINGS.volume, MUTE}; @@ -830,7 +838,72 @@ TEST_P(SpeakerManagerTest, testSetMuteDirective) { m_wakeSetCompletedFuture.wait_for(TIMEOUT); } +/** + * Test setVolume when unmute Directive sent. Setup test by setting volume to 0 and mute to true. + * Expect that the volume is unmuted and set to MIN_UNMUTE_VOLUME, as well at most one + * event is sent. In the event there are no AVS_SPEAKER_VOLUME speakers registered, no event will be sent. + * In addition, only AVS_SPEAKER_VOLUME speakers should be affected. + */ +TEST_P(SpeakerManagerTest, test_setVolumeDirectiveWhenMuted) { + std::vector> speakers; + + for (auto& typeOfSpeaker : GetParam()) { + auto speaker = std::make_shared>(typeOfSpeaker); + speaker->DelegateToReal(); + EXPECT_CALL(*speaker, setVolume(AVS_SET_VOLUME_MIN)).Times(1); + EXPECT_CALL(*speaker, setMute(MUTE)).Times(1); + + if (typeOfSpeaker == SpeakerInterface::Type::AVS_SPEAKER_VOLUME) { + EXPECT_CALL(*speaker, setMute(UNMUTE)).Times(1); + EXPECT_CALL(*speaker, setVolume(MIN_UNMUTE_VOLUME)).Times(1); + } + speakers.push_back(speaker); + } + + m_speakerManager = SpeakerManager::create(speakers, m_mockContextManager, m_mockMessageSender, m_mockExceptionSender); + m_speakerManager->addSpeakerManagerObserver(m_observer); + + for (auto type : getUniqueTypes(speakers)) { + m_speakerManager->setVolume(type, AVS_SET_VOLUME_MIN, true); + } + + for (auto type : getUniqueTypes(speakers)) { + std::future future = m_speakerManager->setMute(type, MUTE, true); + } + + // Check to see if AVS_SPEAKER_VOLUME speakers exist and set EXPECT_CALL accordingly + auto uniqueTypes = getUniqueTypes(speakers); + int eventsSent = 0; + SpeakerInterface::SpeakerSettings unMuteSettings{MIN_UNMUTE_VOLUME, UNMUTE}; + + if (uniqueTypes.count(SpeakerInterface::Type::AVS_SPEAKER_VOLUME)) { + eventsSent = 1; + + EXPECT_CALL(*m_observer, onSpeakerSettingsChanged(SpeakerManagerObserverInterface::Source::DIRECTIVE, SpeakerInterface::Type::AVS_SPEAKER_VOLUME, unMuteSettings)).Times(Exactly(1)); + EXPECT_CALL(*m_mockContextManager, setState(VOLUME_STATE, _, StateRefreshPolicy::NEVER, _)).Times(AnyNumber()); + EXPECT_CALL(*m_mockContextManager, setState(VOLUME_STATE, generateVolumeStateJson(unMuteSettings), StateRefreshPolicy::NEVER, _)).Times(Exactly(1)); + } else { + EXPECT_CALL(*m_observer, onSpeakerSettingsChanged(_, _, _)).Times(0); + EXPECT_CALL(*m_mockContextManager, setState(VOLUME_STATE, _, StateRefreshPolicy::NEVER, _)).Times(0); + } + + EXPECT_CALL(*m_mockMessageSender, sendMessage(_)).Times(eventsSent); + EXPECT_CALL(*(m_mockDirectiveHandlerResult.get()), setCompleted()) + .Times(1) + .WillOnce(InvokeWithoutArgs(this, &SpeakerManagerTest::wakeOnSetCompleted)); + + // Create Directive to unmute the device. + auto attachmentManager = std::make_shared>(); + auto avsMessageHeader = std::make_shared(SET_MUTE.nameSpace, SET_MUTE.name, MESSAGE_ID); + std::shared_ptr directive = + AVSDirective::create("", avsMessageHeader, UNMUTE_PAYLOAD, attachmentManager, ""); + + m_speakerManager->CapabilityAgent::preHandleDirective(directive, std::move(m_mockDirectiveHandlerResult)); + m_speakerManager->CapabilityAgent::handleDirective(MESSAGE_ID); + m_wakeSetCompletedFuture.wait_for(TIMEOUT); +} + } // namespace test } // namespace speakerManager } // namespace capabilityAgents -} // namespace alexaClientSDK +} // namespace alexaClientSDK \ No newline at end of file diff --git a/CapabilityAgents/SpeechSynthesizer/test/SpeechSynthesizerTest.cpp b/CapabilityAgents/SpeechSynthesizer/test/SpeechSynthesizerTest.cpp index 15d922ed31..f4d64fff5a 100644 --- a/CapabilityAgents/SpeechSynthesizer/test/SpeechSynthesizerTest.cpp +++ b/CapabilityAgents/SpeechSynthesizer/test/SpeechSynthesizerTest.cpp @@ -364,7 +364,7 @@ void SpeechSynthesizerTest::wakeOnStopped() { * Expected result is that @c acquireChannel is called with the correct channel. On focus changed @c FOREGROUND, audio * should play. Expect the @c ContextManager @c setState is called when state changes to @c PLAYING. */ -TEST_F(SpeechSynthesizerTest, testCallingHandleImmediately) { +TEST_F(SpeechSynthesizerTest, test_callingHandleImmediately) { auto avsMessageHeader = std::make_shared( NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); std::shared_ptr directive = @@ -404,7 +404,7 @@ TEST_F(SpeechSynthesizerTest, testCallingHandleImmediately) { * is called with the correct channel. On focus changed @c FOREGROUND, audio should play. Expect the @c ContextManager * @c setState is called when state changes to @c PLAYING. */ -TEST_F(SpeechSynthesizerTest, testCallingHandle) { +TEST_F(SpeechSynthesizerTest, test_callingHandle) { auto avsMessageHeader = std::make_shared( NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); std::shared_ptr directive = @@ -447,7 +447,7 @@ TEST_F(SpeechSynthesizerTest, testCallingHandle) { * Call preHandle with a valid SPEAK directive. Then call cancelDirective. Expect that neither @c setState nor * @c sendMessage are called since handle was never called to start playing audio. */ -TEST_F(SpeechSynthesizerTest, testCallingCancel) { +TEST_F(SpeechSynthesizerTest, test_callingCancel) { auto avsMessageHeader = std::make_shared( NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); std::shared_ptr directive = @@ -467,7 +467,7 @@ TEST_F(SpeechSynthesizerTest, testCallingCancel) { * @c ContextManager @c setState is called when the state changes to @c PLAYING and then to @c FINISHED. * Expect @c sendMessage is called only once. On cancel, message should not be sent to AVS. */ -TEST_F(SpeechSynthesizerTest, testCallingCancelAfterHandle) { +TEST_F(SpeechSynthesizerTest, test_callingCancelAfterHandle) { auto avsMessageHeader = std::make_shared( NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); std::shared_ptr directive = @@ -520,7 +520,7 @@ TEST_F(SpeechSynthesizerTest, testCallingCancelAfterHandle) { * Testing provideState. * Call @c provideState and expect that setState is called. */ -TEST_F(SpeechSynthesizerTest, testCallingProvideStateWhenNotPlaying) { +TEST_F(SpeechSynthesizerTest, test_callingProvideStateWhenNotPlaying) { EXPECT_CALL(*(m_mockSpeechPlayer.get()), getOffset(_)).Times(0); EXPECT_CALL( *(m_mockContextManager.get()), @@ -539,7 +539,7 @@ TEST_F(SpeechSynthesizerTest, testCallingProvideStateWhenNotPlaying) { * Expect @c getOffset is called. Expect @c setState is called when state changes and when state is * requested via @c provideState. */ -TEST_F(SpeechSynthesizerTest, testCallingProvideStateWhenPlaying) { +TEST_F(SpeechSynthesizerTest, test_callingProvideStateWhenPlaying) { auto avsMessageHeader = std::make_shared( NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); std::shared_ptr directive = @@ -599,7 +599,7 @@ TEST_F(SpeechSynthesizerTest, testCallingProvideStateWhenPlaying) { * Testing barge-in via @c handleDirectiveImmediately when audio is playing back. * Call @c handleDirective. Once playback started notification is received, call @c handleDirectiveImmediately. */ -TEST_F(SpeechSynthesizerTest, testBargeInWhilePlaying) { +TEST_F(SpeechSynthesizerTest, testTimer_bargeInWhilePlaying) { auto avsMessageHeader = std::make_shared( NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); std::shared_ptr directive = @@ -666,7 +666,7 @@ TEST_F(SpeechSynthesizerTest, testBargeInWhilePlaying) { * Expect when handleDirectiveImmediately with a valid SPEAK directive is called, @c SpeechSynthesizer * will react correctly. */ -TEST_F(SpeechSynthesizerTest, testNotCallStopTwice) { +TEST_F(SpeechSynthesizerTest, testTimer_notCallStopTwice) { auto avsMessageHeader = std::make_shared( NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); std::shared_ptr directive = @@ -760,7 +760,7 @@ TEST_F(SpeechSynthesizerTest, testNotCallStopTwice) { /** * Testing executeCancel() completes execution before onFocusChanged() is called. */ -TEST_F(SpeechSynthesizerTest, testCallingCancelBeforeOnFocusChanged) { +TEST_F(SpeechSynthesizerTest, testSlow_callingCancelBeforeOnFocusChanged) { auto avsMessageHeader = std::make_shared( NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); std::shared_ptr directive = @@ -832,7 +832,7 @@ TEST_F(SpeechSynthesizerTest, testCallingCancelBeforeOnFocusChanged) { /** * Testing executeCancel() completes execution before executeStateChange() is called. */ -TEST_F(SpeechSynthesizerTest, testCallingCancelBeforeOnExecuteStateChanged) { +TEST_F(SpeechSynthesizerTest, test_callingCancelBeforeOnExecuteStateChanged) { auto avsMessageHeader = std::make_shared( NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); std::shared_ptr directive = @@ -908,7 +908,7 @@ TEST_F(SpeechSynthesizerTest, testCallingCancelBeforeOnExecuteStateChanged) { * Expect when handleDirectiveImmediately with a valid SPEAK directive is called, @c SpeechSynthesizer * will react correctly. */ -TEST_F(SpeechSynthesizerTest, testMediaPlayerFailedToStop) { +TEST_F(SpeechSynthesizerTest, test_mediaPlayerFailedToStop) { auto avsMessageHeader = std::make_shared( NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); std::shared_ptr directive = @@ -1004,7 +1004,7 @@ TEST_F(SpeechSynthesizerTest, testMediaPlayerFailedToStop) { * * Expected result is that shutdown should succeeded no matter the @c stop return. */ -TEST_F(SpeechSynthesizerTest, testMediaPlayerAlwaysFailToStop) { +TEST_F(SpeechSynthesizerTest, test_mediaPlayerAlwaysFailToStop) { auto speechSynthesizer = SpeechSynthesizer::create( m_mockSpeechPlayer, m_mockMessageSender, @@ -1044,7 +1044,7 @@ TEST_F(SpeechSynthesizerTest, testMediaPlayerAlwaysFailToStop) { * Testing SpeechSynthesizer will call stop() if the SpeechSynthesizer experienced a state change timeout to PLAYING * state. */ -TEST_F(SpeechSynthesizerTest, testSetStateTimeout) { +TEST_F(SpeechSynthesizerTest, testSlow_setStateTimeout) { auto avsMessageHeader = std::make_shared( NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); std::shared_ptr directive = @@ -1110,7 +1110,7 @@ TEST_F(SpeechSynthesizerTest, testSetStateTimeout) { * Testing changing focus state to NONE (local stop) during a speak. * Expect @c setFailed to be called so any subsequent directives with the same dialogRequestId will be dropped. */ -TEST_F(SpeechSynthesizerTest, testGivenPlayingStateFocusBecomesNone) { +TEST_F(SpeechSynthesizerTest, test_givenPlayingStateFocusBecomesNone) { auto avsMessageHeader = std::make_shared( NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); std::shared_ptr directive = @@ -1144,7 +1144,7 @@ TEST_F(SpeechSynthesizerTest, testGivenPlayingStateFocusBecomesNone) { * Testing SpeechSynthesizer will call setFailed() if the SpeechSynthesizer got a onPlaybackStopped() callback while * it is in PLAYING state. */ -TEST_F(SpeechSynthesizerTest, testOnPlayedStopped) { +TEST_F(SpeechSynthesizerTest, test_onPlayedStopped) { auto avsMessageHeader = std::make_shared( NAMESPACE_SPEECH_SYNTHESIZER, NAME_SPEAK, MESSAGE_ID_TEST, DIALOG_REQUEST_ID_TEST); std::shared_ptr directive = diff --git a/CapabilityAgents/System/a4btest/RevokeAuthorizationHandlerTest.cpp b/CapabilityAgents/System/a4btest/RevokeAuthorizationHandlerTest.cpp index 321cbeb786..ef12458168 100644 --- a/CapabilityAgents/System/a4btest/RevokeAuthorizationHandlerTest.cpp +++ b/CapabilityAgents/System/a4btest/RevokeAuthorizationHandlerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -97,7 +97,7 @@ void RevokeAuthorizationHandlerTest::SetUp() { /** * This case tests if @c RevokeAuthorizationHandler basic create function works properly */ -TEST_F(RevokeAuthorizationHandlerTest, createSuccessfully) { +TEST_F(RevokeAuthorizationHandlerTest, test_createSuccessfully) { ASSERT_NE(nullptr, RevokeAuthorizationHandler::create(m_mockExceptionEncounteredSender)); } @@ -105,7 +105,7 @@ TEST_F(RevokeAuthorizationHandlerTest, createSuccessfully) { * This case tests if possible @c nullptr parameters passed to @c RevokeAuthorizationHandler::create are handled * properly. */ -TEST_F(RevokeAuthorizationHandlerTest, createWithError) { +TEST_F(RevokeAuthorizationHandlerTest, test_createWithError) { ASSERT_EQ(nullptr, RevokeAuthorizationHandler::create(nullptr)); } @@ -113,7 +113,7 @@ TEST_F(RevokeAuthorizationHandlerTest, createWithError) { * This case tests if a directive is handled properly and passed to the registered observer. * It uses the directive sequencer to ensure getCapabilities properly identifies the namespace/directive name. */ -TEST_F(RevokeAuthorizationHandlerTest, handleDirectiveProperly) { +TEST_F(RevokeAuthorizationHandlerTest, test_handleDirectiveProperly) { auto revokeHandler = RevokeAuthorizationHandler::create(m_mockExceptionEncounteredSender); ASSERT_NE(nullptr, revokeHandler); @@ -137,7 +137,7 @@ TEST_F(RevokeAuthorizationHandlerTest, handleDirectiveProperly) { /** * This case tests if handleDirectiveImmediately handles the directive properly. */ -TEST_F(RevokeAuthorizationHandlerTest, handleDirectiveImmediatelyProperly) { +TEST_F(RevokeAuthorizationHandlerTest, test_handleDirectiveImmediatelyProperly) { auto revokeHandler = RevokeAuthorizationHandler::create(m_mockExceptionEncounteredSender); ASSERT_NE(nullptr, revokeHandler); @@ -151,7 +151,7 @@ TEST_F(RevokeAuthorizationHandlerTest, handleDirectiveImmediatelyProperly) { /** * This case tests if handleDirectiveImmediately handles a @c nullptr directive correctly and does not notify observers. */ -TEST_F(RevokeAuthorizationHandlerTest, handleDirectiveImmediatelyNullDirective) { +TEST_F(RevokeAuthorizationHandlerTest, test_handleDirectiveImmediatelyNullDirective) { auto revokeHandler = RevokeAuthorizationHandler::create(m_mockExceptionEncounteredSender); ASSERT_NE(nullptr, revokeHandler); @@ -164,7 +164,7 @@ TEST_F(RevokeAuthorizationHandlerTest, handleDirectiveImmediatelyNullDirective) /** * This case tests if handleDirective handles a @c nullptr DirectiveInfo correctly and does not notify observers. */ -TEST_F(RevokeAuthorizationHandlerTest, handleDirectiveNullDirectiveInfo) { +TEST_F(RevokeAuthorizationHandlerTest, test_handleDirectiveNullDirectiveInfo) { auto revokeHandler = RevokeAuthorizationHandler::create(m_mockExceptionEncounteredSender); ASSERT_NE(nullptr, revokeHandler); @@ -177,7 +177,7 @@ TEST_F(RevokeAuthorizationHandlerTest, handleDirectiveNullDirectiveInfo) { /** * This case tests if cancelDirective handles a @c nullptr DirectiveInfo safely. */ -TEST_F(RevokeAuthorizationHandlerTest, cancelDirectiveNullDirectiveInfo) { +TEST_F(RevokeAuthorizationHandlerTest, test_cancelDirectiveNullDirectiveInfo) { auto revokeHandler = RevokeAuthorizationHandler::create(m_mockExceptionEncounteredSender); ASSERT_NE(nullptr, revokeHandler); @@ -190,7 +190,7 @@ TEST_F(RevokeAuthorizationHandlerTest, cancelDirectiveNullDirectiveInfo) { /** * This case tests when a registered observer is removed, it does not receive notifications. */ -TEST_F(RevokeAuthorizationHandlerTest, removeObserverSuccessfully) { +TEST_F(RevokeAuthorizationHandlerTest, test_removeObserverSuccessfully) { auto revokeHandler = RevokeAuthorizationHandler::create(m_mockExceptionEncounteredSender); ASSERT_NE(nullptr, revokeHandler); @@ -218,7 +218,7 @@ TEST_F(RevokeAuthorizationHandlerTest, removeObserverSuccessfully) { * Test to verify the preHandleDirective method doesn't really take action, as there is no pre-handle * work supported at this time. */ -TEST_F(RevokeAuthorizationHandlerTest, preHandleDirectiveTest) { +TEST_F(RevokeAuthorizationHandlerTest, test_preHandleDirective) { auto revokeHandler = RevokeAuthorizationHandler::create(m_mockExceptionEncounteredSender); ASSERT_NE(nullptr, revokeHandler); @@ -228,7 +228,7 @@ TEST_F(RevokeAuthorizationHandlerTest, preHandleDirectiveTest) { /** * Test to verify the addObserver method successfully ignores @c nullptr inputs. */ -TEST_F(RevokeAuthorizationHandlerTest, addObserverIgnoreNullPtr) { +TEST_F(RevokeAuthorizationHandlerTest, test_addObserverIgnoreNullPtr) { auto revokeHandler = RevokeAuthorizationHandler::create(m_mockExceptionEncounteredSender); ASSERT_NE(nullptr, revokeHandler); @@ -239,7 +239,7 @@ TEST_F(RevokeAuthorizationHandlerTest, addObserverIgnoreNullPtr) { /** * Test to verify the removeObserver method successfully ignores @c nullptr inputs. */ -TEST_F(RevokeAuthorizationHandlerTest, removeObserverIgnoreNullPtr) { +TEST_F(RevokeAuthorizationHandlerTest, test_removeObserverIgnoreNullPtr) { auto revokeHandler = RevokeAuthorizationHandler::create(m_mockExceptionEncounteredSender); ASSERT_NE(nullptr, revokeHandler); diff --git a/CapabilityAgents/System/test/EndpointHandlerTest.cpp b/CapabilityAgents/System/test/EndpointHandlerTest.cpp index c3f007423a..52eae7bfbc 100644 --- a/CapabilityAgents/System/test/EndpointHandlerTest.cpp +++ b/CapabilityAgents/System/test/EndpointHandlerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -92,14 +92,14 @@ void EndpointHandlerTest::SetUp() { /** * This case tests if @c EndpointHandler basic create function works properly */ -TEST_F(EndpointHandlerTest, createSuccessfully) { +TEST_F(EndpointHandlerTest, test_createSuccessfully) { ASSERT_NE(nullptr, EndpointHandler::create(m_mockAVSEndpointAssigner, m_mockExceptionEncounteredSender)); } /** * This case tests if possible @c nullptr parameters passed to @c EndpointHandler::create are handled properly. */ -TEST_F(EndpointHandlerTest, createWithError) { +TEST_F(EndpointHandlerTest, test_createWithError) { ASSERT_EQ(nullptr, EndpointHandler::create(m_mockAVSEndpointAssigner, nullptr)); ASSERT_EQ(nullptr, EndpointHandler::create(nullptr, m_mockExceptionEncounteredSender)); ASSERT_EQ(nullptr, EndpointHandler::create(nullptr, nullptr)); @@ -108,7 +108,7 @@ TEST_F(EndpointHandlerTest, createWithError) { /** * This case tests if a directive is handled properly. */ -TEST_F(EndpointHandlerTest, handleDirectiveProperly) { +TEST_F(EndpointHandlerTest, test_handleDirectiveProperly) { auto endpointHandler = EndpointHandler::create(m_mockAVSEndpointAssigner, m_mockExceptionEncounteredSender); ASSERT_NE(nullptr, endpointHandler); diff --git a/CapabilityAgents/System/test/SoftwareInfoTest.cpp b/CapabilityAgents/System/test/SoftwareInfoTest.cpp index a0421bb8e4..8649f9b4c1 100644 --- a/CapabilityAgents/System/test/SoftwareInfoTest.cpp +++ b/CapabilityAgents/System/test/SoftwareInfoTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -171,7 +171,7 @@ void SoftwareInfoSenderTest::SetUp() { /** * Verify that providing an invalid firmware version will cause SoftwareInfoSender::create() to fail. */ -TEST_F(SoftwareInfoSenderTest, createFailedInvalidFirmwareVersion) { +TEST_F(SoftwareInfoSenderTest, test_createFailedInvalidFirmwareVersion) { ASSERT_FALSE(SoftwareInfoSender::create( INVALID_FIRMWARE_VERSION, true, @@ -184,7 +184,7 @@ TEST_F(SoftwareInfoSenderTest, createFailedInvalidFirmwareVersion) { /** * Verify that passing false for sendSoftwareInfoUponConnect will NOT cause SoftwareInfoSender::create() to fail. */ -TEST_F(SoftwareInfoSenderTest, createSuccessWithsendSoftwareInfoUponConnectFalse) { +TEST_F(SoftwareInfoSenderTest, test_createSuccessWithsendSoftwareInfoUponConnectFalse) { auto softwareInfoSender = SoftwareInfoSender::create( FIRST_FIRMWARE_VERSION, false, @@ -199,7 +199,7 @@ TEST_F(SoftwareInfoSenderTest, createSuccessWithsendSoftwareInfoUponConnectFalse /** * Verify that passing nullptr for observer will NOT cause SoftwareInfoSender::create() to fail. */ -TEST_F(SoftwareInfoSenderTest, createSuccessWithObserverNull) { +TEST_F(SoftwareInfoSenderTest, test_createSuccessWithObserverNull) { auto softwareInfoSender = SoftwareInfoSender::create( 1, true, nullptr, m_mockConnection, m_mockMessageSender, m_mockExceptionEncounteredSender); ASSERT_TRUE(softwareInfoSender); @@ -209,7 +209,7 @@ TEST_F(SoftwareInfoSenderTest, createSuccessWithObserverNull) { /** * Verify that passing nullptr for connection will cause SoftwareInfoSender::create() to fail. */ -TEST_F(SoftwareInfoSenderTest, createFailedConnectionNull) { +TEST_F(SoftwareInfoSenderTest, test_createFailedConnectionNull) { ASSERT_FALSE(SoftwareInfoSender::create( 1, true, m_mockObserver, nullptr, m_mockMessageSender, m_mockExceptionEncounteredSender)); } @@ -217,7 +217,7 @@ TEST_F(SoftwareInfoSenderTest, createFailedConnectionNull) { /** * Verify that not providing a @c MessageSender will cause @c SoftwareInfoSender::create() to fail. */ -TEST_F(SoftwareInfoSenderTest, createFailedMessageSenderNull) { +TEST_F(SoftwareInfoSenderTest, test_createFailedMessageSenderNull) { ASSERT_FALSE(SoftwareInfoSender::create( 1, true, m_mockObserver, m_mockConnection, nullptr, m_mockExceptionEncounteredSender)); } @@ -225,7 +225,7 @@ TEST_F(SoftwareInfoSenderTest, createFailedMessageSenderNull) { /** * Verify that not providing a @c MessageSender will cause @c SoftwareInfoSender::create() to fail. */ -TEST_F(SoftwareInfoSenderTest, createFailedExceptionEncounteredSenderNull) { +TEST_F(SoftwareInfoSenderTest, test_createFailedExceptionEncounteredSenderNull) { ASSERT_FALSE(SoftwareInfoSender::create(1, true, m_mockObserver, m_mockConnection, m_mockMessageSender, nullptr)); } @@ -233,7 +233,7 @@ TEST_F(SoftwareInfoSenderTest, createFailedExceptionEncounteredSenderNull) { * Verify that no SoftwareInfo event or ExceptionEncountered message is sent if @c sendSoftwareInfoOnConnect is * @c false and ReportSoftwareInfo directive is not received. */ -TEST_F(SoftwareInfoSenderTest, noSoftwareInfoEventSentByDefault) { +TEST_F(SoftwareInfoSenderTest, test_noSoftwareInfoEventSentByDefault) { EXPECT_CALL(*(m_mockObserver.get()), onFirmwareVersionAccepted(_)).Times(0); EXPECT_CALL(*(m_mockMessageSender.get()), sendMessage(_)).Times(0); EXPECT_CALL(*(m_mockExceptionEncounteredSender.get()), sendExceptionEncountered(_, _, _)).Times(0); @@ -274,7 +274,7 @@ TEST_F(SoftwareInfoSenderTest, noSoftwareInfoEventSentByDefault) { * Verify that no attempt is made to send a SoftwareInfo event or and ExceptionEncounteredEvent if no connection * has been established - even if @c sendSoftwareInfoOnConnect is @c true. */ -TEST_F(SoftwareInfoSenderTest, nothingSentBeforeConnected) { +TEST_F(SoftwareInfoSenderTest, test_nothingSentBeforeConnected) { EXPECT_CALL(*(m_mockObserver.get()), onFirmwareVersionAccepted(_)).Times(0); EXPECT_CALL(*(m_mockMessageSender.get()), sendMessage(_)).Times(0); EXPECT_CALL(*(m_mockExceptionEncounteredSender.get()), sendExceptionEncountered(_, _, _)).Times(0); @@ -294,7 +294,7 @@ TEST_F(SoftwareInfoSenderTest, nothingSentBeforeConnected) { * Verify that one SoftwareInfo event is sent and no ExceptionEncountered message is sent if @c * sendSoftwareInfoOnConnect is @c true, a connection is made, and no ReportSoftwareInfo directive is received. */ -TEST_F(SoftwareInfoSenderTest, softwareInfoSentUponConnectIfSendSetTrueBeforeConnect) { +TEST_F(SoftwareInfoSenderTest, test_softwareInfoSentUponConnectIfSendSetTrueBeforeConnect) { std::promise versionAcceptedPromise; EXPECT_CALL(*(m_mockObserver.get()), onFirmwareVersionAccepted(_)) .Times(1) @@ -341,7 +341,7 @@ TEST_F(SoftwareInfoSenderTest, softwareInfoSentUponConnectIfSendSetTrueBeforeCon * Verify that an event is sent if a @c ReportSoftwareInfo directive is received even if @c sendSoftwareInfoOnConnect is * @c false. */ -TEST_F(SoftwareInfoSenderTest, reportSoftwareInfoReceived) { +TEST_F(SoftwareInfoSenderTest, test_reportSoftwareInfoReceived) { std::promise versionAcceptedPromise; EXPECT_CALL(*(m_mockObserver.get()), onFirmwareVersionAccepted(_)) .Times(1) @@ -384,7 +384,7 @@ TEST_F(SoftwareInfoSenderTest, reportSoftwareInfoReceived) { * Verify that handling a @c ReportSoftwareInfo directive cancels incomplete handling of any previous * ReportSoftwareInfo directive. */ -TEST_F(SoftwareInfoSenderTest, reportSoftwareInfoCancellsPreviousDirective) { +TEST_F(SoftwareInfoSenderTest, test_reportSoftwareInfoCancellsPreviousDirective) { // This status causes the first send request to retry, until set to something else. std::atomic status( MessageRequestObserverInterface::Status::SERVER_INTERNAL_ERROR_V2); @@ -443,7 +443,7 @@ TEST_F(SoftwareInfoSenderTest, reportSoftwareInfoCancellsPreviousDirective) { /** * Verify that notification that the firmware version was accepted by @c AVS is only sent once. */ -TEST_F(SoftwareInfoSenderTest, delayedReportSoftwareInfoNotifiesOnce) { +TEST_F(SoftwareInfoSenderTest, test_delayedReportSoftwareInfoNotifiesOnce) { std::promise versionAcceptedPromise; EXPECT_CALL(*(m_mockObserver.get()), onFirmwareVersionAccepted(_)) .Times(1) @@ -495,7 +495,7 @@ TEST_F(SoftwareInfoSenderTest, delayedReportSoftwareInfoNotifiesOnce) { /** * Verify that SoftwareInfoSender retries sending. */ -TEST_F(SoftwareInfoSenderTest, verifySendRetries) { +TEST_F(SoftwareInfoSenderTest, testSlow_verifySendRetries) { std::promise versionAcceptedPromise; EXPECT_CALL(*(m_mockObserver.get()), onFirmwareVersionAccepted(_)) .Times(1) @@ -533,7 +533,7 @@ TEST_F(SoftwareInfoSenderTest, verifySendRetries) { /** * Verify that attempting to set an invalid firmware version fails. */ -TEST_F(SoftwareInfoSenderTest, setInvalidFirmwareVersion) { +TEST_F(SoftwareInfoSenderTest, test_setInvalidFirmwareVersion) { EXPECT_CALL(*(m_mockMessageSender.get()), sendMessage(_)).Times(0); EXPECT_CALL(*(m_mockExceptionEncounteredSender.get()), sendExceptionEncountered(_, _, _)).Times(0); @@ -563,7 +563,7 @@ TEST_F(SoftwareInfoSenderTest, setInvalidFirmwareVersion) { * Verify that handling a @c ReportSoftwareInfo directive cancels incomplete handling of any previous * ReportSoftwareInfo directive. */ -TEST_F(SoftwareInfoSenderTest, setFirmwareVersionCancellsPreviousSetting) { +TEST_F(SoftwareInfoSenderTest, test_setFirmwareVersionCancellsPreviousSetting) { // This status causes the first send request to retry, until set to something else. std::atomic status( MessageRequestObserverInterface::Status::SERVER_INTERNAL_ERROR_V2); diff --git a/CapabilityAgents/System/test/UserInactivityMonitorTest.cpp b/CapabilityAgents/System/test/UserInactivityMonitorTest.cpp index d68232d5f8..d626377201 100644 --- a/CapabilityAgents/System/test/UserInactivityMonitorTest.cpp +++ b/CapabilityAgents/System/test/UserInactivityMonitorTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -118,7 +118,7 @@ void UserInactivityMonitorTest::SetUp() { /** * This case tests if @c UserInactivityMonitor basic create function works properly */ -TEST_F(UserInactivityMonitorTest, createSuccessfully) { +TEST_F(UserInactivityMonitorTest, test_createSuccessfully) { std::mutex exitMutex; std::unique_lock exitLock(exitMutex); EXPECT_CALL(*m_mockMessageSender, sendMessage(ResultOf(&checkMessageRequestAndReleaseTrigger, Eq(true)))); @@ -133,7 +133,7 @@ TEST_F(UserInactivityMonitorTest, createSuccessfully) { /** * This case tests if possible @c nullptr parameters passed to @c UserInactivityMonitor::create are handled properly. */ -TEST_F(UserInactivityMonitorTest, createWithError) { +TEST_F(UserInactivityMonitorTest, test_createWithError) { ASSERT_EQ(nullptr, UserInactivityMonitor::create(m_mockMessageSender, nullptr)); ASSERT_EQ(nullptr, UserInactivityMonitor::create(nullptr, m_mockExceptionEncounteredSender)); ASSERT_EQ(nullptr, UserInactivityMonitor::create(nullptr, nullptr)); @@ -142,7 +142,7 @@ TEST_F(UserInactivityMonitorTest, createWithError) { /** * This case tests if a directive is handled properly. */ -TEST_F(UserInactivityMonitorTest, handleDirectiveProperly) { +TEST_F(UserInactivityMonitorTest, test_handleDirectiveProperly) { std::mutex exitMutex; std::unique_lock exitLock(exitMutex); std::promise notifyObserverPromise1; @@ -188,7 +188,7 @@ TEST_F(UserInactivityMonitorTest, handleDirectiveProperly) { /** * This case tests if multiple requests are being sent up to AVS. */ -TEST_F(UserInactivityMonitorTest, sendMultipleReports) { +TEST_F(UserInactivityMonitorTest, test_sendMultipleReports) { InSequence s; std::mutex exitMutex; std::unique_lock exitLock(exitMutex); @@ -205,7 +205,7 @@ TEST_F(UserInactivityMonitorTest, sendMultipleReports) { /** * Verify that timeSinceUserInactivity works as expected. */ -TEST_F(UserInactivityMonitorTest, verifyInactivityTime) { +TEST_F(UserInactivityMonitorTest, test_verifyInactivityTime) { auto userInactivityMonitor = UserInactivityMonitor::create(m_mockMessageSender, m_mockExceptionEncounteredSender); ASSERT_NE(nullptr, userInactivityMonitor); @@ -223,7 +223,7 @@ TEST_F(UserInactivityMonitorTest, verifyInactivityTime) { /** * This case tests if multiple requests are being sent up to AVS with a reset during the process. */ -TEST_F(UserInactivityMonitorTest, sendMultipleReportsWithReset) { +TEST_F(UserInactivityMonitorTest, test_sendMultipleReportsWithReset) { InSequence s; std::mutex exitMutex; std::unique_lock exitLock(exitMutex); diff --git a/CapabilityAgents/TemplateRuntime/src/TemplateRuntime.cpp b/CapabilityAgents/TemplateRuntime/src/TemplateRuntime.cpp index 880482f11c..33adb544cc 100644 --- a/CapabilityAgents/TemplateRuntime/src/TemplateRuntime.cpp +++ b/CapabilityAgents/TemplateRuntime/src/TemplateRuntime.cpp @@ -450,6 +450,11 @@ void TemplateRuntime::executeAudioPlayerInfoUpdates(avsCommon::avs::PlayerActivi executeAudioPlayerStartTimer(state); } executeDisplayCardEvent(m_audioItemInExecution.directive); + } else { + // The RenderTemplateCard is cleared before it's displayed, so we should release the focus. + if (TemplateRuntime::State::ACQUIRING == m_state) { + m_state = TemplateRuntime::State::RELEASING; + } } } @@ -465,12 +470,18 @@ void TemplateRuntime::executeAudioPlayerStartTimer(avsCommon::avs::PlayerActivit void TemplateRuntime::executeRenderPlayerInfoCallbacks(bool isClearCard) { ACSDK_DEBUG3(LX("executeRenderPlayerInfoCallbacks").d("isClearCard", isClearCard ? "True" : "False")); - for (auto& observer : m_observers) { - if (isClearCard) { + if (isClearCard) { + for (auto& observer : m_observers) { observer->clearPlayerInfoCard(); - } else { - observer->renderPlayerInfoCard( - m_audioItemInExecution.directive->directive->getPayload(), m_audioPlayerInfo, m_focus); + } + } else { + if (!m_audioItemInExecution.directive) { + ACSDK_ERROR(LX("executeRenderPlayerInfoCallbacksFao;ed").d("reason", "nullAudioItemInExecution")); + return; + } + auto payload = m_audioItemInExecution.directive->directive->getPayload(); + for (auto& observer : m_observers) { + observer->renderPlayerInfoCard(payload, m_audioPlayerInfo, m_focus); } } } @@ -647,7 +658,8 @@ void TemplateRuntime::executeOnFocusChangedEvent(avsCommon::avs::FocusState newF switch (newFocus) { case FocusState::FOREGROUND: case FocusState::BACKGROUND: - weirdFocusState = true; + m_focusManager->releaseChannel(CHANNEL_NAME, shared_from_this()); + nextState = TemplateRuntime::State::RELEASING; break; case FocusState::NONE: nextState = TemplateRuntime::State::IDLE; diff --git a/CapabilityAgents/TemplateRuntime/test/TemplateRuntimeTest.cpp b/CapabilityAgents/TemplateRuntime/test/TemplateRuntimeTest.cpp index 4804ba0250..28976555a3 100644 --- a/CapabilityAgents/TemplateRuntime/test/TemplateRuntimeTest.cpp +++ b/CapabilityAgents/TemplateRuntime/test/TemplateRuntimeTest.cpp @@ -291,7 +291,7 @@ void TemplateRuntimeTest::wakeOnReleaseChannel() { /** * Tests creating the TemplateRuntime with a null audioPlayerInterface. */ -TEST_F(TemplateRuntimeTest, testNullAudioPlayerInterface) { +TEST_F(TemplateRuntimeTest, test_nullAudioPlayerInterface) { auto templateRuntime = TemplateRuntime::create(nullptr, m_mockFocusManager, m_mockExceptionSender); ASSERT_EQ(templateRuntime, nullptr); } @@ -299,7 +299,7 @@ TEST_F(TemplateRuntimeTest, testNullAudioPlayerInterface) { /** * Tests creating the TemplateRuntime with a null focusManagerInterface. */ -TEST_F(TemplateRuntimeTest, testNullFocusManagerInterface) { +TEST_F(TemplateRuntimeTest, test_nullFocusManagerInterface) { auto templateRuntime = TemplateRuntime::create(m_mockAudioPlayerInterface, nullptr, m_mockExceptionSender); ASSERT_EQ(templateRuntime, nullptr); } @@ -307,7 +307,7 @@ TEST_F(TemplateRuntimeTest, testNullFocusManagerInterface) { /** * Tests creating the TemplateRuntime with a null exceptionSender. */ -TEST_F(TemplateRuntimeTest, testNullExceptionSender) { +TEST_F(TemplateRuntimeTest, test_nullExceptionSender) { auto templateRuntime = TemplateRuntime::create(m_mockAudioPlayerInterface, m_mockFocusManager, nullptr); ASSERT_EQ(templateRuntime, nullptr); } @@ -316,7 +316,7 @@ TEST_F(TemplateRuntimeTest, testNullExceptionSender) { * Tests that the TemplateRuntime successfully add itself with the AudioPlayer at constructor time, and * successfully remove itself with the AudioPlayer during shutdown. */ -TEST_F(TemplateRuntimeTest, testAudioPlayerAddRemoveObserver) { +TEST_F(TemplateRuntimeTest, test_audioPlayerAddRemoveObserver) { auto mockAudioPlayerInterface = std::make_shared>(); auto mockExceptionSender = std::make_shared>(); auto mockFocusManager = std::make_shared>(); @@ -329,7 +329,7 @@ TEST_F(TemplateRuntimeTest, testAudioPlayerAddRemoveObserver) { /** * Tests unknown Directive. Expect that the sendExceptionEncountered and setFailed will be called. */ -TEST_F(TemplateRuntimeTest, testUnknownDirective) { +TEST_F(TemplateRuntimeTest, test_unknownDirective) { // Create Directive. auto attachmentManager = std::make_shared>(); auto avsMessageHeader = std::make_shared(NAMESPACE, UNKNOWN_DIRECTIVE, MESSAGE_ID); @@ -349,7 +349,7 @@ TEST_F(TemplateRuntimeTest, testUnknownDirective) { * Tests RenderTemplate Directive. Expect that the renderTemplateCard callback will be called and clearTemplateCard will * be called after 2s after DialogUXState is changed to IDLE state. */ -TEST_F(TemplateRuntimeTest, testRenderTemplateDirective) { +TEST_F(TemplateRuntimeTest, testSlow_renderTemplateDirective) { // Create Directive. auto attachmentManager = std::make_shared>(); auto avsMessageHeader = std::make_shared(TEMPLATE.nameSpace, TEMPLATE.name, MESSAGE_ID); @@ -379,7 +379,9 @@ TEST_F(TemplateRuntimeTest, testRenderTemplateDirective) { * Tests RenderTemplate Directive. Expect that the renderTemplateCard callback will be called and clearTemplateCard will * not be called if DialogUXState goes to IDLE state and then goes EXPECTING and SPEAKING state. */ -TEST_F(TemplateRuntimeTest, testRenderTemplateDirectiveWillNotClearCardAfterGoingToExpectingStateAfterGoingToIDLE) { +TEST_F( + TemplateRuntimeTest, + testRenderTemplateDirectiveWillNotClearCardAfterGoingToExpectingStateAfterGoingToIDLESlowTest) { // Create Directive. auto attachmentManager = std::make_shared>(); auto avsMessageHeader = std::make_shared(TEMPLATE.nameSpace, TEMPLATE.name, MESSAGE_ID); @@ -418,7 +420,7 @@ TEST_F(TemplateRuntimeTest, testRenderTemplateDirectiveWillNotClearCardAfterGoin * Tests RenderTemplate Directive using the handleDirectiveImmediately. Expect that the renderTemplateCard * callback will be called. */ -TEST_F(TemplateRuntimeTest, testHandleDirectiveImmediately) { +TEST_F(TemplateRuntimeTest, test_handleDirectiveImmediately) { // Create Directive. auto attachmentManager = std::make_shared>(); auto avsMessageHeader = std::make_shared(TEMPLATE.nameSpace, TEMPLATE.name, MESSAGE_ID); @@ -438,7 +440,7 @@ TEST_F(TemplateRuntimeTest, testHandleDirectiveImmediately) { * that the renderTemplateCard callback will be called and clearPlayerInfoCard will be called after 2s after Audio State * is changed to FINISHED state. */ -TEST_F(TemplateRuntimeTest, testRenderPlayerInfoDirectiveBefore) { +TEST_F(TemplateRuntimeTest, testSlow_renderPlayerInfoDirectiveBefore) { // Create Directive. auto attachmentManager = std::make_shared>(); auto avsMessageHeader = std::make_shared(PLAYER_INFO.nameSpace, PLAYER_INFO.name, MESSAGE_ID); @@ -482,7 +484,7 @@ TEST_F(TemplateRuntimeTest, testRenderPlayerInfoDirectiveBefore) { * Tests RenderTemplate Directive received after the corresponding AudioPlayer call. Expect * that the renderTemplateCard callback will be called. */ -TEST_F(TemplateRuntimeTest, testRenderPlayerInfoDirectiveAfter) { +TEST_F(TemplateRuntimeTest, test_renderPlayerInfoDirectiveAfter) { // Create Directive. auto attachmentManager = std::make_shared>(); auto avsMessageHeader = std::make_shared(PLAYER_INFO.nameSpace, PLAYER_INFO.name, MESSAGE_ID); @@ -511,7 +513,7 @@ TEST_F(TemplateRuntimeTest, testRenderPlayerInfoDirectiveAfter) { * Tests RenderTemplate Directive received without an audioItemId. Expect that the * sendExceptionEncountered and setFailed will be called. */ -TEST_F(TemplateRuntimeTest, testRenderPlayerInfoDirectiveWithoutAudioItemId) { +TEST_F(TemplateRuntimeTest, test_renderPlayerInfoDirectiveWithoutAudioItemId) { // Create Directive. auto attachmentManager = std::make_shared>(); auto avsMessageHeader = std::make_shared(PLAYER_INFO.nameSpace, PLAYER_INFO.name, MESSAGE_ID); @@ -532,7 +534,7 @@ TEST_F(TemplateRuntimeTest, testRenderPlayerInfoDirectiveWithoutAudioItemId) { * Tests when a malformed RenderTemplate Directive is received. Expect that the * sendExceptionEncountered and setFailed will be called. */ -TEST_F(TemplateRuntimeTest, testMalformedRenderPlayerInfoDirective) { +TEST_F(TemplateRuntimeTest, test_malformedRenderPlayerInfoDirective) { // Create Directive. auto attachmentManager = std::make_shared>(); auto avsMessageHeader = std::make_shared(PLAYER_INFO.nameSpace, PLAYER_INFO.name, MESSAGE_ID); @@ -554,7 +556,7 @@ TEST_F(TemplateRuntimeTest, testMalformedRenderPlayerInfoDirective) { * AUDIO_ITEM_ID is received. Expect that the renderTemplateCard callback will not be called until * the AudioPlayer notified the handling of AUDIO_ITEM_ID later. */ -TEST_F(TemplateRuntimeTest, testRenderPlayerInfoDirectiveDifferentAudioItemId) { +TEST_F(TemplateRuntimeTest, test_renderPlayerInfoDirectiveDifferentAudioItemId) { // Create Directive. auto attachmentManager = std::make_shared>(); auto avsMessageHeader = std::make_shared(PLAYER_INFO.nameSpace, PLAYER_INFO.name, MESSAGE_ID); @@ -589,7 +591,7 @@ TEST_F(TemplateRuntimeTest, testRenderPlayerInfoDirectiveDifferentAudioItemId) { * the payload, audioPlayerState and offset to match to the ones passed in by the * AudioPlayerObserverInterface. */ -TEST_F(TemplateRuntimeTest, testRenderPlayerInfoDirectiveAudioStateUpdate) { +TEST_F(TemplateRuntimeTest, test_renderPlayerInfoDirectiveAudioStateUpdate) { // Create Directive. auto attachmentManager = std::make_shared>(); auto avsMessageHeader = std::make_shared(PLAYER_INFO.nameSpace, PLAYER_INFO.name, MESSAGE_ID); @@ -680,7 +682,7 @@ TEST_F(TemplateRuntimeTest, testRenderPlayerInfoDirectiveAudioStateUpdate) { /** * Tests that if focus is changed to none, the clearTemplateCard() will be called. */ -TEST_F(TemplateRuntimeTest, testFocusNone) { +TEST_F(TemplateRuntimeTest, test_focusNone) { // Create Directive. auto attachmentManager = std::make_shared>(); auto avsMessageHeader = std::make_shared(TEMPLATE.nameSpace, TEMPLATE.name, MESSAGE_ID); @@ -708,7 +710,7 @@ TEST_F(TemplateRuntimeTest, testFocusNone) { /** * Tests that if displayCardCleared() is called, the clearTemplateCard() will not be called. */ -TEST_F(TemplateRuntimeTest, testDisplayCardCleared) { +TEST_F(TemplateRuntimeTest, test_displayCardCleared) { // Create Directive. auto attachmentManager = std::make_shared>(); auto avsMessageHeader = std::make_shared(TEMPLATE.nameSpace, TEMPLATE.name, MESSAGE_ID); @@ -743,7 +745,7 @@ TEST_F(TemplateRuntimeTest, testDisplayCardCleared) { * Tests that if another displayCard event is sent before channel's focus is set to none, the state machine would * transition to REACQUIRING state and acquireChannel again to display the card. */ -TEST_F(TemplateRuntimeTest, testReacquireChannel) { +TEST_F(TemplateRuntimeTest, test_reacquireChannel) { // Create RenderPlayerInfo Directive and wait until PlayerInfo card is displayed. auto attachmentManager = std::make_shared>(); auto avsMessageHeader = std::make_shared(PLAYER_INFO.nameSpace, PLAYER_INFO.name, MESSAGE_ID); @@ -786,6 +788,57 @@ TEST_F(TemplateRuntimeTest, testReacquireChannel) { m_wakeRenderTemplateCardFuture.wait_for(TIMEOUT); } +/** + * Test that we should skip rendering a player info card if the audio has already changed. + */ +TEST_F(TemplateRuntimeTest, testRenderPlayerInfoAfterPlayerActivityChanged) { + // Create Directive. + auto attachmentManager = std::make_shared>(); + auto avsMessageHeader = std::make_shared(PLAYER_INFO.nameSpace, PLAYER_INFO.name, MESSAGE_ID); + std::shared_ptr directive = + AVSDirective::create("", avsMessageHeader, PLAYERINFO_PAYLOAD, attachmentManager, ""); + + AudioPlayerObserverInterface::Context context; + context.audioItemId = AUDIO_ITEM_ID; + m_templateRuntime->onPlayerActivityChanged(avsCommon::avs::PlayerActivity::PLAYING, context); + + ::testing::InSequence s; + EXPECT_CALL(*m_mockFocusManager, acquireChannel(_, _, _)).WillOnce(Return(true)); + // Send a directive first to TemplateRuntime + EXPECT_CALL(*m_mockDirectiveHandlerResult, setCompleted()) + .Times(Exactly(1)) + .WillOnce(InvokeWithoutArgs(this, &TemplateRuntimeTest::wakeOnSetCompleted)); + m_templateRuntime->CapabilityAgent::preHandleDirective(directive, std::move(m_mockDirectiveHandlerResult)); + m_templateRuntime->CapabilityAgent::handleDirective(MESSAGE_ID); + m_wakeSetCompletedFuture.wait_for(TIMEOUT); + + // Test onAudioPlayed() callback with 100ms offset + std::promise wakePlayPromise; + std::future wakePlayFuture = wakePlayPromise.get_future(); + context.offset = std::chrono::milliseconds(100); + EXPECT_CALL(*m_mockGui, renderPlayerInfoCard(PLAYERINFO_PAYLOAD, _, _)).Times(0); + EXPECT_CALL(*m_mockFocusManager, releaseChannel(_, _)).Times(Exactly(1)).WillOnce(InvokeWithoutArgs([this] { + auto releaseChannelSuccess = std::make_shared>(); + std::future returnValue = releaseChannelSuccess->get_future(); + m_templateRuntime->onFocusChanged(avsCommon::avs::FocusState::NONE); + releaseChannelSuccess->set_value(true); + wakeOnReleaseChannel(); + return returnValue; + })); + + m_templateRuntime->CapabilityAgent::preHandleDirective(directive, std::move(m_mockDirectiveHandlerResult)); + m_templateRuntime->CapabilityAgent::handleDirective(MESSAGE_ID); + m_wakeSetCompletedFuture.wait_for(TIMEOUT); + m_wakeRenderTemplateCardFuture.wait_for(TIMEOUT); + m_templateRuntime->displayCardCleared(); + m_wakeReleaseChannelFuture.wait_for(TIMEOUT); + context.audioItemId = AUDIO_ITEM_ID_1; + m_templateRuntime->onPlayerActivityChanged(avsCommon::avs::PlayerActivity::PLAYING, context); + m_templateRuntime->onFocusChanged(avsCommon::avs::FocusState::FOREGROUND); + m_templateRuntime->displayCardCleared(); + m_wakeReleaseChannelFuture.wait_for(TIMEOUT); +} + } // namespace test } // namespace templateRuntime } // namespace capabilityAgents diff --git a/CertifiedSender/include/CertifiedSender/CertifiedSender.h b/CertifiedSender/include/CertifiedSender/CertifiedSender.h index aac3383775..fdb2dd6ff7 100644 --- a/CertifiedSender/include/CertifiedSender/CertifiedSender.h +++ b/CertifiedSender/include/CertifiedSender/CertifiedSender.h @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -139,13 +140,13 @@ class CertifiedSender /// Captures if the @c MessageRequest has been processed or not by AVS. bool m_responseReceived; /// Mutex used to enforce thread safety. - std::mutex m_mutex; + std::mutex m_requestMutex; /// The condition variable used when waiting for the @c MessageRequest to be processed. - std::condition_variable m_cv; + std::condition_variable m_requestCv; /// The database id associated with this @c MessageRequest. int m_dbId; /// A control so we may allow the message to stop waiting to be sent. - bool m_isShuttingDown; + bool m_isRequestShuttingDown; }; /** @@ -199,16 +200,22 @@ class CertifiedSender /// The thread that will actually handle the sending of messages. std::thread m_workerThread; + /// A control so we may disable the worker thread on shutdown. bool m_isShuttingDown; + /// Mutex to protect access to class data members. std::mutex m_mutex; + /// A condition variable with which to notify the worker thread that a new item was added to the queue. std::condition_variable m_workerThreadCV; /// A variable to capture if we are currently connected to AVS. bool m_isConnected; + /// Retry Timer Object for transport. + avsCommon::utils::RetryTimer m_retryTimer; + /// Our queue of requests that should be sent. std::deque> m_messagesToSend; @@ -226,6 +233,9 @@ class CertifiedSender /// Executor to decouple the public-facing api from possibly inefficient persistent storage implementations. avsCommon::utils::threading::Executor m_executor; + + // A condition variable for the main loop to wait for during back-off. + std::condition_variable m_backoffWaitCV; }; } // namespace certifiedSender diff --git a/CertifiedSender/src/CertifiedSender.cpp b/CertifiedSender/src/CertifiedSender.cpp index a401120f9e..70ef45cb3c 100644 --- a/CertifiedSender/src/CertifiedSender.cpp +++ b/CertifiedSender/src/CertifiedSender.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -38,35 +38,46 @@ static const std::string TAG("CertifiedSender"); */ #define LX(event) alexaClientSDK::avsCommon::utils::logger::LogEntry(TAG, event) +/* + * Retry times on subsequent retries for when a message could not be sent to the server over a valid AVS connection. + * These numbers are based on the formula: 10 * 5^n, where n is the number of retries. + */ +static const std::vector EXPONENTIAL_BACKOFF_RETRY_TABLE = { + 10000, // Retry 1: 10s + 50000, // Retry 2: 50s + 250000, // Retry 3: 250s = 4min 10s + 1250000 // Retry 4: 1250s = 20min 50s +}; + CertifiedSender::CertifiedMessageRequest::CertifiedMessageRequest(const std::string& jsonContent, int dbId) : MessageRequest{jsonContent}, m_responseReceived{false}, m_dbId{dbId}, - m_isShuttingDown{false} { + m_isRequestShuttingDown{false} { } void CertifiedSender::CertifiedMessageRequest::exceptionReceived(const std::string& exceptionMessage) { - std::lock_guard lock(m_mutex); + std::lock_guard lock(m_requestMutex); m_sendMessageStatus = MessageRequestObserverInterface::Status::SERVER_INTERNAL_ERROR_V2; m_responseReceived = true; - m_cv.notify_all(); + m_requestCv.notify_all(); } void CertifiedSender::CertifiedMessageRequest::sendCompleted( MessageRequestObserverInterface::Status sendMessageStatus) { - std::lock_guard lock(m_mutex); + std::lock_guard lock(m_requestMutex); if (!m_responseReceived) { m_sendMessageStatus = sendMessageStatus; m_responseReceived = true; - m_cv.notify_all(); + m_requestCv.notify_all(); } } MessageRequestObserverInterface::Status CertifiedSender::CertifiedMessageRequest::waitForCompletion() { - std::unique_lock lock(m_mutex); - m_cv.wait(lock, [this]() { return m_isShuttingDown || m_responseReceived; }); + std::unique_lock lock(m_requestMutex); + m_requestCv.wait(lock, [this]() { return m_isRequestShuttingDown || m_responseReceived; }); - if (m_isShuttingDown) { + if (m_isRequestShuttingDown) { return MessageRequestObserverInterface::Status::TIMEDOUT; } @@ -78,9 +89,9 @@ int CertifiedSender::CertifiedMessageRequest::getDbId() { } void CertifiedSender::CertifiedMessageRequest::shutdown() { - std::lock_guard lock(m_mutex); - m_isShuttingDown = true; - m_cv.notify_all(); + std::lock_guard lock(m_requestMutex); + m_isRequestShuttingDown = true; + m_requestCv.notify_all(); } std::shared_ptr CertifiedSender::create( @@ -114,6 +125,7 @@ CertifiedSender::CertifiedSender( m_queueSizeHardLimit{queueSizeHardLimit}, m_isShuttingDown{false}, m_isConnected{false}, + m_retryTimer(EXPONENTIAL_BACKOFF_RETRY_TABLE), m_messageSender{messageSender}, m_connection{connection}, m_storage{storage} { @@ -128,6 +140,7 @@ CertifiedSender::~CertifiedSender() { lock.unlock(); m_workerThreadCV.notify_one(); + m_backoffWaitCV.notify_one(); if (m_workerThread.joinable()) { m_workerThread.join(); @@ -156,7 +169,37 @@ bool CertifiedSender::init() { return true; } +/** + * A function to evaluate if the given status suggests that the client should retry sending the message. + * + * @param status The status being queried. + * @return Whether the status means the client should keep retrying. + */ +inline bool shouldRetryTransmission(MessageRequestObserverInterface::Status status) { + switch (status) { + case MessageRequestObserverInterface::Status::SUCCESS: + case MessageRequestObserverInterface::Status::SUCCESS_NO_CONTENT: + case MessageRequestObserverInterface::Status::SERVER_INTERNAL_ERROR_V2: + case MessageRequestObserverInterface::Status::CANCELED: + case MessageRequestObserverInterface::Status::SERVER_OTHER_ERROR: + case MessageRequestObserverInterface::Status::BAD_REQUEST: + return false; + case MessageRequestObserverInterface::Status::THROTTLED: + case MessageRequestObserverInterface::Status::PENDING: + case MessageRequestObserverInterface::Status::NOT_CONNECTED: + case MessageRequestObserverInterface::Status::NOT_SYNCHRONIZED: + case MessageRequestObserverInterface::Status::TIMEDOUT: + case MessageRequestObserverInterface::Status::PROTOCOL_ERROR: + case MessageRequestObserverInterface::Status::INTERNAL_ERROR: + case MessageRequestObserverInterface::Status::REFUSED: + case MessageRequestObserverInterface::Status::INVALID_AUTH: + return true; + } + return false; +} + void CertifiedSender::mainloop() { + int failedSendRetryCount = 0; while (true) { std::unique_lock lock(m_mutex); @@ -168,7 +211,7 @@ void CertifiedSender::mainloop() { } if (m_isShuttingDown) { - ACSDK_DEBUG9(LX("CertifiedSender worker thread done. exiting mainloop.")); + ACSDK_DEBUG9(LX("CertifiedSender worker thread done. Exiting mainloop.")); return; } @@ -181,16 +224,7 @@ void CertifiedSender::mainloop() { auto status = m_currentMessage->waitForCompletion(); - if (MessageRequest::isServerStatus(status)) { - lock.lock(); - - if (!m_storage->erase(m_currentMessage->getDbId())) { - ACSDK_ERROR(LX("mainloop : could not erase message from storage.")); - } - - m_messagesToSend.pop_front(); - lock.unlock(); - } else { + if (shouldRetryTransmission(status)) { // If we couldn't send the message ok, let's push a fresh instance to the front of the deque. This allows // ACL to continue interacting with the old instance (for example, if it is involved in a complex flow // of exception / onCompleted handling), and allows us to safely try sending the new instance. @@ -199,6 +233,36 @@ void CertifiedSender::mainloop() { m_messagesToSend.push_front(std::make_shared( m_currentMessage->getJsonContent(), m_currentMessage->getDbId())); lock.unlock(); + + // Ensures that we do not DDOS the AVS endpoint, just in case we have a valid AVS connection but + // the server is returning some non-server HTTP error. + auto timeout = m_retryTimer.calculateTimeToRetry(failedSendRetryCount); + ACSDK_DEBUG5(LX(__func__).d("failedSendRetryCount", failedSendRetryCount).d("timeout", timeout.count())); + + failedSendRetryCount++; + + lock.lock(); + m_backoffWaitCV.wait_for(lock, timeout, [this]() { return m_isShuttingDown; }); + if (m_isShuttingDown) { + ACSDK_DEBUG9(LX("CertifiedSender worker thread done. Exiting mainloop.")); + return; + } + lock.unlock(); + } else { + /* + * We should not retry to send the message (either because it was sent successfully or because trying again + * is not expected to solve the issue) + */ + lock.lock(); + + if (!m_storage->erase(m_currentMessage->getDbId())) { + ACSDK_ERROR(LX("mainloop : could not erase message from storage.")); + } + + m_messagesToSend.pop_front(); + lock.unlock(); + // Resetting the fail count. + failedSendRetryCount = 0; } } } @@ -206,8 +270,9 @@ void CertifiedSender::mainloop() { void CertifiedSender::onConnectionStatusChanged( ConnectionStatusObserverInterface::Status status, ConnectionStatusObserverInterface::ChangedReason reason) { - std::lock_guard lock(m_mutex); + std::unique_lock lock(m_mutex); m_isConnected = (ConnectionStatusObserverInterface::Status::CONNECTED == status); + lock.unlock(); m_workerThreadCV.notify_one(); } diff --git a/CertifiedSender/test/CertifiedSenderTest.cpp b/CertifiedSender/test/CertifiedSenderTest.cpp index ec6b6b170c..2d8f559cd6 100644 --- a/CertifiedSender/test/CertifiedSenderTest.cpp +++ b/CertifiedSender/test/CertifiedSenderTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -99,7 +99,7 @@ class CertifiedSenderTest : public ::testing::Test { /** * Check that @c clearData() method clears the persistent message storage and the current msg queue */ -TEST_F(CertifiedSenderTest, clearDataTest) { +TEST_F(CertifiedSenderTest, test_clearData) { EXPECT_CALL(*m_storage, clearDatabase()).Times(1); m_certifiedSender->clearData(); } diff --git a/CertifiedSender/test/MessageStorageTest.cpp b/CertifiedSender/test/MessageStorageTest.cpp index db13767d8f..c20671e20f 100644 --- a/CertifiedSender/test/MessageStorageTest.cpp +++ b/CertifiedSender/test/MessageStorageTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -106,14 +106,14 @@ static bool isOpen(const std::shared_ptr& storage) { /** * Test basic construction. Database should not be open. */ -TEST_F(MessageStorageTest, testConstructionAndDestruction) { +TEST_F(MessageStorageTest, test_constructionAndDestruction) { ASSERT_FALSE(isOpen(m_storage)); } /** * Test database creation. */ -TEST_F(MessageStorageTest, testDatabaseCreation) { +TEST_F(MessageStorageTest, test_databaseCreation) { ASSERT_FALSE(isOpen(m_storage)); createDatabase(); ASSERT_TRUE(isOpen(m_storage)); @@ -122,7 +122,7 @@ TEST_F(MessageStorageTest, testDatabaseCreation) { /** * Test opening and closing a database. */ -TEST_F(MessageStorageTest, testOpenAndCloseDatabase) { +TEST_F(MessageStorageTest, test_openAndCloseDatabase) { ASSERT_FALSE(isOpen(m_storage)); createDatabase(); ASSERT_TRUE(isOpen(m_storage)); @@ -137,7 +137,7 @@ TEST_F(MessageStorageTest, testOpenAndCloseDatabase) { /** * Test storing records in the database. */ -TEST_F(MessageStorageTest, testDatabaseStoreAndLoad) { +TEST_F(MessageStorageTest, test_databaseStoreAndLoad) { createDatabase(); ASSERT_TRUE(isOpen(m_storage)); @@ -172,7 +172,7 @@ TEST_F(MessageStorageTest, testDatabaseStoreAndLoad) { /** * Test erasing a record from the database. */ -TEST_F(MessageStorageTest, testDatabaseErase) { +TEST_F(MessageStorageTest, test_databaseErase) { createDatabase(); ASSERT_TRUE(isOpen(m_storage)); @@ -204,7 +204,7 @@ TEST_F(MessageStorageTest, testDatabaseErase) { /** * Test clearing the database. */ -TEST_F(MessageStorageTest, testDatabaseClear) { +TEST_F(MessageStorageTest, test_databaseClear) { createDatabase(); ASSERT_TRUE(isOpen(m_storage)); diff --git a/ContextManager/test/ContextManagerTest.cpp b/ContextManager/test/ContextManagerTest.cpp index 59e7dc8e44..926b27a7fc 100644 --- a/ContextManager/test/ContextManagerTest.cpp +++ b/ContextManager/test/ContextManagerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -561,7 +561,7 @@ void ContextManagerTest::SetUp() { * Set the state with a @c StateRefreshPolicy @c ALWAYS for a @c StateProviderInterface that is registered with the * @c ContextManager. Expect @c SetStateResult @c SUCCESS is returned. */ -TEST_F(ContextManagerTest, testSetStateForRegisteredProvider) { +TEST_F(ContextManagerTest, test_setStateForRegisteredProvider) { ASSERT_EQ( SetStateResult::SUCCESS, m_contextManager->setState( @@ -575,7 +575,7 @@ TEST_F(ContextManagerTest, testSetStateForRegisteredProvider) { * Set the state with a @c StateRefreshPolicy @c NEVER for a @c StateProviderInterface that is not registered with the * @c ContextManager. Expect @c SetStateResult @c SUCCESS is returned. */ -TEST_F(ContextManagerTest, testSetStateForUnregisteredProvider) { +TEST_F(ContextManagerTest, test_setStateForUnregisteredProvider) { ASSERT_EQ(SetStateResult::SUCCESS, m_contextManager->setState(ALERTS, ALERTS_PAYLOAD, StateRefreshPolicy::NEVER)); } @@ -583,7 +583,7 @@ TEST_F(ContextManagerTest, testSetStateForUnregisteredProvider) { * Set the state with a @c StateRefreshPolicy @c ALWAYS for a @c StateProviderInterface that is not registered with * the @c ContextManager. Expect @c SetStateResult @c STATE_PROVIDER_NOT_REGISTERED is returned. */ -TEST_F(ContextManagerTest, testSetStateForUnregisteredProviderWithRefreshPolicyAlways) { +TEST_F(ContextManagerTest, test_setStateForUnregisteredProviderWithRefreshPolicyAlways) { m_alerts = MockStateProvider::create( m_contextManager, ALERTS, ALERTS_PAYLOAD, StateRefreshPolicy::NEVER, DEFAULT_SLEEP_TIME); ASSERT_EQ( @@ -597,7 +597,7 @@ TEST_F(ContextManagerTest, testSetStateForUnregisteredProviderWithRefreshPolicyA * @c ContextManager. Request for context by calling @c getContext. Expect that the context is returned within the * timeout period. Check the context that is returned by the @c ContextManager. Expect it should match the test value. */ -TEST_F(ContextManagerTest, testGetContext) { +TEST_F(ContextManagerTest, test_getContext) { ASSERT_EQ( SetStateResult::SUCCESS, m_contextManager->setState( @@ -622,7 +622,7 @@ TEST_F(ContextManagerTest, testGetContext) { * @c ContextManager. Request for context by calling @c getContext by multiple requesters. Expect that the context is * returned to each of the requesters within the timeout period. */ -TEST_F(ContextManagerTest, testMultipleGetContextRequests) { +TEST_F(ContextManagerTest, test_multipleGetContextRequests) { ASSERT_EQ( SetStateResult::SUCCESS, m_contextManager->setState( @@ -655,7 +655,7 @@ TEST_F(ContextManagerTest, testMultipleGetContextRequests) { * Request for context by calling @c getContext. Expect that the context is returned within the * timeout period. Check the context that is returned by the @c ContextManager matches the test context. */ -TEST_F(ContextManagerTest, testSetProviderTwice) { +TEST_F(ContextManagerTest, test_setProviderTwice) { ASSERT_EQ( SetStateResult::SUCCESS, m_contextManager->setState( @@ -692,7 +692,7 @@ TEST_F(ContextManagerTest, testSetProviderTwice) { * Set the states with a @c StateRefreshPolicy @c ALWAYS for @c StateProviderInterfaces. Request for context by calling * @c getContext. Expect that failure occurs due to timeout. */ -TEST_F(ContextManagerTest, testProvideStateTimeout) { +TEST_F(ContextManagerTest, test_provideStateTimeout) { m_alerts = MockStateProvider::create( m_contextManager, ALERTS, ALERTS_PAYLOAD, StateRefreshPolicy::NEVER, TIMEOUT_SLEEP_TIME); m_contextManager->setStateProvider(ALERTS, m_alerts); @@ -723,7 +723,7 @@ TEST_F(ContextManagerTest, testProvideStateTimeout) { * @c StateRefreshPolicy @c ALWAYS for the @c StateProviderInterface that was unregistered. Expect @c SetStateResult * @c STATE_PROVIDER_NOT_REGISTERED is returned. */ -TEST_F(ContextManagerTest, testRemoveProvider) { +TEST_F(ContextManagerTest, test_removeProvider) { m_contextManager->setStateProvider(SPEECH_SYNTHESIZER, nullptr); ASSERT_EQ( SetStateResult::STATE_PROVIDER_NOT_REGISTERED, @@ -739,7 +739,7 @@ TEST_F(ContextManagerTest, testRemoveProvider) { * that is registered with the @c ContextManager with a wrong token value. Expect that * @c SetStateResult @c STATE_TOKEN_OUTDATED is returned. */ -TEST_F(ContextManagerTest, testIncorrectToken) { +TEST_F(ContextManagerTest, test_incorrectToken) { m_contextManager->getContext(m_contextRequester); ASSERT_TRUE(m_contextRequester->waitForContext(DEFAULT_TIMEOUT)); ASSERT_EQ( @@ -761,7 +761,7 @@ TEST_F(ContextManagerTest, testIncorrectToken) { * * Check the context that is returned by the @c ContextManager. Expect it should match the test value. */ -TEST_F(ContextManagerTest, testEmptyProvider) { +TEST_F(ContextManagerTest, test_emptyProvider) { auto dummyProvider = MockStateProvider::create( m_contextManager, DUMMY_PROVIDER, "", StateRefreshPolicy::SOMETIMES, DEFAULT_SLEEP_TIME); m_contextManager->setStateProvider(DUMMY_PROVIDER, dummyProvider); diff --git a/EqualizerImplementations/test/EqualizerControllerTest.cpp b/EqualizerImplementations/test/EqualizerControllerTest.cpp index 4c89c73a34..66b6ff1d0c 100644 --- a/EqualizerImplementations/test/EqualizerControllerTest.cpp +++ b/EqualizerImplementations/test/EqualizerControllerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -100,7 +100,7 @@ void EqualizerControllerTest::SetUp() { } // Test internal state right after controller creation -TEST_F(EqualizerControllerTest, providedEmptyConfig_shouldUseDefaults) { +TEST_F(EqualizerControllerTest, test_providedEmptyConfig_shouldUseDefaults) { auto controller = EqualizerController::create(m_modeController, m_configuration, m_storage); auto configuration = controller->getConfiguration(); @@ -127,7 +127,7 @@ TEST_F(EqualizerControllerTest, providedEmptyConfig_shouldUseDefaults) { } // Test simple changes -TEST_F(EqualizerControllerTest, changeBandLevels_shouldSucceed) { +TEST_F(EqualizerControllerTest, test_changeBandLevels_shouldSucceed) { auto controller = EqualizerController::create(m_modeController, m_configuration, m_storage); controller->setBandLevel(EqualizerBand::TREBLE, NON_DEFAULT_TREBLE); @@ -150,7 +150,7 @@ TEST_F(EqualizerControllerTest, changeBandLevels_shouldSucceed) { } // Test simple changes with invalid levels -TEST_F(EqualizerControllerTest, setInvalidBandLevels_shouldClampToSupportedRange) { +TEST_F(EqualizerControllerTest, test_setInvalidBandLevels_shouldClampToSupportedRange) { auto controller = EqualizerController::create(m_modeController, m_configuration, m_storage); controller->setBandLevel(EqualizerBand::TREBLE, BELOW_MIN_LEVEL); @@ -169,7 +169,7 @@ TEST_F(EqualizerControllerTest, setInvalidBandLevels_shouldClampToSupportedRange } // Test mode changes -TEST_F(EqualizerControllerTest, setMode_shouldSucceed) { +TEST_F(EqualizerControllerTest, test_setMode_shouldSucceed) { auto controller = EqualizerController::create(m_modeController, m_configuration, m_storage); controller->setCurrentMode(EqualizerMode::NIGHT); @@ -179,7 +179,7 @@ TEST_F(EqualizerControllerTest, setMode_shouldSucceed) { } // Test invalid modes -TEST_F(EqualizerControllerTest, setInvalidMode_shouldNotChangeMode) { +TEST_F(EqualizerControllerTest, test_setInvalidMode_shouldNotChangeMode) { auto controller = EqualizerController::create(m_modeController, m_configuration, m_storage); controller->setCurrentMode(EqualizerMode::MOVIE); @@ -189,7 +189,7 @@ TEST_F(EqualizerControllerTest, setInvalidMode_shouldNotChangeMode) { } // Test single listener reaction on band level changes -TEST_F(EqualizerControllerTest, providedBandLevelChanges_addRemoveListener_shouldFollowSubscriptionStatus) { +TEST_F(EqualizerControllerTest, test_providedBandLevelChanges_addRemoveListener_shouldFollowSubscriptionStatus) { auto controller = EqualizerController::create(m_modeController, m_configuration, m_storage); auto listener = std::make_shared>(); @@ -222,7 +222,7 @@ TEST_F(EqualizerControllerTest, providedBandLevelChanges_addRemoveListener_shoul } // Test single listener reaction on mode changes -TEST_F(EqualizerControllerTest, providedModeChanges_addRemoveListener_shouldFollowSubscriptionStatus) { +TEST_F(EqualizerControllerTest, test_providedModeChanges_addRemoveListener_shouldFollowSubscriptionStatus) { auto controller = EqualizerController::create(m_modeController, m_configuration, m_storage); auto listener = std::make_shared>(); @@ -250,7 +250,9 @@ TEST_F(EqualizerControllerTest, providedModeChanges_addRemoveListener_shouldFoll } // Test multiple listeners reaction on changes -TEST_F(EqualizerControllerTest, providedBandLevelChanges_addRemoveMultipleListeners_shouldFollowSubscriptionStatus) { +TEST_F( + EqualizerControllerTest, + test_providedBandLevelChanges_addRemoveMultipleListeners_shouldFollowSubscriptionStatus) { auto controller = EqualizerController::create(m_modeController, m_configuration, m_storage); // Variables to hold state reported by onEqualizerStateChanged() @@ -283,7 +285,7 @@ TEST_F(EqualizerControllerTest, providedBandLevelChanges_addRemoveMultipleListen } // Test the synchronous nature of callbacks -TEST_F(EqualizerControllerTest, triggerChangesMultipleTimes_ExpectListenersNotifiedSameTimes) { +TEST_F(EqualizerControllerTest, test_triggerChangesMultipleTimes_ExpectListenersNotifiedSameTimes) { auto controller = EqualizerController::create(m_modeController, m_configuration, m_storage); auto listener = std::make_shared>(); @@ -300,7 +302,7 @@ TEST_F(EqualizerControllerTest, triggerChangesMultipleTimes_ExpectListenersNotif } // Test single equalizer registrations -TEST_F(EqualizerControllerTest, providedBandLevelChanges_addRemoveSingleEqualizer_shouldFollowRegistrationStatus) { +TEST_F(EqualizerControllerTest, test_providedBandLevelChanges_addRemoveSingleEqualizer_shouldFollowRegistrationStatus) { auto controller = EqualizerController::create(m_modeController, m_configuration, m_storage); auto equalizer = std::make_shared>(); @@ -324,7 +326,9 @@ TEST_F(EqualizerControllerTest, providedBandLevelChanges_addRemoveSingleEqualize } // Test multiple equalizer registrations -TEST_F(EqualizerControllerTest, providedBandLevelChanges_addRemoveMultipleEqualizers_shouldFollowRegistrationStatus) { +TEST_F( + EqualizerControllerTest, + test_providedBandLevelChanges_addRemoveMultipleEqualizers_shouldFollowRegistrationStatus) { auto controller = EqualizerController::create(m_modeController, m_configuration, m_storage); auto equalizer1 = std::make_shared>(); @@ -359,7 +363,7 @@ TEST_F(EqualizerControllerTest, providedBandLevelChanges_addRemoveMultipleEquali } // Test synchronous nature of equalizer handling -TEST_F(EqualizerControllerTest, triggerChangesMultipleTimes_ExpectEqualizersCalledSameTimes) { +TEST_F(EqualizerControllerTest, test_triggerChangesMultipleTimes_ExpectEqualizersCalledSameTimes) { auto controller = EqualizerController::create(m_modeController, m_configuration, m_storage); auto equalizer = std::make_shared>(); @@ -376,7 +380,7 @@ TEST_F(EqualizerControllerTest, triggerChangesMultipleTimes_ExpectEqualizersCall } // Test persistent storage operations -TEST_F(EqualizerControllerTest, saveLoadStateWithPersistentStorage_shouldSucceed) { +TEST_F(EqualizerControllerTest, test_saveLoadStateWithPersistentStorage_shouldSucceed) { EXPECT_CALL(*(m_storage.get()), loadState()).Times(1); auto controller = EqualizerController::create(m_modeController, m_configuration, m_storage); @@ -396,7 +400,7 @@ TEST_F(EqualizerControllerTest, saveLoadStateWithPersistentStorage_shouldSucceed controller->setCurrentMode(EqualizerMode::TV); } -TEST_F(EqualizerControllerTest, setLevelBelowEqualizerMinimum_shouldClamp) { +TEST_F(EqualizerControllerTest, test_setLevelBelowEqualizerMinimum_shouldClamp) { EXPECT_CALL(*(m_storage.get()), loadState()).Times(1); auto controller = EqualizerController::create(m_modeController, m_configuration, m_storage); @@ -413,7 +417,7 @@ TEST_F(EqualizerControllerTest, setLevelBelowEqualizerMinimum_shouldClamp) { EXPECT_EQ(bandLevelMap[EqualizerBand::MIDRANGE], MAX_LEVEL); } -TEST_F(EqualizerControllerTest, setLevelAboveEqualizerMaximum_shouldClamp) { +TEST_F(EqualizerControllerTest, test_setLevelAboveEqualizerMaximum_shouldClamp) { EXPECT_CALL(*(m_storage.get()), loadState()).Times(1); auto controller = EqualizerController::create(m_modeController, m_configuration, m_storage); diff --git a/EqualizerImplementations/test/EqualizerLinearBandMapperTest.cpp b/EqualizerImplementations/test/EqualizerLinearBandMapperTest.cpp index 7aecfa1582..8731f4cbe0 100644 --- a/EqualizerImplementations/test/EqualizerLinearBandMapperTest.cpp +++ b/EqualizerImplementations/test/EqualizerLinearBandMapperTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -86,13 +86,13 @@ void EqualizerLinearBandMapperTest::testAllValuesEqual(int numberOfBands, int va } /// Valid parameters -TEST_F(EqualizerLinearBandMapperTest, givenValidParameters_create_shouldSucceed) { +TEST_F(EqualizerLinearBandMapperTest, test_givenValidParameters_create_shouldSucceed) { auto bandMapper = EqualizerLinearBandMapper::create(VALID_NUMBER_OF_BANDS); EXPECT_THAT(bandMapper, NotNull()); } /// Invalid parameters -TEST_F(EqualizerLinearBandMapperTest, givenInvalidParameters_create_shouldFail) { +TEST_F(EqualizerLinearBandMapperTest, test_givenInvalidParameters_create_shouldFail) { auto bandMapper = EqualizerLinearBandMapper::create(INVALID_NUMBER_OF_BANDS_BELOW); EXPECT_THAT(bandMapper, IsNull()); @@ -101,7 +101,7 @@ TEST_F(EqualizerLinearBandMapperTest, givenInvalidParameters_create_shouldFail) } /// Test mapping AVS bands to the same number of bands. No value must be modified. -TEST_F(EqualizerLinearBandMapperTest, givenSameAsAVSBands_map_shouldNotModifyLevels) { +TEST_F(EqualizerLinearBandMapperTest, test_givenSameAsAVSBands_map_shouldNotModifyLevels) { auto numberOfAVSBands = EqualizerBandValues.size(); auto bandMapper = EqualizerLinearBandMapper::create(numberOfAVSBands); @@ -119,53 +119,53 @@ TEST_F(EqualizerLinearBandMapperTest, givenSameAsAVSBands_map_shouldNotModifyLev } /// AVS bands < target bands. Mapping non-zero value. -TEST_F(EqualizerLinearBandMapperTest, givenMoreBandsToMapTo_mapAllSameNonZero_shouldMapToSame) { +TEST_F(EqualizerLinearBandMapperTest, test_givenMoreBandsToMapTo_mapAllSameNonZero_shouldMapToSame) { int numberOfAVSBands = EqualizerBandValues.size(); testAllValuesEqual(numberOfAVSBands + 1, BAND_LEVEL_TOP); } /// AVS bands < target bands. Mapping zero value. -TEST_F(EqualizerLinearBandMapperTest, givenMoreBandsToMapTo_mapAllSameZero_shouldMapToSame) { +TEST_F(EqualizerLinearBandMapperTest, test_givenMoreBandsToMapTo_mapAllSameZero_shouldMapToSame) { int numberOfAVSBands = EqualizerBandValues.size(); testAllValuesEqual(numberOfAVSBands + 1, BAND_LEVEL_ZERO); } /// AVS bands * 2 = target bands. Mapping non-zero value. No averaged bands. -TEST_F(EqualizerLinearBandMapperTest, givenDoubleBandsToMapTo_mapAllSameNonZero_shouldMapToSame) { +TEST_F(EqualizerLinearBandMapperTest, test_givenDoubleBandsToMapTo_mapAllSameNonZero_shouldMapToSame) { int numberOfAVSBands = EqualizerBandValues.size(); testAllValuesEqual(numberOfAVSBands * 2, BAND_LEVEL_TOP); } /// AVS bands * 2 = target bands. Mapping zero value. No averaged bands. -TEST_F(EqualizerLinearBandMapperTest, givenDoubleBandsToMapTo_mapAllSameZero_shouldMapToSame) { +TEST_F(EqualizerLinearBandMapperTest, test_givenDoubleBandsToMapTo_mapAllSameZero_shouldMapToSame) { int numberOfAVSBands = EqualizerBandValues.size(); testAllValuesEqual(numberOfAVSBands * 2, BAND_LEVEL_ZERO); } /// AVS bands > target bands. Mapping non-zero value. -TEST_F(EqualizerLinearBandMapperTest, givenLessBandsToMapTo_mapAllSameNonZero_shouldMapToSame) { +TEST_F(EqualizerLinearBandMapperTest, test_givenLessBandsToMapTo_mapAllSameNonZero_shouldMapToSame) { int numberOfAVSBands = EqualizerBandValues.size(); testAllValuesEqual(numberOfAVSBands - 1, BAND_LEVEL_TOP); } /// AVS bands > target bands. Mapping zero value. -TEST_F(EqualizerLinearBandMapperTest, givenLessBandsToMapTo_mapAllSameZero_shouldMapToSame) { +TEST_F(EqualizerLinearBandMapperTest, test_givenLessBandsToMapTo_mapAllSameZero_shouldMapToSame) { int numberOfAVSBands = EqualizerBandValues.size(); testAllValuesEqual(numberOfAVSBands - 1, BAND_LEVEL_ZERO); } /// Mapping AVS bands to 1 target band. Non-zero value. -TEST_F(EqualizerLinearBandMapperTest, givenOneBandToMapTo_mapNonZero_shouldMapToSame) { +TEST_F(EqualizerLinearBandMapperTest, test_givenOneBandToMapTo_mapNonZero_shouldMapToSame) { testAllValuesEqual(1, BAND_LEVEL_TOP); } /// Mapping AVS bands to 1 target band. Zero value. -TEST_F(EqualizerLinearBandMapperTest, givenOneBandToMapTo_mapZero_shouldMapToSame) { +TEST_F(EqualizerLinearBandMapperTest, test_givenOneBandToMapTo_mapZero_shouldMapToSame) { testAllValuesEqual(1, BAND_LEVEL_ZERO); } /// Since mapper has a linear nature mapped values must keep the same average as original ones. Testing this here. -TEST_F(EqualizerLinearBandMapperTest, givenAnyNumberOfBands_map_shouldKeepAverageLevel) { +TEST_F(EqualizerLinearBandMapperTest, test_givenAnyNumberOfBands_map_shouldKeepAverageLevel) { int numberOfAVSBands = EqualizerBandValues.size(); for (int targetBandsCount = 1; targetBandsCount < numberOfAVSBands * 10; targetBandsCount++) { @@ -191,7 +191,7 @@ TEST_F(EqualizerLinearBandMapperTest, givenAnyNumberOfBands_map_shouldKeepAverag } /// Test specific transformation. This test depends on current number of bands supported by AVS. -TEST_F(EqualizerLinearBandMapperTest, givenMoreBandsToMapTo_mapSpecificValues_shouldMapToSpecificOutput) { +TEST_F(EqualizerLinearBandMapperTest, test_givenMoreBandsToMapTo_mapSpecificValues_shouldMapToSpecificOutput) { int numberOfAVSBands = EqualizerBandValues.size(); ASSERT_EQ(numberOfAVSBands, CURRENT_NUMBER_OF_AVS_BANDS); @@ -215,7 +215,7 @@ TEST_F(EqualizerLinearBandMapperTest, givenMoreBandsToMapTo_mapSpecificValues_sh } /// Test specific transformation. This test depends on current number of bands supported by AVS. -TEST_F(EqualizerLinearBandMapperTest, givenEvenMoreBandsToMapTo_mapSpecificValues_shouldMapToSpecificOutput) { +TEST_F(EqualizerLinearBandMapperTest, test_givenEvenMoreBandsToMapTo_mapSpecificValues_shouldMapToSpecificOutput) { int numberOfAVSBands = EqualizerBandValues.size(); ASSERT_EQ(numberOfAVSBands, CURRENT_NUMBER_OF_AVS_BANDS); @@ -240,7 +240,7 @@ TEST_F(EqualizerLinearBandMapperTest, givenEvenMoreBandsToMapTo_mapSpecificValue } /// Test specific transformation. This test depends on current number of bands supported by AVS. -TEST_F(EqualizerLinearBandMapperTest, givenLessBandsToMapTo_mapSpecificValues_shouldMapToSpecificOutput) { +TEST_F(EqualizerLinearBandMapperTest, test_givenLessBandsToMapTo_mapSpecificValues_shouldMapToSpecificOutput) { int numberOfAVSBands = EqualizerBandValues.size(); ASSERT_EQ(numberOfAVSBands, CURRENT_NUMBER_OF_AVS_BANDS); @@ -262,7 +262,7 @@ TEST_F(EqualizerLinearBandMapperTest, givenLessBandsToMapTo_mapSpecificValues_sh } /// Test specific transformation. This test depends on current number of bands supported by AVS. -TEST_F(EqualizerLinearBandMapperTest, givenEvenLessBandsToMapTo_mapSpecificValues_shouldMapToSpecificOutput) { +TEST_F(EqualizerLinearBandMapperTest, test_givenEvenLessBandsToMapTo_mapSpecificValues_shouldMapToSpecificOutput) { int numberOfAVSBands = EqualizerBandValues.size(); ASSERT_EQ(numberOfAVSBands, CURRENT_NUMBER_OF_AVS_BANDS); @@ -283,7 +283,7 @@ TEST_F(EqualizerLinearBandMapperTest, givenEvenLessBandsToMapTo_mapSpecificValue } /// -TEST_F(EqualizerLinearBandMapperTest, givenOneBandSupported_mapToOneBand_shouldMapSameValue) { +TEST_F(EqualizerLinearBandMapperTest, test_givenOneBandSupported_mapToOneBand_shouldMapSameValue) { EqualizerBandLevelMap bandLevelMap = {{EqualizerBand::BASS, BAND_LEVEL_BOTTOM}}; std::array mappedValues{}; @@ -296,7 +296,7 @@ TEST_F(EqualizerLinearBandMapperTest, givenOneBandSupported_mapToOneBand_shouldM EXPECT_EQ(mappedValues[0], BAND_LEVEL_BOTTOM); } -TEST_F(EqualizerLinearBandMapperTest, givenOneBandSupported_mapToTwoBands_shouldMapToBothSame) { +TEST_F(EqualizerLinearBandMapperTest, test_givenOneBandSupported_mapToTwoBands_shouldMapToBothSame) { EqualizerBandLevelMap bandLevelMap = {{EqualizerBand::BASS, BAND_LEVEL_BOTTOM}}; std::array mappedValues{}; @@ -310,7 +310,7 @@ TEST_F(EqualizerLinearBandMapperTest, givenOneBandSupported_mapToTwoBands_should EXPECT_EQ(mappedValues[1], BAND_LEVEL_BOTTOM); } -TEST_F(EqualizerLinearBandMapperTest, givenTwoBandsSupported_mapToOneBands_shouldMapToAverage) { +TEST_F(EqualizerLinearBandMapperTest, test_givenTwoBandsSupported_mapToOneBands_shouldMapToAverage) { EqualizerBandLevelMap bandLevelMap = {{EqualizerBand::BASS, BAND_LEVEL_BOTTOM}, {EqualizerBand::MIDRANGE, BAND_LEVEL_ZERO}}; diff --git a/EqualizerImplementations/test/InMemoryEqualizerConfigurationTest.cpp b/EqualizerImplementations/test/InMemoryEqualizerConfigurationTest.cpp index 4489ad8ad9..9e9a7335a2 100644 --- a/EqualizerImplementations/test/InMemoryEqualizerConfigurationTest.cpp +++ b/EqualizerImplementations/test/InMemoryEqualizerConfigurationTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -78,35 +78,35 @@ EqualizerState InMemoryEqualizerConfigurationTest::getDefaultState() { } /// Simple successful case -TEST_F(InMemoryEqualizerConfigurationTest, providedValidParameters_createInstance_shouldSucceed) { +TEST_F(InMemoryEqualizerConfigurationTest, test_providedValidParameters_createInstance_shouldSucceed) { m_configuration = InMemoryEqualizerConfiguration::create( MIN_LEVEL, MAX_LEVEL, getDefaultBands(), getDefaultModes(), getDefaultState()); ASSERT_THAT(m_configuration, NotNull()); } /// Min level > Max level -TEST_F(InMemoryEqualizerConfigurationTest, providedInalidLevelRange_createInstance_shouldFail) { +TEST_F(InMemoryEqualizerConfigurationTest, test_providedInalidLevelRange_createInstance_shouldFail) { m_configuration = InMemoryEqualizerConfiguration::create( MAX_LEVEL, MIN_LEVEL, getDefaultBands(), getDefaultModes(), getDefaultState()); ASSERT_THAT(m_configuration, IsNull()); } /// Min and Max are equal (DEFAULT_LEVEL), must succeed -TEST_F(InMemoryEqualizerConfigurationTest, providedMixMaxLevelSetToDefault_createInstance_shouldSucceed) { +TEST_F(InMemoryEqualizerConfigurationTest, test_providedMixMaxLevelSetToDefault_createInstance_shouldSucceed) { m_configuration = InMemoryEqualizerConfiguration::create( DEFAULT_LEVEL, DEFAULT_LEVEL, getDefaultBands(), getDefaultModes(), getDefaultState()); ASSERT_THAT(m_configuration, NotNull()); } /// Min and Max are equal (non-DEFAULT_LEVEL), must fail because all modes use DEFAULT_LEVEL as band levels. -TEST_F(InMemoryEqualizerConfigurationTest, providedSameNonDefaultMixMaxLevel_createInstance_shouldSucceed) { +TEST_F(InMemoryEqualizerConfigurationTest, test_providedSameNonDefaultMixMaxLevel_createInstance_shouldSucceed) { m_configuration = InMemoryEqualizerConfiguration::create( MAX_LEVEL, MAX_LEVEL, getDefaultBands(), getDefaultModes(), getDefaultState()); ASSERT_THAT(m_configuration, IsNull()); } /// Invalid band value in default state (above max) -TEST_F(InMemoryEqualizerConfigurationTest, providedDefaultStateLevelAboveMax_createInstance_shouldFail) { +TEST_F(InMemoryEqualizerConfigurationTest, test_providedDefaultStateLevelAboveMax_createInstance_shouldFail) { auto state = getDefaultState(); state.bandLevels[EqualizerBand::TREBLE] = ABOVE_MAX_LEVEL; m_configuration = @@ -115,7 +115,7 @@ TEST_F(InMemoryEqualizerConfigurationTest, providedDefaultStateLevelAboveMax_cre } /// Invalid band value in default state (below min) -TEST_F(InMemoryEqualizerConfigurationTest, providedDefaultStateLevelBelowMin_createInstance_shouldFail) { +TEST_F(InMemoryEqualizerConfigurationTest, test_providedDefaultStateLevelBelowMin_createInstance_shouldFail) { auto state = getDefaultState(); state.bandLevels[EqualizerBand::TREBLE] = BELOW_MIN_LEVEL; m_configuration = @@ -124,7 +124,9 @@ TEST_F(InMemoryEqualizerConfigurationTest, providedDefaultStateLevelBelowMin_cre } /// Invalid band value in default state (below min, another band) -TEST_F(InMemoryEqualizerConfigurationTest, providedDefaultStateLevelBelowMinDifferentBand_createInstance_shouldFail) { +TEST_F( + InMemoryEqualizerConfigurationTest, + test_providedDefaultStateLevelBelowMinDifferentBand_createInstance_shouldFail) { auto state = getDefaultState(); state.bandLevels[EqualizerBand::BASS] = BELOW_MIN_LEVEL; m_configuration = @@ -135,7 +137,7 @@ TEST_F(InMemoryEqualizerConfigurationTest, providedDefaultStateLevelBelowMinDiff // Bands // Test no modes supported -TEST_F(InMemoryEqualizerConfigurationTest, providedNoModes_createInstance_shouldSucceed) { +TEST_F(InMemoryEqualizerConfigurationTest, test_providedNoModes_createInstance_shouldSucceed) { auto bands = std::set({EqualizerBand::MIDRANGE}); auto state = EqualizerState{EqualizerMode::NONE, EqualizerBandLevelMap({{EqualizerBand::MIDRANGE, DEFAULT_LEVEL}})}; auto modes = std::set({}); @@ -144,7 +146,7 @@ TEST_F(InMemoryEqualizerConfigurationTest, providedNoModes_createInstance_should } // Default state with supported mode -TEST_F(InMemoryEqualizerConfigurationTest, providedSupportedModeInDefaultState_createInstance_shouldSucceed) { +TEST_F(InMemoryEqualizerConfigurationTest, test_providedSupportedModeInDefaultState_createInstance_shouldSucceed) { auto bands = std::set({EqualizerBand::MIDRANGE}); auto state = EqualizerState{EqualizerMode::NIGHT, EqualizerBandLevelMap({{EqualizerBand::MIDRANGE, DEFAULT_LEVEL}})}; @@ -154,7 +156,7 @@ TEST_F(InMemoryEqualizerConfigurationTest, providedSupportedModeInDefaultState_c } // Default state with unsupported mode -TEST_F(InMemoryEqualizerConfigurationTest, providedUnsupportedModeInDefaultState_createInstance_shouldFail) { +TEST_F(InMemoryEqualizerConfigurationTest, test_providedUnsupportedModeInDefaultState_createInstance_shouldFail) { auto bands = std::set({EqualizerBand::MIDRANGE}); auto state = EqualizerState{EqualizerMode::TV, EqualizerBandLevelMap({{EqualizerBand::MIDRANGE, DEFAULT_LEVEL}})}; auto modes = std::set({EqualizerMode::NIGHT}); @@ -163,7 +165,7 @@ TEST_F(InMemoryEqualizerConfigurationTest, providedUnsupportedModeInDefaultState } // EqualizerMode::NONE could be provided as valid mode but will be ignored -TEST_F(InMemoryEqualizerConfigurationTest, providedNONEModeAsSupported_createInstance_shouldSucceed) { +TEST_F(InMemoryEqualizerConfigurationTest, test_providedNONEModeAsSupported_createInstance_shouldSucceed) { auto bands = std::set({EqualizerBand::MIDRANGE}); auto state = EqualizerState{EqualizerMode::NONE, EqualizerBandLevelMap({{EqualizerBand::MIDRANGE, DEFAULT_LEVEL}})}; auto modes = std::set({EqualizerMode::NIGHT, EqualizerMode::NONE}); @@ -171,7 +173,7 @@ TEST_F(InMemoryEqualizerConfigurationTest, providedNONEModeAsSupported_createIns ASSERT_THAT(m_configuration, NotNull()); } -TEST_F(InMemoryEqualizerConfigurationTest, providedValidConfiguration_isSupportedMethods_shouldSucceed) { +TEST_F(InMemoryEqualizerConfigurationTest, test_providedValidConfiguration_isSupportedMethods_shouldSucceed) { auto bands = std::set({EqualizerBand::MIDRANGE}); auto state = EqualizerState{EqualizerMode::NONE, EqualizerBandLevelMap({{EqualizerBand::MIDRANGE, DEFAULT_LEVEL}})}; auto modes = std::set({EqualizerMode::NIGHT, EqualizerMode::TV}); diff --git a/EqualizerImplementations/test/SDKConfigEqualizerConfigurationTest.cpp b/EqualizerImplementations/test/SDKConfigEqualizerConfigurationTest.cpp index b40cec2032..e68d2be312 100644 --- a/EqualizerImplementations/test/SDKConfigEqualizerConfigurationTest.cpp +++ b/EqualizerImplementations/test/SDKConfigEqualizerConfigurationTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -98,7 +98,7 @@ static ConfigurationNode generateConfigFromJSON(std::string json) { } // Test creation with an empty configuration -TEST_F(SDKConfigEqualizerConfigurationTest, providedEmptyConfig_shouldSucceed) { +TEST_F(SDKConfigEqualizerConfigurationTest, test_providedEmptyConfig_shouldSucceed) { auto defaultConfig = InMemoryEqualizerConfiguration::createDefault(); ConfigurationNode rootNode; @@ -107,7 +107,7 @@ TEST_F(SDKConfigEqualizerConfigurationTest, providedEmptyConfig_shouldSucceed) { } // Empty configuration should lead to default values. -TEST_F(SDKConfigEqualizerConfigurationTest, providedEmptyConfig_shouldUseDefaultConfig) { +TEST_F(SDKConfigEqualizerConfigurationTest, test_providedEmptyConfig_shouldUseDefaultConfig) { auto defaultConfig = InMemoryEqualizerConfiguration::createDefault(); ConfigurationNode rootNode; @@ -124,7 +124,7 @@ TEST_F(SDKConfigEqualizerConfigurationTest, providedEmptyConfig_shouldUseDefault } // Test the case when only some of the bands supported -TEST_F(SDKConfigEqualizerConfigurationTest, providedLimitedBandsDefined_shouldSucceed) { +TEST_F(SDKConfigEqualizerConfigurationTest, test_providedLimitedBandsDefined_shouldSucceed) { ConfigurationNode rootNode = generateConfigFromJSON(JSON_LIMITED_BANDS); auto config = SDKConfigEqualizerConfiguration::create(rootNode); @@ -136,7 +136,7 @@ TEST_F(SDKConfigEqualizerConfigurationTest, providedLimitedBandsDefined_shouldSu } // Test the case when only some of the bands supported, one of them is not explicitly mentioned. -TEST_F(SDKConfigEqualizerConfigurationTest, providedLimitedBandsOneMissing_shouldSucceed) { +TEST_F(SDKConfigEqualizerConfigurationTest, test_providedLimitedBandsOneMissing_shouldSucceed) { ConfigurationNode rootNode = generateConfigFromJSON(JSON_LIMITED_BANDS_ONE_MISSING); auto config = SDKConfigEqualizerConfiguration::create(rootNode); @@ -149,7 +149,7 @@ TEST_F(SDKConfigEqualizerConfigurationTest, providedLimitedBandsOneMissing_shoul } // Test empty bands branch behavior -TEST_F(SDKConfigEqualizerConfigurationTest, havingEmptyBandList_shouldUseHardDefaults) { +TEST_F(SDKConfigEqualizerConfigurationTest, test_havingEmptyBandList_shouldUseHardDefaults) { ConfigurationNode rootNode = generateConfigFromJSON(JSON_NO_BANDS_PROVIDED); auto config = SDKConfigEqualizerConfiguration::create(rootNode); @@ -167,7 +167,7 @@ TEST_F(SDKConfigEqualizerConfigurationTest, havingEmptyBandList_shouldUseHardDef } // Test invalid band listed in supported bands branch -TEST_F(SDKConfigEqualizerConfigurationTest, havingOnlyInvalidBand_shouldSucceedAndSupportNone) { +TEST_F(SDKConfigEqualizerConfigurationTest, test_havingOnlyInvalidBand_shouldSucceedAndSupportNone) { ConfigurationNode rootNode = generateConfigFromJSON(JSON_INVALID_BAND); auto config = SDKConfigEqualizerConfiguration::create(rootNode); @@ -179,7 +179,7 @@ TEST_F(SDKConfigEqualizerConfigurationTest, havingOnlyInvalidBand_shouldSucceedA } // Test modes branch containing one mode enabled -TEST_F(SDKConfigEqualizerConfigurationTest, oneModeDefinedAndEnabled_shouldPutOthersToDefaults) { +TEST_F(SDKConfigEqualizerConfigurationTest, test_oneModeDefinedAndEnabled_shouldPutOthersToDefaults) { ConfigurationNode rootNode = generateConfigFromJSON(JSON_ONE_MODE_MENTIONED_ENABLED); auto config = SDKConfigEqualizerConfiguration::create(rootNode); @@ -201,7 +201,7 @@ TEST_F(SDKConfigEqualizerConfigurationTest, oneModeDefinedAndEnabled_shouldPutOt } // Test modes branch containing one mode disabled -TEST_F(SDKConfigEqualizerConfigurationTest, oneModeDefinedAndDisabled_shouldPutOthersToDefaults) { +TEST_F(SDKConfigEqualizerConfigurationTest, test_oneModeDefinedAndDisabled_shouldPutOthersToDefaults) { ConfigurationNode rootNode = generateConfigFromJSON(JSON_ONE_MODE_MENTIONED_DISABLED); auto config = SDKConfigEqualizerConfiguration::create(rootNode); @@ -223,7 +223,7 @@ TEST_F(SDKConfigEqualizerConfigurationTest, oneModeDefinedAndDisabled_shouldPutO } // Test the empty default state branch -TEST_F(SDKConfigEqualizerConfigurationTest, givenEmptyDefaultStateBranchEmpty_shouldUseHardDefaults) { +TEST_F(SDKConfigEqualizerConfigurationTest, test_givenEmptyDefaultStateBranchEmpty_shouldUseHardDefaults) { ConfigurationNode rootNode = generateConfigFromJSON(JSON_EMPTY_DEFAULT_STATE_BRANCH); auto config = SDKConfigEqualizerConfiguration::create(rootNode); ASSERT_THAT(config, NotNull()); @@ -234,7 +234,7 @@ TEST_F(SDKConfigEqualizerConfigurationTest, givenEmptyDefaultStateBranchEmpty_sh } // Test default state with supported mode -TEST_F(SDKConfigEqualizerConfigurationTest, givenSupportedDefaultMode_shouldSucceed) { +TEST_F(SDKConfigEqualizerConfigurationTest, test_givenSupportedDefaultMode_shouldSucceed) { ConfigurationNode rootNode = generateConfigFromJSON(JSON_DEFAULT_MODE_SUPPORTED); auto config = SDKConfigEqualizerConfiguration::create(rootNode); ASSERT_THAT(config, NotNull()); @@ -243,21 +243,21 @@ TEST_F(SDKConfigEqualizerConfigurationTest, givenSupportedDefaultMode_shouldSucc } // Test default state with unsupported mode -TEST_F(SDKConfigEqualizerConfigurationTest, givenUnsupportedDefaultMode_shouldFail) { +TEST_F(SDKConfigEqualizerConfigurationTest, test_givenUnsupportedDefaultMode_shouldFail) { ConfigurationNode rootNode = generateConfigFromJSON(JSON_DEFAULT_MODE_UNSUPPORTED); auto config = SDKConfigEqualizerConfiguration::create(rootNode); ASSERT_THAT(config, IsNull()); } // Test not all supported bands being provided in default state -TEST_F(SDKConfigEqualizerConfigurationTest, havingNotAllBandsInDefaultState_shouldFail) { +TEST_F(SDKConfigEqualizerConfigurationTest, test_havingNotAllBandsInDefaultState_shouldFail) { ConfigurationNode rootNode = generateConfigFromJSON(JSON_DEFAULT_STATE_MISSING_BANDS); auto config = SDKConfigEqualizerConfiguration::create(rootNode); ASSERT_THAT(config, IsNull()); } // Test empty default state bands while not bands supported -TEST_F(SDKConfigEqualizerConfigurationTest, havingNoBandsDefinedInDefaultStateWithNoBandsSupported_shouldSucceed) { +TEST_F(SDKConfigEqualizerConfigurationTest, test_havingNoBandsDefinedInDefaultStateWithNoBandsSupported_shouldSucceed) { ConfigurationNode rootNode = generateConfigFromJSON(JSON_DEFAULT_STATE_BANDS_EMPTY_NO_BANDS_SUPPORTED); auto config = SDKConfigEqualizerConfiguration::create(rootNode); ASSERT_THAT(config, NotNull()); diff --git a/Integration/AlexaClientSDKConfig.json b/Integration/AlexaClientSDKConfig.json index 3422fecab4..4cd8b897a3 100644 --- a/Integration/AlexaClientSDKConfig.json +++ b/Integration/AlexaClientSDKConfig.json @@ -1,4 +1,4 @@ - { +{ "cblAuthDelegate":{ // Path to CBLAuthDelegate's database file. e.g. /home/ubuntu/Build/cblAuthDelegate.db // Note: The directory specified must be valid. @@ -92,7 +92,7 @@ // e.g. "firmwareVersion": 123 // The default endpoint to connect to. // See https://developer.amazon.com/docs/alexa-voice-service/api-overview.html#endpoints for regions and values - // e.g. "endpoint": "https://avs-alexa-na.amazon.com" + // e.g. "endpoint": "https://alexa.na.gateway.devices.a2z.com" // Example of specifying suggested latency in seconds when openning PortAudio stream. By default, // when this paramater isn't specified, SampleApp calls Pa_OpenDefaultStream to use the default value. @@ -205,6 +205,13 @@ // "maxLevel": 6 // } + // Example of setting the minUnmuteVolume level in SpeakerManager + // "speakerManagerCapabilityAgent": { + // // If present, shall override the default minUnmuteVolume value that the device restores to when unmuting + // // at volume level 0. + // // "minUnmuteVolume": 10 + // } + } @@ -231,4 +238,4 @@ // To enable DEBUG, build with cmake option -DCMAKE_BUILD_TYPE=DEBUG. By default it is built with RELEASE build. // And run the SampleApp similar to the following command. -// e.g. ./SampleApp /home/ubuntu/.../AlexaClientSDKConfig.json /home/ubuntu/KittAiModels/ DEBUG9" +// e.g. ./SampleApp /home/ubuntu/.../AlexaClientSDKConfig.json /home/ubuntu/KittAiModels/ DEBUG9" \ No newline at end of file diff --git a/Integration/test/AlertsIntegrationTest.cpp b/Integration/test/AlertsIntegrationTest.cpp index 23903d7274..29df070f3d 100644 --- a/Integration/test/AlertsIntegrationTest.cpp +++ b/Integration/test/AlertsIntegrationTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -584,7 +584,7 @@ class AlertsTest : public ::testing::Test { * * Set a 5 second timer, ensure it goes off, then use local stop and make sure the timer is stopped. */ -TEST_F(AlertsTest, handleOneTimerWithLocalStop) { +TEST_F(AlertsTest, test_handleOneTimerWithLocalStop) { // Write audio to SDS saying "Set a timer for 5 seconds" sendAudioFileAsRecognize(RECOGNIZE_TIMER_AUDIO_FILE_NAME); TestMessageSender::SendParams sendParams = m_avsConnectionManager->waitForNext(WAIT_FOR_TIMEOUT_DURATION); @@ -634,7 +634,7 @@ TEST_F(AlertsTest, handleOneTimerWithLocalStop) { * * Set two second timer, ensure they go off, then stop both timers. */ -TEST_F(AlertsTest, handleMultipleTimersWithLocalStop) { +TEST_F(AlertsTest, test_handleMultipleTimersWithLocalStop) { // Write audio to SDS saying "Set a timer for 15 seconds". sendAudioFileAsRecognize(RECOGNIZE_VERY_LONG_TIMER_AUDIO_FILE_NAME); TestMessageSender::SendParams sendParams = m_avsConnectionManager->waitForNext(WAIT_FOR_TIMEOUT_DURATION); @@ -731,7 +731,7 @@ TEST_F(AlertsTest, handleMultipleTimersWithLocalStop) { * Set a 5 second timer, ensure it goes off, then have a test client acquire the Alerts channel. Ensure that the alert * is stopped. */ -TEST_F(AlertsTest, stealChannelFromActiveAlert) { +TEST_F(AlertsTest, test_stealChannelFromActiveAlert) { // Write audio to SDS saying "Set a timer for 5 seconds" sendAudioFileAsRecognize(RECOGNIZE_TIMER_AUDIO_FILE_NAME); TestMessageSender::SendParams sendParams = m_avsConnectionManager->waitForNext(WAIT_FOR_TIMEOUT_DURATION); @@ -761,7 +761,7 @@ TEST_F(AlertsTest, stealChannelFromActiveAlert) { // Steal the alerts channel. ASSERT_TRUE( - m_focusManager->acquireChannel(FocusManager::ALERTS_CHANNEL_NAME, m_testDialogClient, ALERTS_ACTIVITY_ID)); + m_focusManager->acquireChannel(FocusManager::ALERT_CHANNEL_NAME, m_testDialogClient, ALERTS_ACTIVITY_ID)); // AlertStopped Event is sent. sendParams = m_avsConnectionManager->waitForNext(WAIT_FOR_TIMEOUT_DURATION); @@ -770,7 +770,7 @@ TEST_F(AlertsTest, stealChannelFromActiveAlert) { ASSERT_EQ(m_alertObserver->waitForNext(WAIT_FOR_TIMEOUT_DURATION).state, AlertObserverInterface::State::STOPPED); // Release the alerts channel. - m_focusManager->releaseChannel(FocusManager::ALERTS_CHANNEL_NAME, m_testDialogClient); + m_focusManager->releaseChannel(FocusManager::ALERT_CHANNEL_NAME, m_testDialogClient); // Low priority Test client gets back permission to the test channel. EXPECT_EQ( @@ -784,7 +784,7 @@ TEST_F(AlertsTest, stealChannelFromActiveAlert) { * Set a 5 second timer, then call disconnect, wait for the alert to become active and reconnect. * Locally stop the alert and ensure AlertStopped is sent. */ -TEST_F(AlertsTest, DisconnectAndReconnectBeforeLocalStop) { +TEST_F(AlertsTest, test_disconnectAndReconnectBeforeLocalStop) { // Write audio to SDS saying "Set a timer for 5 seconds" sendAudioFileAsRecognize(RECOGNIZE_TIMER_AUDIO_FILE_NAME); TestMessageSender::SendParams sendParams = m_avsConnectionManager->waitForNext(WAIT_FOR_TIMEOUT_DURATION); @@ -844,7 +844,7 @@ TEST_F(AlertsTest, DisconnectAndReconnectBeforeLocalStop) { * Set a 5 second timer, then call disconnect then reconnect. Once the alert is active, locally stop the alert * and ensure AlertStopped is sent. */ -TEST_F(AlertsTest, DisconnectAndReconnect) { +TEST_F(AlertsTest, test_disconnectAndReconnect) { // Write audio to SDS saying "Set a timer for 5 seconds" sendAudioFileAsRecognize(RECOGNIZE_TIMER_AUDIO_FILE_NAME); TestMessageSender::SendParams sendParams = m_avsConnectionManager->waitForNext(WAIT_FOR_TIMEOUT_DURATION); @@ -892,7 +892,7 @@ TEST_F(AlertsTest, DisconnectAndReconnect) { * Set a 5 second timer, then call removeAllAlerts. Wait and ensure that the alert does not become active and no * events are sent for it. */ -TEST_F(AlertsTest, RemoveAllAlertsBeforeAlertIsActive) { +TEST_F(AlertsTest, test_removeAllAlertsBeforeAlertIsActive) { // Write audio to SDS saying "Set a timer for 5 seconds" sendAudioFileAsRecognize(RECOGNIZE_TIMER_AUDIO_FILE_NAME); TestMessageSender::SendParams sendParams = m_avsConnectionManager->waitForNext(WAIT_FOR_TIMEOUT_DURATION); @@ -942,7 +942,7 @@ TEST_F(AlertsTest, RemoveAllAlertsBeforeAlertIsActive) { * Set a 10 second timer, then send audio of "Cancel the timer" as a recognize event. Ensure the timer does not go off * and the DeleteAlertSucceeded event is sent. */ -TEST_F(AlertsTest, cancelAlertBeforeItIsActive) { +TEST_F(AlertsTest, test_cancelAlertBeforeItIsActive) { // Write audio to SDS saying "Set a timer for 10 seconds" sendAudioFileAsRecognize(RECOGNIZE_LONG_TIMER_AUDIO_FILE_NAME); TestMessageSender::SendParams sendParams = m_avsConnectionManager->waitForNext(WAIT_FOR_TIMEOUT_DURATION); @@ -994,7 +994,7 @@ TEST_F(AlertsTest, cancelAlertBeforeItIsActive) { * Close the storage before asking for a 5 second timer. SetAlertFailed and then DeleteAlertSucceeded events are then * sent. Deletion succeeds because missing alert is not treated as an error. */ -TEST_F(AlertsTest, RemoveStorageBeforeAlarmIsSet) { +TEST_F(AlertsTest, test_removeStorageBeforeAlarmIsSet) { m_alertStorage->close(); // Write audio to SDS saying "Set a timer for 5 seconds" @@ -1045,9 +1045,12 @@ TEST_F(AlertsTest, RemoveStorageBeforeAlarmIsSet) { * Test when an alert is active and the user barges in and gets one speak in response * * Set a 5 second timer and wait until it is active. Send a recognize event asking for joke and see that the alert goes - * into the background. When the speak is complete, the alert is forgrounded and can be locally stopped. + * into the background. When the speak is complete, the alert is foregrounded and can be locally stopped. + * + * Note: Disabling test as sometimes "tell me a joke" causes multiple speech started and speech finished events to + * be sent based on user config making this integration test unstable. */ -TEST_F(AlertsTest, UserShortUnrelatedBargeInOnActiveTimer) { +TEST_F(AlertsTest, DISABLED_testTimer_userShortUnrelatedBargeInOnActive) { // Write audio to SDS saying "Set a timer for 5 seconds" sendAudioFileAsRecognize(RECOGNIZE_TIMER_AUDIO_FILE_NAME); TestMessageSender::SendParams sendParams = m_avsConnectionManager->waitForNext(WAIT_FOR_TIMEOUT_DURATION); @@ -1115,7 +1118,7 @@ TEST_F(AlertsTest, UserShortUnrelatedBargeInOnActiveTimer) { * Set a 5 second timer and wait until it is active. Send a recognize event asking "what's up" and see that the alert * goes into the background. When all the speaks are complete, the alert is forgrounded and can be locally stopped. */ -TEST_F(AlertsTest, DISABLED_UserLongUnrelatedBargeInOnActiveTimer) { +TEST_F(AlertsTest, DISABLED_testTimer_UserLongUnrelatedBargeInOnActive) { // Write audio to SDS saying "Set a timer for 5 seconds" sendAudioFileAsRecognize(RECOGNIZE_TIMER_AUDIO_FILE_NAME); TestMessageSender::SendParams sendParams = m_avsConnectionManager->waitForNext(WAIT_FOR_TIMEOUT_DURATION); @@ -1200,7 +1203,7 @@ TEST_F(AlertsTest, DISABLED_UserLongUnrelatedBargeInOnActiveTimer) { * the alert has become active in the background. Once the alert is active, call stopCapture and see that is is in the * foreground before locally stopping it. */ -TEST_F(AlertsTest, UserSpeakingWhenAlertShouldBeActive) { +TEST_F(AlertsTest, test_userSpeakingWhenAlertShouldBeActive) { // Write audio to SDS saying "Set a timer for 10 seconds" sendAudioFileAsRecognize(RECOGNIZE_LONG_TIMER_AUDIO_FILE_NAME); TestMessageSender::SendParams sendParams = m_avsConnectionManager->waitForNext(WAIT_FOR_TIMEOUT_DURATION); @@ -1248,12 +1251,15 @@ TEST_F(AlertsTest, UserSpeakingWhenAlertShouldBeActive) { sendStartedParams = m_avsConnectionManager->waitForNext(WAIT_FOR_TIMEOUT_DURATION); ASSERT_TRUE(checkSentEventName(sendStartedParams, NAME_SPEECH_STARTED)); - sendFinishedParams = m_avsConnectionManager->waitForNext(WAIT_FOR_TIMEOUT_DURATION); + sendParams = m_avsConnectionManager->waitForNext(WAIT_FOR_TIMEOUT_DURATION); if (getSentEventName(sendParams) == NAME_SPEECH_FINISHED) { + ASSERT_TRUE(checkSentEventName(sendParams, NAME_SPEECH_FINISHED)); sendParams = m_avsConnectionManager->waitForNext(WAIT_FOR_TIMEOUT_DURATION); ASSERT_TRUE(checkSentEventName(sendParams, NAME_ALERT_ENTERED_FOREGROUND)); } else { - ASSERT_TRUE(checkSentEventName(sendFinishedParams, NAME_SPEECH_FINISHED)); + ASSERT_TRUE(checkSentEventName(sendParams, NAME_ALERT_ENTERED_FOREGROUND)); + sendParams = m_avsConnectionManager->waitForNext(WAIT_FOR_TIMEOUT_DURATION); + ASSERT_TRUE(checkSentEventName(sendParams, NAME_SPEECH_FINISHED)); } std::this_thread::sleep_for(std::chrono::milliseconds(800)); @@ -1267,7 +1273,7 @@ TEST_F(AlertsTest, UserSpeakingWhenAlertShouldBeActive) { ASSERT_TRUE(focusChanged); } -TEST_F(AlertsTest, handleOneTimerWithVocalStop) { +TEST_F(AlertsTest, test_handleOneTimerWithVocalStop) { // Write audio to SDS saying "Set a timer for 5 seconds" sendAudioFileAsRecognize(RECOGNIZE_TIMER_AUDIO_FILE_NAME); TestMessageSender::SendParams sendParams = m_avsConnectionManager->waitForNext(WAIT_FOR_TIMEOUT_DURATION); diff --git a/Integration/test/AlexaAuthorizationDelegateTest.cpp b/Integration/test/AlexaAuthorizationDelegateTest.cpp index 09dfd93153..9e2c4cee57 100644 --- a/Integration/test/AlexaAuthorizationDelegateTest.cpp +++ b/Integration/test/AlexaAuthorizationDelegateTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -66,7 +66,7 @@ AlexaAuthorizationDelegateTest::~AlexaAuthorizationDelegateTest() { * If valid clientID, refreshToken, clientSecret are provided in the AuthDelegate.config file, then AuthDelegate should * be able to retrieve the valid refresh token (get authorized). */ -TEST_F(AlexaAuthorizationDelegateTest, refreshAuthToken) { +TEST_F(AlexaAuthorizationDelegateTest, test_refreshAuthToken) { auto authDelegateContext = AuthDelegateTestContext::create(g_configPath); ASSERT_TRUE(authDelegateContext); @@ -85,7 +85,7 @@ TEST_F(AlexaAuthorizationDelegateTest, refreshAuthToken) { * If an invalid client_id is sent to @c LWA, a "InvalidValue" response will be sent back and we should * notify the observer of the unrecoverable error. */ -TEST_F(AlexaAuthorizationDelegateTest, invalidClientIdWithUnrecoverableError) { +TEST_F(AlexaAuthorizationDelegateTest, test_invalidClientIdWithUnrecoverableError) { auto authDelegateContext = AuthDelegateTestContext::create(g_configPath, R"({ "deviceInfo" : { "clientId" : "InvalidClientId" } })"); ASSERT_TRUE(authDelegateContext); diff --git a/Integration/test/AlexaCommunicationsLibraryTest.cpp b/Integration/test/AlexaCommunicationsLibraryTest.cpp index 4238ce5269..6c87aaa6e0 100644 --- a/Integration/test/AlexaCommunicationsLibraryTest.cpp +++ b/Integration/test/AlexaCommunicationsLibraryTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2016-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -299,7 +299,7 @@ class AlexaCommunicationsLibraryTest : public ::testing::Test { }; /// Test connecting and disconnecting from AVS. -TEST_F(AlexaCommunicationsLibraryTest, testConnectAndDisconnect) { +TEST_F(AlexaCommunicationsLibraryTest, test_connectAndDisconnect) { // Connect is called in SetUp and disconnect is called in TearDown. Simply check that we are connected. ASSERT_TRUE(m_avsConnectionManager->isConnected()); } @@ -311,7 +311,7 @@ TEST_F(AlexaCommunicationsLibraryTest, testConnectAndDisconnect) { * * @see https://developer.amazon.com/public/solutions/alexa/alexa-voice-service/reference/system#synchronizestate */ -TEST_F(AlexaCommunicationsLibraryTest, testSendEvent) { +TEST_F(AlexaCommunicationsLibraryTest, test_sendEvent) { sendEvent( SYNCHRONIZE_STATE_JSON, avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::SUCCESS_NO_CONTENT, @@ -322,7 +322,7 @@ TEST_F(AlexaCommunicationsLibraryTest, testSendEvent) { * Function that tests the behavior of the ACL when an improperly formatted message is sent, expecting the server * to return a bad request status. */ -TEST_F(AlexaCommunicationsLibraryTest, testSendInvalidEvent) { +TEST_F(AlexaCommunicationsLibraryTest, test_sendInvalidEvent) { sendEvent( BAD_SYNCHRONIZE_STATE_JSON, avsCommon::sdkInterfaces::MessageRequestObserverInterface::Status::BAD_REQUEST, @@ -337,7 +337,7 @@ TEST_F(AlexaCommunicationsLibraryTest, testSendInvalidEvent) { * * @see https://developer.amazon.com/public/solutions/alexa/alexa-voice-service/reference/speechrecognizer#recognize */ -TEST_F(AlexaCommunicationsLibraryTest, testSendEventWithAttachment) { +TEST_F(AlexaCommunicationsLibraryTest, test_sendEventWithAttachment) { auto attachmentReader = createAttachmentReader(g_inputPath + "/" + RECOGNIZE_AUDIO_FILE_NAME); sendEvent( CT_RECOGNIZE_EVENT_JSON, @@ -354,7 +354,7 @@ TEST_F(AlexaCommunicationsLibraryTest, testSendEventWithAttachment) { * * @see https://developer.amazon.com/public/solutions/alexa/alexa-voice-service/reference/audioplayer#states */ -TEST_F(AlexaCommunicationsLibraryTest, testSendEventAndReceiveDirective) { +TEST_F(AlexaCommunicationsLibraryTest, test_sendEventAndReceiveDirective) { auto attachmentReader = createAttachmentReader(g_inputPath + "/" + RECOGNIZE_AUDIO_FILE_NAME); sendEvent( CT_RECOGNIZE_EVENT_JSON, @@ -369,7 +369,7 @@ TEST_F(AlexaCommunicationsLibraryTest, testSendEventAndReceiveDirective) { /** * Test sending multiple Events in succession and verify that AVS responds to each of them. */ -TEST_F(AlexaCommunicationsLibraryTest, testSendEventsSerially) { +TEST_F(AlexaCommunicationsLibraryTest, test_sendEventsSerially) { const int NUMBER_OF_SUCCESSIVE_SENDS = 10; for (int i = 0; i < NUMBER_OF_SUCCESSIVE_SENDS; ++i) { auto attachmentReader = createAttachmentReader(g_inputPath + "/" + RECOGNIZE_AUDIO_FILE_NAME); @@ -384,7 +384,7 @@ TEST_F(AlexaCommunicationsLibraryTest, testSendEventsSerially) { /** * Test sending multiple Events concurrently and verify that AVS responds to each of them. */ -TEST_F(AlexaCommunicationsLibraryTest, testSendEventsConcurrently) { +TEST_F(AlexaCommunicationsLibraryTest, test_sendEventsConcurrently) { std::vector> futures; for (int i = 0; i < MAX_CONCURRENT_STREAMS; ++i) { @@ -407,7 +407,7 @@ TEST_F(AlexaCommunicationsLibraryTest, testSendEventsConcurrently) { * * @see https://developer.amazon.com/public/solutions/alexa/alexa-voice-service/reference/speechrecognizer#profiles */ -TEST_F(AlexaCommunicationsLibraryTest, testReceiveDirectiveOnDownchannel) { +TEST_F(AlexaCommunicationsLibraryTest, test_receiveDirectiveOnDownchannel) { auto attachmentReader = createAttachmentReader(g_inputPath + "/" + SILENCE_AUDIO_FILE_NAME); sendEvent( NF_RECOGNIZE_EVENT_JSON, @@ -422,7 +422,7 @@ TEST_F(AlexaCommunicationsLibraryTest, testReceiveDirectiveOnDownchannel) { /** * Test that a connection to AVS persists between sending Events. */ -TEST_F(AlexaCommunicationsLibraryTest, testPersistentConnection) { +TEST_F(AlexaCommunicationsLibraryTest, test_persistentConnection) { auto attachmentReader = createAttachmentReader(g_inputPath + "/" + RECOGNIZE_AUDIO_FILE_NAME); sendEvent( CT_RECOGNIZE_EVENT_JSON, @@ -442,7 +442,7 @@ TEST_F(AlexaCommunicationsLibraryTest, testPersistentConnection) { /** * Test add- and removeConnectionStatuObserver, expecting the observer to be updated only when it is added. */ -TEST_F(AlexaCommunicationsLibraryTest, testMultipleConnectionStatusObservers) { +TEST_F(AlexaCommunicationsLibraryTest, test_multipleConnectionStatusObservers) { auto observer = std::make_shared(); m_avsConnectionManager->addConnectionStatusObserver(observer); diff --git a/Integration/test/AlexaDirectiveSequencerLibraryTest.cpp b/Integration/test/AlexaDirectiveSequencerLibraryTest.cpp index 811860b412..074f84ef41 100644 --- a/Integration/test/AlexaDirectiveSequencerLibraryTest.cpp +++ b/Integration/test/AlexaDirectiveSequencerLibraryTest.cpp @@ -442,7 +442,7 @@ bool getToken(TestDirectiveHandler::DirectiveParams params, std::string& returnT * This test is intended to test @c DirectiveSequencer's ability to pass an @c AVSDirective to a @c DirectiveHandler * that has been registered to handle an @c AVSDirective. */ -TEST_F(AlexaDirectiveSequencerLibraryTest, sendEventWithDirective) { +TEST_F(AlexaDirectiveSequencerLibraryTest, test_sendEventWithDirective) { DirectiveHandlerConfiguration config; config[SET_MUTE_PAIR] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, false); config[SPEAK_PAIR] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, true); @@ -472,7 +472,7 @@ TEST_F(AlexaDirectiveSequencerLibraryTest, sendEventWithDirective) { * request. It then verifies that handleDirective() is called for the subsequent directives without waiting for * completion of handling of any of the directives. */ -TEST_F(AlexaDirectiveSequencerLibraryTest, sendDirectiveGroupWithoutBlocking) { +TEST_F(AlexaDirectiveSequencerLibraryTest, test_sendDirectiveGroupWithoutBlocking) { DirectiveHandlerConfiguration config; auto audioNonBlockingPolicy = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, false); config[SET_MUTE_PAIR] = audioNonBlockingPolicy; @@ -518,7 +518,7 @@ TEST_F(AlexaDirectiveSequencerLibraryTest, sendDirectiveGroupWithoutBlocking) { * It then verifies that the directive handler was not called for the @c AVSDirectives expected to result from the * second event. */ -TEST_F(AlexaDirectiveSequencerLibraryTest, sendDirectiveWithDifferentDialogRequestID) { +TEST_F(AlexaDirectiveSequencerLibraryTest, test_sendDirectiveWithDifferentDialogRequestID) { DirectiveHandlerConfiguration config; auto audioNonBlockingPolicy = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, false); config[SET_MUTE_PAIR] = audioNonBlockingPolicy; @@ -568,7 +568,7 @@ TEST_F(AlexaDirectiveSequencerLibraryTest, sendDirectiveWithDifferentDialogReque * are then consumed verifying cancellation of @c AVSDirectives from the first group and handling of @c AVSDirectives * in the second group. */ -TEST_F(AlexaDirectiveSequencerLibraryTest, dropQueueAfterBargeIn) { +TEST_F(AlexaDirectiveSequencerLibraryTest, test_dropQueueAfterBargeIn) { DirectiveHandlerConfiguration config; config[SET_MUTE_PAIR] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, false); config[SPEAK_PAIR] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, true); @@ -630,7 +630,7 @@ TEST_F(AlexaDirectiveSequencerLibraryTest, dropQueueAfterBargeIn) { * @c SetAlert directives do not have a @c dialogRequestId value. This test uses that fact to verify that * @c AVSDirectives with no @c dialogRequestId are processed properly. */ -TEST_F(AlexaDirectiveSequencerLibraryTest, sendDirectiveWithoutADialogRequestID) { +TEST_F(AlexaDirectiveSequencerLibraryTest, test_sendDirectiveWithoutADialogRequestID) { DirectiveHandlerConfiguration config; auto audioNonBlockingPolicy = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, false); config[SPEAK_PAIR] = audioNonBlockingPolicy; @@ -712,7 +712,7 @@ TEST_F(AlexaDirectiveSequencerLibraryTest, sendDirectiveWithoutADialogRequestID) * number of @c preHandleDirective() and @c handleDirective() callbacks verifying that the counts come out to the * same value in the end. */ -TEST_F(AlexaDirectiveSequencerLibraryTest, sendDirectivesForPreHandling) { +TEST_F(AlexaDirectiveSequencerLibraryTest, test_sendDirectivesForPreHandling) { DirectiveHandlerConfiguration config; config[SET_MUTE_PAIR] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, false); config[SPEAK_PAIR] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, true); @@ -756,7 +756,7 @@ TEST_F(AlexaDirectiveSequencerLibraryTest, sendDirectivesForPreHandling) { * canned @c Recognize request. When @c handleDirective() is called for the blocking @c AVSDirective, setFailed() * is called to trigger the cancellation of subsequent @c AVSDirectives in the same group. */ -TEST_F(AlexaDirectiveSequencerLibraryTest, cancelDirectivesWhileInQueue) { +TEST_F(AlexaDirectiveSequencerLibraryTest, test_cancelDirectivesWhileInQueue) { DirectiveHandlerConfiguration config; config[SET_MUTE_PAIR] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, false); config[SPEAK_PAIR] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, true); @@ -800,7 +800,7 @@ TEST_F(AlexaDirectiveSequencerLibraryTest, cancelDirectivesWhileInQueue) { * directive and then nothing until setComplete() is called for that directive. Then expect the directive handler * to receive at least one subsequent directive. */ -TEST_F(AlexaDirectiveSequencerLibraryTest, oneBlockingDirectiveAtTheFront) { +TEST_F(AlexaDirectiveSequencerLibraryTest, test_oneBlockingDirectiveAtTheFront) { DirectiveHandlerConfiguration config; config[SET_MUTE_PAIR] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, true); config[SPEAK_PAIR] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, false); @@ -862,7 +862,7 @@ TEST_F(AlexaDirectiveSequencerLibraryTest, oneBlockingDirectiveAtTheFront) { * @c AVSDirective, @c handleDirective() should be called for the subsequent (and @c NON_BLOCKING) @c AVSDirectives * without waiting for the completion of any subsequent @c AVSDirectives. */ -TEST_F(AlexaDirectiveSequencerLibraryTest, oneBlockingDirectiveInTheMiddle) { +TEST_F(AlexaDirectiveSequencerLibraryTest, test_oneBlockingDirectiveInTheMiddle) { DirectiveHandlerConfiguration config; config[SET_MUTE_PAIR] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, false); config[SPEAK_PAIR] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, true); @@ -917,7 +917,7 @@ TEST_F(AlexaDirectiveSequencerLibraryTest, oneBlockingDirectiveInTheMiddle) { * To do this, no handler is set for a directive (@c SetMute) that is known to come down consistently in response to * a Recognize event, instead an exception encountered is expected. */ -TEST_F(AlexaDirectiveSequencerLibraryTest, noDirectiveHandlerRegisteredForADirectiveAtTheFront) { +TEST_F(AlexaDirectiveSequencerLibraryTest, test_noDirectiveHandlerRegisteredForADirectiveAtTheFront) { // Don't Register a DirectiveHandler for SetMute. DirectiveHandlerConfiguration config; config[SPEAK_PAIR] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, false); @@ -945,7 +945,7 @@ TEST_F(AlexaDirectiveSequencerLibraryTest, noDirectiveHandlerRegisteredForADirec * To do this, no handler is set for a directive (@c SetMute) that is known to come down consistently in response to * a Recognize event, instead an exception encountered is expected. */ -TEST_F(AlexaDirectiveSequencerLibraryTest, noDirectiveHandlerRegisteredForADirectiveInTheMiddle) { +TEST_F(AlexaDirectiveSequencerLibraryTest, test_noDirectiveHandlerRegisteredForADirectiveInTheMiddle) { // Don't Register a DirectiveHandler for Speak. DirectiveHandlerConfiguration config; config[SET_MUTE_PAIR] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, false); @@ -974,7 +974,7 @@ TEST_F(AlexaDirectiveSequencerLibraryTest, noDirectiveHandlerRegisteredForADirec * is expected to refuse the second handler. This directive is known to come down consistently in response to a * Recognize event. The Handler that was first set is the only one that should receive the directive. */ -TEST_F(AlexaDirectiveSequencerLibraryTest, twoDirectiveHandlersRegisteredForADirective) { +TEST_F(AlexaDirectiveSequencerLibraryTest, test_twoDirectiveHandlersRegisteredForADirective) { DirectiveHandlerConfiguration handlerAConfig; auto audioBlockingPolicy = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, true); handlerAConfig[SET_MUTE_PAIR] = audioBlockingPolicy; @@ -1018,7 +1018,7 @@ TEST_F(AlexaDirectiveSequencerLibraryTest, twoDirectiveHandlersRegisteredForADir * event that will prompt a multi-turn directive, receiving a directive group that contains ExpectSpeech, sending a * recognize event to respond to Alexa's question, and receiving the final directive group. */ -TEST_F(AlexaDirectiveSequencerLibraryTest, multiturnScenario) { +TEST_F(AlexaDirectiveSequencerLibraryTest, test_multiturnScenario) { DirectiveHandlerConfiguration config; auto audioNonBlockingPolicy = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, false); config[SET_MUTE_PAIR] = audioNonBlockingPolicy; @@ -1072,7 +1072,7 @@ TEST_F(AlexaDirectiveSequencerLibraryTest, multiturnScenario) { /** * Test ability to get an attachment from @c AttachmentManager. */ -TEST_F(AlexaDirectiveSequencerLibraryTest, getAttachmentWithContentId) { +TEST_F(AlexaDirectiveSequencerLibraryTest, test_getAttachmentWithContentId) { DirectiveHandlerConfiguration config; config[SPEAK_PAIR] = BlockingPolicy(BlockingPolicy::MEDIUM_AUDIO, true); diff --git a/Integration/test/AudioInputProcessorIntegrationTest.cpp b/Integration/test/AudioInputProcessorIntegrationTest.cpp index 3072d3208e..0e9ddec87b 100644 --- a/Integration/test/AudioInputProcessorIntegrationTest.cpp +++ b/Integration/test/AudioInputProcessorIntegrationTest.cpp @@ -457,7 +457,7 @@ class AudioInputProcessorTest : public ::testing::Test { m_AudioInputProcessor->addObserver(m_dialogUXStateAggregator); m_testClient = std::make_shared(); - ASSERT_TRUE(m_focusManager->acquireChannel(FocusManager::ALERTS_CHANNEL_NAME, m_testClient, ALARM_ACTIVITY_ID)); + ASSERT_TRUE(m_focusManager->acquireChannel(FocusManager::ALERT_CHANNEL_NAME, m_testClient, ALARM_ACTIVITY_ID)); ASSERT_EQ(m_testClient->waitForFocusChange(LONG_TIMEOUT_DURATION), FocusState::FOREGROUND); m_StateObserver = std::make_shared(); @@ -642,7 +642,7 @@ std::vector readAudioFromFile(const std::string& fileName, const int& headerP * directive. */ #if defined(KWD_KITTAI) || defined(KWD_SENSORY) -TEST_F(AudioInputProcessorTest, wakeWordJoke) { +TEST_F(AudioInputProcessorTest, test_wakeWordJoke) { // Put audio onto the SDS saying "Alexa, Tell me a joke". bool error; std::string file = g_inputPath + ALEXA_JOKE_AUDIO_FILE; @@ -693,7 +693,7 @@ TEST_F(AudioInputProcessorTest, wakeWordJoke) { * AudioInputProcessor is then observed to send a Recognize event to AVS which responds with no directives. */ #if defined(KWD_KITTAI) || defined(KWD_SENSORY) -TEST_F(AudioInputProcessorTest, wakeWordSilence) { +TEST_F(AudioInputProcessorTest, test_wakeWordSilence) { // Put audio onto the SDS saying "Alexa ......". bool error; std::string file = g_inputPath + ALEXA_SILENCE_AUDIO_FILE; @@ -738,7 +738,7 @@ TEST_F(AudioInputProcessorTest, wakeWordSilence) { * and ExpectSpeech directive. Audio of "Lions" is then fed into the stream and another recognize event is sent. */ #if defined(KWD_KITTAI) || defined(KWD_SENSORY) -TEST_F(AudioInputProcessorTest, wakeWordMultiturn) { +TEST_F(AudioInputProcessorTest, test_wakeWordMultiturn) { // Put audio onto the SDS saying "Alexa, wikipedia". bool error; std::string file = g_inputPath + ALEXA_WIKI_AUDIO_FILE; @@ -834,7 +834,7 @@ TEST_F(AudioInputProcessorTest, wakeWordMultiturn) { * but no directives are given in response. */ #if defined(KWD_KITTAI) || defined(KWD_SENSORY) -TEST_F(AudioInputProcessorTest, wakeWordMultiturnWithoutUserResponse) { +TEST_F(AudioInputProcessorTest, test_wakeWordMultiturnWithoutUserResponse) { // Put audio onto the SDS saying "Alexa, wikipedia". bool error; std::string file = g_inputPath + ALEXA_WIKI_AUDIO_FILE; @@ -929,7 +929,7 @@ TEST_F(AudioInputProcessorTest, wakeWordMultiturnWithoutUserResponse) { * AudioInputProcessor is then observed to send a Recognize event to AVS which responds with a SetMute and Speak * directive. */ -TEST_F(AudioInputProcessorTest, DISABLED_tapToTalkJoke) { +TEST_F(AudioInputProcessorTest, DISABLED_test_tapToTalkJoke) { // Signal to the AIP to start recognizing. ASSERT_TRUE(m_tapToTalkButton->startRecognizing(m_AudioInputProcessor, m_TapToTalkAudioProvider)); @@ -975,7 +975,7 @@ TEST_F(AudioInputProcessorTest, DISABLED_tapToTalkJoke) { } // ACSDK-2410 Disable this test temporarily due to running into issues with Raspberry Pi -TEST_F(AudioInputProcessorTest, DISABLED_tapToTalkTimeOpus) { +TEST_F(AudioInputProcessorTest, DISABLED_test_tapToTalkTimeOpus) { m_compatibleAudioFormat.sampleRateHz = COMPATIBLE_SAMPLE_RATE_OPUS_32; m_compatibleAudioFormat.numChannels = COMPATIBLE_NUM_CHANNELS; m_compatibleAudioFormat.endianness = COMPATIBLE_ENDIANNESS; @@ -1027,7 +1027,7 @@ TEST_F(AudioInputProcessorTest, DISABLED_tapToTalkTimeOpus) { * To do this, audio of "....." is fed into a stream after button sends recognize to AudioInputProcessor. The * AudioInputProcessor is then observed to send a Recognize event to AVS which responds no directives. */ -TEST_F(AudioInputProcessorTest, tapToTalkSilence) { +TEST_F(AudioInputProcessorTest, test_tapToTalkSilence) { // Signal to the AIP to start recognizing. ASSERT_TRUE(m_tapToTalkButton->startRecognizing(m_AudioInputProcessor, m_TapToTalkAudioProvider)); @@ -1072,7 +1072,7 @@ TEST_F(AudioInputProcessorTest, tapToTalkSilence) { * To do this, no audio is fed into a stream after button sends recognize to AudioInputProcessor. The * AudioInputProcessor is then observed to send a Recognize event to AVS which responds with no directive. */ -TEST_F(AudioInputProcessorTest, tapToTalkNoAudio) { +TEST_F(AudioInputProcessorTest, test_tapToTalkNoAudio) { // Signal to the AIP to start recognizing. ASSERT_TRUE(m_tapToTalkButton->startRecognizing(m_AudioInputProcessor, m_TapToTalkAudioProvider)); @@ -1107,7 +1107,7 @@ TEST_F(AudioInputProcessorTest, tapToTalkNoAudio) { * with a SetMute and Speak directive. */ #if defined(KWD_KITTAI) || defined(KWD_SENSORY) -TEST_F(AudioInputProcessorTest, tapToTalkWithWakeWordConflict) { +TEST_F(AudioInputProcessorTest, test_tapToTalkWithWakeWordConflict) { // Signal to the AIP to start recognizing. ASSERT_TRUE(m_tapToTalkButton->startRecognizing(m_AudioInputProcessor, m_TapToTalkAudioProvider)); @@ -1160,7 +1160,7 @@ TEST_F(AudioInputProcessorTest, tapToTalkWithWakeWordConflict) { * AudioInputProcessor is then observed to send a Recognize event to AVS which responds with a SetMute, Speak, * and ExpectSpeech directive. Audio of "Lions" is then fed into the stream and another recognize event is sent. */ -TEST_F(AudioInputProcessorTest, tapToTalkMultiturn) { +TEST_F(AudioInputProcessorTest, test_tapToTalkMultiturn) { // Signal to the AIP to start recognizing. ASSERT_TRUE(m_tapToTalkButton->startRecognizing(m_AudioInputProcessor, m_TapToTalkAudioProvider)); @@ -1255,7 +1255,7 @@ TEST_F(AudioInputProcessorTest, tapToTalkMultiturn) { * and ExpectSpeech directive. Audio of "...." is then fed into the stream and another recognize event is sent * but no directives are given in response. */ -TEST_F(AudioInputProcessorTest, tapToTalkMultiturnWithoutUserResponse) { +TEST_F(AudioInputProcessorTest, test_tapToTalkMultiturnWithoutUserResponse) { // Signal to the AIP to start recognizing. ASSERT_TRUE(m_tapToTalkButton->startRecognizing(m_AudioInputProcessor, m_TapToTalkAudioProvider)); @@ -1362,7 +1362,7 @@ TEST_F(AudioInputProcessorTest, tapToTalkMultiturnWithoutUserResponse) { * To do this, audio of "Tell me a joke" is fed into a stream after button sends recognize to AudioInputProcessor. The * button then sends a reset command and no recognize event is sent. */ -TEST_F(AudioInputProcessorTest, tapToTalkCancel) { +TEST_F(AudioInputProcessorTest, test_tapToTalkCancel) { // Signal to the AIP to start recognizing. ASSERT_TRUE(m_tapToTalkButton->startRecognizing(m_AudioInputProcessor, m_TapToTalkAudioProvider)); @@ -1396,7 +1396,7 @@ TEST_F(AudioInputProcessorTest, tapToTalkCancel) { * AudioInputProcessor is then observed to send a Recognize event to AVS which responds with a SetMute and Speak * directive. */ -TEST_F(AudioInputProcessorTest, holdToTalkJoke) { +TEST_F(AudioInputProcessorTest, test_holdToTalkJoke) { // Signal to the AIP to start recognizing. ASSERT_NE(nullptr, m_HoldToTalkAudioProvider); ASSERT_TRUE(m_holdToTalkButton->startRecognizing(m_AudioInputProcessor, m_HoldToTalkAudioProvider)); @@ -1452,7 +1452,7 @@ TEST_F(AudioInputProcessorTest, holdToTalkJoke) { * AudioInputProcessor is then observed to send a Recognize event to AVS which responds with a SetMute, Speak, * and ExpectSpeech directive. Audio of "Lions" is then fed into the stream and another recognize event is sent. */ -TEST_F(AudioInputProcessorTest, holdToTalkMultiturn) { +TEST_F(AudioInputProcessorTest, test_holdToTalkMultiturn) { // Signal to the AIP to start recognizing. ASSERT_TRUE(m_holdToTalkButton->startRecognizing(m_AudioInputProcessor, m_HoldToTalkAudioProvider)); @@ -1557,7 +1557,7 @@ TEST_F(AudioInputProcessorTest, holdToTalkMultiturn) { * and ExpectSpeech directive. Audio of "...." is then fed into the stream and another recognize event is sent * but no directives are given in response. */ -TEST_F(AudioInputProcessorTest, holdToTalkMultiTurnWithSilence) { +TEST_F(AudioInputProcessorTest, test_holdToTalkMultiTurnWithSilence) { // Signal to the AIP to start recognizing. ASSERT_TRUE(m_holdToTalkButton->startRecognizing(m_AudioInputProcessor, m_HoldToTalkAudioProvider)); @@ -1678,7 +1678,7 @@ TEST_F(AudioInputProcessorTest, holdToTalkMultiTurnWithSilence) { * and ExpectSpeech directive. The button does not trigger another recognize so no recognize event is sent * and no directives are given in response. ExpectSpeechTimedOut event is observed to be sent. */ -TEST_F(AudioInputProcessorTest, holdToTalkMultiturnWithTimeOut) { +TEST_F(AudioInputProcessorTest, test_holdToTalkMultiturnWithTimeOut) { // Signal to the AIP to start recognizing. ASSERT_TRUE(m_holdToTalkButton->startRecognizing(m_AudioInputProcessor, m_HoldToTalkAudioProvider)); @@ -1748,7 +1748,7 @@ TEST_F(AudioInputProcessorTest, holdToTalkMultiturnWithTimeOut) { * To do this, no audio is fed into a stream after button sends recognize to AudioInputProcessor. The * AudioInputProcessor is then observed to send a Recognize event to AVS which responds with no directive. */ -TEST_F(AudioInputProcessorTest, holdToTalkNoAudio) { +TEST_F(AudioInputProcessorTest, test_holdToTalkNoAudio) { // Signal to the AIP to start recognizing. ASSERT_TRUE(m_holdToTalkButton->startRecognizing(m_AudioInputProcessor, m_HoldToTalkAudioProvider)); @@ -1790,7 +1790,7 @@ TEST_F(AudioInputProcessorTest, holdToTalkNoAudio) { * To do this, audio of "Tell me a joke" is fed into a stream after button sends recognize to AudioInputProcessor. The * button then sends a cancel command and no recognize event is sent. */ -TEST_F(AudioInputProcessorTest, holdToTalkCancel) { +TEST_F(AudioInputProcessorTest, test_holdToTalkCancel) { // Signal to the AIP to start recognizing. ASSERT_NE(nullptr, m_HoldToTalkAudioProvider); ASSERT_TRUE(m_holdToTalkButton->startRecognizing(m_AudioInputProcessor, m_HoldToTalkAudioProvider)); @@ -1833,7 +1833,7 @@ TEST_F(AudioInputProcessorTest, holdToTalkCancel) { * To do this, audio of "Tell me a joke" is fed into a stream that is being read by a wake word engine. The * lack of the wakeword or button-initiated recognize results in no recognize event being sent. */ -TEST_F(AudioInputProcessorTest, audioWithoutAnyTrigger) { +TEST_F(AudioInputProcessorTest, test_audioWithoutAnyTrigger) { // Put audio onto the SDS saying "Tell me a joke" without a trigger. bool error; std::string file = g_inputPath + JOKE_AUDIO_FILE; diff --git a/Integration/test/AudioPlayerIntegrationTest.cpp b/Integration/test/AudioPlayerIntegrationTest.cpp index 6b0890f225..14d73a77a2 100644 --- a/Integration/test/AudioPlayerIntegrationTest.cpp +++ b/Integration/test/AudioPlayerIntegrationTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -553,7 +553,7 @@ class AudioPlayerTest : public ::testing::Test { * tests then observe that the correct events are sent in order. * */ -TEST_F(AudioPlayerTest, SingASong) { +TEST_F(AudioPlayerTest, test_singASong) { // Sing me a song. sendAudioFileAsRecognize(RECOGNIZE_SING_FILE_NAME); bool focusChanged; @@ -604,8 +604,11 @@ TEST_F(AudioPlayerTest, SingASong) { * of Play directives, and a final Speak directive is received. The tests then observe that the correct events are sent * in order. * + * @note ACSDK-2373 - Test is disabled due to an assumption that each flash briefing must be less than 2min in length, + * and this is making this integration test unstable. + * */ -TEST_F(AudioPlayerTest, FlashBriefing) { +TEST_F(AudioPlayerTest, DISABLED_test_flashBriefing) { // Ask for a flashbriefing. sendAudioFileAsRecognize(RECOGNIZE_FLASHBRIEFING_FILE_NAME); diff --git a/Integration/test/NetworkIntegrationTests.cpp b/Integration/test/NetworkIntegrationTests.cpp index 11d4da0386..12c625e483 100644 --- a/Integration/test/NetworkIntegrationTests.cpp +++ b/Integration/test/NetworkIntegrationTests.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -173,7 +173,7 @@ void NetworkIntegrationTests::deleteDelay() { /** * Test if connection and disconnection can be established after delay is introduced. */ -TEST_F(NetworkIntegrationTests, testConnectAfterSlowConnection) { +TEST_F(NetworkIntegrationTests, test_connectAfterSlowConnection) { addDelay(DELAY_TIME); connect(); disconnect(); @@ -182,7 +182,7 @@ TEST_F(NetworkIntegrationTests, testConnectAfterSlowConnection) { /** * Establish Connection, and introduce delay and check if @c connectionStatus remains CONNECTED. */ -TEST_F(NetworkIntegrationTests, testConnectBeforeSlowConnection) { +TEST_F(NetworkIntegrationTests, test_connectBeforeSlowConnection) { connect(); addDelay(DELAY_TIME); disconnect(); @@ -191,7 +191,7 @@ TEST_F(NetworkIntegrationTests, testConnectBeforeSlowConnection) { /** * Establish connection, introduce delay and test if connect can be done again. */ -TEST_F(NetworkIntegrationTests, testReConnectAfterDelay) { +TEST_F(NetworkIntegrationTests, test_reConnectAfterDelay) { connect(); addDelay(DELAY_TIME); disconnect(); @@ -203,7 +203,7 @@ TEST_F(NetworkIntegrationTests, testReConnectAfterDelay) { * Establish connection, introduce a delay, send a message, check if the Status of MessageRequest * is SUCCESS. */ -TEST_F(NetworkIntegrationTests, testSendEventAfterDelayPass) { +TEST_F(NetworkIntegrationTests, test_sendEventAfterDelayPass) { connect(); addDelay(DELAY_TIME); sendEvent( @@ -217,7 +217,7 @@ TEST_F(NetworkIntegrationTests, testSendEventAfterDelayPass) { * Establish connection, introduce a longer delay time of greater than 30 seconds, send a message, * the Status of MessageRequest will be TIMEDOUT. */ -TEST_F(NetworkIntegrationTests, testSendEventAfterDelayFails) { +TEST_F(NetworkIntegrationTests, test_sendEventAfterDelayFails) { connect(); addDelay(LONG_DELAY_TIME); sendEvent( diff --git a/Integration/test/ServerDisconnectIntegrationTest.cpp b/Integration/test/ServerDisconnectIntegrationTest.cpp index 010a6f21cd..f346227b50 100644 --- a/Integration/test/ServerDisconnectIntegrationTest.cpp +++ b/Integration/test/ServerDisconnectIntegrationTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -247,8 +247,10 @@ void ServerDisconnectIntegrationTest::TearDown() { /** * Test if server side disconnect occurs by trying to connect to AVS using the same configuration * using two different @c AVSConnectionManager. + * + * @note Disabling this test until it can be updated to reflect server side changes. */ -TEST_F(ServerDisconnectIntegrationTest, testConnect) { +TEST_F(ServerDisconnectIntegrationTest, DISABLED_test_connect) { m_firstAvsCommunication->connect(); ASSERT_TRUE(m_firstAvsCommunication->getConnectionStatusObserver()->waitFor( ConnectionStatusObserverInterface::Status::CONNECTED)); @@ -265,8 +267,10 @@ TEST_F(ServerDisconnectIntegrationTest, testConnect) { /** * Test if server side disconnect occurs by trying to connect to AVS using the same configuration * using two different @c AVSConnectionManager and reconnecting one of the connections. + * + * @note Disabling this test until it can be updated to reflect server side changes. */ -TEST_F(ServerDisconnectIntegrationTest, testReConnect) { +TEST_F(ServerDisconnectIntegrationTest, DISABLED_test_reConnect) { m_firstAvsCommunication->connect(); ASSERT_TRUE(m_firstAvsCommunication->getConnectionStatusObserver()->waitFor( ConnectionStatusObserverInterface::Status::CONNECTED)); @@ -293,8 +297,10 @@ TEST_F(ServerDisconnectIntegrationTest, testReConnect) { /** * Test sending a message while having a server side disconnect. The send fails to return the expected * status of SUCCESS. + * + * @note Disabling this test until it can be updated to reflect server side changes. */ -TEST_F(ServerDisconnectIntegrationTest, testSendEvent) { +TEST_F(ServerDisconnectIntegrationTest, DISABLED_test_sendEvent) { m_firstAvsCommunication->connect(); ASSERT_TRUE(m_firstAvsCommunication->getConnectionStatusObserver()->waitFor( ConnectionStatusObserverInterface::Status::CONNECTED)); diff --git a/Integration/test/SpeechSynthesizerIntegrationTest.cpp b/Integration/test/SpeechSynthesizerIntegrationTest.cpp index 0939a79db6..1e47e67a13 100644 --- a/Integration/test/SpeechSynthesizerIntegrationTest.cpp +++ b/Integration/test/SpeechSynthesizerIntegrationTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -329,8 +329,7 @@ class SpeechSynthesizerTest : public ::testing::Test { m_focusManager = std::make_shared(FocusManager::getDefaultAudioChannels()); m_testClient = std::make_shared(); - ASSERT_TRUE( - m_focusManager->acquireChannel(FocusManager::ALERTS_CHANNEL_NAME, m_testClient, ALERTS_ACTIVITY_ID)); + ASSERT_TRUE(m_focusManager->acquireChannel(FocusManager::ALERT_CHANNEL_NAME, m_testClient, ALERTS_ACTIVITY_ID)); ASSERT_EQ(m_testClient->waitForFocusChange(WAIT_FOR_TIMEOUT_DURATION), FocusState::FOREGROUND); #ifdef GSTREAMER_MEDIA_PLAYER @@ -533,7 +532,7 @@ class SpeechSynthesizerTest : public ::testing::Test { * then return to a finished state. * */ -TEST_F(SpeechSynthesizerTest, handleOneSpeech) { +TEST_F(SpeechSynthesizerTest, test_handleOneSpeech) { // SpeechSynthesizerObserverInterface defaults to a FINISHED state. ASSERT_EQ( m_speechSynthesizerObserver->waitForNext(WAIT_FOR_TIMEOUT_DURATION), @@ -597,7 +596,7 @@ TEST_F(SpeechSynthesizerTest, handleOneSpeech) { * done by sending a Recognize event to AVS with audio of "What's up?" which returns four sets of SetMute and Speak. * */ -TEST_F(SpeechSynthesizerTest, handleMultipleConsecutiveSpeaks) { +TEST_F(SpeechSynthesizerTest, test_handleMultipleConsecutiveSpeaks) { // SpeechSynthesizerObserverInterface defaults to a FINISHED state. ASSERT_EQ( m_speechSynthesizerObserver->waitForNext(WAIT_FOR_TIMEOUT_DURATION), @@ -664,7 +663,7 @@ TEST_F(SpeechSynthesizerTest, handleMultipleConsecutiveSpeaks) { * all directives are cancelled. * */ -TEST_F(SpeechSynthesizerTest, bargeInOnOneSpeech) { +TEST_F(SpeechSynthesizerTest, test_bargeInOnOneSpeech) { // SpeechSynthesizerObserverInterface defaults to a FINISHED state. ASSERT_EQ( m_speechSynthesizerObserver->waitForNext(WAIT_FOR_TIMEOUT_DURATION), @@ -732,7 +731,7 @@ TEST_F(SpeechSynthesizerTest, bargeInOnOneSpeech) { * Once the first Speak reaches the SpeechSynthesizer, the dialogRequestID is changed and all directives are cancelled. * */ -TEST_F(SpeechSynthesizerTest, bargeInOnMultipleSpeaksAtTheBeginning) { +TEST_F(SpeechSynthesizerTest, test_bargeInOnMultipleSpeaksAtTheBeginning) { // SpeechSynthesizerObserverInterface defaults to a FINISHED state. ASSERT_EQ( m_speechSynthesizerObserver->waitForNext(WAIT_FOR_TIMEOUT_DURATION), @@ -800,7 +799,7 @@ TEST_F(SpeechSynthesizerTest, bargeInOnMultipleSpeaksAtTheBeginning) { * While the Speak directives are being handled, the dialogRequestID is changed and all directives are cancelled. * */ -TEST_F(SpeechSynthesizerTest, bargeInOnMultipleSpeaksInTheMiddle) { +TEST_F(SpeechSynthesizerTest, test_bargeInOnMultipleSpeaksInTheMiddle) { // SpeechSynthesizerObserverInterface defaults to a FINISHED state. ASSERT_EQ( m_speechSynthesizerObserver->waitForNext(WAIT_FOR_TIMEOUT_DURATION), @@ -906,7 +905,7 @@ TEST_F(SpeechSynthesizerTest, bargeInOnMultipleSpeaksInTheMiddle) { * then return to a finished state. Another recognize event is then sent to AVS is response to the ExpectSpeech * directive which prompts another Speak directive to be handled. */ -TEST_F(SpeechSynthesizerTest, multiturnScenario) { +TEST_F(SpeechSynthesizerTest, test_multiturnScenario) { // SpeechSynthesizerObserverInterface defaults to a FINISHED state. ASSERT_EQ( m_speechSynthesizerObserver->waitForNext(WAIT_FOR_TIMEOUT_DURATION), @@ -1033,7 +1032,7 @@ TEST_F(SpeechSynthesizerTest, multiturnScenario) { * This test is intended to test the SpeechSynthesizer's ability to do nothing when there are no Speak directives. A * Recognize event with audio of "Volume up" is sent to AVS to prompt a AdjustVolume directive but no Speak directives. */ -TEST_F(SpeechSynthesizerTest, handleNoSpeakDirectives) { +TEST_F(SpeechSynthesizerTest, test_handleNoSpeakDirectives) { // SpeechSynthesizerObserverInterface defaults to a FINISHED state. ASSERT_EQ( m_speechSynthesizerObserver->waitForNext(WAIT_FOR_TIMEOUT_DURATION), @@ -1092,7 +1091,7 @@ TEST_F(SpeechSynthesizerTest, handleNoSpeakDirectives) { * This test is intended to test the SpeechSynthesizer's ability to do nothing when there are no Speak directives. No * Recognize events are sent to trigger any directives. */ -TEST_F(SpeechSynthesizerTest, handleNoDirectives) { +TEST_F(SpeechSynthesizerTest, test_handleNoDirectives) { // SpeechSynthesizerObserverInterface defaults to a FINISHED state. ASSERT_EQ( m_speechSynthesizerObserver->waitForNext(WAIT_FOR_TIMEOUT_DURATION), diff --git a/KWD/KittAi/test/KittAiKeyWordDetectorTest.cpp b/KWD/KittAi/test/KittAiKeyWordDetectorTest.cpp index ce1f7aa1d0..328e7a3e3f 100644 --- a/KWD/KittAi/test/KittAiKeyWordDetectorTest.cpp +++ b/KWD/KittAi/test/KittAiKeyWordDetectorTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -307,7 +307,7 @@ class KittAiKeyWordTest : public ::testing::Test { }; /// Tests that we don't get back a valid detector if an invalid stream is passed in. -TEST_F(KittAiKeyWordTest, invalidStream) { +TEST_F(KittAiKeyWordTest, test_invalidStream) { auto detector = KittAiKeyWordDetector::create( nullptr, compatibleAudioFormat, @@ -321,7 +321,7 @@ TEST_F(KittAiKeyWordTest, invalidStream) { } /// Tests that we don't get back a valid detector if an invalid endianness is passed in. -TEST_F(KittAiKeyWordTest, incompatibleEndianness) { +TEST_F(KittAiKeyWordTest, test_incompatibleEndianness) { auto rawBuffer = std::make_shared(500000); auto uniqueSds = avsCommon::avs::AudioInputStream::create(rawBuffer, 2, 1); std::shared_ptr sds = std::move(uniqueSds); @@ -341,7 +341,7 @@ TEST_F(KittAiKeyWordTest, incompatibleEndianness) { } /// Tests that we get back the expected number of keywords for the four_alexa.wav file for one keyword observer. -TEST_F(KittAiKeyWordTest, getExpectedNumberOfDetectionsInFourAlexasAudioFileForOneObserver) { +TEST_F(KittAiKeyWordTest, test_getExpectedNumberOfDetectionsInFourAlexasAudioFileForOneObserver) { auto fourAlexasBuffer = std::make_shared(500000); auto fourAlexasSds = avsCommon::avs::AudioInputStream::create(fourAlexasBuffer, 2, 1); std::shared_ptr fourAlexasAudioBuffer = std::move(fourAlexasSds); @@ -376,7 +376,7 @@ TEST_F(KittAiKeyWordTest, getExpectedNumberOfDetectionsInFourAlexasAudioFileForO } /// Tests that we get back the expected number of keywords for the four_alexa.wav file for two keyword observers. -TEST_F(KittAiKeyWordTest, getExpectedNumberOfDetectionsInFourAlexasAudioFileForTwoObservers) { +TEST_F(KittAiKeyWordTest, test_getExpectedNumberOfDetectionsInFourAlexasAudioFileForTwoObservers) { auto fourAlexasBuffer = std::make_shared(500000); auto fourAlexasSds = avsCommon::avs::AudioInputStream::create(fourAlexasBuffer, 2, 1); std::shared_ptr fourAlexasAudioBuffer = std::move(fourAlexasSds); @@ -420,7 +420,7 @@ TEST_F(KittAiKeyWordTest, getExpectedNumberOfDetectionsInFourAlexasAudioFileForT * Tests that we get back the expected number of keywords for the alexa_stop_alexa_joke.wav file for one keyword * observer. */ -TEST_F(KittAiKeyWordTest, getExpectedNumberOfDetectionsInAlexaStopAlexaJokeAudioFileForOneObserver) { +TEST_F(KittAiKeyWordTest, test_getExpectedNumberOfDetectionsInAlexaStopAlexaJokeAudioFileForOneObserver) { auto alexaStopAlexaJokeBuffer = std::make_shared(500000); auto alexaStopAlexaJokeSds = avsCommon::avs::AudioInputStream::create(alexaStopAlexaJokeBuffer, 2, 1); std::shared_ptr alexaStopAlexaJokeAudioBuffer = std::move(alexaStopAlexaJokeSds); @@ -458,7 +458,7 @@ TEST_F(KittAiKeyWordTest, getExpectedNumberOfDetectionsInAlexaStopAlexaJokeAudio * Tests that we get back the expected number of keywords for the alexa_stop_alexa_joke.wav file for two keyword * observer. */ -TEST_F(KittAiKeyWordTest, getExpectedNumberOfDetectionsInAlexaStopAlexaJokeAudioFileForTwoObservers) { +TEST_F(KittAiKeyWordTest, test_getExpectedNumberOfDetectionsInAlexaStopAlexaJokeAudioFileForTwoObservers) { auto alexaStopAlexaJokeBuffer = std::make_shared(500000); auto alexaStopAlexaJokeSds = avsCommon::avs::AudioInputStream::create(alexaStopAlexaJokeBuffer, 2, 1); std::shared_ptr alexaStopAlexaJokeAudioBuffer = std::move(alexaStopAlexaJokeSds); @@ -500,7 +500,7 @@ TEST_F(KittAiKeyWordTest, getExpectedNumberOfDetectionsInAlexaStopAlexaJokeAudio } /// Tests that the detector state changes to ACTIVE when the detector is initialized properly. -TEST_F(KittAiKeyWordTest, getActiveState) { +TEST_F(KittAiKeyWordTest, test_getActiveState) { auto alexaStopAlexaJokeBuffer = std::make_shared(500000); auto alexaStopAlexaJokeSds = avsCommon::avs::AudioInputStream::create(alexaStopAlexaJokeBuffer, 2, 1); std::shared_ptr alexaStopAlexaJokeAudioBuffer = std::move(alexaStopAlexaJokeSds); @@ -536,7 +536,7 @@ TEST_F(KittAiKeyWordTest, getActiveState) { * Tests that the stream is closed and that the detector state changes to STREAM_CLOSED when we close the only writer * of the SDS passed in and all keyword detections have occurred. */ -TEST_F(KittAiKeyWordTest, getStreamClosedState) { +TEST_F(KittAiKeyWordTest, test_getStreamClosedState) { auto alexaStopAlexaJokeBuffer = std::make_shared(500000); auto alexaStopAlexaJokeSds = avsCommon::avs::AudioInputStream::create(alexaStopAlexaJokeBuffer, 2, 1); std::shared_ptr alexaStopAlexaJokeAudioBuffer = std::move(alexaStopAlexaJokeSds); diff --git a/KWD/Sensory/test/SensoryKeywordDetectorTest.cpp b/KWD/Sensory/test/SensoryKeywordDetectorTest.cpp index ad11fde2c8..9fc46db84c 100644 --- a/KWD/Sensory/test/SensoryKeywordDetectorTest.cpp +++ b/KWD/Sensory/test/SensoryKeywordDetectorTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -317,14 +317,14 @@ class SensoryKeywordTest : public ::testing::Test { }; /// Tests that we don't get back a valid detector if an invalid stream is passed in. -TEST_F(SensoryKeywordTest, invalidStream) { +TEST_F(SensoryKeywordTest, test_invalidStream) { auto detector = SensoryKeywordDetector::create( nullptr, compatibleAudioFormat, {keyWordObserver1}, {stateObserver}, modelFilePath); ASSERT_FALSE(detector); } /// Tests that we don't get back a valid detector if an invalid endianness is passed in. -TEST_F(SensoryKeywordTest, incompatibleEndianness) { +TEST_F(SensoryKeywordTest, test_incompatibleEndianness) { auto rawBuffer = std::make_shared(500000); auto uniqueSds = avsCommon::avs::AudioInputStream::create(rawBuffer, 2, 1); std::shared_ptr sds = std::move(uniqueSds); @@ -337,7 +337,7 @@ TEST_F(SensoryKeywordTest, incompatibleEndianness) { } /// Tests that we get back the expected number of keywords for the four_alexa.wav file for one keyword observer. -TEST_F(SensoryKeywordTest, getExpectedNumberOfDetectionsInFourAlexasAudioFileForOneObserver) { +TEST_F(SensoryKeywordTest, test_getExpectedNumberOfDetectionsInFourAlexasAudioFileForOneObserver) { auto fourAlexasBuffer = std::make_shared(500000); auto fourAlexasSds = avsCommon::avs::AudioInputStream::create(fourAlexasBuffer, 2, 1); std::shared_ptr fourAlexasAudioBuffer = std::move(fourAlexasSds); @@ -370,7 +370,7 @@ TEST_F(SensoryKeywordTest, getExpectedNumberOfDetectionsInFourAlexasAudioFileFor } /// Tests that we get back the expected number of keywords for the four_alexa.wav file for two keyword observers. -TEST_F(SensoryKeywordTest, getExpectedNumberOfDetectionsInFourAlexasAudioFileForTwoObservers) { +TEST_F(SensoryKeywordTest, test_getExpectedNumberOfDetectionsInFourAlexasAudioFileForTwoObservers) { auto fourAlexasBuffer = std::make_shared(500000); auto fourAlexasSds = avsCommon::avs::AudioInputStream::create(fourAlexasBuffer, 2, 1); std::shared_ptr fourAlexasAudioBuffer = std::move(fourAlexasSds); @@ -419,7 +419,7 @@ TEST_F(SensoryKeywordTest, getExpectedNumberOfDetectionsInFourAlexasAudioFileFor * Tests that we get back the expected number of keywords for the alexa_stop_alexa_joke.wav file for one keyword * observer. */ -TEST_F(SensoryKeywordTest, getExpectedNumberOfDetectionsInAlexaStopAlexaJokeAudioFileForOneObserver) { +TEST_F(SensoryKeywordTest, test_getExpectedNumberOfDetectionsInAlexaStopAlexaJokeAudioFileForOneObserver) { auto alexaStopAlexaJokeBuffer = std::make_shared(500000); auto alexaStopAlexaJokeSds = avsCommon::avs::AudioInputStream::create(alexaStopAlexaJokeBuffer, 2, 1); std::shared_ptr alexaStopAlexaJokeAudioBuffer = std::move(alexaStopAlexaJokeSds); @@ -453,7 +453,7 @@ TEST_F(SensoryKeywordTest, getExpectedNumberOfDetectionsInAlexaStopAlexaJokeAudi } /// Tests that the detector state changes to ACTIVE when the detector is initialized properly. -TEST_F(SensoryKeywordTest, getActiveState) { +TEST_F(SensoryKeywordTest, test_getActiveState) { auto alexaStopAlexaJokeBuffer = std::make_shared(500000); auto alexaStopAlexaJokeSds = avsCommon::avs::AudioInputStream::create(alexaStopAlexaJokeBuffer, 2, 1); std::shared_ptr alexaStopAlexaJokeAudioBuffer = std::move(alexaStopAlexaJokeSds); @@ -482,7 +482,7 @@ TEST_F(SensoryKeywordTest, getActiveState) { * Tests that the stream is closed and that the detector state changes to STREAM_CLOSED when we close the only writer * of the SDS passed in and all keyword detections have occurred. */ -TEST_F(SensoryKeywordTest, getStreamClosedState) { +TEST_F(SensoryKeywordTest, test_getStreamClosedState) { auto alexaStopAlexaJokeBuffer = std::make_shared(500000); auto alexaStopAlexaJokeSds = avsCommon::avs::AudioInputStream::create(alexaStopAlexaJokeBuffer, 2, 1); std::shared_ptr alexaStopAlexaJokeAudioBuffer = std::move(alexaStopAlexaJokeSds); @@ -524,7 +524,7 @@ TEST_F(SensoryKeywordTest, getStreamClosedState) { * observer even when SDS has other data prior to the audio file in it. This tests that the reference point that the * Sensory wrapper uses is working as expected. */ -TEST_F(SensoryKeywordTest, getExpectedNumberOfDetectionsInAlexaStopAlexaJokeAudioFileWithRandomDataAtBeginning) { +TEST_F(SensoryKeywordTest, test_getExpectedNumberOfDetectionsInAlexaStopAlexaJokeAudioFileWithRandomDataAtBeginning) { auto alexaStopAlexaJokeBuffer = std::make_shared(500000); auto alexaStopAlexaJokeSds = avsCommon::avs::AudioInputStream::create(alexaStopAlexaJokeBuffer, 2, 1); std::shared_ptr alexaStopAlexaJokeAudioBuffer = std::move(alexaStopAlexaJokeSds); diff --git a/KWD/test/AbstractKeywordDetectorTest.cpp b/KWD/test/AbstractKeywordDetectorTest.cpp index e9de0d4cc1..60abc82e49 100644 --- a/KWD/test/AbstractKeywordDetectorTest.cpp +++ b/KWD/test/AbstractKeywordDetectorTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -93,14 +93,14 @@ class AbstractKeyWordDetectorTest : public ::testing::Test { } }; -TEST_F(AbstractKeyWordDetectorTest, testAddKeyWordObserver) { +TEST_F(AbstractKeyWordDetectorTest, test_addKeyWordObserver) { detector->addKeyWordObserver(keyWordObserver1); EXPECT_CALL(*keyWordObserver1, onKeyWordDetected(_, _, _, _, _)).Times(1); detector->sendKeyWordCallToObservers(); } -TEST_F(AbstractKeyWordDetectorTest, testAddMultipleKeyWordObserver) { +TEST_F(AbstractKeyWordDetectorTest, test_addMultipleKeyWordObserver) { detector->addKeyWordObserver(keyWordObserver1); detector->addKeyWordObserver(keyWordObserver2); @@ -109,7 +109,7 @@ TEST_F(AbstractKeyWordDetectorTest, testAddMultipleKeyWordObserver) { detector->sendKeyWordCallToObservers(); } -TEST_F(AbstractKeyWordDetectorTest, testRemoveKeyWordObserver) { +TEST_F(AbstractKeyWordDetectorTest, test_removeKeyWordObserver) { detector->addKeyWordObserver(keyWordObserver1); detector->addKeyWordObserver(keyWordObserver2); @@ -124,7 +124,7 @@ TEST_F(AbstractKeyWordDetectorTest, testRemoveKeyWordObserver) { detector->sendKeyWordCallToObservers(); } -TEST_F(AbstractKeyWordDetectorTest, testAddStateObserver) { +TEST_F(AbstractKeyWordDetectorTest, test_addStateObserver) { detector->addKeyWordDetectorStateObserver(stateObserver1); EXPECT_CALL(*stateObserver1, onStateChanged(_)).Times(1); @@ -132,7 +132,7 @@ TEST_F(AbstractKeyWordDetectorTest, testAddStateObserver) { avsCommon::sdkInterfaces::KeyWordDetectorStateObserverInterface::KeyWordDetectorState::ACTIVE); } -TEST_F(AbstractKeyWordDetectorTest, testAddMultipleStateObservers) { +TEST_F(AbstractKeyWordDetectorTest, test_addMultipleStateObservers) { detector->addKeyWordDetectorStateObserver(stateObserver1); detector->addKeyWordDetectorStateObserver(stateObserver2); @@ -142,7 +142,7 @@ TEST_F(AbstractKeyWordDetectorTest, testAddMultipleStateObservers) { avsCommon::sdkInterfaces::KeyWordDetectorStateObserverInterface::KeyWordDetectorState::ACTIVE); } -TEST_F(AbstractKeyWordDetectorTest, testRemoveStateObserver) { +TEST_F(AbstractKeyWordDetectorTest, test_removeStateObserver) { detector->addKeyWordDetectorStateObserver(stateObserver1); detector->addKeyWordDetectorStateObserver(stateObserver2); @@ -159,7 +159,7 @@ TEST_F(AbstractKeyWordDetectorTest, testRemoveStateObserver) { avsCommon::sdkInterfaces::KeyWordDetectorStateObserverInterface::KeyWordDetectorState::STREAM_CLOSED); } -TEST_F(AbstractKeyWordDetectorTest, testObserversDontGetNotifiedOfSameStateTwice) { +TEST_F(AbstractKeyWordDetectorTest, test_observersDontGetNotifiedOfSameStateTwice) { detector->addKeyWordDetectorStateObserver(stateObserver1); EXPECT_CALL(*stateObserver1, onStateChanged(_)).Times(1); diff --git a/MediaPlayer/AndroidSLESMediaPlayer/src/AndroidSLESMediaPlayer.cpp b/MediaPlayer/AndroidSLESMediaPlayer/src/AndroidSLESMediaPlayer.cpp index 1462949321..484fadf32f 100644 --- a/MediaPlayer/AndroidSLESMediaPlayer/src/AndroidSLESMediaPlayer.cpp +++ b/MediaPlayer/AndroidSLESMediaPlayer/src/AndroidSLESMediaPlayer.cpp @@ -124,7 +124,8 @@ AndroidSLESMediaPlayer::SourceId AndroidSLESMediaPlayer::setSource( auto input = FFmpegAttachmentInputController::create(attachmentReader, format); auto newId = configureNewRequest(std::move(input)); if (ERROR == newId) { - ACSDK_ERROR(LX("setSourceFailed").d("type", "attachment").d("format", format)); + ACSDK_ERROR( + LX("setSourceFailed").d("name", RequiresShutdown::name()).d("type", "attachment").d("format", format)); } return newId; } @@ -138,7 +139,11 @@ AndroidSLESMediaPlayer::SourceId AndroidSLESMediaPlayer::setSource( auto input = FFmpegUrlInputController::create(playlistParser, url, offset, repeat); auto newId = configureNewRequest(std::move(input), playlistParser, offset); if (ERROR == newId) { - ACSDK_ERROR(LX("setSourceFailed").d("type", "url").d("offset(ms)", offset.count()).sensitive("url", url)); + ACSDK_ERROR(LX("setSourceFailed") + .d("name", RequiresShutdown::name()) + .d("type", "url") + .d("offset(ms)", offset.count()) + .sensitive("url", url)); } return newId; @@ -148,7 +153,7 @@ AndroidSLESMediaPlayer::SourceId AndroidSLESMediaPlayer::setSource(std::shared_p auto input = FFmpegStreamInputController::create(stream, repeat); auto newId = configureNewRequest(std::move(input)); if (ERROR == newId) { - ACSDK_ERROR(LX("setSourceFailed").d("type", "istream").d("repeat", repeat)); + ACSDK_ERROR(LX("setSourceFailed").d("name", RequiresShutdown::name()).d("type", "istream").d("repeat", repeat)); } return newId; } @@ -161,7 +166,10 @@ bool AndroidSLESMediaPlayer::play(SourceId id) { SLuint32 state; auto result = (*m_player)->GetPlayState(m_player, &state); if (result != SL_RESULT_SUCCESS) { - ACSDK_ERROR(LX("playFailed").d("reason", "getPlayStateFailed").d("result", result)); + ACSDK_ERROR(LX("playFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "getPlayStateFailed") + .d("result", result)); return false; } @@ -169,7 +177,11 @@ bool AndroidSLESMediaPlayer::play(SourceId id) { // set the player's state to playing result = (*m_player)->SetPlayState(m_player, SL_PLAYSTATE_PLAYING); if (result != SL_RESULT_SUCCESS) { - ACSDK_ERROR(LX("playFailed").d("reason", "setPlayStateFailed").d("result", result).d("id", id)); + ACSDK_ERROR(LX("playFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "setPlayStateFailed") + .d("result", result) + .d("id", id)); return false; } @@ -179,9 +191,17 @@ bool AndroidSLESMediaPlayer::play(SourceId id) { return true; } - ACSDK_ERROR(LX("playFailed").d("reason", "invalidState").d("requestId", id).d("state", state)); + ACSDK_ERROR(LX("playFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "invalidState") + .d("requestId", id) + .d("state", state)); } else { - ACSDK_ERROR(LX("playFailed").d("reason", "invalidId").d("requestId", id).d("currentId", m_sourceId)); + ACSDK_ERROR(LX("playFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "invalidId") + .d("requestId", id) + .d("currentId", m_sourceId)); } return false; } @@ -193,7 +213,11 @@ bool AndroidSLESMediaPlayer::stop(SourceId id) { if (id == m_sourceId) { return stopLocked(); } - ACSDK_ERROR(LX("stopFailed").d("reason", "Invalid Id").d("requestId", id).d("currentId", id)); + ACSDK_ERROR(LX("stopFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "Invalid Id") + .d("requestId", id) + .d("currentId", id)); return false; } @@ -201,14 +225,22 @@ bool AndroidSLESMediaPlayer::stopLocked() { SLuint32 state; auto result = (*m_player)->GetPlayState(m_player, &state); if (result != SL_RESULT_SUCCESS) { - ACSDK_ERROR(LX("stopFailed").d("reason", "getPlayStateFailed").d("result", result).d("id", m_sourceId)); + ACSDK_ERROR(LX("stopFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "getPlayStateFailed") + .d("result", result) + .d("id", m_sourceId)); return false; } if (state != SL_PLAYSTATE_STOPPED) { auto result = (*m_player)->SetPlayState(m_player, SL_PLAYSTATE_STOPPED); if (result != SL_RESULT_SUCCESS) { - ACSDK_ERROR(LX("stopFailed").d("reason", "setPlayStateFailed").d("result", result).d("id", m_sourceId)); + ACSDK_ERROR(LX("stopFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "setPlayStateFailed") + .d("result", result) + .d("id", m_sourceId)); return false; } if (m_observer) { @@ -226,14 +258,21 @@ bool AndroidSLESMediaPlayer::pause(SourceId id) { SLuint32 state; auto result = (*m_player)->GetPlayState(m_player, &state); if (result != SL_RESULT_SUCCESS) { - ACSDK_ERROR(LX("pauseFailed").d("reason", "getPlayStateFailed").d("result", result)); + ACSDK_ERROR(LX("pauseFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "getPlayStateFailed") + .d("result", result)); return false; } if (SL_PLAYSTATE_PLAYING == state) { result = (*m_player)->SetPlayState(m_player, SL_PLAYSTATE_PAUSED); if (result != SL_RESULT_SUCCESS) { - ACSDK_ERROR(LX("pauseFailed").d("reason", "setPlayStateFailed").d("result", result).d("id", id)); + ACSDK_ERROR(LX("pauseFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "setPlayStateFailed") + .d("result", result) + .d("id", id)); return false; } @@ -243,9 +282,17 @@ bool AndroidSLESMediaPlayer::pause(SourceId id) { return true; } - ACSDK_ERROR(LX("pauseFailed").d("reason", "invalidState").d("requestId", id).d("state", state)); + ACSDK_ERROR(LX("pauseFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "invalidState") + .d("requestId", id) + .d("state", state)); } else { - ACSDK_ERROR(LX("pauseFailed").d("reason", "invalidId").d("requestId", id).d("currentId", m_sourceId)); + ACSDK_ERROR(LX("pauseFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "invalidId") + .d("requestId", id) + .d("currentId", m_sourceId)); } return false; } @@ -258,14 +305,21 @@ bool AndroidSLESMediaPlayer::resume(SourceId id) { SLuint32 state; auto result = (*m_player)->GetPlayState(m_player, &state); if (result != SL_RESULT_SUCCESS) { - ACSDK_ERROR(LX("resumeFailed").d("reason", "getPlayStateFailed").d("result", result)); + ACSDK_ERROR(LX("resumeFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "getPlayStateFailed") + .d("result", result)); return false; } if (SL_PLAYSTATE_PAUSED == state) { result = (*m_player)->SetPlayState(m_player, SL_PLAYSTATE_PLAYING); if (result != SL_RESULT_SUCCESS) { - ACSDK_ERROR(LX("resumeFailed").d("reason", "setPlayStateFailed").d("result", result).d("id", id)); + ACSDK_ERROR(LX("resumeFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "setPlayStateFailed") + .d("result", result) + .d("id", id)); return false; } @@ -275,9 +329,17 @@ bool AndroidSLESMediaPlayer::resume(SourceId id) { return true; } - ACSDK_ERROR(LX("resumeFailed").d("reason", "invalidState").d("requestId", id).d("state", state)); + ACSDK_ERROR(LX("resumeFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "invalidState") + .d("requestId", id) + .d("state", state)); } else { - ACSDK_ERROR(LX("resumeFailed").d("reason", "invalidId").d("requestId", id).d("currentId", m_sourceId)); + ACSDK_ERROR(LX("resumeFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "invalidId") + .d("requestId", id) + .d("currentId", m_sourceId)); } return false; } @@ -298,6 +360,7 @@ void AndroidSLESMediaPlayer::setObserver(std::shared_ptr lock{m_operationMutex}; stopLocked(); m_observer.reset(); @@ -314,6 +377,7 @@ void AndroidSLESMediaPlayer::doShutdown() { } AndroidSLESMediaPlayer::~AndroidSLESMediaPlayer() { + ACSDK_DEBUG9(LX(__func__).d("name", RequiresShutdown::name())); m_mediaQueue.reset(); doShutdown(); } @@ -327,7 +391,8 @@ MediaPlayerInterface::SourceId AndroidSLESMediaPlayer::configureNewRequest( // Use global lock to stop player and set new source id. std::lock_guard lock{m_operationMutex}; if (m_hasShutdown) { - ACSDK_ERROR(LX("configureNewRequestFailed").d("reason", "playerHasShutdown")); + ACSDK_ERROR( + LX("configureNewRequestFailed").d("name", RequiresShutdown::name()).d("reason", "playerHasShutdown")); return ERROR; } @@ -353,6 +418,7 @@ MediaPlayerInterface::SourceId AndroidSLESMediaPlayer::configureNewRequest( m_mediaQueue = AndroidSLESMediaQueue::create(m_playerObject, std::move(decoder), callback, m_config); if (!m_mediaQueue) { ACSDK_ERROR(LX("configureNewRequestFailed") + .d("name", RequiresShutdown::name()) .d("reason", "failedToCreateMediaQueue") .d("decoder", inputController.get())); return ERROR; @@ -368,18 +434,18 @@ std::unique_ptr AndroidSLESMediaPlayer::create( const PlaybackConfiguration& config, const std::string& name) { if (!contentFetcherFactory) { - ACSDK_ERROR(LX("createFailed").d("reason", "invalidContentFetcherFactory")); + ACSDK_ERROR(LX("createFailed").d("name", name).d("reason", "invalidContentFetcherFactory")); return nullptr; } if (!engine) { - ACSDK_ERROR(LX("createFailed").d("reason", "invalidEngine")); + ACSDK_ERROR(LX("createFailed").d("name", name).d("reason", "invalidEngine")); return nullptr; } std::shared_ptr outputMix = engine->createOutputMix(); if (!outputMix) { - ACSDK_ERROR(LX("createFailed").d("reason", "invalidOutputMix")); + ACSDK_ERROR(LX("createFailed").d("name", name).d("reason", "invalidOutputMix")); return nullptr; } @@ -393,19 +459,19 @@ std::unique_ptr AndroidSLESMediaPlayer::create( std::shared_ptr playerObject = engine->createPlayer(audioSource, audioSink, enableEqualizer); if (!playerObject) { - ACSDK_ERROR(LX("createFailed").d("reason", "createPlayerFailed")); + ACSDK_ERROR(LX("createFailed").d("name", name).d("reason", "createPlayerFailed")); return nullptr; } SLPlayItf playerInterface; if (!playerObject->getInterface(SL_IID_PLAY, &playerInterface)) { - ACSDK_ERROR(LX("createFailed").d("reason", "getPlayerInterfaceFailed")); + ACSDK_ERROR(LX("createFailed").d("name", name).d("reason", "getPlayerInterfaceFailed")); return nullptr; } auto speaker = AndroidSLESSpeaker::create(engine, outputMix, playerObject, speakerType); if (!speaker) { - ACSDK_ERROR(LX("createFailed").d("reason", "createSpeakerFailed")); + ACSDK_ERROR(LX("createFailed").d("name", name).d("reason", "createSpeakerFailed")); return nullptr; } @@ -413,7 +479,7 @@ std::unique_ptr AndroidSLESMediaPlayer::create( SLEqualizerItf equalizerItf = nullptr; if (enableEqualizer) { if (!playerObject->getInterface(SL_IID_EQUALIZER, &equalizerItf)) { - ACSDK_ERROR(LX("createFailed").d("reason", "equalizerInterfaceUnavailable")); + ACSDK_ERROR(LX("createFailed").d("name", name).d("reason", "equalizerInterfaceUnavailable")); return nullptr; } } @@ -429,14 +495,16 @@ std::unique_ptr AndroidSLESMediaPlayer::create( config, name)); if (!player->registerPrefetchStatusCallback()) { - ACSDK_WARN( - LX(__func__).m("Media player will be unable to retrieve prefetch status information. This may cause choppy " - "playback when connection is poor.")); + ACSDK_WARN(LX(__func__) + .d("name", name) + .m("Media player will be unable to retrieve prefetch status information. This may cause choppy " + "playback when connection is poor.")); } if (enableEqualizer) { if (!player->initializeEqualizer()) { ACSDK_ERROR(LX("createFailed") + .d("name", name) .m("Equalizer does not seem to be supported in this environment. You should turn it " "off in the configuration by setting 'equalizer.enabled' value to false.")); return nullptr; @@ -483,14 +551,20 @@ void AndroidSLESMediaPlayer::onQueueEvent( case AndroidSLESMediaQueue::QueueEvent::ERROR: result = (*m_player)->GetPlayState(m_player, &state); if (result != SL_RESULT_SUCCESS) { - ACSDK_ERROR(LX("onQueueEventFailed").d("reason", "getPlayStateFailed").d("result", result)); + ACSDK_ERROR(LX("onQueueEventFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "getPlayStateFailed") + .d("result", result)); break; } if (state != SL_PLAYSTATE_STOPPED) { result = (*m_player)->SetPlayState(m_player, SL_PLAYSTATE_STOPPED); if (result != SL_RESULT_SUCCESS) { - ACSDK_ERROR(LX("onQueueEventFailed").d("result", result).d("id", m_sourceId)); + ACSDK_ERROR(LX("onQueueEventFailed") + .d("name", RequiresShutdown::name()) + .d("result", result) + .d("id", m_sourceId)); break; } @@ -502,7 +576,10 @@ void AndroidSLESMediaPlayer::onQueueEvent( case AndroidSLESMediaQueue::QueueEvent::FINISHED_PLAYING: result = (*m_player)->SetPlayState(m_player, SL_PLAYSTATE_STOPPED); if (result != SL_RESULT_SUCCESS) { - ACSDK_ERROR(LX("onQueueEventFailed").d("result", result).d("id", m_sourceId)); + ACSDK_ERROR(LX("onQueueEventFailed") + .d("name", RequiresShutdown::name()) + .d("result", result) + .d("id", m_sourceId)); break; } @@ -516,6 +593,7 @@ void AndroidSLESMediaPlayer::onQueueEvent( } } else { ACSDK_DEBUG9(LX("eventIgnored") + .d("name", RequiresShutdown::name()) .d("status", static_cast(status)) .d("requestId", eventId) .d("currentId", m_sourceId)); @@ -528,11 +606,15 @@ void AndroidSLESMediaPlayer::onPrefetchStatusChange(SLuint32 event) { uint32_t status; auto result = (*m_prefetchStatus)->GetPrefetchStatus(m_prefetchStatus, &status); if (result != SL_RESULT_SUCCESS) { - ACSDK_WARN(LX("prefetchStatusFailed").d("result", result)); + ACSDK_WARN(LX("prefetchStatusFailed").d("name", RequiresShutdown::name()).d("result", result)); return; } - ACSDK_DEBUG9(LX("onPrefetchStatusChange").d("event", event).d("observer", m_observer).d("status", status)); + ACSDK_DEBUG9(LX("onPrefetchStatusChange") + .d("name", RequiresShutdown::name()) + .d("event", event) + .d("observer", m_observer) + .d("status", status)); if ((SL_PREFETCHSTATUS_UNDERFLOW == status)) { if (!m_almostDone) { m_observer->onBufferUnderrun(m_sourceId); @@ -550,20 +632,28 @@ void prefetchStatusCallback(SLPrefetchStatusItf caller, void* pContext, SLuint32 bool AndroidSLESMediaPlayer::registerPrefetchStatusCallback() { SLPrefetchStatusItf prefetchStatusInterface; if (!m_playerObject->getInterface(SL_IID_PREFETCHSTATUS, &prefetchStatusInterface)) { - ACSDK_ERROR(LX("unavailablePrefetchInformation.").d("reason", "interfaceUnavailable")); + ACSDK_ERROR(LX("unavailablePrefetchInformation.") + .d("name", RequiresShutdown::name()) + .d("reason", "interfaceUnavailable")); return false; } auto result = (*prefetchStatusInterface)->SetCallbackEventsMask(prefetchStatusInterface, SL_PREFETCHEVENT_STATUSCHANGE); if (result != SL_RESULT_SUCCESS) { - ACSDK_ERROR(LX("unavailablePrefetchInformation.").d("reason", "setEventMaskFailed").d("result", result)); + ACSDK_ERROR(LX("unavailablePrefetchInformation.") + .d("name", RequiresShutdown::name()) + .d("reason", "setEventMaskFailed") + .d("result", result)); return false; } result = (*prefetchStatusInterface)->RegisterCallback(prefetchStatusInterface, prefetchStatusCallback, this); if (result != SL_RESULT_SUCCESS) { - ACSDK_ERROR(LX("unavailablePrefetchInformation.").d("reason", "registerCallbackFailed").d("result", result)); + ACSDK_ERROR(LX("unavailablePrefetchInformation.") + .d("name", RequiresShutdown::name()) + .d("reason", "registerCallbackFailed") + .d("result", result)); return false; } @@ -586,14 +676,20 @@ bool AndroidSLESMediaPlayer::initializeEqualizer() { auto result = (*m_equalizer)->SetEnabled(m_equalizer, SL_BOOLEAN_TRUE); if (result != SL_RESULT_SUCCESS) { - ACSDK_ERROR(LX("initializeEqualizerFailed").d("reason", "SetEnabled failed").d("result", result)); + ACSDK_ERROR(LX("initializeEqualizerFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "SetEnabled failed") + .d("result", result)); return false; } SLuint16 nbBands = 0; result = (*m_equalizer)->GetNumberOfBands(m_equalizer, &nbBands); if (result != SL_RESULT_SUCCESS) { - ACSDK_ERROR(LX("initializeEqualizerFailed").d("reason", "GetNumberOfBands failed").d("result", result)); + ACSDK_ERROR(LX("initializeEqualizerFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "GetNumberOfBands failed") + .d("result", result)); return false; } @@ -601,14 +697,19 @@ bool AndroidSLESMediaPlayer::initializeEqualizer() { m_numberOfEqualizerBands = nbBands; if (0 == m_numberOfEqualizerBands) { - ACSDK_ERROR(LX("initializeEqualizerFailed").d("reason", "No equalizer bands supported").d("result", result)); + ACSDK_ERROR(LX("initializeEqualizerFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "No equalizer bands supported") + .d("result", result)); return false; } // Create band mapper m_bandMapper = EqualizerLinearBandMapper::create(m_numberOfEqualizerBands); if (nullptr == m_bandMapper) { - ACSDK_ERROR(LX("initializeEqualizerFailed").d("reason", "Failed to create band mapper")); + ACSDK_ERROR(LX("initializeEqualizerFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "Failed to create band mapper")); return false; } @@ -618,7 +719,10 @@ bool AndroidSLESMediaPlayer::initializeEqualizer() { SLmilliHertz bandFrequency; result = (*m_equalizer)->GetCenterFreq(m_equalizer, bandIndex, &bandFrequency); if (result != SL_RESULT_SUCCESS) { - ACSDK_ERROR(LX("initializeEqualizerFailed").d("reason", "GetBandLevelRange failed").d("result", result)); + ACSDK_ERROR(LX("initializeEqualizerFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "GetBandLevelRange failed") + .d("result", result)); return false; } frequencyToBandMap[bandFrequency] = bandIndex; @@ -633,7 +737,10 @@ bool AndroidSLESMediaPlayer::initializeEqualizer() { result = (*m_equalizer)->GetBandLevelRange(m_equalizer, &minLevel, &maxLevel); if (result != SL_RESULT_SUCCESS) { - ACSDK_ERROR(LX("initializeEqualizerFailed").d("reason", "GetBandLevelRange failed").d("result", result)); + ACSDK_ERROR(LX("initializeEqualizerFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "GetBandLevelRange failed") + .d("result", result)); return false; } @@ -649,7 +756,9 @@ void AndroidSLESMediaPlayer::setEqualizerBandLevels( ACSDK_DEBUG5(LX(__func__)); if (nullptr == m_bandMapper) { - ACSDK_ERROR(LX("setEqualizerBandLevelsFailed").d("reason", "Equalizer is not enabled for this instance")); + ACSDK_ERROR(LX("setEqualizerBandLevelsFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "Equalizer is not enabled for this instance")); return; } @@ -660,7 +769,10 @@ void AndroidSLESMediaPlayer::setEqualizerBandLevels( } m_bandMapper->mapEqualizerBands(bandLevelMap, [this](int index, int level) { - ACSDK_DEBUG7(LX("setEqualizerBandLevels").d("band index", index).d("band level", level)); + ACSDK_DEBUG7(LX("setEqualizerBandLevels") + .d("name", RequiresShutdown::name()) + .d("band index", index) + .d("band level", level)); auto result = (*m_equalizer) ->SetBandLevel(m_equalizer, m_growingFrequenceBandMap[index], level * DECIBELL_TO_MILLIBELL_MULT); diff --git a/MediaPlayer/AndroidSLESMediaPlayer/test/AndroidSLESMediaPlayerTest.cpp b/MediaPlayer/AndroidSLESMediaPlayer/test/AndroidSLESMediaPlayerTest.cpp index 8f6ee5e6ad..e0799da56f 100644 --- a/MediaPlayer/AndroidSLESMediaPlayer/test/AndroidSLESMediaPlayerTest.cpp +++ b/MediaPlayer/AndroidSLESMediaPlayer/test/AndroidSLESMediaPlayerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -206,20 +206,20 @@ class AndroidSLESMediaPlayerTest : public Test { }; /// Test create with null factory. -TEST_F(AndroidSLESMediaPlayerTest, testCreateNullFactory) { +TEST_F(AndroidSLESMediaPlayerTest, test_createNullFactory) { auto player = AndroidSLESMediaPlayer::create(nullptr, m_engine, SpeakerInterface::Type::AVS_SPEAKER_VOLUME, false); EXPECT_EQ(player, nullptr); } /// Test create with null engine. -TEST_F(AndroidSLESMediaPlayerTest, testCreateNullEngine) { +TEST_F(AndroidSLESMediaPlayerTest, test_createNullEngine) { auto factory = std::make_shared(); auto player = AndroidSLESMediaPlayer::create(factory, nullptr, SpeakerInterface::Type::AVS_SPEAKER_VOLUME, false); EXPECT_EQ(player, nullptr); } /// Test buffer queue with media player. -TEST_F(AndroidSLESMediaPlayerTest, testBQMediaPlayer) { +TEST_F(AndroidSLESMediaPlayerTest, test_bQMediaPlayer) { auto id = m_player->setSource(m_reader, nullptr); WaitEvent finishedEvent; @@ -233,7 +233,7 @@ TEST_F(AndroidSLESMediaPlayerTest, testBQMediaPlayer) { } /// Test buffer queue with media player and raw file. -TEST_F(AndroidSLESMediaPlayerTest, testBQRawMediaPlayer) { +TEST_F(AndroidSLESMediaPlayerTest, test_bQRawMediaPlayer) { auto format = avsCommon::utils::AudioFormat{.dataSigned = true, .numChannels = 2, .sampleSizeInBits = 16, @@ -253,7 +253,7 @@ TEST_F(AndroidSLESMediaPlayerTest, testBQRawMediaPlayer) { } /// Test that media is played correct even if a timeout happens in the first read. -TEST_F(AndroidSLESMediaPlayerTest, testFirstReadTimeout) { +TEST_F(AndroidSLESMediaPlayerTest, test_firstReadTimeout) { // This read iteration indicates the first read call. static const ssize_t firstIteration = 0; m_reader = std::make_shared(MP3_INPUT_CSTR, MP3_INPUT_SIZE, firstIteration); @@ -270,7 +270,7 @@ TEST_F(AndroidSLESMediaPlayerTest, testFirstReadTimeout) { } /// Test that media is played correct even after a timeout during initialization. -TEST_F(AndroidSLESMediaPlayerTest, testInitializeTimeout) { +TEST_F(AndroidSLESMediaPlayerTest, test_initializeTimeout) { // This read iteration occurs during decoder initialization. static const ssize_t initializationIteration = 1; m_reader = std::make_shared(MP3_INPUT_CSTR, MP3_INPUT_SIZE, initializationIteration); @@ -287,7 +287,7 @@ TEST_F(AndroidSLESMediaPlayerTest, testInitializeTimeout) { } /// Test that media is played correct even after a timeout during decoding. -TEST_F(AndroidSLESMediaPlayerTest, testDecodingTimeout) { +TEST_F(AndroidSLESMediaPlayerTest, test_decodingTimeout) { // This read iteration occurs during decoding state. const ssize_t decodeIteration = 10; m_reader = std::make_shared(MP3_INPUT_CSTR, MP3_INPUT_SIZE, decodeIteration); @@ -304,7 +304,7 @@ TEST_F(AndroidSLESMediaPlayerTest, testDecodingTimeout) { } /// Test media player and istream source. -TEST_F(AndroidSLESMediaPlayerTest, testStreamMediaPlayer) { +TEST_F(AndroidSLESMediaPlayerTest, test_streamMediaPlayer) { auto id = m_player->setSource(createStream(), false); WaitEvent finishedEvent; @@ -318,7 +318,7 @@ TEST_F(AndroidSLESMediaPlayerTest, testStreamMediaPlayer) { } /// Test media player, istream source and repeat on. -TEST_F(AndroidSLESMediaPlayerTest, testStreamRepeatMediaPlayer) { +TEST_F(AndroidSLESMediaPlayerTest, test_streamRepeatMediaPlayer) { auto repeat = true; auto id = m_player->setSource(createStream(), repeat); @@ -332,7 +332,7 @@ TEST_F(AndroidSLESMediaPlayerTest, testStreamRepeatMediaPlayer) { } /// Test media player pause / resume. -TEST_F(AndroidSLESMediaPlayerTest, testResumeMediaPlayer) { +TEST_F(AndroidSLESMediaPlayerTest, test_resumeMediaPlayer) { auto repeat = true; auto id = m_player->setSource(createStream(), repeat); @@ -354,14 +354,14 @@ TEST_F(AndroidSLESMediaPlayerTest, testResumeMediaPlayer) { } /// Test play fails with wrong id. -TEST_F(AndroidSLESMediaPlayerTest, testPlayFailed) { +TEST_F(AndroidSLESMediaPlayerTest, test_playFailed) { auto id = m_player->setSource(m_reader, nullptr); EXPECT_CALL(*m_observer, onPlaybackStarted(_)).Times(0); EXPECT_FALSE(m_player->play(id + 1)); } /// Test pause fails with wrong id. -TEST_F(AndroidSLESMediaPlayerTest, testPauseFailed) { +TEST_F(AndroidSLESMediaPlayerTest, test_pauseFailed) { auto id = m_player->setSource(m_reader, nullptr); EXPECT_CALL(*m_observer, onPlaybackStarted(id)).Times(1); EXPECT_CALL(*m_observer, onPlaybackPaused(_)).Times(0); @@ -371,7 +371,7 @@ TEST_F(AndroidSLESMediaPlayerTest, testPauseFailed) { } /// Test pause fails if not playing. -TEST_F(AndroidSLESMediaPlayerTest, testPauseFailedNotPlaying) { +TEST_F(AndroidSLESMediaPlayerTest, test_pauseFailedNotPlaying) { auto id = m_player->setSource(m_reader, nullptr); EXPECT_CALL(*m_observer, onPlaybackStarted(id)).Times(0); EXPECT_CALL(*m_observer, onPlaybackPaused(_)).Times(0); @@ -379,7 +379,7 @@ TEST_F(AndroidSLESMediaPlayerTest, testPauseFailedNotPlaying) { } /// Test resume fails after stop. -TEST_F(AndroidSLESMediaPlayerTest, testResumeFailedAfterStop) { +TEST_F(AndroidSLESMediaPlayerTest, test_resumeFailedAfterStop) { auto id = m_player->setSource(m_reader, nullptr); EXPECT_CALL(*m_observer, onPlaybackStarted(id)).Times(1); EXPECT_CALL(*m_observer, onPlaybackStopped(id)).Times(1); @@ -390,7 +390,7 @@ TEST_F(AndroidSLESMediaPlayerTest, testResumeFailedAfterStop) { } /// Test stop fails with wrong id. -TEST_F(AndroidSLESMediaPlayerTest, testStopFailed) { +TEST_F(AndroidSLESMediaPlayerTest, test_stopFailed) { auto id = m_player->setSource(m_reader, nullptr); auto fakeId = id + 1; EXPECT_CALL(*m_observer, onPlaybackStarted(id)).Times(1); @@ -402,7 +402,7 @@ TEST_F(AndroidSLESMediaPlayerTest, testStopFailed) { } /// Test get offset. -TEST_F(AndroidSLESMediaPlayerTest, testGetOffset) { +TEST_F(AndroidSLESMediaPlayerTest, test_getOffset) { auto id = m_player->setSource(m_reader, nullptr); WaitEvent finishedEvent; diff --git a/MediaPlayer/AndroidSLESMediaPlayer/test/AndroidSLESMediaQueueTest.cpp b/MediaPlayer/AndroidSLESMediaPlayer/test/AndroidSLESMediaQueueTest.cpp index b5dfff02fe..165988efb4 100644 --- a/MediaPlayer/AndroidSLESMediaPlayer/test/AndroidSLESMediaQueueTest.cpp +++ b/MediaPlayer/AndroidSLESMediaPlayer/test/AndroidSLESMediaQueueTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -207,7 +207,7 @@ void AndroidSLESMediaQueueTest::TearDown() { } /// Test buffer queue create. -TEST_F(AndroidSLESMediaQueueTest, testCreateSucceed) { +TEST_F(AndroidSLESMediaQueueTest, test_createSucceed) { std::pair done = {DecoderInterface::Status::DONE, 0}; auto decoder = avsCommon::utils::memory::make_unique>(); EXPECT_CALL(*decoder, read(_, _)).WillOnce(Return(done)); @@ -223,7 +223,7 @@ TEST_F(AndroidSLESMediaQueueTest, testCreateSucceed) { } /// Check that create fail if we are missing the OpenSL ES object. -TEST_F(AndroidSLESMediaQueueTest, testCreateFailMissingSlObject) { +TEST_F(AndroidSLESMediaQueueTest, test_createFailMissingSlObject) { auto decoder = avsCommon::utils::memory::make_unique>(); auto mediaQueue = AndroidSLESMediaQueue::create( nullptr, @@ -236,7 +236,7 @@ TEST_F(AndroidSLESMediaQueueTest, testCreateFailMissingSlObject) { } /// Check that create fail if the @c SL_IID_ANDROIDSIMPLEBUFFERQUEUE is missing. -TEST_F(AndroidSLESMediaQueueTest, testCreateFailMissingInterface) { +TEST_F(AndroidSLESMediaQueueTest, test_createFailMissingInterface) { m_objectMock->mockGetInterface(SL_IID_ANDROIDSIMPLEBUFFERQUEUE, nullptr); auto decoder = avsCommon::utils::memory::make_unique>(); auto mediaQueue = AndroidSLESMediaQueue::create( @@ -250,7 +250,7 @@ TEST_F(AndroidSLESMediaQueueTest, testCreateFailMissingInterface) { } /// Check that create fail if the decoder is missing. -TEST_F(AndroidSLESMediaQueueTest, testCreateFailMissingDecoder) { +TEST_F(AndroidSLESMediaQueueTest, test_createFailMissingDecoder) { auto mediaQueue = AndroidSLESMediaQueue::create( m_slObject, nullptr, @@ -262,14 +262,14 @@ TEST_F(AndroidSLESMediaQueueTest, testCreateFailMissingDecoder) { } /// Check that create fail if the callback function is missing. -TEST_F(AndroidSLESMediaQueueTest, testCreateFailMissingCallback) { +TEST_F(AndroidSLESMediaQueueTest, test_createFailMissingCallback) { auto decoder = avsCommon::utils::memory::make_unique>(); auto mediaQueue = AndroidSLESMediaQueue::create(m_slObject, std::move(decoder), nullptr, PlaybackConfiguration()); EXPECT_EQ(mediaQueue, nullptr); } /// Check that create fail if the callback function cannot be registered. -TEST_F(AndroidSLESMediaQueueTest, testCreateFailRegisterCallback) { +TEST_F(AndroidSLESMediaQueueTest, test_createFailRegisterCallback) { m_queueMock->get().RegisterCallback = mockRegisterCallbackFailed; auto decoder = avsCommon::utils::memory::make_unique>(); auto mediaQueue = AndroidSLESMediaQueue::create(m_slObject, std::move(decoder), nullptr, PlaybackConfiguration()); @@ -277,7 +277,7 @@ TEST_F(AndroidSLESMediaQueueTest, testCreateFailRegisterCallback) { } /// Test buffer queue events when the media queue succeeds to read data from the decoder. -TEST_F(AndroidSLESMediaQueueTest, testOnBufferQueueSucceed) { +TEST_F(AndroidSLESMediaQueueTest, test_onBufferQueueSucceed) { // Always return valid read. // Arbitrary number of bytes that is > 0. constexpr size_t bytesRead{1000}; @@ -306,7 +306,7 @@ TEST_F(AndroidSLESMediaQueueTest, testOnBufferQueueSucceed) { } /// Test buffer queue events when the media queue succeeds to read data from the decoder till the end of the stream. -TEST_F(AndroidSLESMediaQueueTest, testEnqueueTillDone) { +TEST_F(AndroidSLESMediaQueueTest, test_enqueueTillDone) { // Arbitrary number of bytes that is > 0. constexpr size_t bytesRead{1000}; std::pair ok = {DecoderInterface::Status::OK, bytesRead}; @@ -341,7 +341,7 @@ TEST_F(AndroidSLESMediaQueueTest, testEnqueueTillDone) { } /// Test that the buffer queue emits an error event when the decoder fails. -TEST_F(AndroidSLESMediaQueueTest, testDecoderFailure) { +TEST_F(AndroidSLESMediaQueueTest, test_decoderFailure) { std::pair error = {DecoderInterface::Status::ERROR, 0}; auto decoder = avsCommon::utils::memory::make_unique>(); EXPECT_CALL(*decoder, read(_, _)).WillOnce(Return(error)); @@ -358,7 +358,7 @@ TEST_F(AndroidSLESMediaQueueTest, testDecoderFailure) { } /// Test buffer queue events emits an error event when it fails to enqueue a buffer -TEST_F(AndroidSLESMediaQueueTest, testEnqueueFailure) { +TEST_F(AndroidSLESMediaQueueTest, test_enqueueFailure) { // Always return valid read. // Arbitrary number of bytes that is > 0. constexpr size_t bytesRead{1000}; diff --git a/MediaPlayer/AndroidSLESMediaPlayer/test/AndroidSLESSpeakerTest.cpp b/MediaPlayer/AndroidSLESMediaPlayer/test/AndroidSLESSpeakerTest.cpp index b26600935b..57ffe2dca9 100644 --- a/MediaPlayer/AndroidSLESMediaPlayer/test/AndroidSLESSpeakerTest.cpp +++ b/MediaPlayer/AndroidSLESMediaPlayer/test/AndroidSLESSpeakerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -148,21 +148,21 @@ void AndroidSLESSpeakerTest::SetUp() { } /// Test speaker create with null engine. -TEST_F(AndroidSLESSpeakerTest, testCreateNullEngine) { +TEST_F(AndroidSLESSpeakerTest, test_createNullEngine) { auto speaker = AndroidSLESSpeaker::create(nullptr, m_outputMix, m_slObject, AndroidSLESSpeaker::Type::AVS_SPEAKER_VOLUME); EXPECT_EQ(speaker, nullptr); } /// Test speaker create with null output mix. -TEST_F(AndroidSLESSpeakerTest, testCreateNullSpeaker) { +TEST_F(AndroidSLESSpeakerTest, test_createNullSpeaker) { auto speaker = AndroidSLESSpeaker::create(m_engine, m_outputMix, nullptr, AndroidSLESSpeaker::Type::AVS_SPEAKER_VOLUME); EXPECT_EQ(speaker, nullptr); } /// Test speaker create with null engine. -TEST_F(AndroidSLESSpeakerTest, testCreateInterfaceUnavailable) { +TEST_F(AndroidSLESSpeakerTest, test_createInterfaceUnavailable) { m_objectMock->mockGetInterface(SL_IID_VOLUME, nullptr); auto speaker = AndroidSLESSpeaker::create(m_engine, m_outputMix, m_slObject, AndroidSLESSpeaker::Type::AVS_SPEAKER_VOLUME); @@ -170,7 +170,7 @@ TEST_F(AndroidSLESSpeakerTest, testCreateInterfaceUnavailable) { } /// Test speaker create with invalid device configuration. -TEST_F(AndroidSLESSpeakerTest, testCreateInvalidMaxVolume) { +TEST_F(AndroidSLESSpeakerTest, test_createInvalidMaxVolume) { auto mockInvalidMaxVolume = [](SLVolumeItf self, SLmillibel* volume) -> SLresult { *volume = INVALID_MAX_VOLUME; return SL_RESULT_SUCCESS; @@ -182,7 +182,7 @@ TEST_F(AndroidSLESSpeakerTest, testCreateInvalidMaxVolume) { } /// Test set and get volume succeed. -TEST_F(AndroidSLESSpeakerTest, testSetVolumeSucceed) { +TEST_F(AndroidSLESSpeakerTest, test_setVolumeSucceed) { int8_t volume = (AVS_SET_VOLUME_MAX - AVS_SET_VOLUME_MIN) / 2; // Set volume to 50% of max. EXPECT_TRUE(m_speaker->setVolume(volume)); @@ -192,7 +192,7 @@ TEST_F(AndroidSLESSpeakerTest, testSetVolumeSucceed) { } /// Test set volume failed. -TEST_F(AndroidSLESSpeakerTest, testSetVolumeFailed) { +TEST_F(AndroidSLESSpeakerTest, test_setVolumeFailed) { m_volumeMock->get().SetVolumeLevel = mockSetVolumeFailed; int8_t volume = (AVS_SET_VOLUME_MAX - AVS_SET_VOLUME_MIN) / 2; // Set volume to 50% of max. @@ -200,7 +200,7 @@ TEST_F(AndroidSLESSpeakerTest, testSetVolumeFailed) { } /// Test get volume failed. -TEST_F(AndroidSLESSpeakerTest, testGetVolumeFailed) { +TEST_F(AndroidSLESSpeakerTest, test_getVolumeFailed) { m_volumeMock->get().GetVolumeLevel = mockGetVolumeFailed; AndroidSLESSpeaker::SpeakerSettings settings; @@ -208,7 +208,7 @@ TEST_F(AndroidSLESSpeakerTest, testGetVolumeFailed) { } /// Test set and get mute succeed. -TEST_F(AndroidSLESSpeakerTest, testSetMuteSucceed) { +TEST_F(AndroidSLESSpeakerTest, test_setMuteSucceed) { bool mute = !g_mute; // Toggle mute. EXPECT_TRUE(m_speaker->setMute(mute)); @@ -218,20 +218,20 @@ TEST_F(AndroidSLESSpeakerTest, testSetMuteSucceed) { } /// Test set mute failed. -TEST_F(AndroidSLESSpeakerTest, testSetMuteFailed) { +TEST_F(AndroidSLESSpeakerTest, test_setMuteFailed) { m_volumeMock->get().SetMute = mockSetMuteFailed; EXPECT_FALSE(m_speaker->setMute(!g_mute)); } /// Test get mute failed. -TEST_F(AndroidSLESSpeakerTest, testGetMuteFailed) { +TEST_F(AndroidSLESSpeakerTest, test_getMuteFailed) { m_volumeMock->get().GetMute = mockGetMuteFailed; AndroidSLESSpeaker::SpeakerSettings settings; EXPECT_FALSE(m_speaker->getSpeakerSettings(&settings)); } /// Test adjust and get volume succeed. -TEST_F(AndroidSLESSpeakerTest, testAdjustVolumeSucceed) { +TEST_F(AndroidSLESSpeakerTest, test_adjustVolumeSucceed) { int8_t volume = (AVS_SET_VOLUME_MAX - AVS_SET_VOLUME_MIN) / 2; // Set volume to 50% of max then add 50% more. EXPECT_TRUE(m_speaker->setVolume(volume)); EXPECT_TRUE(m_speaker->adjustVolume(volume)); @@ -242,7 +242,7 @@ TEST_F(AndroidSLESSpeakerTest, testAdjustVolumeSucceed) { } /// Test adjust volume failed. -TEST_F(AndroidSLESSpeakerTest, testAdjustVolumeFailed) { +TEST_F(AndroidSLESSpeakerTest, test_adjustVolumeFailed) { m_volumeMock->get().SetVolumeLevel = mockSetVolumeFailed; int8_t volume = (AVS_SET_VOLUME_MAX - AVS_SET_VOLUME_MIN) * 0.1; // Adjust volume by 10% of max. @@ -250,7 +250,7 @@ TEST_F(AndroidSLESSpeakerTest, testAdjustVolumeFailed) { } /// Test adjust volume over maximum value. Speaker should be adjusted till maximum. -TEST_F(AndroidSLESSpeakerTest, testAdjustVolumeOverMax) { +TEST_F(AndroidSLESSpeakerTest, test_adjustVolumeOverMax) { int8_t delta = 10; // Try to adjust volume by a random value. int8_t volume = AVS_SET_VOLUME_MAX; EXPECT_TRUE(m_speaker->setVolume(volume)); @@ -262,7 +262,7 @@ TEST_F(AndroidSLESSpeakerTest, testAdjustVolumeOverMax) { } /// Test adjust volume below minimum value. Speaker should be adjusted to minimum. -TEST_F(AndroidSLESSpeakerTest, testAdjustVolumeUnderMin) { +TEST_F(AndroidSLESSpeakerTest, test_adjustVolumeUnderMin) { int8_t delta = -10; // Try to adjust volume by a random value. int8_t volume = AVS_SET_VOLUME_MIN; EXPECT_TRUE(m_speaker->setVolume(volume)); @@ -274,7 +274,7 @@ TEST_F(AndroidSLESSpeakerTest, testAdjustVolumeUnderMin) { } /// Test set and get volume on values in different ranges to guarantee accuracy. -TEST_F(AndroidSLESSpeakerTest, testSetVolumeAccuracy) { +TEST_F(AndroidSLESSpeakerTest, test_setVolumeAccuracy) { auto speakerPtr = m_speaker.get(); auto check = [speakerPtr](int8_t avsVolume) { AndroidSLESSpeaker::SpeakerSettings settings; @@ -295,7 +295,7 @@ TEST_F(AndroidSLESSpeakerTest, testSetVolumeAccuracy) { } /// Test that the conversion from avs volume to device volume. -TEST_F(AndroidSLESSpeakerTest, testSetDeviceVolume) { +TEST_F(AndroidSLESSpeakerTest, test_setDeviceVolume) { auto speakerPtr = m_speaker.get(); auto check = [speakerPtr](int8_t avsVolume, SLmillibel expected) { EXPECT_TRUE(speakerPtr->setVolume(avsVolume)); diff --git a/MediaPlayer/AndroidSLESMediaPlayer/test/FFmpegAttachmentInputControllerTest.cpp b/MediaPlayer/AndroidSLESMediaPlayer/test/FFmpegAttachmentInputControllerTest.cpp index a37c9ea872..3d0957451f 100644 --- a/MediaPlayer/AndroidSLESMediaPlayer/test/FFmpegAttachmentInputControllerTest.cpp +++ b/MediaPlayer/AndroidSLESMediaPlayer/test/FFmpegAttachmentInputControllerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -83,13 +83,13 @@ size_t MockAttachmentReader::read( } /// Test create controller fail. -TEST(FFmpegAttachmentInputControllerTest, testCreateFailed) { +TEST(FFmpegAttachmentInputControllerTest, test_createFailed) { auto reader = FFmpegAttachmentInputController::create(nullptr); EXPECT_EQ(reader, nullptr); } /// Test raw input format. -TEST(FFmpegAttachmentInputControllerTest, testRawArgument) { +TEST(FFmpegAttachmentInputControllerTest, test_rawArgument) { AudioFormat format{.encoding = AudioFormat::Encoding::LPCM, .endianness = AudioFormat::Endianness::LITTLE, .sampleRateHz = 48000, @@ -114,7 +114,7 @@ TEST(FFmpegAttachmentInputControllerTest, testRawArgument) { } /// Test read from attachment reader. -TEST(FFmpegAttachmentInputControllerTest, testReadOk) { +TEST(FFmpegAttachmentInputControllerTest, test_readOk) { auto mockReader = std::make_shared(); auto reader = FFmpegAttachmentInputController::create(mockReader); ASSERT_NE(reader, nullptr); @@ -131,7 +131,7 @@ TEST(FFmpegAttachmentInputControllerTest, testReadOk) { } /// Test read from stream until the end. -TEST(FFmpegAttachmentInputControllerTest, testReadEof) { +TEST(FFmpegAttachmentInputControllerTest, test_readEof) { auto mockReader = std::make_shared(); auto reader = FFmpegAttachmentInputController::create(mockReader); ASSERT_NE(reader, nullptr); diff --git a/MediaPlayer/AndroidSLESMediaPlayer/test/FFmpegDecoderTest.cpp b/MediaPlayer/AndroidSLESMediaPlayer/test/FFmpegDecoderTest.cpp index 0a0dc1c5dd..1f46bcbe2e 100644 --- a/MediaPlayer/AndroidSLESMediaPlayer/test/FFmpegDecoderTest.cpp +++ b/MediaPlayer/AndroidSLESMediaPlayer/test/FFmpegDecoderTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -130,21 +130,21 @@ void FFmpegDecoderTest::writeCorruptedInput(size_t skipInterval) { } /// Test decoder create. -TEST_F(FFmpegDecoderTest, testCreateSucceed) { +TEST_F(FFmpegDecoderTest, test_createSucceed) { writeInput(); auto decoder = FFmpegDecoder::create(std::move(m_reader), PlaybackConfiguration()); EXPECT_NE(decoder, nullptr); } /// Test decoder create with null reader. -TEST_F(FFmpegDecoderTest, testCreateFailedNullReader) { +TEST_F(FFmpegDecoderTest, test_createFailedNullReader) { writeInput(); auto decoder = FFmpegDecoder::create(nullptr, PlaybackConfiguration()); EXPECT_EQ(decoder, nullptr); } /// Test decoding an entire file. -TEST_F(FFmpegDecoderTest, testDecodeFullFile) { +TEST_F(FFmpegDecoderTest, test_decodeFullFile) { writeInput(); auto decoder = FFmpegDecoder::create(std::move(m_reader), PlaybackConfiguration()); ASSERT_NE(decoder, nullptr); @@ -163,7 +163,7 @@ TEST_F(FFmpegDecoderTest, testDecodeFullFile) { } /// Test that it's possible to decode a file that was been truncated past the header. -TEST_F(FFmpegDecoderTest, testTruncatedInput) { +TEST_F(FFmpegDecoderTest, test_truncatedInput) { std::ifstream mediaFile{m_inputFileName, std::ios_base::binary}; mediaFile.seekg(0, std::ios_base::seek_dir::end); writeInput(mediaFile.tellg() / 2); // Write only half of the file. @@ -185,7 +185,7 @@ TEST_F(FFmpegDecoderTest, testTruncatedInput) { } /// Test that the decoder recovers if the file is missing parts of it. -TEST_F(FFmpegDecoderTest, testCorruptedInput) { +TEST_F(FFmpegDecoderTest, test_corruptedInput) { constexpr size_t interval = 10; // Skip a write at this interval. std::ifstream mediaFile{m_inputFileName, std::ios_base::binary}; mediaFile.seekg(0, std::ios_base::seek_dir::end); @@ -208,7 +208,7 @@ TEST_F(FFmpegDecoderTest, testCorruptedInput) { } /// Test that the decoder will error if input has invalid media. -TEST_F(FFmpegDecoderTest, testInvalidInput) { +TEST_F(FFmpegDecoderTest, test_invalidInput) { // Create input with 0101's std::vector input(BUFFER_SIZE, 0x55); attachment::AttachmentWriter::WriteStatus writeStatus; @@ -231,7 +231,7 @@ TEST_F(FFmpegDecoderTest, testInvalidInput) { } /// Check that read with a buffer that is too small fails. -TEST_F(FFmpegDecoderTest, testReadSmallBuffer) { +TEST_F(FFmpegDecoderTest, test_readSmallBuffer) { writeInput(); auto decoder = FFmpegDecoder::create(std::move(m_reader), PlaybackConfiguration()); ASSERT_NE(decoder, nullptr); @@ -247,7 +247,7 @@ TEST_F(FFmpegDecoderTest, testReadSmallBuffer) { } /// Check that we can abort the decoding during initialization. -TEST_F(FFmpegDecoderTest, testAbortInitialization) { +TEST_F(FFmpegDecoderTest, test_abortInitialization) { auto decoder = FFmpegDecoder::create(std::move(m_reader), PlaybackConfiguration()); ASSERT_NE(decoder, nullptr); diff --git a/MediaPlayer/AndroidSLESMediaPlayer/test/FFmpegStreamInputControllerTest.cpp b/MediaPlayer/AndroidSLESMediaPlayer/test/FFmpegStreamInputControllerTest.cpp index 3e92169fc4..b350cb8116 100644 --- a/MediaPlayer/AndroidSLESMediaPlayer/test/FFmpegStreamInputControllerTest.cpp +++ b/MediaPlayer/AndroidSLESMediaPlayer/test/FFmpegStreamInputControllerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -52,20 +52,20 @@ std::shared_ptr createStream() { } /// Test decoder input create succeed. -TEST(FFmpegStreamInputControllerTest, testCreateSucceed) { +TEST(FFmpegStreamInputControllerTest, test_createSucceed) { auto stream = createStream(); auto reader = FFmpegStreamInputController::create(stream, false); EXPECT_NE(reader, nullptr); } /// Test decoder input create with null input failed. -TEST(FFmpegStreamInputControllerTest, testCreateFailed) { +TEST(FFmpegStreamInputControllerTest, test_createFailed) { auto reader = FFmpegStreamInputController::create(nullptr, false); EXPECT_EQ(reader, nullptr); } /// Test read from stream. -TEST(FFmpegStreamInputControllerTest, testReadSucceed) { +TEST(FFmpegStreamInputControllerTest, test_readSucceed) { auto stream = createStream(); auto reader = FFmpegStreamInputController::create(stream, false); ASSERT_NE(reader, nullptr); @@ -82,7 +82,7 @@ TEST(FFmpegStreamInputControllerTest, testReadSucceed) { } /// Test read from stream until the end. -TEST(FFmpegStreamInputControllerTest, testReadEof) { +TEST(FFmpegStreamInputControllerTest, test_readEof) { auto stream = createStream(); auto reader = FFmpegStreamInputController::create(stream, false); ASSERT_NE(reader, nullptr); @@ -100,7 +100,7 @@ TEST(FFmpegStreamInputControllerTest, testReadEof) { } /// Test read with repeat on from a stream. -TEST(FFmpegStreamInputControllerTest, testReadRepeat) { +TEST(FFmpegStreamInputControllerTest, test_readRepeat) { auto stream = createStream(); auto reader = FFmpegStreamInputController::create(stream, true); ASSERT_NE(reader, nullptr); diff --git a/MediaPlayer/AndroidSLESMediaPlayer/test/FFmpegUrlInputControllerTest.cpp b/MediaPlayer/AndroidSLESMediaPlayer/test/FFmpegUrlInputControllerTest.cpp index e64f228bc4..eb9b0a7b95 100644 --- a/MediaPlayer/AndroidSLESMediaPlayer/test/FFmpegUrlInputControllerTest.cpp +++ b/MediaPlayer/AndroidSLESMediaPlayer/test/FFmpegUrlInputControllerTest.cpp @@ -116,7 +116,7 @@ class FFmpegUrlInputControllerTest : public Test { }; /// Test input controller create succeed. -TEST_F(FFmpegUrlInputControllerTest, testCreateSucceed) { +TEST_F(FFmpegUrlInputControllerTest, test_createSucceed) { EXPECT_CALL(*m_parser, initializeParsing(_)).WillOnce(Return(true)); EXPECT_CALL(*m_parser, next()).WillOnce(Return(INVALID_URL_ENTRY)); auto reader = FFmpegUrlInputController::create(m_parser, PLAYLIST_URL, ZERO_OFFSET, DO_NOT_REPEAT); @@ -124,26 +124,26 @@ TEST_F(FFmpegUrlInputControllerTest, testCreateSucceed) { } /// Test input controller create with null playlist parser failed. -TEST_F(FFmpegUrlInputControllerTest, testCreateNullParserFailed) { +TEST_F(FFmpegUrlInputControllerTest, test_createNullParserFailed) { auto reader = FFmpegUrlInputController::create(nullptr, PLAYLIST_URL, ZERO_OFFSET, DO_NOT_REPEAT); EXPECT_EQ(reader, nullptr); } /// Test input controller create with empty url failed. -TEST_F(FFmpegUrlInputControllerTest, testCreateEmptyUrlFailed) { +TEST_F(FFmpegUrlInputControllerTest, test_createEmptyUrlFailed) { auto reader = FFmpegUrlInputController::create(m_parser, "", ZERO_OFFSET, DO_NOT_REPEAT); EXPECT_EQ(reader, nullptr); } /// Test input controller create with null playlist parser failed. -TEST_F(FFmpegUrlInputControllerTest, testCreateInvalidUrlFailed) { +TEST_F(FFmpegUrlInputControllerTest, test_createInvalidUrlFailed) { EXPECT_CALL(*m_parser, initializeParsing(_)).WillOnce(Return(false)); auto reader = FFmpegUrlInputController::create(m_parser, PLAYLIST_URL, ZERO_OFFSET, DO_NOT_REPEAT); EXPECT_EQ(reader, nullptr); } /// Test input controller getContext. -TEST_F(FFmpegUrlInputControllerTest, testGetContextSucceed) { +TEST_F(FFmpegUrlInputControllerTest, test_getContextSucceed) { PlaylistEntry validEntry = PlaylistEntry(INPUT_FOLDER + MP3_FILE_PATH, DURATION, PlaylistParseResult::FINISHED); EXPECT_CALL(*m_parser, initializeParsing(_)).WillOnce(Return(true)); EXPECT_CALL(*m_parser, next()).WillOnce(Return(validEntry)); @@ -158,7 +158,7 @@ TEST_F(FFmpegUrlInputControllerTest, testGetContextSucceed) { } /// Test input controller getContext with non-zero offset. -TEST_F(FFmpegUrlInputControllerTest, testGetContextOffsetSucceed) { +TEST_F(FFmpegUrlInputControllerTest, test_getContextOffsetSucceed) { PlaylistEntry validEntry = PlaylistEntry(INPUT_FOLDER + MP3_FILE_PATH, DURATION, PlaylistParseResult::FINISHED); EXPECT_CALL(*m_parser, initializeParsing(_)).WillOnce(Return(true)); EXPECT_CALL(*m_parser, next()).WillOnce(Return(validEntry)); @@ -174,7 +174,7 @@ TEST_F(FFmpegUrlInputControllerTest, testGetContextOffsetSucceed) { } /// Test input controller getContext. -TEST_F(FFmpegUrlInputControllerTest, testGetContextInvalidUrl) { +TEST_F(FFmpegUrlInputControllerTest, test_getContextInvalidUrl) { EXPECT_CALL(*m_parser, initializeParsing(_)).WillOnce(Return(true)); EXPECT_CALL(*m_parser, next()).WillOnce(Return(INVALID_URL_ENTRY)); auto reader = FFmpegUrlInputController::create(m_parser, PLAYLIST_URL, ZERO_OFFSET, DO_NOT_REPEAT); @@ -186,7 +186,7 @@ TEST_F(FFmpegUrlInputControllerTest, testGetContextInvalidUrl) { } /// Test get context after switching files. -TEST_F(FFmpegUrlInputControllerTest, testGetContextAfterNext) { +TEST_F(FFmpegUrlInputControllerTest, test_getContextAfterNext) { PlaylistEntry validEntry = PlaylistEntry(INPUT_FOLDER + MP3_FILE_PATH, DURATION, PlaylistParseResult::FINISHED); // Parser will return INVALID_URL_ENTRY first, then validEntry @@ -207,7 +207,7 @@ TEST_F(FFmpegUrlInputControllerTest, testGetContextAfterNext) { } /// Test has next when parser isn't done. -TEST_F(FFmpegUrlInputControllerTest, testHasNext) { +TEST_F(FFmpegUrlInputControllerTest, test_hasNext) { PlaylistEntry validEntry = PlaylistEntry(INPUT_FOLDER + MP3_FILE_PATH, DURATION, PlaylistParseResult::STILL_ONGOING); EXPECT_CALL(*m_parser, initializeParsing(_)).WillOnce(Return(true)); @@ -219,7 +219,7 @@ TEST_F(FFmpegUrlInputControllerTest, testHasNext) { } /// Test has next after playlist parser is done. -TEST_F(FFmpegUrlInputControllerTest, testDone) { +TEST_F(FFmpegUrlInputControllerTest, test_done) { PlaylistEntry validEntry = PlaylistEntry(INPUT_FOLDER + MP3_FILE_PATH, DURATION, PlaylistParseResult::FINISHED); EXPECT_CALL(*m_parser, initializeParsing(_)).WillOnce(Return(true)); EXPECT_CALL(*m_parser, next()).WillOnce(Return(validEntry)); @@ -230,7 +230,7 @@ TEST_F(FFmpegUrlInputControllerTest, testDone) { } /// Test parsing playlist with repeat on -TEST_F(FFmpegUrlInputControllerTest, testPlaylistRepeat) { +TEST_F(FFmpegUrlInputControllerTest, test_playlistRepeat) { bool repeat = true; EXPECT_CALL(*m_parser, initializeParsing(TEST_M3U_PLAYLIST_URL)) .WillOnce(Invoke(m_parser.get(), &MockPlaylistParser::initializeParsingReal)) @@ -262,7 +262,7 @@ TEST_F(FFmpegUrlInputControllerTest, testPlaylistRepeat) { } /// Test parsing media url with repeat on -TEST_F(FFmpegUrlInputControllerTest, testMediaUrlRepeat) { +TEST_F(FFmpegUrlInputControllerTest, test_mediaUrlRepeat) { bool repeat = true; EXPECT_CALL(*m_parser, initializeParsing(TEST_MEDIA_URL)) .Times(2) diff --git a/MediaPlayer/GStreamerMediaPlayer/include/MediaPlayer/MediaPlayer.h b/MediaPlayer/GStreamerMediaPlayer/include/MediaPlayer/MediaPlayer.h index dd18f95a00..45bc55761d 100644 --- a/MediaPlayer/GStreamerMediaPlayer/include/MediaPlayer/MediaPlayer.h +++ b/MediaPlayer/GStreamerMediaPlayer/include/MediaPlayer/MediaPlayer.h @@ -66,6 +66,7 @@ class MediaPlayer * @param enableEqualizer Flag, indicating whether equalizer should be enabled for this instance. * @param type The type used to categorize the speaker for volume control. * @param name Readable name for the new instance. + * @param enableLiveMode Flag, indicating if the player is in live mode. * @return An instance of the @c MediaPlayer if successful else a @c nullptr. */ static std::shared_ptr create( @@ -74,8 +75,8 @@ class MediaPlayer bool enableEqualizer = false, avsCommon::sdkInterfaces::SpeakerInterface::Type type = avsCommon::sdkInterfaces::SpeakerInterface::Type::AVS_SPEAKER_VOLUME, - std::string name = ""); - + std::string name = "", + bool enableLiveMode = false); /** * Destructor. */ @@ -200,13 +201,14 @@ class MediaPlayer * @param enableEqualizer Flag, indicating whether equalizer should be enabled for this instance. * @param type The type used to categorize the speaker for volume control. * @param name Readable name of this instance. + * @param enableLiveMode Flag, indicating the player is in live mode */ MediaPlayer( std::shared_ptr contentFetcherFactory, bool enableEqualizer, avsCommon::sdkInterfaces::SpeakerInterface::Type type, - std::string name); - + std::string name, + bool enableLiveMode); /** * The worker loop to run the glib mainloop. */ @@ -619,6 +621,9 @@ class MediaPlayer /// Stream offset before we teardown the pipeline std::chrono::milliseconds m_offsetBeforeTeardown; + + /// Flag to indicate if the player is in live mode. + const bool m_isLiveMode; }; } // namespace mediaPlayer diff --git a/MediaPlayer/GStreamerMediaPlayer/src/MediaPlayer.cpp b/MediaPlayer/GStreamerMediaPlayer/src/MediaPlayer.cpp index f90cac5e07..9c178cef6f 100644 --- a/MediaPlayer/GStreamerMediaPlayer/src/MediaPlayer.cpp +++ b/MediaPlayer/GStreamerMediaPlayer/src/MediaPlayer.cpp @@ -160,9 +160,11 @@ std::shared_ptr MediaPlayer::create( std::shared_ptr contentFetcherFactory, bool enableEqualizer, SpeakerInterface::Type type, - std::string name) { - ACSDK_DEBUG9(LX("createCalled")); - std::shared_ptr mediaPlayer(new MediaPlayer(contentFetcherFactory, enableEqualizer, type, name)); + std::string name, + bool enableLiveMode) { + ACSDK_DEBUG9(LX("createCalled").d("name", name)); + std::shared_ptr mediaPlayer( + new MediaPlayer(contentFetcherFactory, enableEqualizer, type, name, enableLiveMode)); if (mediaPlayer->init()) { return mediaPlayer; } else { @@ -171,7 +173,7 @@ std::shared_ptr MediaPlayer::create( }; MediaPlayer::~MediaPlayer() { - ACSDK_DEBUG9(LX("~MediaPlayerCalled")); + ACSDK_DEBUG9(LX(__func__).d("name", RequiresShutdown::name())); cleanUpSource(); g_main_loop_quit(m_mainLoop); if (m_mainLoopThread.joinable()) { @@ -189,7 +191,7 @@ MediaPlayer::~MediaPlayer() { MediaPlayer::SourceId MediaPlayer::setSource( std::shared_ptr reader, const avsCommon::utils::AudioFormat* audioFormat) { - ACSDK_DEBUG9(LX("setSourceCalled").d("sourceType", "AttachmentReader")); + ACSDK_DEBUG9(LX("setSourceCalled").d("name", RequiresShutdown::name()).d("sourceType", "AttachmentReader")); std::promise promise; auto future = promise.get_future(); std::function callback = [this, &reader, &promise, audioFormat]() { @@ -203,7 +205,7 @@ MediaPlayer::SourceId MediaPlayer::setSource( } MediaPlayer::SourceId MediaPlayer::setSource(std::shared_ptr stream, bool repeat) { - ACSDK_DEBUG9(LX("setSourceCalled").d("sourceType", "istream")); + ACSDK_DEBUG9(LX("setSourceCalled").d("name", RequiresShutdown::name()).d("sourceType", "istream")); std::promise promise; auto future = promise.get_future(); std::function callback = [this, &stream, repeat, &promise]() { @@ -217,7 +219,7 @@ MediaPlayer::SourceId MediaPlayer::setSource(std::shared_ptr strea } MediaPlayer::SourceId MediaPlayer::setSource(const std::string& url, std::chrono::milliseconds offset, bool repeat) { - ACSDK_DEBUG9(LX("setSourceForUrlCalled").sensitive("url", url)); + ACSDK_DEBUG9(LX("setSourceForUrlCalled").d("name", RequiresShutdown::name()).sensitive("url", url)); std::promise promise; auto future = promise.get_future(); std::function callback = [this, url, offset, &promise, repeat]() { @@ -231,7 +233,7 @@ MediaPlayer::SourceId MediaPlayer::setSource(const std::string& url, std::chrono } uint64_t MediaPlayer::getNumBytesBuffered() { - ACSDK_DEBUG9(LX("getNumBytesBuffered")); + ACSDK_DEBUG9(LX("getNumBytesBuffered").d("name", RequiresShutdown::name())); guint64 bytesBuffered = 0; if (m_pipeline.appsrc) { bytesBuffered = gst_app_src_get_current_level_bytes(GST_APP_SRC(m_pipeline.appsrc)); @@ -245,9 +247,9 @@ uint64_t MediaPlayer::getNumBytesBuffered() { } bool MediaPlayer::play(MediaPlayer::SourceId id) { - ACSDK_DEBUG9(LX("playCalled")); + ACSDK_DEBUG9(LX("playCalled").d("name", RequiresShutdown::name())); if (!m_source) { - ACSDK_ERROR(LX("playFailed").d("reason", "sourceNotSet")); + ACSDK_ERROR(LX("playFailed").d("name", RequiresShutdown::name()).d("reason", "sourceNotSet")); return ERROR; } @@ -267,7 +269,7 @@ bool MediaPlayer::play(MediaPlayer::SourceId id) { } bool MediaPlayer::stop(MediaPlayer::SourceId id) { - ACSDK_DEBUG9(LX("stopCalled")); + ACSDK_DEBUG9(LX("stopCalled").d("name", RequiresShutdown::name())); std::promise promise; auto future = promise.get_future(); std::function callback = [this, id, &promise]() { @@ -281,7 +283,7 @@ bool MediaPlayer::stop(MediaPlayer::SourceId id) { } bool MediaPlayer::pause(MediaPlayer::SourceId id) { - ACSDK_DEBUG9(LX("pausedCalled")); + ACSDK_DEBUG9(LX("pausedCalled").d("name", RequiresShutdown::name())); std::promise promise; auto future = promise.get_future(); std::function callback = [this, id, &promise]() { @@ -295,7 +297,7 @@ bool MediaPlayer::pause(MediaPlayer::SourceId id) { } bool MediaPlayer::resume(MediaPlayer::SourceId id) { - ACSDK_DEBUG9(LX("resumeCalled")); + ACSDK_DEBUG9(LX("resumeCalled").d("name", RequiresShutdown::name())); std::promise promise; auto future = promise.get_future(); std::function callback = [this, id, &promise]() { @@ -309,7 +311,7 @@ bool MediaPlayer::resume(MediaPlayer::SourceId id) { } std::chrono::milliseconds MediaPlayer::getOffset(MediaPlayer::SourceId id) { - ACSDK_DEBUG9(LX("getOffsetCalled")); + ACSDK_DEBUG9(LX("getOffsetCalled").d("name", RequiresShutdown::name())); std::promise promise; auto future = promise.get_future(); std::function callback = [this, id, &promise]() { @@ -324,7 +326,7 @@ std::chrono::milliseconds MediaPlayer::getOffset(MediaPlayer::SourceId id) { } void MediaPlayer::setObserver(std::shared_ptr observer) { - ACSDK_DEBUG9(LX("setObserverCalled")); + ACSDK_DEBUG9(LX("setObserverCalled").d("name", RequiresShutdown::name())); std::promise promise; auto future = promise.get_future(); std::function callback = [this, &promise, &observer]() { @@ -338,7 +340,7 @@ void MediaPlayer::setObserver(std::shared_ptr obse } bool MediaPlayer::setVolume(int8_t volume) { - ACSDK_DEBUG9(LX("setVolumeCalled")); + ACSDK_DEBUG9(LX("setVolumeCalled").d("name", RequiresShutdown::name())); std::promise promise; auto future = promise.get_future(); std::function callback = [this, &promise, volume]() { @@ -361,24 +363,26 @@ void MediaPlayer::handleSetVolumeInternal(gdouble gstVolume) { } void MediaPlayer::handleSetVolume(std::promise* promise, int8_t volume) { - ACSDK_DEBUG9(LX("handleSetVolumeCalled")); + ACSDK_DEBUG9(LX("handleSetVolumeCalled").d("name", RequiresShutdown::name())); auto toGstVolume = Normalizer::create(AVS_SET_VOLUME_MIN, AVS_SET_VOLUME_MAX, GST_SET_VOLUME_MIN, GST_SET_VOLUME_MAX); if (!toGstVolume) { - ACSDK_ERROR(LX("handleSetVolumeFailed").d("reason", "createNormalizerFailed")); + ACSDK_ERROR( + LX("handleSetVolumeFailed").d("name", RequiresShutdown::name()).d("reason", "createNormalizerFailed")); promise->set_value(false); return; } gdouble gstVolume; if (!m_pipeline.volume) { - ACSDK_ERROR(LX("handleSetVolumeFailed").d("reason", "volumeElementNull")); + ACSDK_ERROR(LX("handleSetVolumeFailed").d("name", RequiresShutdown::name()).d("reason", "volumeElementNull")); promise->set_value(false); return; } if (!toGstVolume->normalize(volume, &gstVolume)) { - ACSDK_ERROR(LX("handleSetVolumeFailed").d("reason", "normalizeVolumeFailed")); + ACSDK_ERROR( + LX("handleSetVolumeFailed").d("name", RequiresShutdown::name()).d("reason", "normalizeVolumeFailed")); promise->set_value(false); return; } @@ -388,7 +392,7 @@ void MediaPlayer::handleSetVolume(std::promise* promise, int8_t volume) { } bool MediaPlayer::adjustVolume(int8_t delta) { - ACSDK_DEBUG9(LX("adjustVolumeCalled")); + ACSDK_DEBUG9(LX("adjustVolumeCalled").d("name", RequiresShutdown::name())); std::promise promise; auto future = promise.get_future(); std::function callback = [this, &promise, delta]() { @@ -402,18 +406,19 @@ bool MediaPlayer::adjustVolume(int8_t delta) { } void MediaPlayer::handleAdjustVolume(std::promise* promise, int8_t delta) { - ACSDK_DEBUG9(LX("handleAdjustVolumeCalled")); + ACSDK_DEBUG9(LX("handleAdjustVolumeCalled").d("name", RequiresShutdown::name())); auto toGstDeltaVolume = Normalizer::create(AVS_ADJUST_VOLUME_MIN, AVS_ADJUST_VOLUME_MAX, GST_ADJUST_VOLUME_MIN, GST_ADJUST_VOLUME_MAX); if (!toGstDeltaVolume) { - ACSDK_ERROR(LX("handleAdjustVolumeFailed").d("reason", "createNormalizerFailed")); + ACSDK_ERROR( + LX("handleAdjustVolumeFailed").d("name", RequiresShutdown::name()).d("reason", "createNormalizerFailed")); promise->set_value(false); return; } if (!m_pipeline.volume) { - ACSDK_ERROR(LX("adjustVolumeFailed").d("reason", "volumeElementNull")); + ACSDK_ERROR(LX("adjustVolumeFailed").d("name", RequiresShutdown::name()).d("reason", "volumeElementNull")); promise->set_value(false); return; } @@ -423,7 +428,7 @@ void MediaPlayer::handleAdjustVolume(std::promise* promise, int8_t delta) gdouble gstDelta; if (!toGstDeltaVolume->normalize(delta, &gstDelta)) { - ACSDK_ERROR(LX("adjustVolumeFailed").d("reason", "normalizeVolumeFailed")); + ACSDK_ERROR(LX("adjustVolumeFailed").d("name", RequiresShutdown::name()).d("reason", "normalizeVolumeFailed")); promise->set_value(false); return; } @@ -439,7 +444,7 @@ void MediaPlayer::handleAdjustVolume(std::promise* promise, int8_t delta) } bool MediaPlayer::setMute(bool mute) { - ACSDK_DEBUG9(LX("setMuteCalled")); + ACSDK_DEBUG9(LX("setMuteCalled").d("name", RequiresShutdown::name())); std::promise promise; auto future = promise.get_future(); std::function callback = [this, &promise, mute]() { @@ -453,9 +458,9 @@ bool MediaPlayer::setMute(bool mute) { } void MediaPlayer::handleSetMute(std::promise* promise, bool mute) { - ACSDK_DEBUG9(LX("handleSetMuteCalled")); + ACSDK_DEBUG9(LX("handleSetMuteCalled").d("name", RequiresShutdown::name())); if (!m_pipeline.volume) { - ACSDK_ERROR(LX("setMuteFailed").d("reason", "volumeElementNull")); + ACSDK_ERROR(LX("setMuteFailed").d("name", RequiresShutdown::name()).d("reason", "volumeElementNull")); promise->set_value(false); return; } @@ -467,7 +472,7 @@ void MediaPlayer::handleSetMute(std::promise* promise, bool mute) { } bool MediaPlayer::getSpeakerSettings(SpeakerInterface::SpeakerSettings* settings) { - ACSDK_DEBUG9(LX("getSpeakerSettingsCalled")); + ACSDK_DEBUG9(LX("getSpeakerSettingsCalled").d("name", RequiresShutdown::name())); std::promise promise; auto future = promise.get_future(); std::function callback = [this, &promise, settings]() { @@ -483,13 +488,14 @@ bool MediaPlayer::getSpeakerSettings(SpeakerInterface::SpeakerSettings* settings void MediaPlayer::handleGetSpeakerSettings( std::promise* promise, avsCommon::sdkInterfaces::SpeakerInterface::SpeakerSettings* settings) { - ACSDK_DEBUG9(LX("handleGetSpeakerSettingsCalled")); + ACSDK_DEBUG9(LX("handleGetSpeakerSettingsCalled").d("name", RequiresShutdown::name())); if (!settings) { - ACSDK_ERROR(LX("getSpeakerSettingsFailed").d("reason", "nullSettings")); + ACSDK_ERROR(LX("getSpeakerSettingsFailed").d("name", RequiresShutdown::name()).d("reason", "nullSettings")); promise->set_value(false); return; } else if (!m_pipeline.volume) { - ACSDK_ERROR(LX("getSpeakerSettingsFailed").d("reason", "volumeElementNull")); + ACSDK_ERROR( + LX("getSpeakerSettingsFailed").d("name", RequiresShutdown::name()).d("reason", "volumeElementNull")); promise->set_value(false); return; } @@ -497,7 +503,9 @@ void MediaPlayer::handleGetSpeakerSettings( auto toAVSVolume = Normalizer::create(GST_SET_VOLUME_MIN, GST_SET_VOLUME_MAX, AVS_SET_VOLUME_MIN, AVS_SET_VOLUME_MAX); if (!toAVSVolume) { - ACSDK_ERROR(LX("handleGetSpeakerSettingsFailed").d("reason", "createNormalizerFailed")); + ACSDK_ERROR(LX("handleGetSpeakerSettingsFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "createNormalizerFailed")); promise->set_value(false); return; } @@ -514,7 +522,9 @@ void MediaPlayer::handleGetSpeakerSettings( } if (!toAVSVolume->normalize(gstVolume, &avsVolume)) { - ACSDK_ERROR(LX("handleGetSpeakerSettingsFailed").d("reason", "normalizeVolumeFailed")); + ACSDK_ERROR(LX("handleGetSpeakerSettingsFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "normalizeVolumeFailed")); promise->set_value(false); return; } @@ -527,7 +537,7 @@ void MediaPlayer::handleGetSpeakerSettings( } SpeakerInterface::Type MediaPlayer::getSpeakerType() { - ACSDK_DEBUG9(LX("getSpeakerTypeCalled")); + ACSDK_DEBUG9(LX("getSpeakerTypeCalled").d("name", RequiresShutdown::name())); return m_speakerType; } @@ -555,7 +565,8 @@ MediaPlayer::MediaPlayer( std::shared_ptr contentFetcherFactory, bool enableEqualizer, SpeakerInterface::Type type, - std::string name) : + std::string name, + bool enableLiveMode) : RequiresShutdown{name}, m_lastVolume{GST_SET_VOLUME_MAX}, m_isMuted{false}, @@ -571,7 +582,8 @@ MediaPlayer::MediaPlayer( m_playPending{false}, m_pausePending{false}, m_resumePending{false}, - m_pauseImmediately{false} { + m_pauseImmediately{false}, + m_isLiveMode{enableLiveMode} { } void MediaPlayer::workerLoop() { @@ -590,22 +602,22 @@ void MediaPlayer::workerLoop() { bool MediaPlayer::init() { m_workerContext = g_main_context_new(); if (!m_workerContext) { - ACSDK_ERROR(LX("initPlayerFailed").d("reason", "nullWorkerContext")); + ACSDK_ERROR(LX("initPlayerFailed").d("name", RequiresShutdown::name()).d("reason", "nullWorkerContext")); return false; } if (!(m_mainLoop = g_main_loop_new(m_workerContext, false))) { - ACSDK_ERROR(LX("initPlayerFailed").d("reason", "gstMainLoopNewFailed")); + ACSDK_ERROR(LX("initPlayerFailed").d("name", RequiresShutdown::name()).d("reason", "gstMainLoopNewFailed")); return false; }; if (false == gst_init_check(NULL, NULL, NULL)) { - ACSDK_ERROR(LX("initPlayerFailed").d("reason", "gstInitCheckFailed")); + ACSDK_ERROR(LX("initPlayerFailed").d("name", RequiresShutdown::name()).d("reason", "gstInitCheckFailed")); return false; } if (!setupPipeline()) { - ACSDK_ERROR(LX("initPlayerFailed").d("reason", "setupPipelineFailed")); + ACSDK_ERROR(LX("initPlayerFailed").d("name", RequiresShutdown::name()).d("reason", "setupPipelineFailed")); return false; } @@ -617,26 +629,31 @@ bool MediaPlayer::init() { bool MediaPlayer::setupPipeline() { m_pipeline.decodedQueue = gst_element_factory_make("queue2", "decodedQueue"); if (!m_pipeline.decodedQueue) { - ACSDK_ERROR(LX("setupPipelineFailed").d("reason", "createQueueElementFailed")); + ACSDK_ERROR( + LX("setupPipelineFailed").d("name", RequiresShutdown::name()).d("reason", "createQueueElementFailed")); return false; } - g_object_set(m_pipeline.decodedQueue, "use-buffering", TRUE, NULL); + g_object_set(m_pipeline.decodedQueue, "use-buffering", m_isLiveMode ? FALSE : TRUE, NULL); m_pipeline.converter = gst_element_factory_make("audioconvert", "converter"); if (!m_pipeline.converter) { - ACSDK_ERROR(LX("setupPipelineFailed").d("reason", "createConverterElementFailed")); + ACSDK_ERROR( + LX("setupPipelineFailed").d("name", RequiresShutdown::name()).d("reason", "createConverterElementFailed")); return false; } m_pipeline.volume = gst_element_factory_make("volume", "volume"); if (!m_pipeline.volume) { - ACSDK_ERROR(LX("setupPipelineFailed").d("reason", "createVolumeElementFailed")); + ACSDK_ERROR( + LX("setupPipelineFailed").d("name", RequiresShutdown::name()).d("reason", "createVolumeElementFailed")); return false; } if (m_equalizerEnabled) { m_pipeline.equalizer = gst_element_factory_make("equalizer-3bands", "equalizer"); if (!m_pipeline.equalizer) { - ACSDK_ERROR(LX("setupPipelineFailed").d("reason", "createEqualizerElementFailed")); + ACSDK_ERROR(LX("setupPipelineFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "createEqualizerElementFailed")); return false; } } @@ -647,6 +664,7 @@ bool MediaPlayer::setupPipeline() { m_pipeline.audioSink = gst_element_factory_make(audioSinkElement.c_str(), "audio_sink"); if (!m_pipeline.audioSink) { ACSDK_ERROR(LX("setupPipelineFailed") + .d("name", RequiresShutdown::name()) .d("reason", "createAudioSinkElementFailed") .d("audioSinkElement", audioSinkElement)); return false; @@ -654,7 +672,8 @@ bool MediaPlayer::setupPipeline() { GstCaps* caps = gst_caps_new_empty_simple("audio/x-raw"); if (!caps) { - ACSDK_ERROR(LX("setupPipelineFailed").d("reason", "createCapabilityStructFailed")); + ACSDK_ERROR( + LX("setupPipelineFailed").d("name", RequiresShutdown::name()).d("reason", "createCapabilityStructFailed")); return false; } @@ -686,26 +705,33 @@ bool MediaPlayer::setupPipeline() { // Add resample logic if configuration found if (!gst_caps_is_empty(caps)) { - ACSDK_INFO(LX("outputConversion").d("string", gst_caps_to_string(caps))); + ACSDK_INFO( + LX("outputConversion").d("name", RequiresShutdown::name()).d("string", gst_caps_to_string(caps))); m_pipeline.resample = gst_element_factory_make("audioresample", "resample"); if (!m_pipeline.resample) { - ACSDK_ERROR(LX("setupPipelineFailed").d("reason", "createResampleElementFailed")); + ACSDK_ERROR(LX("setupPipelineFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "createResampleElementFailed")); return false; } m_pipeline.caps = gst_element_factory_make("capsfilter", "caps"); if (!m_pipeline.caps) { - ACSDK_ERROR(LX("setupPipelineFailed").d("reason", "createCapabilityElementFailed")); + ACSDK_ERROR(LX("setupPipelineFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "createCapabilityElementFailed")); return false; } g_object_set(G_OBJECT(m_pipeline.caps), "caps", caps, NULL); } else { - ACSDK_INFO(LX("invalidOutputConversion").d("string", gst_caps_to_string(caps))); + ACSDK_INFO(LX("invalidOutputConversion") + .d("name", RequiresShutdown::name()) + .d("string", gst_caps_to_string(caps))); } } else { - ACSDK_DEBUG9(LX("noOutputConversion")); + ACSDK_DEBUG9(LX("noOutputConversion").d("name", RequiresShutdown::name())); } // clean up caps object @@ -713,7 +739,8 @@ bool MediaPlayer::setupPipeline() { m_pipeline.pipeline = gst_pipeline_new("audio-pipeline"); if (!m_pipeline.pipeline) { - ACSDK_ERROR(LX("setupPipelineFailed").d("reason", "createPipelineElementFailed")); + ACSDK_ERROR( + LX("setupPipelineFailed").d("name", RequiresShutdown::name()).d("reason", "createPipelineElementFailed")); return false; } @@ -733,7 +760,9 @@ bool MediaPlayer::setupPipeline() { gst_bin_add(GST_BIN(m_pipeline.pipeline), m_pipeline.equalizer); pipelineTailElement = m_pipeline.equalizer; if (!gst_element_link(m_pipeline.equalizer, m_pipeline.audioSink)) { - ACSDK_ERROR(LX("setupPipelineFailed").d("reason", "failed to linke equalizer to audiosink.")); + ACSDK_ERROR(LX("setupPipelineFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "failed to linke equalizer to audiosink.")); return false; } } @@ -743,7 +772,8 @@ bool MediaPlayer::setupPipeline() { gst_bin_add_many(GST_BIN(m_pipeline.pipeline), m_pipeline.resample, m_pipeline.caps, nullptr); if (!gst_element_link_many(m_pipeline.resample, m_pipeline.caps, pipelineTailElement, nullptr)) { - ACSDK_ERROR(LX("setupPipelineFailed").d("reason", "Failed to link converter.")); + ACSDK_ERROR( + LX("setupPipelineFailed").d("name", RequiresShutdown::name()).d("reason", "Failed to link converter.")); return false; } pipelineTailElement = m_pipeline.resample; @@ -752,7 +782,8 @@ bool MediaPlayer::setupPipeline() { // Complete the pipeline linking if (!gst_element_link_many( m_pipeline.decodedQueue, m_pipeline.converter, m_pipeline.volume, pipelineTailElement, nullptr)) { - ACSDK_ERROR(LX("setupPipelineFailed").d("reason", "Failed to link pipeline.")); + ACSDK_ERROR( + LX("setupPipelineFailed").d("name", RequiresShutdown::name()).d("reason", "Failed to link pipeline.")); return false; } @@ -760,7 +791,7 @@ bool MediaPlayer::setupPipeline() { } void MediaPlayer::tearDownTransientPipelineElements(bool notifyStop) { - ACSDK_DEBUG9(LX("tearDownTransientPipelineElements")); + ACSDK_DEBUG9(LX("tearDownTransientPipelineElements").d("name", RequiresShutdown::name())); m_offsetBeforeTeardown = getCurrentStreamOffset(); if (notifyStop) { sendPlaybackStopped(); @@ -783,7 +814,7 @@ void MediaPlayer::tearDownTransientPipelineElements(bool notifyStop) { } void MediaPlayer::resetPipeline() { - ACSDK_DEBUG9(LX("resetPipeline")); + ACSDK_DEBUG9(LX("resetPipeline").d("name", RequiresShutdown::name())); m_pipeline.pipeline = nullptr; m_pipeline.appsrc = nullptr; m_pipeline.decoder = nullptr; @@ -797,9 +828,9 @@ void MediaPlayer::resetPipeline() { } bool MediaPlayer::queryBufferPercent(gint* percent) { - ACSDK_DEBUG5(LX("queryBufferPercent")); + ACSDK_DEBUG5(LX("queryBufferPercent").d("name", RequiresShutdown::name())); if (!percent) { - ACSDK_ERROR(LX("queryBufferPercentFailed").d("reason", "nullPercent")); + ACSDK_ERROR(LX("queryBufferPercentFailed").d("name", RequiresShutdown::name()).d("reason", "nullPercent")); return false; } GstQuery* query; @@ -810,7 +841,8 @@ bool MediaPlayer::queryBufferPercent(gint* percent) { gst_query_unref(query); return true; } else { - ACSDK_ERROR(LX("queryBufferPercentFailed").d("reason", "bufferingQueryFailed")); + ACSDK_ERROR( + LX("queryBufferPercentFailed").d("name", RequiresShutdown::name()).d("reason", "bufferingQueryFailed")); gst_query_unref(query); return true; } @@ -820,15 +852,16 @@ bool MediaPlayer::queryIsSeekable(bool* isSeekable) { GstState curState; auto stateChange = gst_element_get_state(m_pipeline.pipeline, &curState, NULL, TIMEOUT_ZERO_NANOSECONDS); if (stateChange == GST_STATE_CHANGE_FAILURE) { - ACSDK_ERROR(LX("queryIsSeekableFailed").d("reason", "gstElementGetStateFailed")); + ACSDK_ERROR( + LX("queryIsSeekableFailed").d("name", RequiresShutdown::name()).d("reason", "gstElementGetStateFailed")); return false; } if (stateChange == GST_STATE_CHANGE_ASYNC) { - ACSDK_DEBUG(LX("pipelineNotSeekable").d("reason", "stateChangeAsync")); + ACSDK_DEBUG(LX("pipelineNotSeekable").d("name", RequiresShutdown::name()).d("reason", "stateChangeAsync")); return false; } if ((GST_STATE_PLAYING != curState) && (GST_STATE_PAUSED != curState)) { - ACSDK_DEBUG(LX("pipelineNotSeekable").d("reason", "notPlayingOrPaused")); + ACSDK_DEBUG(LX("pipelineNotSeekable").d("name", RequiresShutdown::name()).d("reason", "notPlayingOrPaused")); *isSeekable = false; return true; } @@ -841,9 +874,10 @@ bool MediaPlayer::queryIsSeekable(bool* isSeekable) { bool MediaPlayer::seek() { bool seekSuccessful = true; - ACSDK_DEBUG9(LX("seekCalled")); + ACSDK_DEBUG9(LX("seekCalled").d("name", RequiresShutdown::name())); if (!m_offsetManager.isSeekable() || !m_offsetManager.isSeekPointSet()) { ACSDK_ERROR(LX("seekFailed") + .d("name", RequiresShutdown::name()) .d("reason", "invalidState") .d("isSeekable", m_offsetManager.isSeekable()) .d("seekPointSet", m_offsetManager.isSeekPointSet())); @@ -853,10 +887,12 @@ bool MediaPlayer::seek() { GST_FORMAT_TIME, // ns static_cast(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT), std::chrono::duration_cast(m_offsetManager.getSeekPoint()).count())) { - ACSDK_ERROR(LX("seekFailed").d("reason", "gstElementSeekSimpleFailed")); + ACSDK_ERROR(LX("seekFailed").d("name", RequiresShutdown::name()).d("reason", "gstElementSeekSimpleFailed")); seekSuccessful = false; } else { - ACSDK_DEBUG(LX("seekSuccessful").d("offsetInMs", m_offsetManager.getSeekPoint().count())); + ACSDK_DEBUG(LX("seekSuccessful") + .d("name", RequiresShutdown::name()) + .d("offsetInMs", m_offsetManager.getSeekPoint().count())); } m_offsetManager.clear(); @@ -891,7 +927,7 @@ gboolean MediaPlayer::removeSource(guint tag) { } void MediaPlayer::onError() { - ACSDK_DEBUG9(LX("onError")); + ACSDK_DEBUG9(LX("onError").d("name", RequiresShutdown::name())); /* * Instead of calling the queueCallback, we are calling g_idle_add here directly here because we want this callback * to be non-blocking. To do this, we are creating a static callback function with the this pointer passed in as @@ -904,6 +940,7 @@ void MediaPlayer::onError() { } void MediaPlayer::doShutdown() { + ACSDK_DEBUG9(LX(__func__).d("name", RequiresShutdown::name())); if (m_urlConverter) { m_urlConverter->shutdown(); } @@ -916,8 +953,8 @@ gboolean MediaPlayer::onCallback(const std::function* callback) { } void MediaPlayer::onPadAdded(GstElement* decoder, GstPad* pad, gpointer pointer) { - ACSDK_DEBUG9(LX("onPadAddedCalled")); auto mediaPlayer = static_cast(pointer); + ACSDK_DEBUG9(LX("onPadAddedCalled").d("name", mediaPlayer->name())); std::promise promise; auto future = promise.get_future(); std::function callback = [mediaPlayer, &promise, decoder, pad]() { @@ -930,7 +967,7 @@ void MediaPlayer::onPadAdded(GstElement* decoder, GstPad* pad, gpointer pointer) } void MediaPlayer::handlePadAdded(std::promise* promise, GstElement* decoder, GstPad* pad) { - ACSDK_DEBUG9(LX("handlePadAddedSignalCalled")); + ACSDK_DEBUG9(LX("handlePadAddedSignalCalled").d("name", RequiresShutdown::name())); gst_element_link(decoder, m_pipeline.decodedQueue); promise->set_value(); } @@ -940,14 +977,16 @@ gboolean MediaPlayer::onBusMessage(GstBus* bus, GstMessage* message, gpointer me } gboolean MediaPlayer::handleBusMessage(GstMessage* message) { - ACSDK_DEBUG9( - LX("messageReceived").d("type", GST_MESSAGE_TYPE_NAME(message)).d("source", GST_MESSAGE_SRC_NAME(message))); + ACSDK_DEBUG9(LX("messageReceived") + .d("name", RequiresShutdown::name()) + .d("type", GST_MESSAGE_TYPE_NAME(message)) + .d("source", GST_MESSAGE_SRC_NAME(message))); switch (GST_MESSAGE_TYPE(message)) { case GST_MESSAGE_EOS: if (GST_MESSAGE_SRC(message) == GST_OBJECT_CAST(m_pipeline.pipeline)) { if (!m_source->handleEndOfStream()) { const std::string errorMessage{"reason=sourceHandleEndOfStreamFailed"}; - ACSDK_ERROR(LX("handleBusMessageFailed").m(errorMessage)); + ACSDK_ERROR(LX("handleBusMessageFailed").d("name", RequiresShutdown::name()).m(errorMessage)); sendPlaybackError(ErrorType::MEDIA_ERROR_INTERNAL_DEVICE_ERROR, errorMessage); break; } @@ -956,14 +995,14 @@ gboolean MediaPlayer::handleBusMessage(GstMessage* message) { if (m_source->hasAdditionalData()) { if (GST_STATE_CHANGE_FAILURE == gst_element_set_state(m_pipeline.pipeline, GST_STATE_NULL)) { const std::string errorMessage{"reason=setPipelineToNullFailed"}; - ACSDK_ERROR(LX("continuingPlaybackFailed").m(errorMessage)); + ACSDK_ERROR(LX("continuingPlaybackFailed").d("name", RequiresShutdown::name()).m(errorMessage)); sendPlaybackError(ErrorType::MEDIA_ERROR_INTERNAL_DEVICE_ERROR, errorMessage); break; } if (GST_STATE_CHANGE_FAILURE == gst_element_set_state(m_pipeline.pipeline, GST_STATE_PLAYING)) { const std::string errorMessage{"reason=setPipelineToPlayingFailed"}; - ACSDK_ERROR(LX("continuingPlaybackFailed").m(errorMessage)); + ACSDK_ERROR(LX("continuingPlaybackFailed").d("name", RequiresShutdown::name()).m(errorMessage)); sendPlaybackError(ErrorType::MEDIA_ERROR_INTERNAL_DEVICE_ERROR, errorMessage); break; } @@ -980,6 +1019,7 @@ gboolean MediaPlayer::handleBusMessage(GstMessage* message) { std::string messageSrcName = GST_MESSAGE_SRC_NAME(message); ACSDK_ERROR(LX("handleBusMessageError") + .d("name", RequiresShutdown::name()) .d("source", messageSrcName) .d("error", error->message) .d("debug", debug ? debug : "noInfo")); @@ -1069,11 +1109,11 @@ gboolean MediaPlayer::handleBusMessage(GstMessage* message) { * TODO: (ACSDK-828) Investigate why frames are arriving late to the sink causing MPEG-TS files to * play choppily */ - ACSDK_DEBUG5(LX("audioSink").m("Sync option set to false.")); + ACSDK_DEBUG5(LX("audioSink").d("name", RequiresShutdown::name()).m("Sync option set to false.")); g_object_set(m_pipeline.audioSink, "sync", FALSE, NULL); } else if (GST_STATE_NULL == newState) { // Reset sync state back to true if tsdemux changes to NULL state - ACSDK_DEBUG5(LX("audioSink").m("Sync option set to true.")); + ACSDK_DEBUG5(LX("audioSink").d("name", RequiresShutdown::name()).m("Sync option set to true.")); g_object_set(m_pipeline.audioSink, "sync", TRUE, NULL); } } @@ -1083,7 +1123,10 @@ gboolean MediaPlayer::handleBusMessage(GstMessage* message) { case GST_MESSAGE_BUFFERING: { gint bufferPercent = 0; gst_message_parse_buffering(message, &bufferPercent); - ACSDK_DEBUG9(LX("handleBusMessage").d("message", "GST_MESSAGE_BUFFERING").d("percent", bufferPercent)); + ACSDK_DEBUG9(LX("handleBusMessage") + .d("name", RequiresShutdown::name()) + .d("message", "GST_MESSAGE_BUFFERING") + .d("percent", bufferPercent)); if (bufferPercent < 100) { if (GST_STATE_CHANGE_FAILURE == gst_element_set_state(m_pipeline.pipeline, GST_STATE_PAUSED)) { @@ -1107,6 +1150,7 @@ gboolean MediaPlayer::handleBusMessage(GstMessage* message) { } ACSDK_DEBUG9(LX("offsetState") + .d("name", RequiresShutdown::name()) .d("isSeekable", m_offsetManager.isSeekable()) .d("isSeekPointSet", m_offsetManager.isSeekPointSet())); @@ -1146,7 +1190,7 @@ std::unique_ptr MediaPlayer::collectTags(GstMessage* message } void MediaPlayer::sendStreamTagsToObserver(std::unique_ptr vectorOfTags) { - ACSDK_DEBUG(LX("callingOnTags")); + ACSDK_DEBUG(LX("callingOnTags").d("name", RequiresShutdown::name())); if (m_playerObserver) { m_playerObserver->onTags(m_currentId, std::move(vectorOfTags)); } @@ -1157,14 +1201,16 @@ void MediaPlayer::handleSetAttachmentReaderSource( std::promise* promise, const avsCommon::utils::AudioFormat* audioFormat, bool repeat) { - ACSDK_DEBUG(LX("handleSetAttachmentReaderSourceCalled")); + ACSDK_DEBUG(LX("handleSetAttachmentReaderSourceCalled").d("name", RequiresShutdown::name())); tearDownTransientPipelineElements(true); std::shared_ptr source = AttachmentReaderSource::create(this, reader, audioFormat, repeat); if (!source) { - ACSDK_ERROR(LX("handleSetAttachmentReaderSourceFailed").d("reason", "sourceIsNullptr")); + ACSDK_ERROR(LX("handleSetAttachmentReaderSourceFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "sourceIsNullptr")); promise->set_value(ERROR_SOURCE_ID); return; } @@ -1174,7 +1220,9 @@ void MediaPlayer::handleSetAttachmentReaderSource( * to the callback which performs the linking of the decoder source pad to decodedQueue sink pad. */ if (!g_signal_connect(m_pipeline.decoder, "pad-added", G_CALLBACK(onPadAdded), this)) { - ACSDK_ERROR(LX("handleSetAttachmentReaderSourceFailed").d("reason", "connectPadAddedSignalFailed")); + ACSDK_ERROR(LX("handleSetAttachmentReaderSourceFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "connectPadAddedSignalFailed")); promise->set_value(ERROR_SOURCE_ID); return; } @@ -1189,14 +1237,15 @@ void MediaPlayer::handleSetIStreamSource( std::shared_ptr stream, bool repeat, std::promise* promise) { - ACSDK_DEBUG(LX("handleSetSourceCalled")); + ACSDK_DEBUG(LX("handleSetSourceCalled").d("name", RequiresShutdown::name())); tearDownTransientPipelineElements(true); std::shared_ptr source = IStreamSource::create(this, stream, repeat); if (!source) { - ACSDK_ERROR(LX("handleSetIStreamSourceFailed").d("reason", "sourceIsNullptr")); + ACSDK_ERROR( + LX("handleSetIStreamSourceFailed").d("name", RequiresShutdown::name()).d("reason", "sourceIsNullptr")); promise->set_value(ERROR_SOURCE_ID); return; } @@ -1206,7 +1255,9 @@ void MediaPlayer::handleSetIStreamSource( * to the callback which performs the linking of the decoder source pad to the decodedQueue sink pad. */ if (!g_signal_connect(m_pipeline.decoder, "pad-added", G_CALLBACK(onPadAdded), this)) { - ACSDK_ERROR(LX("handleSetIStreamSourceFailed").d("reason", "connectPadAddedSignalFailed")); + ACSDK_ERROR(LX("handleSetIStreamSourceFailed") + .d("name", RequiresShutdown::name()) + .d("reason", "connectPadAddedSignalFailed")); promise->set_value(ERROR_SOURCE_ID); return; } @@ -1221,27 +1272,28 @@ void MediaPlayer::handleSetUrlSource( std::chrono::milliseconds offset, std::promise* promise, bool repeat) { - ACSDK_DEBUG(LX("handleSetSourceForUrlCalled")); + ACSDK_DEBUG(LX("handleSetSourceForUrlCalled").d("name", RequiresShutdown::name())); tearDownTransientPipelineElements(true); m_urlConverter = alexaClientSDK::playlistParser::UrlContentToAttachmentConverter::create( m_contentFetcherFactory, url, shared_from_this(), offset); if (!m_urlConverter) { - ACSDK_ERROR(LX("setSourceUrlFailed").d("reason", "badUrlConverter")); + ACSDK_ERROR(LX("setSourceUrlFailed").d("name", RequiresShutdown::name()).d("reason", "badUrlConverter")); promise->set_value(ERROR_SOURCE_ID); return; } auto attachment = m_urlConverter->getAttachment(); if (!attachment) { - ACSDK_ERROR(LX("setSourceUrlFailed").d("reason", "badAttachmentReceived")); + ACSDK_ERROR(LX("setSourceUrlFailed").d("name", RequiresShutdown::name()).d("reason", "badAttachmentReceived")); promise->set_value(ERROR_SOURCE_ID); return; } std::shared_ptr reader = attachment->createReader(sds::ReaderPolicy::NONBLOCKING); if (!reader) { - ACSDK_ERROR(LX("setSourceUrlFailed").d("reason", "failedToCreateAttachmentReader")); + ACSDK_ERROR( + LX("setSourceUrlFailed").d("name", RequiresShutdown::name()).d("reason", "failedToCreateAttachmentReader")); promise->set_value(ERROR_SOURCE_ID); return; } @@ -1249,9 +1301,10 @@ void MediaPlayer::handleSetUrlSource( } void MediaPlayer::handlePlay(SourceId id, std::promise* promise) { - ACSDK_DEBUG(LX("handlePlayCalled").d("idPassed", id).d("currentId", (m_currentId))); + ACSDK_DEBUG( + LX("handlePlayCalled").d("name", RequiresShutdown::name()).d("idPassed", id).d("currentId", (m_currentId))); if (!validateSourceAndId(id)) { - ACSDK_ERROR(LX("handlePlayFailed")); + ACSDK_ERROR(LX("handlePlayFailed").d("name", RequiresShutdown::name())); promise->set_value(false); return; } @@ -1259,17 +1312,17 @@ void MediaPlayer::handlePlay(SourceId id, std::promise* promise) { GstState curState; auto stateChange = gst_element_get_state(m_pipeline.pipeline, &curState, NULL, TIMEOUT_ZERO_NANOSECONDS); if (stateChange == GST_STATE_CHANGE_FAILURE) { - ACSDK_ERROR(LX("handlePlayFailed").d("reason", "gstElementGetStateFailed")); + ACSDK_ERROR(LX("handlePlayFailed").d("name", RequiresShutdown::name()).d("reason", "gstElementGetStateFailed")); promise->set_value(false); return; } if (curState == GST_STATE_PLAYING) { - ACSDK_DEBUG(LX("handlePlayFailed").d("reason", "alreadyPlaying")); + ACSDK_DEBUG(LX("handlePlayFailed").d("name", RequiresShutdown::name()).d("reason", "alreadyPlaying")); promise->set_value(false); return; } if (m_playPending) { - ACSDK_DEBUG(LX("handlePlayFailed").d("reason", "playCurrentlyPending")); + ACSDK_DEBUG(LX("handlePlayFailed").d("name", RequiresShutdown::name()).d("reason", "playCurrentlyPending")); promise->set_value(false); return; } @@ -1280,28 +1333,33 @@ void MediaPlayer::handlePlay(SourceId id, std::promise* promise) { m_pauseImmediately = false; promise->set_value(true); - /* - * If the pipeline is completely buffered, then go straight to PLAY otherwise, - * set pipeline to PAUSED state to attempt buffering. The pipeline will be set to PLAY upon receiving buffer - * percent = 100. - */ GstState startingState = GST_STATE_PAUSED; - gint percent = 0; - if ((GST_STATE_PAUSED == curState) && (queryBufferPercent(&percent))) { - if (100 == percent) { - startingState = GST_STATE_PLAYING; + if (!m_isLiveMode) { + /* + * If the pipeline is completely buffered, then go straight to PLAY otherwise, + * set pipeline to PAUSED state to attempt buffering. The pipeline will be set to PLAY upon receiving buffer + * percent = 100. + */ + + gint percent = 0; + if ((GST_STATE_PAUSED == curState) && (queryBufferPercent(&percent))) { + if (100 == percent) { + startingState = GST_STATE_PLAYING; + } } + } else { + startingState = GST_STATE_PLAYING; } - stateChange = gst_element_set_state(m_pipeline.pipeline, startingState); ACSDK_DEBUG(LX("handlePlay") + .d("name", RequiresShutdown::name()) .d("startingState", gst_element_state_get_name(startingState)) .d("stateReturn", gst_element_state_change_return_get_name(stateChange))); switch (stateChange) { case GST_STATE_CHANGE_FAILURE: { const std::string errorMessage{"reason=gstElementSetStateFailure"}; - ACSDK_ERROR(LX("handlePlayFailed").m(errorMessage)); + ACSDK_ERROR(LX("handlePlayFailed").d("name", RequiresShutdown::name()).m(errorMessage)); sendPlaybackError(ErrorType::MEDIA_ERROR_INTERNAL_DEVICE_ERROR, errorMessage); } return; @@ -1319,9 +1377,10 @@ void MediaPlayer::handlePlay(SourceId id, std::promise* promise) { } void MediaPlayer::handleStop(MediaPlayer::SourceId id, std::promise* promise) { - ACSDK_DEBUG(LX("handleStopCalled").d("idPassed", id).d("currentId", (m_currentId))); + ACSDK_DEBUG( + LX("handleStopCalled").d("name", RequiresShutdown::name()).d("idPassed", id).d("currentId", (m_currentId))); if (!validateSourceAndId(id)) { - ACSDK_ERROR(LX("handleStopFailed")); + ACSDK_ERROR(LX("handleStopFailed").d("name", RequiresShutdown::name())); promise->set_value(false); return; } @@ -1330,27 +1389,29 @@ void MediaPlayer::handleStop(MediaPlayer::SourceId id, std::promise* promi GstState pending; auto stateChangeRet = gst_element_get_state(m_pipeline.pipeline, &curState, &pending, TIMEOUT_ZERO_NANOSECONDS); if (GST_STATE_CHANGE_FAILURE == stateChangeRet) { - ACSDK_ERROR(LX("handleStopFailed").d("reason", "gstElementGetStateFailure")); + ACSDK_ERROR( + LX("handleStopFailed").d("name", RequiresShutdown::name()).d("reason", "gstElementGetStateFailure")); promise->set_value(false); return; } // Only stop if currently not stopped. if (curState == GST_STATE_NULL) { - ACSDK_ERROR(LX("handleStopFailed").d("reason", "alreadyStopped")); + ACSDK_ERROR(LX("handleStopFailed").d("name", RequiresShutdown::name()).d("reason", "alreadyStopped")); promise->set_value(false); return; } if (pending == GST_STATE_NULL) { - ACSDK_ERROR(LX("handleStopFailed").d("reason", "alreadyStopping")); + ACSDK_ERROR(LX("handleStopFailed").d("name", RequiresShutdown::name()).d("reason", "alreadyStopping")); promise->set_value(false); return; } stateChangeRet = gst_element_set_state(m_pipeline.pipeline, GST_STATE_NULL); if (GST_STATE_CHANGE_FAILURE == stateChangeRet) { - ACSDK_ERROR(LX("handleStopFailed").d("reason", "gstElementSetStateFailure")); + ACSDK_ERROR( + LX("handleStopFailed").d("name", RequiresShutdown::name()).d("reason", "gstElementSetStateFailure")); promise->set_value(false); } else { /* @@ -1368,9 +1429,10 @@ void MediaPlayer::handleStop(MediaPlayer::SourceId id, std::promise* promi } void MediaPlayer::handlePause(MediaPlayer::SourceId id, std::promise* promise) { - ACSDK_DEBUG(LX("handlePauseCalled").d("idPassed", id).d("currentId", (m_currentId))); + ACSDK_DEBUG( + LX("handlePauseCalled").d("name", RequiresShutdown::name()).d("idPassed", id).d("currentId", (m_currentId))); if (!validateSourceAndId(id)) { - ACSDK_ERROR(LX("handlePauseFailed")); + ACSDK_ERROR(LX("handlePauseFailed").d("name", RequiresShutdown::name())); promise->set_value(false); return; } @@ -1378,7 +1440,8 @@ void MediaPlayer::handlePause(MediaPlayer::SourceId id, std::promise* prom GstState curState; auto stateChangeRet = gst_element_get_state(m_pipeline.pipeline, &curState, NULL, TIMEOUT_ZERO_NANOSECONDS); if (GST_STATE_CHANGE_FAILURE == stateChangeRet) { - ACSDK_ERROR(LX("handlePauseFailed").d("reason", "gstElementGetStateFailure")); + ACSDK_ERROR( + LX("handlePauseFailed").d("name", RequiresShutdown::name()).d("reason", "gstElementGetStateFailure")); promise->set_value(false); return; } @@ -1387,38 +1450,41 @@ void MediaPlayer::handlePause(MediaPlayer::SourceId id, std::promise* prom * If a play() or resume() call is pending, we want to try pausing immediately to avoid blips in audio. */ if (m_playPending || m_resumePending) { - ACSDK_DEBUG9(LX("handlePauseCalled").d("info", "playOrResumePending")); + ACSDK_DEBUG9(LX("handlePauseCalled").d("name", RequiresShutdown::name()).d("info", "playOrResumePending")); if (m_pausePending) { - ACSDK_DEBUG(LX("handlePauseFailed").d("reason", "pauseCurrentlyPending")); + ACSDK_DEBUG( + LX("handlePauseFailed").d("name", RequiresShutdown::name()).d("reason", "pauseCurrentlyPending")); promise->set_value(false); return; } stateChangeRet = gst_element_set_state(m_pipeline.pipeline, GST_STATE_PAUSED); if (GST_STATE_CHANGE_FAILURE == stateChangeRet) { - ACSDK_ERROR(LX("handlePauseFailed").d("reason", "gstElementSetStateFailure")); + ACSDK_ERROR( + LX("handlePauseFailed").d("name", RequiresShutdown::name()).d("reason", "gstElementSetStateFailure")); promise->set_value(false); } else { m_pauseImmediately = true; - ACSDK_DEBUG(LX("handlePause").d("pauseImmediately", "true")); + ACSDK_DEBUG(LX("handlePause").d("name", RequiresShutdown::name()).d("pauseImmediately", "true")); promise->set_value(true); } return; } if (curState != GST_STATE_PLAYING) { - ACSDK_ERROR(LX("handlePauseFailed").d("reason", "noAudioPlaying")); + ACSDK_ERROR(LX("handlePauseFailed").d("name", RequiresShutdown::name()).d("reason", "noAudioPlaying")); promise->set_value(false); return; } if (m_pausePending) { - ACSDK_DEBUG(LX("handlePauseFailed").d("reason", "pauseCurrentlyPending")); + ACSDK_DEBUG(LX("handlePauseFailed").d("name", RequiresShutdown::name()).d("reason", "pauseCurrentlyPending")); promise->set_value(false); return; } stateChangeRet = gst_element_set_state(m_pipeline.pipeline, GST_STATE_PAUSED); if (GST_STATE_CHANGE_FAILURE == stateChangeRet) { - ACSDK_ERROR(LX("handlePauseFailed").d("reason", "gstElementSetStateFailure")); + ACSDK_ERROR( + LX("handlePauseFailed").d("name", RequiresShutdown::name()).d("reason", "gstElementSetStateFailure")); promise->set_value(false); } else { m_pausePending = true; @@ -1427,9 +1493,10 @@ void MediaPlayer::handlePause(MediaPlayer::SourceId id, std::promise* prom } void MediaPlayer::handleResume(MediaPlayer::SourceId id, std::promise* promise) { - ACSDK_DEBUG(LX("handleResumeCalled").d("idPassed", id).d("currentId", (m_currentId))); + ACSDK_DEBUG( + LX("handleResumeCalled").d("name", RequiresShutdown::name()).d("idPassed", id).d("currentId", (m_currentId))); if (!validateSourceAndId(id)) { - ACSDK_ERROR(LX("handleResumeFailed")); + ACSDK_ERROR(LX("handleResumeFailed").d("name", RequiresShutdown::name())); promise->set_value(false); return; } @@ -1438,26 +1505,27 @@ void MediaPlayer::handleResume(MediaPlayer::SourceId id, std::promise* pro auto stateChangeRet = gst_element_get_state(m_pipeline.pipeline, &curState, NULL, TIMEOUT_ZERO_NANOSECONDS); if (GST_STATE_CHANGE_FAILURE == stateChangeRet) { - ACSDK_ERROR(LX("handleResumeFailed").d("reason", "gstElementGetStateFailure")); + ACSDK_ERROR( + LX("handleResumeFailed").d("name", RequiresShutdown::name()).d("reason", "gstElementGetStateFailure")); promise->set_value(false); return; } if (GST_STATE_PLAYING == curState) { - ACSDK_ERROR(LX("handleResumeFailed").d("reason", "alreadyPlaying")); + ACSDK_ERROR(LX("handleResumeFailed").d("name", RequiresShutdown::name()).d("reason", "alreadyPlaying")); promise->set_value(false); return; } // Only unpause if currently paused. if (GST_STATE_PAUSED != curState) { - ACSDK_ERROR(LX("handleResumeFailed").d("reason", "notCurrentlyPaused")); + ACSDK_ERROR(LX("handleResumeFailed").d("name", RequiresShutdown::name()).d("reason", "notCurrentlyPaused")); promise->set_value(false); return; } if (m_resumePending) { - ACSDK_DEBUG(LX("handleResumeFailed").d("reason", "resumeCurrentlyPending")); + ACSDK_DEBUG(LX("handleResumeFailed").d("name", RequiresShutdown::name()).d("reason", "resumeCurrentlyPending")); promise->set_value(false); return; } @@ -1466,7 +1534,8 @@ void MediaPlayer::handleResume(MediaPlayer::SourceId id, std::promise* pro // buffer or go straight to play stateChangeRet = gst_element_set_state(m_pipeline.pipeline, GST_STATE_PLAYING); if (GST_STATE_CHANGE_FAILURE == stateChangeRet) { - ACSDK_ERROR(LX("handleResumeFailed").d("reason", "gstElementSetStateFailure")); + ACSDK_ERROR( + LX("handleResumeFailed").d("name", RequiresShutdown::name()).d("reason", "gstElementSetStateFailure")); promise->set_value(false); } else { m_resumePending = true; @@ -1476,11 +1545,14 @@ void MediaPlayer::handleResume(MediaPlayer::SourceId id, std::promise* pro } void MediaPlayer::handleGetOffset(SourceId id, std::promise* promise) { - ACSDK_DEBUG9(LX("handleGetOffsetCalled").d("idPassed", id).d("currentId", (m_currentId))); + ACSDK_DEBUG9(LX("handleGetOffsetCalled") + .d("name", RequiresShutdown::name()) + .d("idPassed", id) + .d("currentId", (m_currentId))); // Check if pipeline is set. if (!m_pipeline.pipeline) { - ACSDK_INFO(LX("handleGetOffsetStopped").m("pipelineNotSet")); + ACSDK_INFO(LX("handleGetOffsetStopped").m("pipelineNotSet").d("name", RequiresShutdown::name())); promise->set_value(MEDIA_PLAYER_INVALID_OFFSET); return; } @@ -1494,7 +1566,7 @@ void MediaPlayer::handleGetOffset(SourceId id, std::promise(std::chrono::nanoseconds(position))); - ACSDK_DEBUG9(LX("getCurrentStreamOffset").d("offsetInMilliseconds", offsetInMilliseconds.count())); + ACSDK_DEBUG9(LX("getCurrentStreamOffset") + .d("name", RequiresShutdown::name()) + .d("offsetInMilliseconds", offsetInMilliseconds.count())); } return offsetInMilliseconds; @@ -1536,14 +1616,14 @@ std::chrono::milliseconds MediaPlayer::getCurrentStreamOffset() { void MediaPlayer::handleSetObserver( std::promise* promise, std::shared_ptr observer) { - ACSDK_DEBUG(LX("handleSetObserverCalled")); + ACSDK_DEBUG(LX("handleSetObserverCalled").d("name", RequiresShutdown::name())); m_playerObserver = observer; promise->set_value(); } void MediaPlayer::sendPlaybackStarted() { if (!m_playbackStartedSent) { - ACSDK_DEBUG(LX("callingOnPlaybackStarted").d("currentId", m_currentId)); + ACSDK_DEBUG(LX("callingOnPlaybackStarted").d("name", RequiresShutdown::name()).d("currentId", m_currentId)); m_playbackStartedSent = true; m_playPending = false; if (m_playerObserver) { @@ -1560,7 +1640,7 @@ void MediaPlayer::sendPlaybackFinished() { m_playbackStartedSent = false; if (!m_playbackFinishedSent) { m_playbackFinishedSent = true; - ACSDK_DEBUG(LX("callingOnPlaybackFinished").d("currentId", m_currentId)); + ACSDK_DEBUG(LX("callingOnPlaybackFinished").d("name", RequiresShutdown::name()).d("currentId", m_currentId)); if (m_playerObserver) { m_playerObserver->onPlaybackFinished(m_currentId); } @@ -1574,7 +1654,7 @@ void MediaPlayer::sendPlaybackFinished() { } void MediaPlayer::sendPlaybackPaused() { - ACSDK_DEBUG(LX("callingOnPlaybackPaused").d("currentId", m_currentId)); + ACSDK_DEBUG(LX("callingOnPlaybackPaused").d("name", RequiresShutdown::name()).d("currentId", m_currentId)); m_pausePending = false; m_isPaused = true; if (m_playerObserver) { @@ -1583,7 +1663,7 @@ void MediaPlayer::sendPlaybackPaused() { } void MediaPlayer::sendPlaybackResumed() { - ACSDK_DEBUG(LX("callingOnPlaybackResumed").d("currentId", m_currentId)); + ACSDK_DEBUG(LX("callingOnPlaybackResumed").d("name", RequiresShutdown::name()).d("currentId", m_currentId)); m_resumePending = false; m_isPaused = false; if (m_playerObserver) { @@ -1595,7 +1675,7 @@ void MediaPlayer::sendPlaybackStopped() { if (m_currentId == ERROR_SOURCE_ID) { return; } - ACSDK_DEBUG(LX("callingOnPlaybackStopped").d("currentId", m_currentId)); + ACSDK_DEBUG(LX("callingOnPlaybackStopped").d("name", RequiresShutdown::name()).d("currentId", m_currentId)); if (m_playerObserver && ERROR_SOURCE_ID != m_currentId) { m_playerObserver->onPlaybackStopped(m_currentId); } @@ -1611,7 +1691,11 @@ void MediaPlayer::sendPlaybackError(const ErrorType& type, const std::string& er if (m_currentId == ERROR_SOURCE_ID) { return; } - ACSDK_DEBUG(LX("callingOnPlaybackError").d("type", type).d("error", error).d("currentId", m_currentId)); + ACSDK_DEBUG(LX("callingOnPlaybackError") + .d("name", RequiresShutdown::name()) + .d("type", type) + .d("error", error) + .d("currentId", m_currentId)); m_playPending = false; m_pausePending = false; m_resumePending = false; @@ -1628,14 +1712,14 @@ void MediaPlayer::sendPlaybackError(const ErrorType& type, const std::string& er } void MediaPlayer::sendBufferUnderrun() { - ACSDK_DEBUG(LX("callingOnBufferUnderrun").d("currentId", m_currentId)); + ACSDK_DEBUG(LX("callingOnBufferUnderrun").d("name", RequiresShutdown::name()).d("currentId", m_currentId)); if (m_playerObserver) { m_playerObserver->onBufferUnderrun(m_currentId); } } void MediaPlayer::sendBufferRefilled() { - ACSDK_DEBUG(LX("callingOnBufferRefilled").d("currentId", m_currentId)); + ACSDK_DEBUG(LX("callingOnBufferRefilled").d("name", RequiresShutdown::name()).d("currentId", m_currentId)); if (m_playerObserver) { m_playerObserver->onBufferRefilled(m_currentId); } @@ -1643,19 +1727,20 @@ void MediaPlayer::sendBufferRefilled() { bool MediaPlayer::validateSourceAndId(SourceId id) { if (!m_source) { - ACSDK_ERROR(LX("validateSourceAndIdFailed").d("reason", "sourceNotSet")); + ACSDK_ERROR(LX("validateSourceAndIdFailed").d("name", RequiresShutdown::name()).d("reason", "sourceNotSet")); return false; } if (id != m_currentId) { - ACSDK_ERROR(LX("validateSourceAndIdFailed").d("reason", "sourceIdMismatch")); + ACSDK_ERROR( + LX("validateSourceAndIdFailed").d("name", RequiresShutdown::name()).d("reason", "sourceIdMismatch")); return false; } return true; } gboolean MediaPlayer::onErrorCallback(gpointer pointer) { - ACSDK_DEBUG9(LX("onErrorCallback")); auto mediaPlayer = static_cast(pointer); + ACSDK_DEBUG9(LX("onErrorCallback").d("name", mediaPlayer->name())); mediaPlayer->sendPlaybackError(ErrorType::MEDIA_ERROR_INTERNAL_DEVICE_ERROR, "streamingError"); return false; } diff --git a/MediaPlayer/GStreamerMediaPlayer/test/ErrorTypeConversionTest.cpp b/MediaPlayer/GStreamerMediaPlayer/test/ErrorTypeConversionTest.cpp index e434578ebc..92964800e1 100644 --- a/MediaPlayer/GStreamerMediaPlayer/test/ErrorTypeConversionTest.cpp +++ b/MediaPlayer/GStreamerMediaPlayer/test/ErrorTypeConversionTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -29,7 +29,7 @@ using namespace avsCommon::utils::mediaPlayer; /** * Test to verify that the ErrorTypes convert to the error strings properly. */ -TEST(ErrorTypeConversionTest, ErrorTypeToString) { +TEST(ErrorTypeConversionTest, test_errorTypeToString) { const std::map m = { {ErrorType::MEDIA_ERROR_UNKNOWN, "MEDIA_ERROR_UNKNOWN"}, {ErrorType::MEDIA_ERROR_INVALID_REQUEST, "MEDIA_ERROR_INVALID_REQUEST"}, @@ -45,7 +45,7 @@ TEST(ErrorTypeConversionTest, ErrorTypeToString) { /** * Test to verify that the correct GErrors convert to the proper ErrorType. */ -TEST(ErrorTypeConversionTest, GstCoreErrorToErrorType) { +TEST(ErrorTypeConversionTest, test_gstCoreErrorToErrorType) { const std::map, ErrorType> goldStandardMapping = { {{GST_CORE_ERROR_FAILED, false}, ErrorType::MEDIA_ERROR_INTERNAL_DEVICE_ERROR}, {{GST_CORE_ERROR_FAILED, true}, ErrorType::MEDIA_ERROR_INTERNAL_DEVICE_ERROR}, @@ -91,7 +91,7 @@ TEST(ErrorTypeConversionTest, GstCoreErrorToErrorType) { /** * Test to verify that the correct Library GErrors convert to the proper ErrorType. */ -TEST(ErrorTypeConversionTest, GstLibraryErrorToErrorType) { +TEST(ErrorTypeConversionTest, test_gstLibraryErrorToErrorType) { const std::map, ErrorType> goldStandardMapping = { {{GST_LIBRARY_ERROR_FAILED, false}, ErrorType::MEDIA_ERROR_INTERNAL_DEVICE_ERROR}, {{GST_LIBRARY_ERROR_FAILED, true}, ErrorType::MEDIA_ERROR_INTERNAL_DEVICE_ERROR}, @@ -123,7 +123,7 @@ TEST(ErrorTypeConversionTest, GstLibraryErrorToErrorType) { /** * Test to verify that the correct Resource GErrors convert to the proper ErrorType. */ -TEST(ErrorTypeConversionTest, GstResourceErrorToErrorType) { +TEST(ErrorTypeConversionTest, test_gstResourceErrorToErrorType) { const std::map, ErrorType> goldStandardMapping = { {{GST_RESOURCE_ERROR_FAILED, false}, ErrorType::MEDIA_ERROR_INTERNAL_DEVICE_ERROR}, {{GST_RESOURCE_ERROR_FAILED, true}, ErrorType::MEDIA_ERROR_INTERNAL_DEVICE_ERROR}, @@ -174,7 +174,7 @@ TEST(ErrorTypeConversionTest, GstResourceErrorToErrorType) { /** * Test to verify that the correct Stream GErrors convert to the proper ErrorType. */ -TEST(ErrorTypeConversionTest, GstStreamErrorToErrorType) { +TEST(ErrorTypeConversionTest, test_gstStreamErrorToErrorType) { const std::map, ErrorType> goldStandardMapping = { {{GST_STREAM_ERROR_FAILED, false}, ErrorType::MEDIA_ERROR_INTERNAL_DEVICE_ERROR}, {{GST_STREAM_ERROR_FAILED, true}, ErrorType::MEDIA_ERROR_INTERNAL_DEVICE_ERROR}, diff --git a/MediaPlayer/GStreamerMediaPlayer/test/MediaPlayerTest.cpp b/MediaPlayer/GStreamerMediaPlayer/test/MediaPlayerTest.cpp index bf9a1c4d23..3864ee0b41 100644 --- a/MediaPlayer/GStreamerMediaPlayer/test/MediaPlayerTest.cpp +++ b/MediaPlayer/GStreamerMediaPlayer/test/MediaPlayerTest.cpp @@ -602,7 +602,7 @@ bool MockPlayerObserver::waitForTags(SourceId id, const std::chrono::millisecond return true; } -class MediaPlayerTest : public ::testing::Test { +class MediaPlayerTest : public ::testing::TestWithParam { public: void SetUp() override; @@ -633,6 +633,8 @@ class MediaPlayerTest : public ::testing::Test { std::shared_ptr m_playerObserver; }; +INSTANTIATE_TEST_CASE_P(Parameterized, MediaPlayerTest, ::testing::Bool()); + void MediaPlayerTest::SetUp() { // ACSDK-1373 - MediaPlayerTest fail on Windows // with GStreamer 1.14 default audio sink. @@ -641,7 +643,14 @@ void MediaPlayerTest::SetUp() { initialization::AlexaClientSDKInit::initialize({inString}); #endif m_playerObserver = std::make_shared(); - m_mediaPlayer = MediaPlayer::create(std::make_shared()); + + // All the tests will be run with enableLiveMode set to true and false respectively + m_mediaPlayer = MediaPlayer::create( + std::make_shared(), + false, + avsCommon::sdkInterfaces::SpeakerInterface::Type::AVS_SPEAKER_VOLUME, + "", + GetParam()); ASSERT_TRUE(m_mediaPlayer); m_mediaPlayer->setObserver(m_playerObserver); } @@ -671,7 +680,7 @@ void MediaPlayerTest::setIStreamSource(MediaPlayer::SourceId* id, bool repeat) { * Read an audio file into a buffer. Set the source of the @c MediaPlayer to the buffer. Playback audio till the end. * Check whether the playback started and playback finished notifications are received. */ -TEST_F(MediaPlayerTest, testStartPlayWaitForEnd) { +TEST_P(MediaPlayerTest, testSlow_startPlayWaitForEnd) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); @@ -684,7 +693,7 @@ TEST_F(MediaPlayerTest, testStartPlayWaitForEnd) { * Set the source of the @c MediaPlayer to a url representing a single audio file. Playback audio till the end. * Check whether the playback started and playback finished notifications are received. */ -TEST_F(MediaPlayerTest, testStartPlayForUrl) { +TEST_P(MediaPlayerTest, testSlow_startPlayForUrl) { std::string url_single(FILE_PREFIX + inputsDirPath + MP3_FILE_PATH); auto sourceId = m_mediaPlayer->setSource(url_single); ASSERT_NE(ERROR_SOURCE_ID, sourceId); @@ -700,7 +709,7 @@ TEST_F(MediaPlayerTest, testStartPlayForUrl) { * * Consecutive calls to setSource(const std::string url) without play() cause tests to occasionally fail: ACSDK-508. */ -TEST_F(MediaPlayerTest, testConsecutiveSetSource) { +TEST_P(MediaPlayerTest, testSlow_consecutiveSetSource) { std::string url_single(FILE_PREFIX + inputsDirPath + MP3_FILE_PATH); m_mediaPlayer->setSource(""); auto id = m_mediaPlayer->setSource(url_single); @@ -712,7 +721,7 @@ TEST_F(MediaPlayerTest, testConsecutiveSetSource) { /** * Plays a second different type of source after one source has finished playing. */ -TEST_F(MediaPlayerTest, testStartPlayWaitForEndStartPlayAgain) { +TEST_P(MediaPlayerTest, testSlow_startPlayWaitForEndStartPlayAgain) { MediaPlayer::SourceId sourceId; setIStreamSource(&sourceId); @@ -731,7 +740,7 @@ TEST_F(MediaPlayerTest, testStartPlayWaitForEndStartPlayAgain) { * seconds. Playback started notification should be received when the playback starts. Then call @c stop and expect * the playback finished notification is received. */ -TEST_F(MediaPlayerTest, testStopPlay) { +TEST_P(MediaPlayerTest, testSlow_stopPlay) { MediaPlayer::SourceId sourceId; setIStreamSource(&sourceId, true); ASSERT_TRUE(m_mediaPlayer->play(sourceId)); @@ -746,7 +755,7 @@ TEST_F(MediaPlayerTest, testStopPlay) { * seconds. Playback started notification should be received when the playback starts. Then call @c stop and expect * the playback finished notification is received. */ -TEST_F(MediaPlayerTest, testStartPlayCallAfterStopPlay) { +TEST_P(MediaPlayerTest, testSlow_startPlayCallAfterStopPlay) { MediaPlayer::SourceId sourceId; setIStreamSource(&sourceId, true); ASSERT_TRUE(m_mediaPlayer->play(sourceId)); @@ -762,7 +771,7 @@ TEST_F(MediaPlayerTest, testStartPlayCallAfterStopPlay) { * seconds. Playback started notification should be received when the playback starts. Call @c stop. * and wait for the playback finished notification is received. Call @c play again. */ -TEST_F(MediaPlayerTest, testStartPlayCallAfterStopPlayDifferentSource) { +TEST_P(MediaPlayerTest, testSlow_startPlayCallAfterStopPlayDifferentSource) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); ASSERT_TRUE(m_mediaPlayer->play(sourceId)); @@ -782,7 +791,7 @@ TEST_F(MediaPlayerTest, testStartPlayCallAfterStopPlayDifferentSource) { /* * Pause an audio after playback has started. */ -TEST_F(MediaPlayerTest, testPauseDuringPlay) { +TEST_P(MediaPlayerTest, testSlow_pauseDuringPlay) { MediaPlayer::SourceId sourceId; setIStreamSource(&sourceId, true); ASSERT_TRUE(m_mediaPlayer->play(sourceId)); @@ -796,7 +805,7 @@ TEST_F(MediaPlayerTest, testPauseDuringPlay) { /* * Resume paused audio. */ -TEST_F(MediaPlayerTest, testResumeAfterPauseThenStop) { +TEST_P(MediaPlayerTest, testSlow_resumeAfterPauseThenStop) { MediaPlayer::SourceId sourceId; setIStreamSource(&sourceId); ASSERT_TRUE(m_mediaPlayer->play(sourceId)); @@ -812,7 +821,7 @@ TEST_F(MediaPlayerTest, testResumeAfterPauseThenStop) { * Stop of a paused audio after playback has started. An additional stop event should * be sent. */ -TEST_F(MediaPlayerTest, testStopAfterPause) { +TEST_P(MediaPlayerTest, testSlow_stopAfterPause) { MediaPlayer::SourceId sourceId; setIStreamSource(&sourceId); ASSERT_TRUE(m_mediaPlayer->play(sourceId)); @@ -827,7 +836,7 @@ TEST_F(MediaPlayerTest, testStopAfterPause) { /* * Pause of a paused audio after playback has started. The pause() should fail. */ -TEST_F(MediaPlayerTest, testPauseAfterPause) { +TEST_P(MediaPlayerTest, testSlow_pauseAfterPause) { MediaPlayer::SourceId sourceId; setIStreamSource(&sourceId); ASSERT_TRUE(m_mediaPlayer->play(sourceId)); @@ -842,7 +851,7 @@ TEST_F(MediaPlayerTest, testPauseAfterPause) { /* * Calling resume after playback has started. The resume operation should fail. */ -TEST_F(MediaPlayerTest, testResumeAfterPlay) { +TEST_P(MediaPlayerTest, test_resumeAfterPlay) { MediaPlayer::SourceId sourceId; setIStreamSource(&sourceId); ASSERT_TRUE(m_mediaPlayer->play(sourceId)); @@ -858,7 +867,7 @@ TEST_F(MediaPlayerTest, testResumeAfterPlay) { * Check the offset value. Then call @c stop and expect the playback finished notification is received. * Call @c getOffset again. Check the offset value. */ -TEST_F(MediaPlayerTest, testGetOffsetInMilliseconds) { +TEST_P(MediaPlayerTest, testSlow_getOffsetInMilliseconds) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); ASSERT_TRUE(m_mediaPlayer->play(sourceId)); @@ -876,14 +885,14 @@ TEST_F(MediaPlayerTest, testGetOffsetInMilliseconds) { * Test getOffset with a null pipeline. Expect that MEDIA_PLAYER_INVALID_OFFSET is returned. * This currently results in errors on shutdown. Will be fixed by ACSDK-446. */ -TEST_F(MediaPlayerTest, testGetOffsetInMillisecondsNullPipeline) { +TEST_P(MediaPlayerTest, test_getOffsetInMillisecondsNullPipeline) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); ASSERT_EQ(MEDIA_PLAYER_INVALID_OFFSET, m_mediaPlayer->getOffset(sourceId + 1)); } /// Tests that calls to getOffset fail when the pipeline is in a stopped state. -TEST_F(MediaPlayerTest, testGetOffsetWhenStoppedFails) { +TEST_P(MediaPlayerTest, testSlow_getOffsetWhenStoppedFails) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); ASSERT_TRUE(m_mediaPlayer->play(sourceId)); @@ -897,7 +906,7 @@ TEST_F(MediaPlayerTest, testGetOffsetWhenStoppedFails) { } /// Tests that calls to getOffset succeed when the pipeline is in a paused state. -TEST_F(MediaPlayerTest, testGetOffsetWhenPaused) { +TEST_P(MediaPlayerTest, testSlow_getOffsetWhenPaused) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); ASSERT_TRUE(m_mediaPlayer->play(sourceId)); @@ -919,7 +928,7 @@ TEST_F(MediaPlayerTest, testGetOffsetWhenPaused) { // * Check the offset value. Wait for playback to finish and expect the playback finished notification is received. // * Repeat the above for a new source. // */ -TEST_F(MediaPlayerTest, testPlayingTwoAttachments) { +TEST_P(MediaPlayerTest, testSlow_playingTwoAttachments) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); ASSERT_TRUE(m_mediaPlayer->play(sourceId)); @@ -942,7 +951,7 @@ TEST_F(MediaPlayerTest, testPlayingTwoAttachments) { * when the playback starts. Wait for playback to finish and expect the playback finished notification is received. * To a human ear the playback of this test is expected to sound reasonably smooth. */ -TEST_F(MediaPlayerTest, testUnsteadyReads) { +TEST_P(MediaPlayerTest, testSlow_unsteadyReads) { // clang-format off MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId, @@ -974,7 +983,7 @@ TEST_F(MediaPlayerTest, testUnsteadyReads) { * notification is received. To a human ear the playback of this test is expected to sound reasonably smooth * initially, then be interrupted for a few seconds, and then continue fairly smoothly. */ -TEST_F(MediaPlayerTest, testRecoveryFromPausedReads) { +TEST_P(MediaPlayerTest, testSlow_recoveryFromPausedReads) { MediaPlayer::SourceId sourceId; // clang-format off setAttachmentReaderSource(&sourceId, @@ -1002,7 +1011,7 @@ TEST_F(MediaPlayerTest, testRecoveryFromPausedReads) { } /// Tests playing a dummy playlist -TEST_F(MediaPlayerTest, testStartPlayWithUrlPlaylistWaitForEnd) { +TEST_P(MediaPlayerTest, testSlow_startPlayWithUrlPlaylistWaitForEnd) { MediaPlayer::SourceId sourceId = m_mediaPlayer->setSource(TEST_M3U_PLAYLIST_URL); ASSERT_NE(ERROR_SOURCE_ID, sourceId); ASSERT_TRUE(m_mediaPlayer->play(sourceId)); @@ -1016,7 +1025,7 @@ TEST_F(MediaPlayerTest, testStartPlayWithUrlPlaylistWaitForEnd) { * Test setting the offset to a seekable source. Setting the offset should succeed and playback should start from the * offset. */ -TEST_F(MediaPlayerTest, testSetOffsetSeekableSource) { +TEST_P(MediaPlayerTest, testSlow_setOffsetSeekableSource) { std::chrono::milliseconds offset(OFFSET); std::string url_single(FILE_PREFIX + inputsDirPath + MP3_FILE_PATH); @@ -1040,7 +1049,7 @@ TEST_F(MediaPlayerTest, testSetOffsetSeekableSource) { /** * Test setting the offset outside the bounds of the source. Playback will immediately end. */ -TEST_F(MediaPlayerTest, DISABLED_testSetOffsetOutsideBounds) { +TEST_P(MediaPlayerTest, DISABLED_test_setOffsetOutsideBounds) { std::chrono::milliseconds outOfBounds(MP3_FILE_LENGTH + PADDING); std::string url_single(FILE_PREFIX + inputsDirPath + MP3_FILE_PATH); @@ -1057,7 +1066,7 @@ TEST_F(MediaPlayerTest, DISABLED_testSetOffsetOutsideBounds) { * * Consecutive calls to setSource(const std::string url) without play() cause tests to occasionally fail: ACSDK-508. */ -TEST_F(MediaPlayerTest, DISABLED_testSetSourceResetsOffset) { +TEST_P(MediaPlayerTest, DISABLED_test_setSourceResetsOffset) { std::chrono::milliseconds offset(OFFSET); std::string url_single(FILE_PREFIX + inputsDirPath + MP3_FILE_PATH); @@ -1086,7 +1095,7 @@ TEST_F(MediaPlayerTest, DISABLED_testSetSourceResetsOffset) { * Test consecutive setSource() and play() calls. Expect the PlaybackStarted and PlaybackFinished will be received * before the timeout. */ -TEST_F(MediaPlayerTest, testRepeatAttachment) { +TEST_P(MediaPlayerTest, testSlow_repeatAttachment) { MediaPlayer::SourceId sourceId; for (int i = 0; i < 10; i++) { setAttachmentReaderSource(&sourceId); @@ -1100,7 +1109,7 @@ TEST_F(MediaPlayerTest, testRepeatAttachment) { /** * Test that the media plays after a volume change. */ -TEST_F(MediaPlayerTest, testSetVolumePlays) { +TEST_P(MediaPlayerTest, testSlow_setVolumePlays) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); @@ -1123,7 +1132,7 @@ TEST_F(MediaPlayerTest, testSetVolumePlays) { /** * Test that the media plays after a volume adjustment. */ -TEST_F(MediaPlayerTest, testAdjustVolumePlaysDuringPlay) { +TEST_P(MediaPlayerTest, testSlow_adjustVolumePlaysDuringPlay) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); @@ -1142,7 +1151,7 @@ TEST_F(MediaPlayerTest, testAdjustVolumePlaysDuringPlay) { /** * Test that the media plays after a volume adjustment. */ -TEST_F(MediaPlayerTest, testAdjustVolumePlays) { +TEST_P(MediaPlayerTest, testSlow_adjustVolumePlays) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); @@ -1167,7 +1176,7 @@ TEST_F(MediaPlayerTest, testAdjustVolumePlays) { * Test the play behavior when the media is adjusted out of bounds. The volume should be capped * at the bounds. The media should play to completion. */ -TEST_F(MediaPlayerTest, testAdjustVolumeOutOfBounds) { +TEST_P(MediaPlayerTest, testSlow_adjustVolumeOutOfBounds) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); @@ -1192,7 +1201,7 @@ TEST_F(MediaPlayerTest, testAdjustVolumeOutOfBounds) { /** * Test the media plays to completion even if it's muted. */ -TEST_F(MediaPlayerTest, testSetMutePlays) { +TEST_P(MediaPlayerTest, testSlow_setMutePlays) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); @@ -1216,7 +1225,7 @@ TEST_F(MediaPlayerTest, testSetMutePlays) { /** * Test that the speaker settings can be retrieved. */ -TEST_F(MediaPlayerTest, testGetSpeakerSettings) { +TEST_P(MediaPlayerTest, test_getSpeakerSettings) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); SpeakerInterface::SpeakerSettings settings; @@ -1232,7 +1241,7 @@ TEST_F(MediaPlayerTest, testGetSpeakerSettings) { * Tests this rounding edgecase. Calling adjustVolume(-10) with volume at 90 resulted in a value of 79 * when not rounded properly. */ -TEST_F(MediaPlayerTest, testRoundingEdgeCase) { +TEST_P(MediaPlayerTest, test_roundingEdgeCase) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); @@ -1249,7 +1258,7 @@ TEST_F(MediaPlayerTest, testRoundingEdgeCase) { * Check whether the playback started and playback finished notifications are received. * Check whether the tags were read from the file. */ -TEST_F(MediaPlayerTest, testReadTags) { +TEST_P(MediaPlayerTest, testSlow_readTags) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); @@ -1264,7 +1273,7 @@ TEST_F(MediaPlayerTest, testReadTags) { } /// Tests that consecutive calls to the same public API fails -TEST_F(MediaPlayerTest, testConsecutiveSameApiCalls) { +TEST_P(MediaPlayerTest, test_consecutiveSameApiCalls) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); @@ -1282,7 +1291,7 @@ TEST_F(MediaPlayerTest, testConsecutiveSameApiCalls) { } /// Tests that pausing immediately before waiting for a callback is valid. -TEST_F(MediaPlayerTest, testImmediatePause) { +TEST_P(MediaPlayerTest, testSlow_immediatePause) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); @@ -1296,7 +1305,7 @@ TEST_F(MediaPlayerTest, testImmediatePause) { } /// Tests setting multiple set source calls and observing onPlaybackStopped and onPlaybackFinished calls -TEST_F(MediaPlayerTest, multiplePlayAndSetSource) { +TEST_P(MediaPlayerTest, testSlow_multiplePlayAndSetSource) { MediaPlayer::SourceId sourceId; MediaPlayer::SourceId secondSourceId; MediaPlayer::SourceId thirdSourceId; @@ -1320,7 +1329,7 @@ TEST_F(MediaPlayerTest, multiplePlayAndSetSource) { } /// Tests passing an invalid source id to a play() call -TEST_F(MediaPlayerTest, invalidSourceId) { +TEST_P(MediaPlayerTest, test_invalidSourceId) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); @@ -1328,7 +1337,7 @@ TEST_F(MediaPlayerTest, invalidSourceId) { } /// Tests that two consecutive calls to pause fails. -TEST_F(MediaPlayerTest, doublePause) { +TEST_P(MediaPlayerTest, test_doublePause) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); @@ -1339,7 +1348,7 @@ TEST_F(MediaPlayerTest, doublePause) { } /// Tests that a resume when already playing fails -TEST_F(MediaPlayerTest, resumeWhenPlaying) { +TEST_P(MediaPlayerTest, test_resumeWhenPlaying) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); @@ -1349,7 +1358,7 @@ TEST_F(MediaPlayerTest, resumeWhenPlaying) { } /// Tests that a resume when stopped (not paused) fails -TEST_F(MediaPlayerTest, resumeWhenStopped) { +TEST_P(MediaPlayerTest, test_resumeWhenStopped) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); @@ -1361,7 +1370,7 @@ TEST_F(MediaPlayerTest, resumeWhenStopped) { } /// Tests that a stop callback when playing leads to an onPlaybackStopped callback -TEST_F(MediaPlayerTest, newSetSourceLeadsToStoppedCallback) { +TEST_P(MediaPlayerTest, test_newSetSourceLeadsToStoppedCallback) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); @@ -1375,7 +1384,7 @@ TEST_F(MediaPlayerTest, newSetSourceLeadsToStoppedCallback) { } /// Tests that resuming after a pause with a pending play leads to an onPlaybackResumed callback. -TEST_F(MediaPlayerTest, resumeAfterPauseWithPendingPlay) { +TEST_P(MediaPlayerTest, testSlow_resumeAfterPauseWithPendingPlay) { MediaPlayer::SourceId sourceId; setAttachmentReaderSource(&sourceId); @@ -1398,7 +1407,7 @@ TEST_F(MediaPlayerTest, resumeAfterPauseWithPendingPlay) { } /// Tests that playing continues until stop is called when repeat is on -TEST_F(MediaPlayerTest, testRepeatPlayForUrl) { +TEST_P(MediaPlayerTest, testSlow_repeatPlayForUrl) { bool repeat = true; std::string url_single(FILE_PREFIX + inputsDirPath + MP3_FILE_PATH); auto sourceId = m_mediaPlayer->setSource(url_single, std::chrono::milliseconds::zero(), repeat); diff --git a/MediaPlayer/GStreamerMediaPlayer/test/NormalizerTest.cpp b/MediaPlayer/GStreamerMediaPlayer/test/NormalizerTest.cpp index 7d3beaf681..7fc6b9cfe5 100644 --- a/MediaPlayer/GStreamerMediaPlayer/test/NormalizerTest.cpp +++ b/MediaPlayer/GStreamerMediaPlayer/test/NormalizerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -29,35 +29,35 @@ class NormalizerTest : public ::testing::Test {}; /** * Test normalize with a nullptr. */ -TEST_F(NormalizerTest, testNormalizeNullResult) { +TEST_F(NormalizerTest, test_normalizeNullResult) { ASSERT_FALSE(Normalizer::create(0, 1, 0, 1)->normalize(1, nullptr)); } /** * Test create with a source min larger than source max. */ -TEST_F(NormalizerTest, testCreateSourceMinGreaterThanMax) { +TEST_F(NormalizerTest, test_createSourceMinGreaterThanMax) { ASSERT_EQ(Normalizer::create(100, 0, 0, 1), nullptr); } /** * Test create with a source min equal to source max. */ -TEST_F(NormalizerTest, testCreateSourceMinEqualToMax) { +TEST_F(NormalizerTest, test_createSourceMinEqualToMax) { ASSERT_EQ(Normalizer::create(0, 0, 0, 1), nullptr); } /** * Test create with a normalized min larger than normalized max. */ -TEST_F(NormalizerTest, testCreateNormalizeMinGreaterThanMax) { +TEST_F(NormalizerTest, test_createNormalizeMinGreaterThanMax) { ASSERT_EQ(Normalizer::create(0, 1, 100, 1), nullptr); } /** * Test normalize with a normalized min equal to normalized max. */ -TEST_F(NormalizerTest, testNormalizeNormalizedMinEqualToMax) { +TEST_F(NormalizerTest, test_normalizeNormalizedMinEqualToMax) { double result; ASSERT_TRUE(Normalizer::create(0, 10, 1, 1)->normalize(2, &result)); ASSERT_EQ(result, 1); @@ -66,7 +66,7 @@ TEST_F(NormalizerTest, testNormalizeNormalizedMinEqualToMax) { /** * Test normalize with an input outside the source bounds. */ -TEST_F(NormalizerTest, testNormalizeInputOutsideSourceBounds) { +TEST_F(NormalizerTest, test_normalizeInputOutsideSourceBounds) { double result; ASSERT_FALSE(Normalizer::create(0, 1, 0, 1)->normalize(2, &result)); } @@ -74,7 +74,7 @@ TEST_F(NormalizerTest, testNormalizeInputOutsideSourceBounds) { /** * Test normalizing to the same range. */ -TEST_F(NormalizerTest, testNormalizeSameScale) { +TEST_F(NormalizerTest, test_normalizeSameScale) { double result; ASSERT_TRUE(Normalizer::create(0, 2, 0, 2)->normalize(1, &result)); ASSERT_EQ(result, 1); @@ -83,7 +83,7 @@ TEST_F(NormalizerTest, testNormalizeSameScale) { /** * Test normalizing to a smaller range. */ -TEST_F(NormalizerTest, testNormalizeScaleDown) { +TEST_F(NormalizerTest, test_normalizeScaleDown) { double result; ASSERT_TRUE(Normalizer::create(0, 100, 0, 10)->normalize(50, &result)); ASSERT_EQ(result, 5); @@ -92,7 +92,7 @@ TEST_F(NormalizerTest, testNormalizeScaleDown) { /** * Test normalizing to a larger range. */ -TEST_F(NormalizerTest, testNormalizeScaleUp) { +TEST_F(NormalizerTest, test_normalizeScaleUp) { double result; ASSERT_TRUE(Normalizer::create(0, 10, 0, 100)->normalize(5, &result)); ASSERT_EQ(result, 50); @@ -101,7 +101,7 @@ TEST_F(NormalizerTest, testNormalizeScaleUp) { /** * Test normalizing to a negative range. */ -TEST_F(NormalizerTest, testNormalizeNegativeRange) { +TEST_F(NormalizerTest, test_normalizeNegativeRange) { double result; ASSERT_TRUE(Normalizer::create(0, 10, -10, 0)->normalize(4, &result)); ASSERT_EQ(result, -6); @@ -110,7 +110,7 @@ TEST_F(NormalizerTest, testNormalizeNegativeRange) { /** * Test where source min != normalize min. */ -TEST_F(NormalizerTest, testNormalizeDifferentMinimums) { +TEST_F(NormalizerTest, test_normalizeDifferentMinimums) { double result; ASSERT_TRUE(Normalizer::create(1, 5, 0, 100)->normalize(2, &result)); ASSERT_EQ(result, 25); @@ -119,7 +119,7 @@ TEST_F(NormalizerTest, testNormalizeDifferentMinimums) { /** * Test where result is a non-integer. */ -TEST_F(NormalizerTest, testNonInteger) { +TEST_F(NormalizerTest, test_nonInteger) { double result; ASSERT_TRUE(Normalizer::create(0, 2, 0, 3)->normalize(1, &result)); ASSERT_EQ(result, 1.5); diff --git a/PlaylistParser/include/PlaylistParser/IterativePlaylistParser.h b/PlaylistParser/include/PlaylistParser/IterativePlaylistParser.h index 529c87c3de..8f4c7a686b 100644 --- a/PlaylistParser/include/PlaylistParser/IterativePlaylistParser.h +++ b/PlaylistParser/include/PlaylistParser/IterativePlaylistParser.h @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. diff --git a/PlaylistParser/include/PlaylistParser/M3UParser.h b/PlaylistParser/include/PlaylistParser/M3UParser.h index 7b2396d328..0b339fb8c0 100644 --- a/PlaylistParser/include/PlaylistParser/M3UParser.h +++ b/PlaylistParser/include/PlaylistParser/M3UParser.h @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -25,6 +25,9 @@ namespace alexaClientSDK { namespace playlistParser { +/// An invalid media sequence number. +static constexpr long INVALID_MEDIA_SEQUENCE = -1; + /** * A struct to contain next play item. * A PlayItem could either be a Playlist URL (to parse) or Media Info (to play). @@ -67,25 +70,39 @@ struct M3UContent { * * @param variantURLs The variant URLs pointing to media playlists. */ - M3UContent(const std::vector variantURLs); + M3UContent(const std::vector& variantURLs); /** * Constructor for parsed content of media playlist. * * @param entries List of PlaylistEntry from parsed content. * @param isLive @c true for live HLS playlists. + * @param mediaSequence The value of the EXT-X-MEDIA-SEQUENCE tag */ - M3UContent(const std::vector entries, bool isLive); + M3UContent( + const std::vector& entries, + bool isLive, + long mediaSequence = INVALID_MEDIA_SEQUENCE); /** * Helper method to check if content is a master playlist. + * + * @return @c true if this represents a master playlist */ bool isMasterPlaylist() const; + /** + * Helper method to tell if the media sequence field is present in the M3U8 document. + * + * @return @c true if this represents a playlist that has the media sequence field. + */ + bool hasMediaSequence() const; + /** * Helper method to check if no URLs are parsed. */ bool empty() const; + /// If this is a master playlist, variantURLs has list of media playlists. const std::vector variantURLs; @@ -94,6 +111,12 @@ struct M3UContent { /// If EXT-X-ENDLIST tag exists, isLive is set to false. const bool isLive; + + /** + * The value of the EXT-X-MEDIA-SEQUENCE tag. The client code is responsible for calling the @c hasMediaSequence() + * method to check if the content of this field should be read. + */ + const long mediaSequence; }; /** @@ -125,6 +148,15 @@ avsCommon::utils::playlistParser::EncryptionInfo parseHLSEncryptionLine( const std::string& line, const std::string& baseURL); +/** + * Helper method that parses the media sequence field. This method assumes that the line passed begins with the media + * sequence tag. + * + * @param line The line to be parsed. + * @return The media sequence value or @c INVALID_MEDIA_SEQUENCE if any issue happened during parsing. + */ +long parsePlaylistMediaSequence(const std::string& line); + /** * Parses #EXT-X-BYTERANGE line of HLS playlist and returns @c ByteRange. * diff --git a/PlaylistParser/src/M3UParser.cpp b/PlaylistParser/src/M3UParser.cpp index 653db40a99..5553b45a17 100644 --- a/PlaylistParser/src/M3UParser.cpp +++ b/PlaylistParser/src/M3UParser.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -40,6 +40,9 @@ static const std::string TAG("M3UParser"); /// The first line of an Extended M3U playlist. static const std::string EXT_M3U_PLAYLIST_HEADER = "#EXTM3U"; +/// The key to identify the media sequence tag. +static const std::string EXTXMEDIASEQUENCE = "#EXT-X-MEDIA-SEQUENCE:"; + /// HLS #EXTINF tag. static const std::string EXTINF = "#EXTINF"; @@ -97,7 +100,7 @@ static const int IV_HEX_STRING_LENGTH = 32; * @param line The #EXTINF line in HLS playlist. * @return parsed runtime in milliseconds from line. */ -std::chrono::milliseconds parseRuntime(std::string line); +std::chrono::milliseconds parseRuntime(const std::string& line); /** * Helper method to convert a line in HLS playlist to absolute URL. @@ -126,16 +129,26 @@ PlayItem::PlayItem(std::string playlistURL) : type(Type::PLAYLIST_URL), playlist PlayItem::PlayItem(PlaylistEntry playlistEntry) : type(Type::MEDIA_INFO), playlistEntry(playlistEntry) { } -M3UContent::M3UContent(const std::vector variantURLs) : variantURLs(variantURLs), isLive(false) { +M3UContent::M3UContent(const std::vector& variantURLs) : + variantURLs(variantURLs), + isLive(false), + mediaSequence(INVALID_MEDIA_SEQUENCE) { } -M3UContent::M3UContent(const std::vector entries, bool isLive) : entries(entries), isLive(isLive) { +M3UContent::M3UContent(const std::vector& entries, bool isLive, long mediaSequence) : + entries(entries), + isLive(isLive), + mediaSequence(mediaSequence) { } bool M3UContent::isMasterPlaylist() const { return !variantURLs.empty(); } +bool M3UContent::hasMediaSequence() const { + return INVALID_MEDIA_SEQUENCE != mediaSequence; +} + bool M3UContent::empty() const { return entries.empty() && variantURLs.empty(); } @@ -155,6 +168,7 @@ M3UContent parseM3UContent(const std::string& playlistURL, const std::string& co std::string line; auto isPlaylistExtendedM3U = false; + auto playlistMediaSequence = INVALID_MEDIA_SEQUENCE; auto isLive = true; auto isMasterPlaylist = false; auto duration = INVALID_DURATION; @@ -175,6 +189,8 @@ M3UContent parseM3UContent(const std::string& playlistURL, const std::string& co if (firstChar == '#') { if (hasPrefix(line, EXT_M3U_PLAYLIST_HEADER)) { isPlaylistExtendedM3U = true; + } else if (hasPrefix(line, EXTXMEDIASEQUENCE)) { + playlistMediaSequence = parsePlaylistMediaSequence(line); } else if (hasPrefix(line, EXTINF)) { duration = parseRuntime(line); } else if (hasPrefix(line, EXTSTREAMINF)) { @@ -224,7 +240,24 @@ M3UContent parseM3UContent(const std::string& playlistURL, const std::string& co entries.back().parseResult = PlaylistParseResult::FINISHED; } - return isMasterPlaylist ? M3UContent(variantURLs) : M3UContent(entries, isLive); + if (isMasterPlaylist) { + return M3UContent(variantURLs); + } else { + return M3UContent(entries, isLive, playlistMediaSequence); + } +} + +long parsePlaylistMediaSequence(const std::string& line) { + auto runner = EXTXMEDIASEQUENCE.length(); + auto stringFromHereOnwards = line.substr(runner); + std::istringstream iss(stringFromHereOnwards); + + long playlistMediaSequence; + iss >> playlistMediaSequence; + if (!iss || (playlistMediaSequence < 0) || (runner == line.length())) { + return INVALID_MEDIA_SEQUENCE; + } + return playlistMediaSequence; } bool getAbsoluteURL(const std::string& baseURL, const std::string& url, std::string* absoluteURL) { @@ -250,7 +283,7 @@ bool isPlaylistExtendedM3U(const std::string& playlistContent) { } } -std::chrono::milliseconds parseRuntime(std::string line) { +std::chrono::milliseconds parseRuntime(const std::string& line) { // #EXTINF:1234.00, blah blah blah have you ever heard the tragedy of darth plagueis the wise? auto runner = EXTINF.length(); diff --git a/PlaylistParser/src/PlaylistParser.cpp b/PlaylistParser/src/PlaylistParser.cpp index fc0fc81b14..a06cb27cb8 100644 --- a/PlaylistParser/src/PlaylistParser.cpp +++ b/PlaylistParser/src/PlaylistParser.cpp @@ -103,7 +103,25 @@ void PlaylistParser::doDepthFirstSearch( */ std::deque playQueue; playQueue.push_front(rootUrl); + + /* + * The last URL that was retrieved from a playlist, which is used skip URLs on future playlists and only notify + * observers about new URLs. + */ std::string lastUrlParsed; + + /* + * Initialized with a negative number, so any value of the media sequence M3U8 field will be recognized as a valid + * new playlist on the first comparison. + */ + long lastMediaSequence = INVALID_MEDIA_SEQUENCE; + + /* + * The number of fragments received on the last playlist parsed. This number is used to check if we should accept + * a playlist gap in which the new playlist does not have the last audio fragment parsed. + */ + int lastNumberOfFragments = 0; + while (!playQueue.empty() && !m_shuttingDown) { if (m_shuttingDown) { return; @@ -184,6 +202,34 @@ void PlaylistParser::doDepthFirstSearch( // as a default. playQueue.push_front(m3uContent.variantURLs.front()); } else { + if (m3uContent.isLive) { + ACSDK_DEBUG9(LX("encounteredLiveHLSPlaylist") + .sensitive("url", playlistURL) + .d("info", "willRetryURLInFuture")); + /* + * Because this URL represents a live playlist which can have additional chunks added to it, we + * need to make a request to this URL again in the future to continue playback of additional + * chunks that get added. + */ + playQueue.push_back(playlistURL); + } + + /* + * M3U8 has an optional field called #EXT-X-MEDIA-SEQUENCE that represents a sequence in which each + * playlist should be played. Depending on the music service provider, the content delivery network + * does not guarantee that playlists are delivered in order. For instance, if a client fetched a + * playlist with the sequence number 100 at 12h00, the same client may fetch the playlist number + * 98 at 12h01. So, if the existence of the field provides the means for such analysis, and this + * playlist's position is not after the last playlist processed, we ignore this playlist. + */ + if (m3uContent.hasMediaSequence() && (lastMediaSequence >= m3uContent.mediaSequence)) { + ACSDK_DEBUG9(LX("foundNonForwardPlaylist") + .sensitive("url", playlistURL) + .d("currentMediaSequence", lastMediaSequence) + .d("playlistMediaSequence", m3uContent.mediaSequence)); + continue; + } + auto entries = m3uContent.entries; // lastUrlParsed is set when we actually parse some urls from the playlist - here, it is our first // pass at this playlist @@ -193,10 +239,12 @@ void PlaylistParser::doDepthFirstSearch( } lastUrlParsed = entries.back().url; } else { - // Setting this to 0 as an initial value so that if we don't see the last URL we parsed in the - // latest pass of the playlist, we stream all the URLs within the playlist as a sort of - // recovery mechanism. This way, if we parse this so far into the future that all the URLs we - // had previously seen are gone, we'll still stream the latest URLs. + /* + * Setting this to 0 as an initial value so that if we don't see the last URL we parsed in the + * latest pass of the playlist, we stream all the URLs within the playlist as a sort of recovery + * mechanism. This way, if we parse this so far into the future that all the URLs we had + * previously seen are gone, we'll still stream the latest URLs. + */ int startPointForNewURLsAdded = 0; for (int i = entries.size() - 1; i >= 0; --i) { if (entries.at(i).url == lastUrlParsed) { @@ -204,23 +252,66 @@ void PlaylistParser::doDepthFirstSearch( startPointForNewURLsAdded = i + 1; } } + + /* + * If the M3U8 content contains the media sequence field, we can compare the playlist just + * received with the previous one to avoid playing a faulty sequence of playlists. + */ + if (m3uContent.hasMediaSequence()) { + /* + * True if the new playlist and the last one that was processed have no audio fragments in + * common. + */ + bool newPlaylistHasNoIntersection = (0 == startPointForNewURLsAdded); + + /* + * We identify a jump in the playlist sequence when the media sequence of the playlist is + * not immediately after the last media sequence processed. The aim is to avoid the user + * hearing gaps in the playback. + * + * Tolerating the jump is important since there is no guarantee that the music provider + * will give us a complete sequence of playlists. + * + * If there was a jump, we tolerate the jump as long as the last URL parsed can be find on + * the playlist. + */ + if ((lastMediaSequence + 1 < m3uContent.mediaSequence) && newPlaylistHasNoIntersection) { + /* + * We also tolerate the gap when the length of the gap is exactly the number of + * fragments in a playlist. + */ + if (m3uContent.mediaSequence - lastMediaSequence == lastNumberOfFragments) { + ACSDK_DEBUG9(LX("foundUrlListGapButToleratingIt") + .sensitive("url", playlistURL) + .d("currentMediaSequence", lastMediaSequence) + .d("playlistMediaSequence", m3uContent.mediaSequence)); + } else { + ACSDK_INFO(LX("foundUrlListGapAndIgnoringLastPlaylistReceived") + .sensitive("url", playlistURL) + .d("currentMediaSequence", lastMediaSequence) + .d("playlistMediaSequence", m3uContent.mediaSequence)); + continue; + } + } else { + ACSDK_DEBUG9(LX("foundNewPlaylistToProcess") + .sensitive("url", playlistURL) + .d("currentMediaSequence", lastMediaSequence) + .d("playlistMediaSequence", m3uContent.mediaSequence)); + } + lastMediaSequence = m3uContent.mediaSequence; + lastNumberOfFragments = entries.size(); + } + + /* + * Adds all audio fragments from the new playlist starting from the first one that did not + * appear on the last playlist that was accepted. + */ for (unsigned i = startPointForNewURLsAdded; i < entries.size(); ++i) { ACSDK_DEBUG9(LX("foundNewURLInLivePlaylist")); observer->onPlaylistEntryParsed(id, entries.at(i)); } lastUrlParsed = entries.back().url; } - if (m3uContent.isLive) { - ACSDK_DEBUG9(LX("encounteredLiveHLSPlaylist") - .sensitive("url", playlistURL) - .d("info", "willRetryURLInFuture")); - /* - * Because this URL represents a live playlist which can have additional chunks added to it, we - * need to make a request to this URL again in the future to continue playback of additional - * chunks that get added. - */ - playQueue.push_back(playlistURL); - } } } else { auto entries = m3uContent.entries; diff --git a/PlaylistParser/test/ContentDecrypterTest.cpp b/PlaylistParser/test/ContentDecrypterTest.cpp index eb080a9dd3..094187bb9c 100644 --- a/PlaylistParser/test/ContentDecrypterTest.cpp +++ b/PlaylistParser/test/ContentDecrypterTest.cpp @@ -100,7 +100,7 @@ std::string ContentDecrypterTest::readDecryptedContent(size_t readSize) { return std::string(buffer.begin(), buffer.end()); } -TEST_F(ContentDecrypterTest, testUnsupportedEncryption) { +TEST_F(ContentDecrypterTest, test_unsupportedEncryption) { auto noEncryption = EncryptionInfo(); auto result = m_decrypter->decryptAndWrite(AES_ENCRYPTED_CONTENT, KEY, noEncryption, m_writer); @@ -108,7 +108,7 @@ TEST_F(ContentDecrypterTest, testUnsupportedEncryption) { EXPECT_FALSE(result); } -TEST_F(ContentDecrypterTest, testAESDecryption) { +TEST_F(ContentDecrypterTest, test_aESDecryption) { auto result = m_decrypter->decryptAndWrite(AES_ENCRYPTED_CONTENT, KEY, AES_ENCRYPTION_INFO, m_writer); auto decryptedString = readDecryptedContent(DECRYPTED_STRING.size()); @@ -116,13 +116,13 @@ TEST_F(ContentDecrypterTest, testAESDecryption) { EXPECT_EQ(DECRYPTED_STRING, decryptedString); } -TEST_F(ContentDecrypterTest, testConvertIVNullByteArray) { +TEST_F(ContentDecrypterTest, test_convertIVNullByteArray) { auto result = ContentDecrypter::convertIVToByteArray(HEX_IV, nullptr); EXPECT_FALSE(result); } -TEST_F(ContentDecrypterTest, testConvertIVIncorrectLength) { +TEST_F(ContentDecrypterTest, test_convertIVIncorrectLength) { ByteVector actualIV; auto result = ContentDecrypter::convertIVToByteArray("0x01", &actualIV); @@ -131,7 +131,7 @@ TEST_F(ContentDecrypterTest, testConvertIVIncorrectLength) { EXPECT_TRUE(actualIV.empty()); } -TEST_F(ContentDecrypterTest, testConvertIVNotHex) { +TEST_F(ContentDecrypterTest, test_convertIVNotHex) { const std::string nonHEX_IV = "0101010101010101010101010101010101"; ByteVector actualIV; @@ -141,7 +141,7 @@ TEST_F(ContentDecrypterTest, testConvertIVNotHex) { EXPECT_TRUE(actualIV.empty()); } -TEST_F(ContentDecrypterTest, testConvertIV) { +TEST_F(ContentDecrypterTest, test_convertIV) { ByteVector actualIV; auto result = ContentDecrypter::convertIVToByteArray(HEX_IV, &actualIV); diff --git a/PlaylistParser/test/IterativePlaylistParserTest.cpp b/PlaylistParser/test/IterativePlaylistParserTest.cpp index ac2b4dab20..b163493ab9 100644 --- a/PlaylistParser/test/IterativePlaylistParserTest.cpp +++ b/PlaylistParser/test/IterativePlaylistParserTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -114,56 +114,56 @@ void IterativePlaylistParserTest::testPlaylist(const std::string& url, const std /** * Tests initialize failure due to an empty playlist url. */ -TEST_F(IterativePlaylistParserTest, testInitializeFailed) { +TEST_F(IterativePlaylistParserTest, test_initializeFailed) { EXPECT_FALSE(m_parser->initializeParsing("")); } /** * Tests successful initialization with non-empty url. */ -TEST_F(IterativePlaylistParserTest, testInitializeOk) { +TEST_F(IterativePlaylistParserTest, test_initializeOk) { EXPECT_TRUE(m_parser->initializeParsing(TEST_M3U_PLAYLIST_URL)); } /** * Tests parsing of a simple M3U playlist. */ -TEST_F(IterativePlaylistParserTest, testParsingPlaylist) { +TEST_F(IterativePlaylistParserTest, test_parsingPlaylist) { testPlaylist(TEST_M3U_PLAYLIST_URL, TEST_M3U_PLAYLIST_URLS, TEST_M3U_DURATIONS); } /** * Tests parsing of an extended M3U/HLS playlist. */ -TEST_F(IterativePlaylistParserTest, testParsingHlsPlaylist) { +TEST_F(IterativePlaylistParserTest, test_parsingHlsPlaylist) { testPlaylist(TEST_HLS_PLAYLIST_URL, TEST_HLS_PLAYLIST_URLS, TEST_HLS_DURATIONS); } /** * Tests parsing of a PLS playlist. */ -TEST_F(IterativePlaylistParserTest, testParsingPlsPlaylist) { +TEST_F(IterativePlaylistParserTest, test_parsingPlsPlaylist) { testPlaylist(TEST_PLS_PLAYLIST_URL, TEST_PLS_PLAYLIST_URLS); } /** * Tests parsing of a simple M3U playlist with relative urls. */ -TEST_F(IterativePlaylistParserTest, testParsingRelativePlaylist) { +TEST_F(IterativePlaylistParserTest, test_parsingRelativePlaylist) { testPlaylist(TEST_M3U_RELATIVE_PLAYLIST_URL, TEST_M3U_RELATIVE_PLAYLIST_URLS); } /** * Tests parsing of a live stream HLS playlist. */ -TEST_F(IterativePlaylistParserTest, testParsingLiveStreamPlaylist) { +TEST_F(IterativePlaylistParserTest, test_parsingLiveStreamPlaylist) { testPlaylist(TEST_HLS_LIVE_STREAM_PLAYLIST_URL, TEST_HLS_LIVE_STREAM_PLAYLIST_URLS, TEST_HLS_LIVE_STREAM_DURATIONS); } /** * Test parsing a media url. We expect the media to be the unique url. */ -TEST_F(IterativePlaylistParserTest, testParseMediaUrl) { +TEST_F(IterativePlaylistParserTest, test_parseMediaUrl) { EXPECT_TRUE(m_parser->initializeParsing(TEST_MEDIA_URL)); auto entry = m_parser->next(); @@ -174,7 +174,7 @@ TEST_F(IterativePlaylistParserTest, testParseMediaUrl) { /** * Test parsing a invalid url. */ -TEST_F(IterativePlaylistParserTest, testParseInvalidUrl) { +TEST_F(IterativePlaylistParserTest, test_parseInvalidUrl) { const std::string invalidUrl = "http://invalid.url"; EXPECT_TRUE(m_parser->initializeParsing(invalidUrl)); @@ -185,7 +185,7 @@ TEST_F(IterativePlaylistParserTest, testParseInvalidUrl) { /** * Test calling @c next() after abort parsing. */ -TEST_F(IterativePlaylistParserTest, testNextFailsAfterAbort) { +TEST_F(IterativePlaylistParserTest, test_nextFailsAfterAbort) { EXPECT_TRUE(m_parser->initializeParsing(TEST_M3U_PLAYLIST_URL)); m_parser->abort(); diff --git a/PlaylistParser/test/M3UParserTest.cpp b/PlaylistParser/test/M3UParserTest.cpp index 3414f32603..6c8c8e2c0c 100644 --- a/PlaylistParser/test/M3UParserTest.cpp +++ b/PlaylistParser/test/M3UParserTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ namespace playlistParser { namespace test { using namespace avsCommon::utils::playlistParser; +using namespace alexaClientSDK::playlistParser; using namespace ::testing; /// Default encryption info (EncryptionInfo::Method::NONE). @@ -56,7 +57,7 @@ void matchEncryptionInfo(const EncryptionInfo& lhs, const EncryptionInfo& rhs) { EXPECT_EQ(lhs.initVector, rhs.initVector); } -TEST(M3UParserTest, testParseKeyNoMethod) { +TEST(M3UParserTest, test_parseKeyNoMethod) { std::string line = "#EXT-X-KEY:"; auto result = parseHLSEncryptionLine(line, ""); @@ -64,7 +65,7 @@ TEST(M3UParserTest, testParseKeyNoMethod) { matchEncryptionInfo(noEncryption, result); } -TEST(M3UParserTest, testParseKeyMethodNone) { +TEST(M3UParserTest, test_parseKeyMethodNone) { std::string line = "#EXT-X-KEY:METHOD=NONE"; auto result = parseHLSEncryptionLine(line, ""); @@ -72,7 +73,7 @@ TEST(M3UParserTest, testParseKeyMethodNone) { matchEncryptionInfo(noEncryption, result); } -TEST(M3UParserTest, testParseKeyMissingKeyURL) { +TEST(M3UParserTest, test_parseKeyMissingKeyURL) { std::string line = "#EXT-X-KEY:METHOD=AES-128"; auto result = parseHLSEncryptionLine(line, ""); @@ -80,7 +81,7 @@ TEST(M3UParserTest, testParseKeyMissingKeyURL) { matchEncryptionInfo(noEncryption, result); } -TEST(M3UParserTest, testParseKeyUnknownMethod) { +TEST(M3UParserTest, test_parseKeyUnknownMethod) { std::string line = "#EXT-X-KEY:METHOD=UNKNOWN"; auto result = parseHLSEncryptionLine(line, ""); @@ -88,7 +89,7 @@ TEST(M3UParserTest, testParseKeyUnknownMethod) { matchEncryptionInfo(noEncryption, result); } -TEST(M3UParserTest, testParseKeyURLClosingQuote) { +TEST(M3UParserTest, test_parseKeyURLClosingQuote) { std::string line = "#EXT-X-KEY:METHOD=SAMPLE-AES,URI=\"https://www.amazon.com"; auto result = parseHLSEncryptionLine(line, ""); @@ -96,7 +97,7 @@ TEST(M3UParserTest, testParseKeyURLClosingQuote) { matchEncryptionInfo(noEncryption, result); } -TEST(M3UParserTest, testParseKeyValidURL) { +TEST(M3UParserTest, test_parseKeyValidURL) { std::string line = "#EXT-X-KEY:METHOD=SAMPLE-AES,URI=\"https://www.amazon.com\""; auto result = parseHLSEncryptionLine(line, ""); @@ -105,7 +106,7 @@ TEST(M3UParserTest, testParseKeyValidURL) { matchEncryptionInfo(expected, result); } -TEST(M3UParserTest, testParseKeyValidInitVector) { +TEST(M3UParserTest, test_parseKeyValidInitVector) { std::string line = "#EXT-X-KEY:METHOD=SAMPLE-AES,IV=0x8e2d35559338d21f2586e79d6cd5c606,URI=\"https://www.amazon.com\""; @@ -116,7 +117,47 @@ TEST(M3UParserTest, testParseKeyValidInitVector) { matchEncryptionInfo(expected, result); } -TEST(M3UParserTest, testParseKeyEncryptionInfo) { +TEST(M3UParserTest, test_parseMediaSequence) { + std::string line = "#EXT-X-MEDIA-SEQUENCE: 12345"; + + auto result = parsePlaylistMediaSequence(line); + + EXPECT_EQ(12345, result); +} + +TEST(M3UParserTest, test_parseMediaSequenceNoSpace) { + std::string line = "#EXT-X-MEDIA-SEQUENCE:12345"; + + auto result = parsePlaylistMediaSequence(line); + + EXPECT_EQ(12345, result); +} + +TEST(M3UParserTest, test_parseEmptyMediaSequence) { + std::string line = "#EXT-X-MEDIA-SEQUENCE: "; + + auto result = parsePlaylistMediaSequence(line); + + EXPECT_EQ(INVALID_MEDIA_SEQUENCE, result); +} + +TEST(M3UParserTest, test_parseManySpacesMediaSequence) { + std::string line = "#EXT-X-MEDIA-SEQUENCE: 12345 "; + + auto result = parsePlaylistMediaSequence(line); + + EXPECT_EQ(12345, result); +} + +TEST(M3UParserTest, test_parseInvalidMediaSequence) { + std::string line = "#EXT-X-MEDIA-SEQUENCE: invalid"; + + auto result = parsePlaylistMediaSequence(line); + + EXPECT_EQ(INVALID_MEDIA_SEQUENCE, result); +} + +TEST(M3UParserTest, test_parseKeyEncryptionInfo) { std::string playlist = EXT_M3U_HEADER + "#EXT-X-KEY:METHOD=SAMPLE-AES,URI=\"https://www.amazon.com\"\n" + MEDIA_URL; auto m3uContent = parseM3UContent(PLAYLIST_URL, playlist); @@ -126,7 +167,7 @@ TEST(M3UParserTest, testParseKeyEncryptionInfo) { matchEncryptionInfo(expected, m3uContent.entries[0].encryptionInfo); } -TEST(M3UParserTest, testParseByteRange) { +TEST(M3UParserTest, test_parseByteRange) { std::string line = "#EXT-X-BYTERANGE:82112@752321"; auto result = parseHLSByteRangeLine(line); @@ -134,7 +175,7 @@ TEST(M3UParserTest, testParseByteRange) { EXPECT_EQ(std::make_tuple(752321, 752321 + 82112 - 1), result); } -TEST(M3UParserTest, testParseByteRangeMissingColon) { +TEST(M3UParserTest, test_parseByteRangeMissingColon) { std::string line = "#EXT-X-BYTERANGE"; auto result = parseHLSByteRangeLine(line); @@ -142,7 +183,7 @@ TEST(M3UParserTest, testParseByteRangeMissingColon) { EXPECT_EQ(defaultByteRange, result); } -TEST(M3UParserTest, testParseByteRangeMissingAt) { +TEST(M3UParserTest, test_parseByteRangeMissingAt) { std::string line = "#EXT-X-BYTERANGE:1234"; auto result = parseHLSByteRangeLine(line); @@ -150,7 +191,7 @@ TEST(M3UParserTest, testParseByteRangeMissingAt) { EXPECT_EQ(defaultByteRange, result); } -TEST(M3UParserTest, testParseByteRangeNonDecimal) { +TEST(M3UParserTest, test_parseByteRangeNonDecimal) { std::string line = "#EXT-X-BYTERANGE:abcd@efgh"; auto result = parseHLSByteRangeLine(line); @@ -158,7 +199,7 @@ TEST(M3UParserTest, testParseByteRangeNonDecimal) { EXPECT_EQ(defaultByteRange, result); } -TEST(M3UParserTest, testHLSParseByteRange) { +TEST(M3UParserTest, test_hLSParseByteRange) { std::string playlist = EXT_M3U_HEADER + "#EXT-X-BYTERANGE:82112@752321\n" + MEDIA_URL; auto m3uContent = parseM3UContent(PLAYLIST_URL, playlist); @@ -166,7 +207,7 @@ TEST(M3UParserTest, testHLSParseByteRange) { EXPECT_EQ(std::make_tuple(752321, 752321 + 82112 - 1), m3uContent.entries[0].byteRange); } -TEST(M3UParserTest, testParseMAPMissingURL) { +TEST(M3UParserTest, test_parseMAPMissingURL) { std::string line = "#EXT-X-MAP:"; auto result = parseHLSMapLine(line, ""); @@ -174,7 +215,7 @@ TEST(M3UParserTest, testParseMAPMissingURL) { EXPECT_EQ(PlaylistParseResult::ERROR, result.parseResult); } -TEST(M3UParserTest, testParseMAPValidURL) { +TEST(M3UParserTest, test_parseMAPValidURL) { std::string line = "#EXT-X-MAP:URI=\"https://www.amazon.com\""; auto result = parseHLSMapLine(line, ""); @@ -184,7 +225,7 @@ TEST(M3UParserTest, testParseMAPValidURL) { EXPECT_EQ(PlaylistEntry::Type::MEDIA_INIT_INFO, result.type); } -TEST(M3UParserTest, testParseMAPValidByteRange) { +TEST(M3UParserTest, test_parseMAPValidByteRange) { std::string line = "#EXT-X-MAP:URI=\"https://www.amazon.com\",BYTERANGE=\"1234@5678\""; auto result = parseHLSMapLine(line, ""); @@ -194,7 +235,7 @@ TEST(M3UParserTest, testParseMAPValidByteRange) { EXPECT_EQ(PlaylistEntry::Type::MEDIA_INIT_INFO, result.type); } -TEST(M3UParserTest, testHLSParseMAP) { +TEST(M3UParserTest, test_hLSParseMAP) { std::string playlist = EXT_M3U_HEADER + "#EXT-X-MAP:URI=\"https://www.amazon.com\"\n" + MEDIA_URL; auto m3uContent = parseM3UContent(PLAYLIST_URL, playlist); @@ -204,7 +245,7 @@ TEST(M3UParserTest, testHLSParseMAP) { EXPECT_EQ(PlaylistEntry::Type::MEDIA_INIT_INFO, entry.type); } -TEST(M3UParserTest, testMasterPlaylist) { +TEST(M3UParserTest, test_masterPlaylist) { std::string playlist = EXT_M3U_HEADER + "#EXT-X-STREAM-INF\n" + PLAYLIST_URL; auto m3uContent = parseM3UContent(MASTER_PLAYLIST_URL, playlist); diff --git a/PlaylistParser/test/PlaylistParserTest.cpp b/PlaylistParser/test/PlaylistParserTest.cpp index c3a70da676..75e7b205de 100644 --- a/PlaylistParser/test/PlaylistParserTest.cpp +++ b/PlaylistParser/test/PlaylistParserTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -115,14 +115,14 @@ class PlaylistParserTest : public ::testing::Test { /** * Tests parsing of an empty playlist. Calls @c parsePlaylist and expects it returns false. */ -TEST_F(PlaylistParserTest, testEmptyUrl) { +TEST_F(PlaylistParserTest, test_emptyUrl) { ASSERT_FALSE(playlistParser->parsePlaylist("", testObserver)); } /** * Tests passing a @c nullptr for the observer. */ -TEST_F(PlaylistParserTest, testNullObserver) { +TEST_F(PlaylistParserTest, test_nullObserver) { ASSERT_FALSE(playlistParser->parsePlaylist("blah", nullptr)); } @@ -130,7 +130,7 @@ TEST_F(PlaylistParserTest, testNullObserver) { * Tests parsing of a simple M3U playlist. * Calls @c parsePlaylist and expects that the result of the parsing is successful. */ -TEST_F(PlaylistParserTest, testParsingPlaylist) { +TEST_F(PlaylistParserTest, testTimer_parsingPlaylist) { ASSERT_TRUE(playlistParser->parsePlaylist(TEST_M3U_PLAYLIST_URL, testObserver)); auto results = testObserver->waitForNCallbacks(TEST_M3U_PLAYLIST_URL_EXPECTED_PARSES); ASSERT_EQ(TEST_M3U_PLAYLIST_URL_EXPECTED_PARSES, results.size()); @@ -149,7 +149,7 @@ TEST_F(PlaylistParserTest, testParsingPlaylist) { * Tests parsing of a simple M3U playlist with relative urls. * Calls @c parsePlaylist and expects that the result of the parsing is successful. */ -TEST_F(PlaylistParserTest, testParsingRelativePlaylist) { +TEST_F(PlaylistParserTest, testTimer_parsingRelativePlaylist) { ASSERT_TRUE(playlistParser->parsePlaylist(TEST_M3U_RELATIVE_PLAYLIST_URL, testObserver)); auto results = testObserver->waitForNCallbacks(TEST_M3U_RELATIVE_PLAYLIST_URL_EXPECTED_PARSES); ASSERT_EQ(TEST_M3U_RELATIVE_PLAYLIST_URL_EXPECTED_PARSES, results.size()); @@ -167,7 +167,7 @@ TEST_F(PlaylistParserTest, testParsingRelativePlaylist) { * Tests parsing of an extended M3U/HLS playlist. * Calls @c parsePlaylist and expects that the result of the parsing is successful. */ -TEST_F(PlaylistParserTest, testParsingHlsPlaylist) { +TEST_F(PlaylistParserTest, testTimer_parsingHlsPlaylist) { ASSERT_TRUE(playlistParser->parsePlaylist(TEST_HLS_PLAYLIST_URL, testObserver)); auto results = testObserver->waitForNCallbacks(TEST_HLS_PLAYLIST_URL_EXPECTED_PARSES); ASSERT_EQ(TEST_HLS_PLAYLIST_URL_EXPECTED_PARSES, results.size()); @@ -186,7 +186,7 @@ TEST_F(PlaylistParserTest, testParsingHlsPlaylist) { * Tests parsing of a PLS playlist. * Calls @c parsePlaylist and expects that the result of the parsing is successful. */ -TEST_F(PlaylistParserTest, testParsingPlsPlaylist) { +TEST_F(PlaylistParserTest, testTimer_parsingPlsPlaylist) { ASSERT_TRUE(playlistParser->parsePlaylist(TEST_PLS_PLAYLIST_URL, testObserver)); auto results = testObserver->waitForNCallbacks(TEST_PLS_PLAYLIST_URL_EXPECTED_PARSES); ASSERT_EQ(TEST_PLS_PLAYLIST_URL_EXPECTED_PARSES, results.size()); @@ -204,7 +204,7 @@ TEST_F(PlaylistParserTest, testParsingPlsPlaylist) { * Tests that the playlist parser skips parsing of unwanted playlist types. * Calls @c parsePlaylist and expects that the result of the parsing is successful. */ -TEST_F(PlaylistParserTest, testNotParsingCertainPlaylistTypes) { +TEST_F(PlaylistParserTest, testTimer_notParsingCertainPlaylistTypes) { ASSERT_TRUE( playlistParser->parsePlaylist(TEST_HLS_PLAYLIST_URL, testObserver, {PlaylistParser::PlaylistType::EXT_M3U})); auto results = testObserver->waitForNCallbacks(1); @@ -216,7 +216,7 @@ TEST_F(PlaylistParserTest, testNotParsingCertainPlaylistTypes) { * Tests parsing of a live stream HLS playlist. * Calls @c parsePlaylist and expects that the result of the parsing is successful. */ -TEST_F(PlaylistParserTest, testParsingLiveStreamPlaylist) { +TEST_F(PlaylistParserTest, testTimer_parsingLiveStreamPlaylist) { ASSERT_TRUE(playlistParser->parsePlaylist(TEST_HLS_LIVE_STREAM_PLAYLIST_URL, testObserver)); auto results = testObserver->waitForNCallbacks(TEST_HLS_LIVE_STREAM_PLAYLIST_EXPECTED_PARSES); ASSERT_EQ(TEST_HLS_LIVE_STREAM_PLAYLIST_EXPECTED_PARSES, results.size()); diff --git a/PlaylistParser/test/PlaylistUtilsTest.cpp b/PlaylistParser/test/PlaylistUtilsTest.cpp index be5366cdf4..f5f9355c97 100644 --- a/PlaylistParser/test/PlaylistUtilsTest.cpp +++ b/PlaylistParser/test/PlaylistUtilsTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -32,7 +32,7 @@ static void verifyGetAbsoluteURLResult(std::string baseURL, std::string relative EXPECT_EQ(expected, actual); } -TEST(PlaylistUtilsTest, testGetAbsoluteURLFromAbsolutePath) { +TEST(PlaylistUtilsTest, test_getAbsoluteURLFromAbsolutePath) { std::string baseURL("http://a/b/c/d.m3u8"); // Success cases. diff --git a/README.md b/README.md index acab27ba90..e2dd540238 100644 --- a/README.md +++ b/README.md @@ -107,12 +107,30 @@ In addition to adopting the [Security Best Practices for Alexa](https://develope **Note**: Feature enhancements, updates, and resolved issues from previous releases are available to view in [CHANGELOG.md](https://github.com/alexa/alexa-client-sdk/blob/master/CHANGELOG.md). -### v1.12.1 released 04/02/2019: +### v1.13.0 released 05/22/2019: + +**Enhancements** + +* When an active Alert moves to the background, the alert now begins after a 10-second delay. Alert loop iteration delays can now no longer last longer than a maximum of 10 seconds, rather than depending on the length of the audio asset. +* Changed NotificationsSpeaker to use Alerts Volume instead of using the speaker volume. +* Allow customers to pass in an implementation of InternetConnectionMonitorInterface which will force AVSConnectionManager to reconnect on internet connectivity loss. +* Added an exponential wait time for retrying transmitting a message via CertifiedSender. +* When Volume is set to 0 and device is unmuted, volume is bumped up to a non-zero value. When Volume is set to 0 and Alexa talks back to you, volume is bumped up to a non-zero value. +* Deprecated HttpResponseCodes.h, which is now present only to ensure backward compatibility. +* The default endpoint for AVS connections has changed. **Bug Fixes** -* Fixed a bug where the same URL was being requested twice when streaming iHeartRadio. Now, a single request is sent. -* Corrected pause/resume handling in `ProgressTimer` so that extra `ProgressReportDelayElapsed` events are not sent to AVS. +* Fixed bug where receiving a Connected = true Property change from BlueZ without UUID information resulted in BlueZBluetoothDevice transitioning to CONNECTED state. +* Fixed bug where MediaStreamingStateChangedEvent may be sent on non-state related property changes. +* Added null check to SQLiteStatement::getColumnText. +* Fixed an issue where database values with unescaped single quotes passed to miscStorage database will fail to be stored. Added a note on the interface that only non-escaped values should be passed. +* Fixed a loop in audio in live stations based on playlists. +* Fixed a race condition in TemplateRuntime that may result in a crash. +* Fixed a race condition where a recognize event due to a EXPECT_SPEECH may end prematurely. +* Changed the name of Alerts channel to Alert channel within AudioActivityTracker. +* Prevented STOP Wakeword detections from generating Recognize events. +* The SQLiteDeviceSettingsStorageTest no longer fails for Android. **Known Issues** @@ -130,3 +148,5 @@ In addition to adopting the [Security Best Practices for Alexa](https://develope * `make integration` is currently not available for Android. In order to run integration tests on Android, you'll need to manually upload the test binary file along with any input file. At that point, the adb can be used to run the integration tests. * On Raspberry Pi running Android Things with HDMI output audio, beginning of speech is truncated when Alexa responds to user text-to-speech (TTS). * When the sample app is restarted and the network connection is lost, the Reminder TTS message does not play. Instead, the default alarm tone will play twice. +* ServerDisconnectIntegratonTest tests have been disabled until they can be updated to reflect new service behavior. +* Devices connected before the Bluetooth CA is initialized are ignored. diff --git a/RegistrationManager/test/CustomerDataManagerTest.cpp b/RegistrationManager/test/CustomerDataManagerTest.cpp index cb832b64fa..f824d0fb9c 100644 --- a/RegistrationManager/test/CustomerDataManagerTest.cpp +++ b/RegistrationManager/test/CustomerDataManagerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -45,14 +45,14 @@ class CustomerDataManagerTest : public ::testing::Test { std::shared_ptr m_dataManager; }; -TEST_F(CustomerDataManagerTest, testEmptyManager) { +TEST_F(CustomerDataManagerTest, test_emptyManager) { m_dataManager->clearData(); } /** * Test that all data handlers are cleared. */ -TEST_F(CustomerDataManagerTest, testClearData) { +TEST_F(CustomerDataManagerTest, test_clearData) { MockCustomerDataHandler handler1{m_dataManager}; MockCustomerDataHandler handler2{m_dataManager}; EXPECT_CALL(handler1, clearData()).Times(1); @@ -63,7 +63,7 @@ TEST_F(CustomerDataManagerTest, testClearData) { /** * Test that removing a data handler does not leave any dangling reference inside @c CustomerDataManager. */ -TEST_F(CustomerDataManagerTest, testClearDataAfterHandlerDeletion) { +TEST_F(CustomerDataManagerTest, test_clearDataAfterHandlerDeletion) { { // CustomerDataHandler will register and deregister with CustomerDataManager during ctor and dtor, respectively. MockCustomerDataHandler handler1{m_dataManager}; diff --git a/RegistrationManager/test/RegistrationManagerTest.cpp b/RegistrationManager/test/RegistrationManagerTest.cpp index f310004f08..0914ffb8e8 100644 --- a/RegistrationManager/test/RegistrationManagerTest.cpp +++ b/RegistrationManager/test/RegistrationManagerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -89,7 +89,7 @@ class RegistrationManagerTest : public ::testing::Test { * - clear data handler's data * - notify registration observer */ -TEST_F(RegistrationManagerTest, testLogout) { +TEST_F(RegistrationManagerTest, test_logout) { EXPECT_CALL(*m_directiveSequencer, disable()); EXPECT_CALL(*m_avsConnectionManager, disable()); EXPECT_CALL(*m_registrationObserver, onLogout()); diff --git a/SampleApp/include/SampleApp/PortAudioMicrophoneWrapper.h b/SampleApp/include/SampleApp/PortAudioMicrophoneWrapper.h index 9a69bdd45f..4607245b51 100644 --- a/SampleApp/include/SampleApp/PortAudioMicrophoneWrapper.h +++ b/SampleApp/include/SampleApp/PortAudioMicrophoneWrapper.h @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. diff --git a/SampleApp/include/SampleApp/SampleApplication.h b/SampleApp/include/SampleApp/SampleApplication.h index 110ec2ffe2..5700b65afe 100644 --- a/SampleApp/include/SampleApp/SampleApplication.h +++ b/SampleApp/include/SampleApp/SampleApplication.h @@ -113,20 +113,6 @@ class SampleApplication { capabilityAgents::externalMediaPlayer::ExternalMediaPlayer::AdapterCreateFunction createFunction); }; - /** - * Signature of functions to create a MediaPlayer. - * - * @param httpContentFetcherFactory The HTTPContentFetcherFactory to be used while creating the mediaPlayers. - * @param type The type of the SpeakerInterface. - * @param name The name of the MediaPlayer instance. - * @return Return shared pointer to the created MediaPlayer instance. - */ - using MediaPlayerCreateFunction = std::shared_ptr (*)( - std::shared_ptr contentFetcherFactory, - bool enableEqualizer, - avsCommon::sdkInterfaces::SpeakerInterface::Type type, - std::string name); - /** * Instances of this class register MediaPlayers to be created. Each third-party adapter registers a mediaPlayer * for itself by instantiating a static instance of the below class supplying their business name, speaker interface @@ -138,13 +124,11 @@ class SampleApplication { * Register a @c MediaPlayer for use by a music provider adapter. * * @param playerId The @c playerId identifying the @c ExternalMediaAdapter to register. - * @speakerType The SpeakerType of the mediaPlayer to be created. - * @param createFunction The function to use to create instances of the mediaPlayer to use for the player. + * @param speakerType The SpeakerType of the mediaPlayer to be created. */ MediaPlayerRegistration( const std::string& playerId, - avsCommon::sdkInterfaces::SpeakerInterface::Type speakerType, - MediaPlayerCreateFunction createFunction); + avsCommon::sdkInterfaces::SpeakerInterface::Type speakerType); }; private: @@ -171,6 +155,7 @@ class SampleApplication { * @param enableEqualizer Flag indicating if equalizer should be enabled for this media player. * @param type The type used to categorize the speaker for volume control. * @param name The media player instance name used for logging purpose. + * @param enableLiveMode Flag, indicating if the player is in live mode. * @return A pointer to the @c ApplicationMediaPlayer and to its speaker if it succeeds; otherwise, return @c * nullptr. */ @@ -179,7 +164,8 @@ class SampleApplication { std::shared_ptr httpContentFetcherFactory, bool enableEqualizer, avsCommon::sdkInterfaces::SpeakerInterface::Type type, - const std::string& name); + const std::string& name, + bool enableLiveMode = false); /// The @c InteractionManager which perform user requests. std::shared_ptr m_interactionManager; @@ -216,17 +202,19 @@ class SampleApplication { /// The @c MediaPlayer used by @c Bluetooth. std::shared_ptr m_bluetoothMediaPlayer; +#ifdef ENABLE_COMMS_AUDIO_PROXY + /// The @c MediaPlayer used by @c Comms. + std::shared_ptr m_commsMediaPlayer; +#endif + /// The @c CapabilitiesDelegate used by the client. std::shared_ptr m_capabilitiesDelegate; /// The @c MediaPlayer used by @c NotificationsCapabilityAgent. std::shared_ptr m_ringtoneMediaPlayer; - using SpeakerTypeAndCreateFunc = - std::pair; - - /// The singleton map from @c playerId to @c MediaPlayerCreateFunction. - static std::unordered_map m_playerToMediaPlayerMap; + /// The singleton map from @c playerId to @c SpeakerInterface::Type. + static std::unordered_map m_playerToSpeakerTypeMap; /// The singleton map from @c playerId to @c ExternalMediaAdapter creation functions. static capabilityAgents::externalMediaPlayer::ExternalMediaPlayer::AdapterCreationMap m_adapterToCreateFuncMap; diff --git a/SampleApp/src/PortAudioMicrophoneWrapper.cpp b/SampleApp/src/PortAudioMicrophoneWrapper.cpp index 499eaa422b..ec9497dcd8 100644 --- a/SampleApp/src/PortAudioMicrophoneWrapper.cpp +++ b/SampleApp/src/PortAudioMicrophoneWrapper.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. diff --git a/SampleApp/src/SampleApplication.cpp b/SampleApp/src/SampleApplication.cpp index 0eea516162..ccf3eca999 100644 --- a/SampleApp/src/SampleApplication.cpp +++ b/SampleApp/src/SampleApplication.cpp @@ -142,8 +142,8 @@ static const std::string DISPLAY_CARD_KEY("displayCardsSupported"); using namespace capabilityAgents::externalMediaPlayer; /// The @c m_playerToMediaPlayerMap Map of the adapter to their speaker-type and MediaPlayer creation methods. -std::unordered_map - SampleApplication::m_playerToMediaPlayerMap; +std::unordered_map + SampleApplication::m_playerToSpeakerTypeMap; /// The singleton map from @c playerId to @c ExternalMediaAdapter creation functions. std::unordered_map SampleApplication::m_adapterToCreateFuncMap; @@ -233,15 +233,12 @@ SampleApplication::AdapterRegistration::AdapterRegistration( SampleApplication::MediaPlayerRegistration::MediaPlayerRegistration( const std::string& playerId, - avsCommon::sdkInterfaces::SpeakerInterface::Type speakerType, - MediaPlayerCreateFunction createFunction) { - if (m_playerToMediaPlayerMap.find(playerId) != m_playerToMediaPlayerMap.end()) { + avsCommon::sdkInterfaces::SpeakerInterface::Type speakerType) { + if (m_playerToSpeakerTypeMap.find(playerId) != m_playerToSpeakerTypeMap.end()) { ACSDK_WARN(LX("MediaPlayer already exists").d("playerId", playerId)); } - m_playerToMediaPlayerMap[playerId] = - std::pair( - speakerType, createFunction); + m_playerToSpeakerTypeMap[playerId] = speakerType; } SampleAppReturnCode SampleApplication::run() { @@ -284,6 +281,12 @@ SampleApplication::~SampleApplication() { m_ringtoneMediaPlayer->shutdown(); } +#ifdef ENABLE_COMMS_AUDIO_PROXY + if (m_commsMediaPlayer) { + m_commsMediaPlayer->shutdown(); + } +#endif + avsCommon::avs::initialization::AlexaClientSDKInit::uninitialize(); } @@ -291,16 +294,16 @@ bool SampleApplication::createMediaPlayersForAdapters( std::shared_ptr httpContentFetcherFactory, std::shared_ptr equalizerRuntimeSetup, std::vector>& additionalSpeakers) { -#ifdef GSTREAMER_MEDIA_PLAYER bool equalizerEnabled = nullptr != equalizerRuntimeSetup; - for (auto& entry : m_playerToMediaPlayerMap) { - auto mediaPlayer = entry.second.second( - httpContentFetcherFactory, equalizerEnabled, entry.second.first, entry.first + "MediaPlayer"); + for (auto& entry : m_playerToSpeakerTypeMap) { + auto mediaPlayerSpeakerPair = createApplicationMediaPlayer( + httpContentFetcherFactory, equalizerEnabled, entry.second, entry.first + "MediaPlayer", false); + auto mediaPlayer = mediaPlayerSpeakerPair.first; + auto speaker = mediaPlayerSpeakerPair.second; if (mediaPlayer) { m_externalMusicProviderMediaPlayersMap[entry.first] = mediaPlayer; - m_externalMusicProviderSpeakersMap[entry.first] = mediaPlayer; - additionalSpeakers.push_back( - std::static_pointer_cast(mediaPlayer)); + m_externalMusicProviderSpeakersMap[entry.first] = speaker; + additionalSpeakers.push_back(speaker); m_adapterMediaPlayers.push_back(mediaPlayer); if (equalizerEnabled) { equalizerRuntimeSetup->addEqualizer(mediaPlayer); @@ -312,14 +315,6 @@ bool SampleApplication::createMediaPlayersForAdapters( } return true; -#else - if (!m_playerToMediaPlayerMap.empty()) { - // TODO(ACSDK-1622) Add support to external media players on android. - ACSDK_CRITICAL(LX("Failed to create media players").d("reason", "unsupportedOperation")); - return false; - } - return true; -#endif } bool SampleApplication::initialize( @@ -445,7 +440,7 @@ bool SampleApplication::initialize( std::tie(m_notificationsMediaPlayer, notificationsSpeaker) = createApplicationMediaPlayer( httpContentFetcherFactory, false, - avsCommon::sdkInterfaces::SpeakerInterface::Type::AVS_SPEAKER_VOLUME, + avsCommon::sdkInterfaces::SpeakerInterface::Type::AVS_ALERTS_VOLUME, "NotificationsMediaPlayer"); if (!m_notificationsMediaPlayer || !notificationsSpeaker) { ACSDK_CRITICAL(LX("Failed to create media player for notifications!")); @@ -475,6 +470,20 @@ bool SampleApplication::initialize( return false; } +#ifdef ENABLE_COMMS_AUDIO_PROXY + std::shared_ptr commsSpeaker; + std::tie(m_commsMediaPlayer, commsSpeaker) = createApplicationMediaPlayer( + httpContentFetcherFactory, + false, + avsCommon::sdkInterfaces::SpeakerInterface::Type::AVS_SPEAKER_VOLUME, + "CommsMediaPlayer", + true); + if (!m_commsMediaPlayer || !commsSpeaker) { + ACSDK_CRITICAL(LX("Failed to create media player for comms!")); + return false; + } +#endif + std::shared_ptr alertsSpeaker; std::tie(m_alertsMediaPlayer, alertsSpeaker) = createApplicationMediaPlayer( httpContentFetcherFactory, @@ -644,6 +653,20 @@ bool SampleApplication::initialize( std::make_shared(), postConnectSynchronizerFactory); + /* + * Creating the buffer (Shared Data Stream) that will hold user audio data. This is the main input into the SDK. + */ + size_t bufferSize = alexaClientSDK::avsCommon::avs::AudioInputStream::calculateBufferSize( + BUFFER_SIZE_IN_SAMPLES, WORD_SIZE, MAX_READERS); + auto buffer = std::make_shared(bufferSize); + std::shared_ptr sharedDataStream = + alexaClientSDK::avsCommon::avs::AudioInputStream::create(buffer, WORD_SIZE, MAX_READERS); + + if (!sharedDataStream) { + ACSDK_CRITICAL(LX("Failed to create shared data stream!")); + return false; + } + /* * Create the BluetoothDeviceManager to communicate with the Bluetooth stack. */ @@ -690,6 +713,11 @@ bool SampleApplication::initialize( #ifdef ENABLE_PCC phoneSpeaker, phoneCaller, +#endif +#ifdef ENABLE_COMMS_AUDIO_PROXY + m_commsMediaPlayer, + commsSpeaker, + sharedDataStream, #endif equalizerRuntimeSetup, audioFactory, @@ -736,20 +764,6 @@ bool SampleApplication::initialize( client->addTemplateRuntimeObserver(m_guiRenderer); } - /* - * Creating the buffer (Shared Data Stream) that will hold user audio data. This is the main input into the SDK. - */ - size_t bufferSize = alexaClientSDK::avsCommon::avs::AudioInputStream::calculateBufferSize( - BUFFER_SIZE_IN_SAMPLES, WORD_SIZE, MAX_READERS); - auto buffer = std::make_shared(bufferSize); - std::shared_ptr sharedDataStream = - alexaClientSDK::avsCommon::avs::AudioInputStream::create(buffer, WORD_SIZE, MAX_READERS); - - if (!sharedDataStream) { - ACSDK_CRITICAL(LX("Failed to create shared data stream!")); - return false; - } - alexaClientSDK::avsCommon::utils::AudioFormat compatibleAudioFormat; compatibleAudioFormat.sampleRateHz = SAMPLE_RATE_HZ; compatibleAudioFormat.sampleSizeInBits = WORD_SIZE * CHAR_BIT; @@ -909,18 +923,20 @@ SampleApplication::createApplicationMediaPlayer( std::shared_ptr httpContentFetcherFactory, bool enableEqualizer, avsCommon::sdkInterfaces::SpeakerInterface::Type type, - const std::string& name) { + const std::string& name, + bool enableLiveMode) { #ifdef GSTREAMER_MEDIA_PLAYER /* * For the SDK, the MediaPlayer happens to also provide volume control functionality. * Note the externalMusicProviderMediaPlayer is not added to the set of SpeakerInterfaces as there would be * more actions needed for these beyond setting the volume control on the MediaPlayer. */ - auto mediaPlayer = - alexaClientSDK::mediaPlayer::MediaPlayer::create(httpContentFetcherFactory, enableEqualizer, type, name); + auto mediaPlayer = alexaClientSDK::mediaPlayer::MediaPlayer::create( + httpContentFetcherFactory, enableEqualizer, type, name, enableLiveMode); return {mediaPlayer, std::static_pointer_cast(mediaPlayer)}; #elif defined(ANDROID_MEDIA_PLAYER) + // TODO - Add support of live mode to AndroidSLESMediaPlayer (ACSDK-2530). auto mediaPlayer = mediaPlayer::android::AndroidSLESMediaPlayer::create( httpContentFetcherFactory, m_openSlEngine, diff --git a/Settings/test/SQLiteDeviceSettingsStorageTest.cpp b/Settings/test/SQLiteDeviceSettingsStorageTest.cpp index c817c8af3e..4b750fe13c 100644 --- a/Settings/test/SQLiteDeviceSettingsStorageTest.cpp +++ b/Settings/test/SQLiteDeviceSettingsStorageTest.cpp @@ -121,7 +121,7 @@ void SQLiteDeviceSettingsStorageTest::TearDown() { /** * Test storing status and values to the database. */ -TEST_F(SQLiteDeviceSettingsStorageTest, insertUpdateSettingValue) { +TEST_F(SQLiteDeviceSettingsStorageTest, test_insertUpdateSettingValue) { const std::string key = "AAAA"; const std::string value1 = "BBBBB"; const std::string value2 = "CCCCC"; @@ -173,7 +173,7 @@ TEST_F(SQLiteDeviceSettingsStorageTest, insertUpdateSettingValue) { /** * Test removing an entry from the database. */ -TEST_F(SQLiteDeviceSettingsStorageTest, deleteSetting) { +TEST_F(SQLiteDeviceSettingsStorageTest, test_deleteSetting) { const std::string key = "AAAA"; const std::string value1 = "BBBBB"; const SettingStatus localStatus = SettingStatus::LOCAL_CHANGE_IN_PROGRESS; diff --git a/Settings/test/SettingStringConversionTest.cpp b/Settings/test/SettingStringConversionTest.cpp index 31dbc67744..44700df658 100644 --- a/Settings/test/SettingStringConversionTest.cpp +++ b/Settings/test/SettingStringConversionTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -143,7 +143,7 @@ std::pair expected(bool result, std::string value) { }; /// Test boolean conversions. -TEST(SettingStringConversionTest, testBoolConversion) { +TEST(SettingStringConversionTest, test_boolConversion) { // Valid conversions EXPECT_EQ(toSettingString(false), expected(true, "false")); EXPECT_EQ(toSettingString(true), expected(true, "true")); @@ -155,7 +155,7 @@ TEST(SettingStringConversionTest, testBoolConversion) { EXPECT_EQ(fromSettingString("not bool", false), std::make_pair(false, false)); }; -TEST(SettingStringConversionTest, testIntegralByteSize) { +TEST(SettingStringConversionTest, test_integralByteSize) { // Valid conversions EXPECT_EQ(fromSettingString("10", 100).first, true); EXPECT_EQ(fromSettingString("10", 100).second, 10); @@ -169,7 +169,7 @@ TEST(SettingStringConversionTest, testIntegralByteSize) { EXPECT_EQ(fromSettingString("not int", 10).second, 10); }; -TEST(SettingStringConversionTest, testArithmeticTypes) { +TEST(SettingStringConversionTest, test_arithmeticTypes) { // Valid conversions EXPECT_EQ(toSettingString('a'), expected(true, "a")); EXPECT_EQ(toSettingString(10), expected(true, "10")); @@ -188,7 +188,7 @@ TEST(SettingStringConversionTest, testArithmeticTypes) { EXPECT_EQ(fromSettingString("not double", 2.2), std::make_pair(false, 2.2)); } -TEST(SettingStringConversionTest, testFromEnum) { +TEST(SettingStringConversionTest, test_fromEnum) { // Valid conversions EXPECT_EQ(toSettingString(HelloEnum::HI), expected(true, R"("HI")")); EXPECT_EQ(fromSettingString(R"("THERE")", HelloEnum::HI), std::make_pair(true, HelloEnum::THERE)); @@ -199,7 +199,7 @@ TEST(SettingStringConversionTest, testFromEnum) { EXPECT_EQ(fromSettingString("-THERE-", HelloEnum::HI), std::make_pair(false, HelloEnum::HI)); } -TEST(SettingStringConversionTest, testFromClass) { +TEST(SettingStringConversionTest, test_fromClass) { // Valid conversions HelloClass newValue; newValue.m_name = "newValue"; diff --git a/Settings/test/SettingTest.cpp b/Settings/test/SettingTest.cpp index ba146797d5..23670cc72c 100644 --- a/Settings/test/SettingTest.cpp +++ b/Settings/test/SettingTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -75,14 +75,14 @@ std::shared_ptr> SettingTest::createSetting() { } /// Test successful create. -TEST_F(SettingTest, testCreate) { +TEST_F(SettingTest, test_create) { auto setting = createSetting(); ASSERT_NE(setting, nullptr); EXPECT_EQ(setting->get(), INIT_VALUE); } /// Test create initial value when restore value is not available. -TEST_F(SettingTest, testCreateNoRestore) { +TEST_F(SettingTest, test_createNoRestore) { m_protocol = std::unique_ptr(new MockSettingProtocol(NEW_VALUE_STR, false, false)); auto setting = createSetting(); ASSERT_NE(setting, nullptr); @@ -90,12 +90,12 @@ TEST_F(SettingTest, testCreateNoRestore) { } /// Test create with null protocol. -TEST_F(SettingTest, testNullCreate) { +TEST_F(SettingTest, test_nullCreate) { EXPECT_EQ(Setting::create(INIT_VALUE, nullptr), nullptr); } /// Test avs change. -TEST_F(SettingTest, testAvsChange) { +TEST_F(SettingTest, test_avsChange) { auto setting = createSetting(); ASSERT_NE(setting, nullptr); @@ -104,7 +104,7 @@ TEST_F(SettingTest, testAvsChange) { } /// Test avs change revert. -TEST_F(SettingTest, testAvsChangeRevert) { +TEST_F(SettingTest, test_avsChangeRevert) { m_protocol = std::unique_ptr(new MockSettingProtocol(INIT_VALUE_STR, true, true)); auto setting = createSetting(); ASSERT_NE(setting, nullptr); @@ -114,7 +114,7 @@ TEST_F(SettingTest, testAvsChangeRevert) { } /// Test local change. -TEST_F(SettingTest, testLocalChange) { +TEST_F(SettingTest, test_localChange) { auto setting = createSetting(); ASSERT_NE(setting, nullptr); @@ -123,7 +123,7 @@ TEST_F(SettingTest, testLocalChange) { } /// Test local change revert. -TEST_F(SettingTest, testLocalChangeRevert) { +TEST_F(SettingTest, test_localChangeRevert) { m_protocol = std::unique_ptr(new MockSettingProtocol(INIT_VALUE_STR, true, true)); auto setting = createSetting(); ASSERT_NE(setting, nullptr); @@ -133,7 +133,7 @@ TEST_F(SettingTest, testLocalChangeRevert) { } /// Test observer notification. -TEST_F(SettingTest, testObserverNotificationLocal) { +TEST_F(SettingTest, test_observerNotificationLocal) { auto setting = createSetting(); ASSERT_NE(setting, nullptr); @@ -145,7 +145,7 @@ TEST_F(SettingTest, testObserverNotificationLocal) { } /// Test observer notification. -TEST_F(SettingTest, testObserverNotificationAvs) { +TEST_F(SettingTest, test_observerNotificationAvs) { auto setting = createSetting(); ASSERT_NE(setting, nullptr); diff --git a/Settings/test/SettingsManagerTest.cpp b/Settings/test/SettingsManagerTest.cpp index 1c4e8a8867..f7a9e5d6f1 100644 --- a/Settings/test/SettingsManagerTest.cpp +++ b/Settings/test/SettingsManagerTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -71,7 +71,7 @@ class SettingsManagerTest : public testing::Test { }; /// Test add settings and setting the setting value. -TEST_F(SettingsManagerTest, testSetExistingSetting) { +TEST_F(SettingsManagerTest, test_setExistingSetting) { auto setting = std::make_shared(INITIAL_INT_VALUE); auto expectedResult = std::pair{true, NEW_INT_VALUE}; @@ -81,13 +81,13 @@ TEST_F(SettingsManagerTest, testSetExistingSetting) { } /// Test set value for setting that hasn't been registered. -TEST_F(SettingsManagerTest, testSetSettingUnavailable) { +TEST_F(SettingsManagerTest, test_setSettingUnavailable) { SettingsManager manager; EXPECT_EQ((m_manager.setValue(NEW_INT_VALUE)), SetSettingResult::UNAVAILABLE_SETTING); } /// Test get value for setting that hasn't been registered. -TEST_F(SettingsManagerTest, testGetExistingSetting) { +TEST_F(SettingsManagerTest, test_getExistingSetting) { auto setting = std::make_shared(INITIAL_INT_VALUE); auto expectedResult = std::pair{true, INITIAL_INT_VALUE}; @@ -96,13 +96,13 @@ TEST_F(SettingsManagerTest, testGetExistingSetting) { } /// Test get value for setting that hasn't been registered. -TEST_F(SettingsManagerTest, testGetSettingUnavailable) { +TEST_F(SettingsManagerTest, test_getSettingUnavailable) { auto expectedResult = std::pair{false, DEFAULT_INT_VALUE}; EXPECT_EQ((m_manager.getValue(DEFAULT_INT_VALUE)), expectedResult); } /// Test registering a setting that already exists. -TEST_F(SettingsManagerTest, testAddExistingSetting) { +TEST_F(SettingsManagerTest, test_addExistingSetting) { auto setting1 = std::make_shared(INITIAL_INT_VALUE); auto setting2 = std::make_shared(INITIAL_INT_VALUE); @@ -111,7 +111,7 @@ TEST_F(SettingsManagerTest, testAddExistingSetting) { } /// Test addObserver for a setting that exists. -TEST_F(SettingsManagerTest, testAddObserver) { +TEST_F(SettingsManagerTest, test_addObserver) { auto setting = std::make_shared(INITIAL_INT_VALUE); auto observer = std::make_shared>(); @@ -120,14 +120,14 @@ TEST_F(SettingsManagerTest, testAddObserver) { } /// Test addObserver for a setting that doesn't exist. -TEST_F(SettingsManagerTest, testAddObserverFailed) { +TEST_F(SettingsManagerTest, test_addObserverFailed) { auto observer = std::make_shared>(); EXPECT_FALSE((m_manager.addObserver(observer))); } /// Test addObserver for a setting that exists. -TEST_F(SettingsManagerTest, testRemoveObserver) { +TEST_F(SettingsManagerTest, test_removeObserver) { auto setting = std::make_shared(INITIAL_INT_VALUE); auto observer = std::make_shared>(); @@ -137,13 +137,13 @@ TEST_F(SettingsManagerTest, testRemoveObserver) { } /// Test addObserver for a setting that doesn't exist. -TEST_F(SettingsManagerTest, testRemoveObserverFailed) { +TEST_F(SettingsManagerTest, test_removeObserverFailed) { auto observer = std::make_shared>(); m_manager.removeObserver(observer); } /// Test manager operations for string setting. -TEST_F(SettingsManagerTest, testSetExistingStringSetting) { +TEST_F(SettingsManagerTest, test_setExistingStringSetting) { std::string initialValue = ""; auto setting = std::make_shared(initialValue); diff --git a/SpeechEncoder/test/SpeechEncoderTest.cpp b/SpeechEncoder/test/SpeechEncoderTest.cpp index 98a08f1db2..ce5e3d7680 100644 --- a/SpeechEncoder/test/SpeechEncoderTest.cpp +++ b/SpeechEncoder/test/SpeechEncoderTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -109,7 +109,7 @@ class SpeechEncoderTest : public ::testing::Test { * This test will feed a dummy PCM stream into SpeechEncoder, then test the behavior with * the mock @c EncoderContext. */ -TEST_F(SpeechEncoderTest, testStartEncoding) { +TEST_F(SpeechEncoderTest, test_startEncoding) { AudioFormat audioFormat = { .encoding = AudioFormat::Encoding::LPCM, .endianness = AudioFormat::Endianness::LITTLE, @@ -162,7 +162,7 @@ TEST_F(SpeechEncoderTest, testStartEncoding) { /** * Test if encoding thread will exit if encoder output is not being consumed on exit. */ -TEST_F(SpeechEncoderTest, testShutdownOnBlockingWrite) { +TEST_F(SpeechEncoderTest, test_shutdownOnBlockingWrite) { AudioFormat audioFormat = { .encoding = AudioFormat::Encoding::LPCM, .endianness = AudioFormat::Endianness::LITTLE, diff --git a/Storage/SQLiteStorage/src/SQLiteMiscStorage.cpp b/Storage/SQLiteStorage/src/SQLiteMiscStorage.cpp index ebdb030db4..6f2af9dbd3 100644 --- a/Storage/SQLiteStorage/src/SQLiteMiscStorage.cpp +++ b/Storage/SQLiteStorage/src/SQLiteMiscStorage.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ #include #include +#include #include #include @@ -28,6 +29,7 @@ namespace sqliteStorage { using namespace avsCommon::utils::configuration; using namespace avsCommon::utils::logger; +using namespace avsCommon::utils::string; /// String to identify log entries originating from this file. static const std::string TAG("SQLiteMiscStorage"); @@ -121,6 +123,17 @@ static std::string getValueTypeString(SQLiteMiscStorage::ValueType valueType); */ static std::string getDBDataType(const std::string& keyValueType); +/** + * Escapes the value of a database entry so that it can be inserted into an SQL query. + * + * @param value The value of a database entry to escape. + * @return The escaped database value. + */ +std::string escapeValue(const std::string& value) { + // Single quotes will be replaced by two single quotes to escape. + return replaceAllSubstring(value, "'", "''"); +} + std::unique_ptr SQLiteMiscStorage::create(const ConfigurationNode& configurationRoot) { auto miscDatabaseConfigurationRoot = configurationRoot[MISC_DATABASE_CONFIGURATION_ROOT_KEY]; if (!miscDatabaseConfigurationRoot) { @@ -663,7 +676,7 @@ bool SQLiteMiscStorage::add( std::string dbTableName = getDBTableName(componentName, tableName); const std::string sqlString = "INSERT INTO " + dbTableName + " (" + KEY_COLUMN_NAME + ", " + VALUE_COLUMN_NAME + - ") VALUES ('" + key + "', '" + value + "');"; + ") VALUES ('" + key + "', '" + escapeValue(value) + "');"; if (!m_db.performQuery(sqlString)) { ACSDK_ERROR(LX(errorEvent).d("Could not add entry (" + key + ", " + value + ") to table", tableName)); @@ -705,8 +718,8 @@ bool SQLiteMiscStorage::update( std::string dbTableName = getDBTableName(componentName, tableName); - const std::string sqlString = "UPDATE " + dbTableName + " SET " + VALUE_COLUMN_NAME + "='" + value + "' WHERE " + - KEY_COLUMN_NAME + "='" + key + "';"; + const std::string sqlString = "UPDATE " + dbTableName + " SET " + VALUE_COLUMN_NAME + "='" + escapeValue(value) + + "' WHERE " + KEY_COLUMN_NAME + "='" + key + "';"; if (!m_db.performQuery(sqlString)) { ACSDK_ERROR(LX(errorEvent).d("Could not update entry for " + key + " in table", tableName)); @@ -749,10 +762,10 @@ bool SQLiteMiscStorage::put( if (!tableEntryExistsValue) { sqlString = "INSERT INTO " + dbTableName + " (" + KEY_COLUMN_NAME + ", " + VALUE_COLUMN_NAME + ") VALUES ('" + - key + "', '" + value + "');"; + key + "', '" + escapeValue(value) + "');"; errorValue = "Could not add entry (" + key + ", " + value + ") to table"; } else { - sqlString = "UPDATE " + dbTableName + " SET " + VALUE_COLUMN_NAME + "='" + value + "' WHERE " + + sqlString = "UPDATE " + dbTableName + " SET " + VALUE_COLUMN_NAME + "='" + escapeValue(value) + "' WHERE " + KEY_COLUMN_NAME + "='" + key + "';"; errorValue = "Could not update entry for " + key + " in table"; } diff --git a/Storage/SQLiteStorage/src/SQLiteStatement.cpp b/Storage/SQLiteStorage/src/SQLiteStatement.cpp index 9642c42965..615303f4f8 100644 --- a/Storage/SQLiteStorage/src/SQLiteStatement.cpp +++ b/Storage/SQLiteStorage/src/SQLiteStatement.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -180,8 +180,8 @@ std::string SQLiteStatement::getColumnText(int index) const { // The reinterpret_cast is needed due to SQLite storing text data as utf8 (ie. const unsigned char*). // We are ok in our implementation to do the cast, since we know we're storing as regular ascii. - const char* rowValue = reinterpret_cast(sqlite3_column_text(m_handle, index)); - return std::string(rowValue); + const unsigned char* rowValue = sqlite3_column_text(m_handle, index); + return rowValue ? std::string(reinterpret_cast(rowValue)) : ""; } int SQLiteStatement::getColumnInt(int index) const { diff --git a/Storage/SQLiteStorage/test/SQLiteDatabaseTest.cpp b/Storage/SQLiteStorage/test/SQLiteDatabaseTest.cpp index 13e06a4cdf..a72017b4c4 100644 --- a/Storage/SQLiteStorage/test/SQLiteDatabaseTest.cpp +++ b/Storage/SQLiteStorage/test/SQLiteDatabaseTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -49,7 +49,7 @@ static std::string generateDbFilePath() { } /// Test to close DB then open it. -TEST(SQLiteDatabaseTest, CloseThenOpen) { +TEST(SQLiteDatabaseTest, test_closeThenOpen) { auto dbFilePath = generateDbFilePath(); SQLiteDatabase db(dbFilePath); ASSERT_TRUE(db.initialize()); @@ -58,7 +58,7 @@ TEST(SQLiteDatabaseTest, CloseThenOpen) { } /// Test to initialize already existing DB. -TEST(SQLiteDatabaseTest, InitializeAlreadyExisting) { +TEST(SQLiteDatabaseTest, test_initializeAlreadyExisting) { auto dbFilePath = generateDbFilePath(); SQLiteDatabase db1(dbFilePath); ASSERT_TRUE(db1.initialize()); @@ -71,19 +71,19 @@ TEST(SQLiteDatabaseTest, InitializeAlreadyExisting) { } /// Test to initialize a bad path. -TEST(SQLiteDatabaseTest, InitializeBadPath) { +TEST(SQLiteDatabaseTest, test_initializeBadPath) { SQLiteDatabase db(BAD_PATH); ASSERT_FALSE(db.initialize()); } /// Test to initialize a directory. -TEST(SQLiteDatabaseTest, InitializeOnDirectory) { +TEST(SQLiteDatabaseTest, test_initializeOnDirectory) { SQLiteDatabase db(g_workingDirectory); ASSERT_FALSE(db.initialize()); } /// Test to initialize DB twice. -TEST(SQLiteDatabaseTest, InitializeTwice) { +TEST(SQLiteDatabaseTest, test_initializeTwice) { SQLiteDatabase db(generateDbFilePath()); ASSERT_TRUE(db.initialize()); @@ -92,7 +92,7 @@ TEST(SQLiteDatabaseTest, InitializeTwice) { } /// Test to open already existing DB. -TEST(SQLiteDatabaseTest, OpenAlreadyExisting) { +TEST(SQLiteDatabaseTest, test_openAlreadyExisting) { auto dbFilePath = generateDbFilePath(); SQLiteDatabase db1(dbFilePath); ASSERT_TRUE(db1.initialize()); @@ -105,19 +105,19 @@ TEST(SQLiteDatabaseTest, OpenAlreadyExisting) { } /// Test to open a bad path. -TEST(SQLiteDatabaseTest, OpenBadPath) { +TEST(SQLiteDatabaseTest, test_openBadPath) { SQLiteDatabase db(BAD_PATH); ASSERT_FALSE(db.open()); } /// Test to open directory. -TEST(SQLiteDatabaseTest, OpenDirectory) { +TEST(SQLiteDatabaseTest, test_openDirectory) { SQLiteDatabase db(g_workingDirectory); ASSERT_FALSE(db.open()); } /// Test to open DB twice. -TEST(SQLiteDatabaseTest, OpenTwice) { +TEST(SQLiteDatabaseTest, test_openTwice) { auto dbFilePath = generateDbFilePath(); SQLiteDatabase db1(dbFilePath); ASSERT_TRUE(db1.initialize()); @@ -131,7 +131,7 @@ TEST(SQLiteDatabaseTest, OpenTwice) { } /// Test transactions commit -TEST(SQLiteDatabaseTest, TransactionsCommit) { +TEST(SQLiteDatabaseTest, test_transactionsCommit) { auto dbFilePath = generateDbFilePath(); SQLiteDatabase db(dbFilePath); ASSERT_TRUE(db.initialize()); @@ -150,7 +150,7 @@ TEST(SQLiteDatabaseTest, TransactionsCommit) { } // Test transactions rollback -TEST(SQLiteDatabaseTest, TransactionsRollback) { +TEST(SQLiteDatabaseTest, test_transactionsRollback) { auto dbFilePath = generateDbFilePath(); SQLiteDatabase db(dbFilePath); ASSERT_TRUE(db.initialize()); @@ -169,7 +169,7 @@ TEST(SQLiteDatabaseTest, TransactionsRollback) { } /// Test nested transactions -TEST(SQLiteDatabaseTest, NestedTransactions) { +TEST(SQLiteDatabaseTest, test_nestedTransactions) { auto dbFilePath = generateDbFilePath(); SQLiteDatabase db(dbFilePath); ASSERT_TRUE(db.initialize()); @@ -183,7 +183,7 @@ TEST(SQLiteDatabaseTest, NestedTransactions) { } /// Test transactions double commit -TEST(SQLiteDatabaseTest, DoubleCommit) { +TEST(SQLiteDatabaseTest, test_doubleCommit) { auto dbFilePath = generateDbFilePath(); SQLiteDatabase db(dbFilePath); ASSERT_TRUE(db.initialize()); @@ -197,7 +197,7 @@ TEST(SQLiteDatabaseTest, DoubleCommit) { } /// Test automatic rollback -TEST(SQLiteDatabaseTest, AutoRollback) { +TEST(SQLiteDatabaseTest, test_autoRollback) { auto dbFilePath = generateDbFilePath(); SQLiteDatabase db(dbFilePath); ASSERT_TRUE(db.initialize()); diff --git a/Storage/SQLiteStorage/test/SQLiteMiscStorageTest.cpp b/Storage/SQLiteStorage/test/SQLiteMiscStorageTest.cpp index ed4ba91d9a..ac7dc85190 100644 --- a/Storage/SQLiteStorage/test/SQLiteMiscStorageTest.cpp +++ b/Storage/SQLiteStorage/test/SQLiteMiscStorageTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. @@ -139,7 +139,7 @@ void SQLiteMiscStorageTest::SetUp() { } /// Tests with creating a string key - string value table -TEST_F(SQLiteMiscStorageTest, createStringKeyValueTable) { +TEST_F(SQLiteMiscStorageTest, test_createStringKeyValueTable) { const std::string tableName = "SQLiteMiscStorageCreateTableTest"; deleteTestTable(tableName); @@ -155,7 +155,7 @@ TEST_F(SQLiteMiscStorageTest, createStringKeyValueTable) { } /// Tests with table entry add, remove, update, put -TEST_F(SQLiteMiscStorageTest, tableEntryTests) { +TEST_F(SQLiteMiscStorageTest, test_tableEntryTests) { const std::string tableName = "SQLiteMiscStorageTableEntryTest"; const std::string tableEntryKey = "tableEntryTestsKey"; const std::string tableEntryAddedValue = "tableEntryAddedValue"; @@ -211,7 +211,7 @@ TEST_F(SQLiteMiscStorageTest, tableEntryTests) { } /// Tests with loading and clearing table entries -TEST_F(SQLiteMiscStorageTest, loadAndClear) { +TEST_F(SQLiteMiscStorageTest, test_loadAndClear) { const std::string tableName = "SQLiteMiscStorageLoadClearTest"; size_t numOfEntries = 3; std::string keyPrefix = "key"; @@ -250,7 +250,7 @@ TEST_F(SQLiteMiscStorageTest, loadAndClear) { } /// Tests with creating and deleting tables -TEST_F(SQLiteMiscStorageTest, createDeleteTable) { +TEST_F(SQLiteMiscStorageTest, test_createDeleteTable) { const std::string tableName = "SQLiteMiscStorageCreateDeleteTest"; deleteTestTable(tableName); @@ -276,6 +276,32 @@ TEST_F(SQLiteMiscStorageTest, createDeleteTable) { ASSERT_FALSE(tableExists); } +/// Test adding a string value with a single quote. +TEST_F(SQLiteMiscStorageTest, test_escapeSingleQuoteCharacters) { + const std::string tableName = "SQLiteMiscStorageTableEntryTest"; + const std::string tableEntryKey = "tableEntryTestsKey"; + const std::string valueWithSingleQuote = "This table's entry"; + + std::string tableEntryValue; + deleteTestTable(tableName); + + createTestTable(tableName, SQLiteMiscStorage::KeyType::STRING_KEY, SQLiteMiscStorage::ValueType::STRING_VALUE); + + /// Entry doesn't exist at first + bool tableEntryExists; + ASSERT_TRUE(m_miscStorage->tableEntryExists(COMPONENT_NAME, tableName, tableEntryKey, &tableEntryExists)); + ASSERT_FALSE(tableEntryExists); + + /// Ensure that add entry works + ASSERT_TRUE(m_miscStorage->add(COMPONENT_NAME, tableName, tableEntryKey, valueWithSingleQuote)); + ASSERT_TRUE(m_miscStorage->tableEntryExists(COMPONENT_NAME, tableName, tableEntryKey, &tableEntryExists)); + ASSERT_TRUE(tableEntryExists); + ASSERT_TRUE(m_miscStorage->get(COMPONENT_NAME, tableName, tableEntryKey, &tableEntryValue)); + ASSERT_EQ(tableEntryValue, valueWithSingleQuote); + + deleteTestTable(tableName); +} + } // namespace test } // namespace sqliteStorage } // namespace storage diff --git a/build/cmake/Comms.cmake b/build/cmake/Comms.cmake index 2597bddec6..34d11e59d5 100644 --- a/build/cmake/Comms.cmake +++ b/build/cmake/Comms.cmake @@ -9,6 +9,7 @@ # option(COMMS "Enable Alexa Comms (Calling)." OFF) +option(COMMS_AUDIO_PROXY "Enable Alexa Comms (Calling) using audio proxy." OFF) if(COMMS) if(NOT COMMS_LIB_PATH) @@ -19,4 +20,9 @@ if(COMMS) endif() message("Creating ${PROJECT_NAME} with Alexa Comms (Calling)") add_definitions(-DENABLE_COMMS) + + if (COMMS_AUDIO_PROXY) + message("Creating ${PROJECT_NAME} with Alexa Comms (Calling) using audio proxy") + add_definitions(-DENABLE_COMMS_AUDIO_PROXY) + endif() endif() diff --git a/tools/Install/android.sh b/tools/Install/android.sh index 95d06ccd17..2ed3196c85 100644 --- a/tools/Install/android.sh +++ b/tools/Install/android.sh @@ -113,6 +113,18 @@ generate_start_script() { EOF } +generate_test_script() { + cat << EOF > "${TEST_SCRIPT}" + echo + echo "==============> BUILDING Tests ==============" + echo + + cd ${BUILD_PATH} + make all -j2 + make test +EOF +} + printInfo() { echo "================================================================================" local ARGUMENT diff --git a/tools/Install/mingw.sh b/tools/Install/mingw.sh index 8a2650e707..6160a234f5 100644 --- a/tools/Install/mingw.sh +++ b/tools/Install/mingw.sh @@ -70,3 +70,15 @@ generate_start_script() { pause EOF } + +generate_test_script() { + cat << EOF > "${TEST_SCRIPT}" + echo + echo "==============> BUILDING Tests ==============" + echo + + cd ${BUILD_PATH} + make all -j2 + make test +EOF +} diff --git a/tools/Install/pi.sh b/tools/Install/pi.sh index d5fb53e586..95b362bc7e 100644 --- a/tools/Install/pi.sh +++ b/tools/Install/pi.sh @@ -79,3 +79,15 @@ generate_start_script() { ./SampleApp "$OUTPUT_CONFIG_FILE" "$THIRD_PARTY_PATH/alexa-rpi/models" DEBUG9 EOF } + +generate_test_script() { + cat << EOF > "${TEST_SCRIPT}" + echo + echo "==============> BUILDING Tests ==============" + echo + mkdir -p "$UNIT_TEST_MODEL_PATH" + cp "$UNIT_TEST_MODEL" "$UNIT_TEST_MODEL_PATH" + cd $BUILD_PATH + make all test -j2 +EOF +} diff --git a/tools/Install/setup.sh b/tools/Install/setup.sh index 98e3137c59..686b5c730d 100644 --- a/tools/Install/setup.sh +++ b/tools/Install/setup.sh @@ -282,16 +282,7 @@ cat $OUTPUT_CONFIG_FILE generate_start_script -cat << EOF > "$TEST_SCRIPT" -echo -echo "==============> BUILDING Tests ==============" -echo -mkdir -p "$UNIT_TEST_MODEL_PATH" -cp "$UNIT_TEST_MODEL" "$UNIT_TEST_MODEL_PATH" -cd $BUILD_PATH -make all test -j2 -chmod +x "$START_SCRIPT" -EOF +generate_test_script echo " **** Completed Configuration/Build ***" diff --git a/tools/Testing.cmake b/tools/Testing.cmake index 8df9b63632..31007834ae 100644 --- a/tools/Testing.cmake +++ b/tools/Testing.cmake @@ -36,7 +36,18 @@ endmacro() macro(configure_test_command testname inputs testsourcefile) if(NOT ANDROID) - GTEST_ADD_TESTS(${testname} "${inputs}" ${testsourcefile}) + if(${CMAKE_VERSION} VERSION_LESS "3.9.6") + GTEST_ADD_TESTS(${testname} "${inputs}" ${testsourcefile}) + else() + GTEST_ADD_TESTS(TARGET ${testname} SOURCES ${testsourcefile} EXTRA_ARGS "${inputs}" TEST_LIST testlist) + foreach(test IN LISTS testlist) + if(${test} MATCHES "testSlow_") + set_tests_properties(${test} PROPERTIES LABELS "slowtest") + elseif(${test} MATCHES "testTimer_") + set_tests_properties(${test} PROPERTIES LABELS "timertest") + endif() + endforeach() + endif() elseif(ANDROID_TEST_AVAILABLE) # Use generator expression to get the test path when available. set(target_path $) @@ -48,3 +59,9 @@ macro(configure_test_command testname inputs testsourcefile) -i "${inputs}") endif() endmacro() + +# Add Custom Targets +add_custom_target(fast-test COMMAND ${CMAKE_CTEST_COMMAND} -LE "slowtest\\\|timertest" --output-on-failure) +add_custom_target(find-slow-test COMMAND ${CMAKE_CTEST_COMMAND} -LE "slowtest\\\|timertest" --output-on-failure --timeout 1) +add_custom_target(slow-test COMMAND ${CMAKE_CTEST_COMMAND} -L "slowtest" --output-on-failure) +add_custom_target(timer-test COMMAND ${CMAKE_CTEST_COMMAND} -L "timertest" --output-on-failure)