From 915d97b4a063c1706a9d24c133c0979c2af5f23d Mon Sep 17 00:00:00 2001 From: KIM JungYong Date: Thu, 12 Jan 2017 15:22:32 +0900 Subject: [PATCH] [IOT-1592] Fix unit test of notification service. Dependency of hippomocks is removed in notification service Bug: https://jira.iotivity.org/browse/IOT-1562 Change-Id: I4d8b44b1c06c1abcc73a15fa87db94056a642b9d Signed-off-by: KIM JungYong Signed-off-by: Philippe Coval Reviewed-on: https://gerrit.iotivity.org/gerrit/16377 Tested-by: jenkins-iotivity Reviewed-by: Dan Mihai Reviewed-by: Dave Thaler Reviewed-by: Uze Choi --- .../notification/src/consumer/NSConsumerCommon.c | 33 +- .../src/consumer/NSConsumerCommunication.c | 15 +- .../src/consumer/NSConsumerInterface.c | 6 +- .../src/consumer/NSConsumerScheduler.c | 42 +- .../src/provider/NSProviderInterface.c | 8 + .../src/provider/NSProviderNotification.c | 2 + .../notification/unittest/NSConsumerSimulator.h | 13 +- service/notification/unittest/NSConsumerTest.cpp | 436 +++++++++------------ .../notification/unittest/NSProviderSimulator.h | 9 +- service/notification/unittest/NSProviderTest.cpp | 236 +++++------ service/notification/unittest/NSUnittestUtil.h | 85 ++++ service/notification/unittest/SConscript | 43 +- service/notification/unittest/oic_svr_db_ns.dat | Bin 0 -> 4991 bytes service/notification/unittest/oic_svr_db_ns.json | 191 +++++++++ 14 files changed, 716 insertions(+), 403 deletions(-) create mode 100644 service/notification/unittest/NSUnittestUtil.h create mode 100644 service/notification/unittest/oic_svr_db_ns.dat create mode 100644 service/notification/unittest/oic_svr_db_ns.json diff --git a/service/notification/src/consumer/NSConsumerCommon.c b/service/notification/src/consumer/NSConsumerCommon.c index 4a2c69a..d169525 100644 --- a/service/notification/src/consumer/NSConsumerCommon.c +++ b/service/notification/src/consumer/NSConsumerCommon.c @@ -106,7 +106,6 @@ void NSSetIsStartedConsumer(bool setValue) { pthread_mutex_destroy(*NSGetStackMutex()); NSOICFree(*NSGetStackMutex()); - *NSGetStackMutex() = NULL; NSOICFree(*NSGetConsumerId()); *NSGetConsumerId() = NULL; @@ -139,7 +138,14 @@ typedef struct void * NSProviderChangedFunc(void * obj) { NSProviderChangedData * data = (NSProviderChangedData *) obj; - (*(NSGetProviderChangedCb()))(data->provider, data->state); + NSProviderStateCallback cb = *(NSGetProviderChangedCb()); + NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(cb, NULL, + { + NSRemoveProvider(data->provider); + NSOICFree(data); + }); + cb(data->provider, data->state); + NSOICFree(data); return NULL; } @@ -183,7 +189,14 @@ void NSSetNotificationSyncCb(NSSyncInfoReceivedCallback cb) void * NSNotificationSyncFunc(void * obj) { - (* NSGetBoneNotificationSyncCb())((NSSyncInfo *) obj); + NSSyncInfoReceivedCallback cb = * NSGetBoneNotificationSyncCb(); + NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(cb, NULL, + { + NSOICFree(obj); + }); + + cb((NSSyncInfo *) obj); + return NULL; } @@ -221,7 +234,13 @@ NSMessageReceivedCallback NSGetMessagePostedCb() void * NSMessagePostFunc(void * obj) { - NSGetMessagePostedCb()((NSMessage *) obj); + NSMessageReceivedCallback cb = NSGetMessagePostedCb(); + NS_VERIFY_NOT_NULL_WITH_POST_CLEANING(cb, NULL, + { + NSRemoveMessage((NSMessage *) obj); + }); + cb((NSMessage *) obj); + return NULL; } @@ -791,6 +810,12 @@ OCStackResult NSInvokeRequest(OCDoHandle * handle, void * callbackFunc, void * callbackData, OCClientContextDeleter cd, OCConnectivityType type) { + if (!NSIsStartedConsumer()) + { + NS_LOG(ERROR, "Consumer service maybe terminated : Ignore request"); + return OC_STACK_ERROR; + } + int mutexRet = pthread_mutex_lock(*(NSGetStackMutex())); NS_VERIFY_NOT_NULL(mutexRet != 0 ? NULL : (void *)1, OC_STACK_ERROR); diff --git a/service/notification/src/consumer/NSConsumerCommunication.c b/service/notification/src/consumer/NSConsumerCommunication.c index 11e4182..5c1c317 100644 --- a/service/notification/src/consumer/NSConsumerCommunication.c +++ b/service/notification/src/consumer/NSConsumerCommunication.c @@ -27,7 +27,11 @@ #include "oic_string.h" #include "ocpayload.h" +#ifdef LOCAL_RUNNING #define NS_SYNC_URI "/notification/sync" +#else +#define NS_SYNC_URI "/notificationTest/sync" +#endif NSSyncInfo * NSCreateSyncInfo_consumer(uint64_t msgId, const char * providerId, NSSyncType state); @@ -316,11 +320,15 @@ void NSConsumerCommunicationTaskProcessing(NSTask * task) NS_LOG_V(DEBUG, "Receive Event : %d", (int)task->taskType); if (task->taskType == TASK_CONSUMER_REQ_SUBSCRIBE) { - NS_VERIFY_NOT_NULL_V(task->taskData); + NS_VERIFY_NOT_NULL_WITH_POST_CLEANING_V(task->taskData, NSOICFree(task)); NS_LOG(DEBUG, "Request Subscribe"); NSResult ret = NSConsumerSubscribeProvider((NSProvider *)task->taskData); NSRemoveProvider_internal((void *) task->taskData); - NS_VERIFY_NOT_NULL_V(ret == NS_OK ? (void *)1 : NULL); + NS_VERIFY_NOT_NULL_WITH_POST_CLEANING_V(ret == NS_OK ? (void *)1 : NULL, + { + NSOICFree(task->taskData); + NSOICFree(task); + }); } else if (task->taskType == TASK_SEND_SYNCINFO) { @@ -412,6 +420,7 @@ void NSConsumerCommunicationTaskProcessing(NSTask * task) NS_VERIFY_NOT_NULL_WITH_POST_CLEANING_V(query, { NSRemoveProvider_internal((void *) provider); + NSOICFree(topicUri); NSOICFree(task); }); NS_LOG_V(DEBUG, "topic query : %s", query); @@ -422,6 +431,8 @@ void NSConsumerCommunicationTaskProcessing(NSTask * task) NS_VERIFY_NOT_NULL_WITH_POST_CLEANING_V(NSOCResultToSuccess(ret) == true ? (void *) 1 : NULL, { NSRemoveProvider_internal((void *) provider); + NSOICFree(query); + NSOICFree(topicUri); NSOICFree(task); }); diff --git a/service/notification/src/consumer/NSConsumerInterface.c b/service/notification/src/consumer/NSConsumerInterface.c index cce720b..a735ec9 100644 --- a/service/notification/src/consumer/NSConsumerInterface.c +++ b/service/notification/src/consumer/NSConsumerInterface.c @@ -58,13 +58,13 @@ NSResult NSStopConsumer() bool isStartedConsumer = NSIsStartedConsumer(); NS_VERIFY_NOT_NULL(isStartedConsumer == true ? (void *) 1 : NULL, NS_ERROR); - NSSetMessagePostedCb(NULL); - NSSetNotificationSyncCb(NULL); - NSSetProviderChangedCb(NULL); NSSetIsStartedConsumer(false); NSConsumerMessageHandlerExit(); + NSSetMessagePostedCb(NULL); + NSSetNotificationSyncCb(NULL); + NSSetProviderChangedCb(NULL); return NS_OK; } diff --git a/service/notification/src/consumer/NSConsumerScheduler.c b/service/notification/src/consumer/NSConsumerScheduler.c index 200661f..89c6a76 100644 --- a/service/notification/src/consumer/NSConsumerScheduler.c +++ b/service/notification/src/consumer/NSConsumerScheduler.c @@ -122,20 +122,40 @@ void NSConsumerMessageHandlerExit() NSConsumerListenerTermiate(); NSCancelAllSubscription(); - NSConsumerThread * thread = *(NSGetMsgHandleThreadHandle()); - NSThreadStop(thread); - NSSetMsgHandleThreadHandle(NULL); NSConsumerQueue * queue = *(NSGetMsgHandleQueue()); + NSConsumerThread * thread = *(NSGetMsgHandleThreadHandle()); + + NSThreadLock(thread); + NS_LOG(DEBUG, "Execute remaining task"); + while (!NSIsQueueEmpty(queue)) + { + NSConsumerQueueObject * obj = NSPopQueue(queue); + NS_LOG_V(DEBUG, "Execute remaining task type : %d", ((NSTask *)(obj->data))->taskType); + + if (obj) + { + NSConsumerTaskProcessing((NSTask *)(obj->data)); + NSOICFree(obj); + } + } + NSThreadUnlock(thread); + NSDestroyQueue(queue); + NSOICFree(queue); NSSetMsgHandleQueue(NULL); + NSThreadLock(thread); + NSThreadStop(thread); + NSSetMsgHandleThreadHandle(NULL); + NSThreadUnlock(thread); + NSOICFree(thread); + NSDestroyInternalCachedList(); } void * NSConsumerMsgHandleThreadFunc(void * threadHandle) { - NSConsumerQueue * queue = *(NSGetMsgHandleQueue());; NSConsumerQueueObject * obj = NULL; NS_LOG(DEBUG, "create thread for consumer message handle"); @@ -144,10 +164,17 @@ void * NSConsumerMsgHandleThreadFunc(void * threadHandle) while (true) { + queueHandleThread = *(NSGetMsgHandleThreadHandle()); + if (NULL == queueHandleThread) + { + break; + } + + NSConsumerQueue * queue = *(NSGetMsgHandleQueue());; if (!queue) { - queue = *(NSGetMsgHandleQueue()); usleep(2000); + queue = *(NSGetMsgHandleQueue()); continue; } @@ -323,7 +350,10 @@ void NSConsumerTaskProcessing(NSTask * task) { NSTask * getTopicTask = (NSTask *)OICMalloc(sizeof(NSTask)); NS_VERIFY_NOT_NULL_WITH_POST_CLEANING_V(getTopicTask, - NSRemoveProvider_internal((void *) task->taskData)); + { + NSRemoveProvider_internal((void *) task->taskData); + NSOICFree(task); + }); getTopicTask->nextTask = NULL; getTopicTask->taskData = (void *) NSCopyProvider_internal((NSProvider_internal *) task->taskData); diff --git a/service/notification/src/provider/NSProviderInterface.c b/service/notification/src/provider/NSProviderInterface.c index 0c6d2b1..74015c0 100644 --- a/service/notification/src/provider/NSProviderInterface.c +++ b/service/notification/src/provider/NSProviderInterface.c @@ -450,6 +450,10 @@ NSResult NSProviderSetConsumerTopic(const char * consumerId, const char * topicN NS_LOG(DEBUG, "provider is not started or " "consumer id should be set for topic subscription or " "Configuration must set to true."); + if (topicSubData) + { + OICFreeAndSetToNull(&topicSubData); + } pthread_mutex_unlock(&nsInitMutex); return NS_FAIL; } @@ -485,6 +489,10 @@ NSResult NSProviderUnsetConsumerTopic(const char * consumerId, const char * topi NS_LOG(DEBUG, "provider is not started or " "consumer id should be set for topic subscription or " "Configuration must set to true."); + if (topicSubData) + { + OICFreeAndSetToNull(&topicSubData); + } pthread_mutex_unlock(&nsInitMutex); return NS_FAIL; } diff --git a/service/notification/src/provider/NSProviderNotification.c b/service/notification/src/provider/NSProviderNotification.c index 02a42d2..7f33a8b 100644 --- a/service/notification/src/provider/NSProviderNotification.c +++ b/service/notification/src/provider/NSProviderNotification.c @@ -135,6 +135,7 @@ NSResult NSSendNotification(NSMessage *msg) if (consumerSubList->head == NULL) { NS_LOG(ERROR, "SubList->head is NULL, empty SubList"); + OCRepPayloadDestroy(payload); return NS_ERROR; } @@ -201,6 +202,7 @@ NSResult NSSendNotification(NSMessage *msg) if (!obCount) { NS_LOG(ERROR, "observer count is zero"); + OCRepPayloadDestroy(payload); return NS_ERROR; } diff --git a/service/notification/unittest/NSConsumerSimulator.h b/service/notification/unittest/NSConsumerSimulator.h index 2bca595..328c6f6 100644 --- a/service/notification/unittest/NSConsumerSimulator.h +++ b/service/notification/unittest/NSConsumerSimulator.h @@ -42,7 +42,9 @@ private: public: NSConsumerSimulator() : m_messageFunc(), m_syncFunc(), - m_syncResource(), isTopicPost(false) { }; + m_syncResource(), isTopicPost(false) + { + }; ~NSConsumerSimulator() = default; NSConsumerSimulator(const NSConsumerSimulator &) = delete; @@ -76,9 +78,11 @@ public: bool cancelObserves() { - if(!msgResourceCancelObserve(OC::QualityOfService::HighQos) && - !syncResourceCancelObserve(OC::QualityOfService::HighQos)) + if(OC_STACK_OK == msgResourceCancelObserve(OC::QualityOfService::HighQos) && + OC_STACK_OK == syncResourceCancelObserve(OC::QualityOfService::HighQos)) + { return true; + } return false; } @@ -99,8 +103,7 @@ private: { if(resource->uri() == "/notification") { - resource->get(std::string("x.org.iotivity.notification"), std::string("oic.if.baseline"), - OC::QueryParamsMap(), std::bind(&NSConsumerSimulator::onGet, this, + resource->get(OC::QueryParamsMap(), std::bind(&NSConsumerSimulator::onGet, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, resource), OC::QualityOfService::LowQos); } diff --git a/service/notification/unittest/NSConsumerTest.cpp b/service/notification/unittest/NSConsumerTest.cpp index 4a57bde..ab21933 100644 --- a/service/notification/unittest/NSConsumerTest.cpp +++ b/service/notification/unittest/NSConsumerTest.cpp @@ -19,31 +19,39 @@ //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #include -#include #include #include #include #include #include +#include +#include "octypes.h" #include "ocstack.h" #include "NSCommon.h" #include "NSConsumerInterface.h" #include "NSProviderSimulator.h" +#include "NSUnittestUtil.h" namespace { NSProviderSimulator g_providerSimul; - NSProvider * g_provider; + NSProvider * g_provider = NULL; std::atomic_bool g_isStartedStack(false); - std::chrono::milliseconds g_waitForResponse(500); + std::chrono::milliseconds g_waitForResponse(1000); - std::condition_variable responseCon; - std::mutex mutexForCondition; + std::condition_variable messageReceive; + std::mutex messageReceiveLock; + + std::condition_variable syncReceive; + std::mutex syncReceiveLock; + + std::condition_variable providerChanged; + std::mutex providerChangedLock; enum class NSSelector { @@ -54,13 +62,33 @@ namespace NSConsumerConfig cfg; NSProviderSimulator::NS_TopicStateList g_topicStateList; + + NSProviderState revState = NS_STOPPED; + NSProviderState expectedState = NS_STOPPED; + uint64_t revId = 0; + NSSyncType type = NS_SYNC_DELETED; + + const std::string testProviderID = "123456789012345678901234567890123456"; + + static FILE* client_open(const char * path, const char * mode) + { + if (0 == strcmp(path, OC_SECURITY_DB_DAT_FILE_NAME)) + { + std::string file_name = "./oic_svr_db_ns.dat"; +#ifndef LOCAL_RUNNING + file_name = "./service/notification/unittest/oic_svr_db_ns.dat"; +#endif + return fopen(file_name.c_str(), mode); + } + else + { + return fopen(path, mode); + } + } } class TestWithMock: public testing::Test { -public: - MockRepository mocks; - protected: virtual ~TestWithMock() noexcept(noexcept(std::declval().~Test())) { @@ -69,15 +97,7 @@ protected: virtual void TearDown() { - try - { - mocks.VerifyAll(); - } - catch (...) - { - mocks.reset(); - throw; - } + } }; @@ -87,24 +107,60 @@ public: NotificationConsumerTest() = default; ~NotificationConsumerTest() = default; - static void NSNotificationReceivedCallbackEmpty(NSMessage *) + static void NSNotificationReceivedCallback(NSMessage * message) { - std::cout << __func__ << std::endl; - } + if (0 != testProviderID.compare(message->providerId)) + { + removeMessage(message); + return; + } - static void NSSyncCallbackEmpty(NSSyncInfo *) - { std::cout << __func__ << std::endl; + std::cout << "Income Notification : " << message->messageId << std::endl; + revId = message->messageId; + + removeMessage(message); + messageReceive.notify_all(); } - static void NSFoundResourceEmpty(std::shared_ptr< OC::OCResource >) + static void NSSyncCallback(NSSyncInfo * sync) { + if (0 != testProviderID.compare(sync->providerId)) + { + free(sync); + return; + } + std::cout << __func__ << std::endl; + std::cout << "Income SyncInfo : " << sync->messageId + << ", State : " << sync->state << std::endl; + type = sync->state; + + free(sync); + syncReceive.notify_all(); } - static void NSProviderChangedCallback(NSProvider *, NSProviderState) + static void NSProviderChangedCallback(NSProvider * provider, NSProviderState state) { - std::cout << __func__ << std::endl; + if (0 != testProviderID.compare(provider->providerId)) + { + free(provider); + return; + } + + std::cout << __func__ << " " << state << std::endl; + if (g_provider) + { + free(g_provider); + g_provider = NULL; + } + g_provider = provider; + + if (expectedState == state) + { + revState = state; + providerChanged.notify_all(); + } } protected: @@ -115,13 +171,15 @@ protected: if (g_isStartedStack == false) { + static OCPersistentStorage gps {client_open, fread, fwrite, fclose, unlink }; OC::PlatformConfig occfg { OC::ServiceType::InProc, OC::ModeType::Both, "0.0.0.0", 0, - OC::QualityOfService::LowQos + OC::QualityOfService::LowQos, + &gps }; OC::OCPlatform::Configure(occfg); @@ -137,8 +195,8 @@ protected: g_isStartedStack = true; cfg.changedCb = NSProviderChangedCallback; - cfg.messageCb = NSNotificationReceivedCallbackEmpty; - cfg.syncInfoCb = NSSyncCallbackEmpty; + cfg.messageCb = NSNotificationReceivedCallback; + cfg.syncInfoCb = NSSyncCallback; } } @@ -153,45 +211,37 @@ protected: TEST_F(NotificationConsumerTest, StartConsumerNegativeNonSetChangedCB) { cfg.changedCb = NULL; - cfg.messageCb = NSNotificationReceivedCallbackEmpty; - cfg.syncInfoCb = NSSyncCallbackEmpty; + cfg.messageCb = NSNotificationReceivedCallback; + cfg.syncInfoCb = NSSyncCallback; EXPECT_EQ(NS_ERROR, NSStartConsumer(cfg)); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); } TEST_F(NotificationConsumerTest, StartConsumerNegativeNonSetNotiReceiveCB) { cfg.changedCb = NSProviderChangedCallback; cfg.messageCb = NULL; - cfg.syncInfoCb = NSSyncCallbackEmpty; + cfg.syncInfoCb = NSSyncCallback; EXPECT_EQ(NS_ERROR, NSStartConsumer(cfg)); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); } TEST_F(NotificationConsumerTest, StartConsumerNegativeNonSetSyncCB) { cfg.changedCb = NSProviderChangedCallback; - cfg.messageCb = NSNotificationReceivedCallbackEmpty; + cfg.messageCb = NSNotificationReceivedCallback; cfg.syncInfoCb = NULL; EXPECT_EQ(NS_ERROR, NSStartConsumer(cfg)); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); } TEST_F(NotificationConsumerTest, StartConsumerPositive) { cfg.changedCb = NSProviderChangedCallback; - cfg.messageCb = NSNotificationReceivedCallbackEmpty; - cfg.syncInfoCb = NSSyncCallbackEmpty; + cfg.messageCb = NSNotificationReceivedCallback; + cfg.syncInfoCb = NSSyncCallback; EXPECT_EQ(NS_OK, NSStartConsumer(cfg)); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); } TEST_F(NotificationConsumerTest, StopConsumerPositive) @@ -206,53 +256,38 @@ TEST_F(NotificationConsumerTest, StopConsumerNegative) TEST_F(NotificationConsumerTest, DiscoverProviderWithNonAccepterWhenStartedConsumerFirst) { - NSProviderState revState = NS_STOPPED; - mocks.OnCallFunc(NSProviderChangedCallback).Do( - [this, & revState](NSProvider *, NSProviderState state) - { - std::cout << "Call Discovered" << std::endl; - revState = state; - responseCon.notify_all(); - }); + revState = NS_STOPPED; + + cfg.changedCb = NSProviderChangedCallback; + cfg.messageCb = NSNotificationReceivedCallback; + cfg.syncInfoCb = NSSyncCallback; + expectedState = NS_DISCOVERED; NSStartConsumer(cfg); g_providerSimul.setAccepter((int)NSSelector::NS_SELECTION_CONSUMER); g_providerSimul.createNotificationResource(); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); + std::unique_lock< std::mutex > lock{ providerChangedLock }; + providerChanged.wait_for(lock, g_waitForResponse); + + EXPECT_EQ(NS_DISCOVERED, revState); NSStopConsumer(); g_providerSimul.deleteNotificationResource(); - - EXPECT_EQ(NS_DISCOVERED, revState); } TEST_F(NotificationConsumerTest, DiscoverProviderWithNonAccepterWhenStartedConsumerAfter) { g_providerSimul.setAccepter((int)NSSelector::NS_SELECTION_CONSUMER); g_providerSimul.createNotificationResource(); - { - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); - } - NSProviderState revState = NS_STOPPED; - mocks.OnCallFunc(NSProviderChangedCallback).Do( - [this, & revState](NSProvider * provider, NSProviderState state) - { - std::cout << "Call Discovered" << std::endl; - - g_provider = provider; - revState = state; - responseCon.notify_all(); - }); + revState = NS_STOPPED; NSStartConsumer(cfg); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); + std::unique_lock< std::mutex > lock{ providerChangedLock }; + providerChanged.wait_for(lock, g_waitForResponse); EXPECT_EQ(NS_DISCOVERED, revState); @@ -262,42 +297,27 @@ TEST_F(NotificationConsumerTest, DiscoverProviderWithNonAccepterWhenStartedConsu TEST_F(NotificationConsumerTest, DiscoverProviderWithNonAccepterWhenRescan) { g_providerSimul.setAccepter((int)NSSelector::NS_SELECTION_CONSUMER); - NSProviderState revState = NS_STOPPED; - mocks.OnCallFunc(NSProviderChangedCallback).Do( - [this, &revState](NSProvider * provider, NSProviderState state) - { - std::cout << "Call Discovered" << std::endl; - revState = state; - g_provider = provider; - std::cout << g_provider->providerId << std::endl; - responseCon.notify_all(); - }); + revState = NS_STOPPED; NSRescanProvider(); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); + std::unique_lock< std::mutex > lock{ providerChangedLock }; + providerChanged.wait_for(lock, g_waitForResponse); EXPECT_EQ(NS_DISCOVERED, revState); } TEST_F(NotificationConsumerTest, ExpectSubscribeSuccess) { - NSProviderState revState = NS_DENY; + revState = NS_DENY; ASSERT_NE(nullptr, g_provider) << "error: discovery failure"; - mocks.OnCallFunc(NSProviderChangedCallback).Do( - [this, & revState](NSProvider * , NSProviderState state) - { - std::cout << "Income Changed Callback : " << state << std::endl; - revState = state; - responseCon.notify_all(); - }); - NSResult ret = NSSubscribe(g_provider->providerId); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); + + expectedState = NS_ALLOW; + std::unique_lock< std::mutex > lock{ providerChangedLock }; + providerChanged.wait_for(lock, g_waitForResponse); EXPECT_EQ(NS_ALLOW, revState); EXPECT_EQ(NS_OK, ret); @@ -308,20 +328,12 @@ TEST_F(NotificationConsumerTest, ExpectReceiveNotification) uint64_t id = 10; std::string title = "title"; std::string msg = "msg"; - uint64_t revId = 0; - - mocks.OnCallFunc(NSNotificationReceivedCallbackEmpty).Do( - [this, & revId](NSMessage * message) - { - std::cout << "Income Notification : " << message->messageId << std::endl; - revId = message->messageId; - responseCon.notify_all(); - }); + revId = 0; g_providerSimul.notifyMessage(id, title, msg); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); + std::unique_lock< std::mutex > lock{ messageReceiveLock }; + messageReceive.wait_for(lock, g_waitForResponse); EXPECT_EQ(id, revId); NSStopConsumer(); @@ -331,34 +343,24 @@ TEST_F(NotificationConsumerTest, ExpectReceiveNotification) TEST_F(NotificationConsumerTest, ExpectReceiveSubAllowWithAccepterisProvider) { g_providerSimul.setAccepter((int)NSSelector::NS_SELECTION_PROVIDER); - NSProviderState revState = NS_DENY; + revState = NS_DENY; g_providerSimul.createNotificationResource(); + + expectedState = NS_DISCOVERED; + NSStartConsumer(cfg); { - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); + std::unique_lock< std::mutex > lock{ providerChangedLock }; + providerChanged.wait_for(lock, g_waitForResponse); } - mocks.OnCallFunc(NSProviderChangedCallback).Do( - [this, & revState](NSProvider * provider, NSProviderState state) - { - std::cout << "Income Changed Callback : " << state << std::endl; - revState = state; - g_provider = provider; - responseCon.notify_all(); - }); - mocks.OnCallFunc(NSProviderChangedCallback).Do( - [this, & revState](NSProvider *, NSProviderState state) - { - std::cout << "Income Changed Callback : " << state << std::endl; - revState = state; - responseCon.notify_all(); - }); - - NSStartConsumer(cfg); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); + expectedState = NS_ALLOW; + { + std::unique_lock< std::mutex > lock{ providerChangedLock }; + providerChanged.wait_for(lock, g_waitForResponse); + } EXPECT_EQ(NS_ALLOW, revState); + expectedState = NS_STOPPED; } TEST_F(NotificationConsumerTest, ExpectReceiveNotificationWithAccepterisProvider) @@ -366,20 +368,12 @@ TEST_F(NotificationConsumerTest, ExpectReceiveNotificationWithAccepterisProvider uint64_t id = 11; std::string title = "title"; std::string msg = "msg"; - uint64_t revId = 1; - - mocks.OnCallFunc(NSNotificationReceivedCallbackEmpty).Do( - [this, & id, & revId](NSMessage * message) - { - std::cout << "Income Notification : " << message->messageId << std::endl; - revId = message->messageId; - responseCon.notify_all(); - }); + revId = 1; g_providerSimul.notifyMessage(id, title, msg); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); + std::unique_lock< std::mutex > lock{ messageReceiveLock }; + messageReceive.wait_for(lock, g_waitForResponse); EXPECT_EQ(id, revId); } @@ -389,34 +383,18 @@ TEST_F(NotificationConsumerTest, ExpectCallbackReadCheckWhenProviderNotifySync) uint64_t id = 12; std::string title = "title"; std::string msg = "msg"; - NSSyncType type = NS_SYNC_DELETED; - - mocks.OnCallFunc(NSNotificationReceivedCallbackEmpty).Do( - [this](NSMessage * message) - { - std::cout << "Income Notification : " << message->messageId << std::endl; - responseCon.notify_all(); - }); - - mocks.OnCallFunc(NSSyncCallbackEmpty).Do( - [& type, this](NSSyncInfo * sync) - { - std::cout << "Income SyncInfo : " << sync->messageId - << ", State : " << sync->state << std::endl; - type = sync->state; - responseCon.notify_all(); - }); + type = NS_SYNC_DELETED; g_providerSimul.notifyMessage(id, title, msg); { - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); + std::unique_lock< std::mutex > lock{ messageReceiveLock }; + messageReceive.wait_for(lock, g_waitForResponse); } g_providerSimul.sendRead(id); { - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); + std::unique_lock< std::mutex > lock{ syncReceiveLock }; + syncReceive.wait_for(lock, g_waitForResponse); } EXPECT_EQ(NS_SYNC_READ, type); @@ -427,34 +405,18 @@ TEST_F(NotificationConsumerTest, ExpectCallbackDismissCheckWhenProviderNotifySyn uint64_t id = 13; std::string title = "title"; std::string msg = "msg"; - NSSyncType type = NS_SYNC_READ; - - mocks.OnCallFunc(NSNotificationReceivedCallbackEmpty).Do( - [this](NSMessage * message) - { - std::cout << "Income Notification : " << message->messageId << std::endl; - responseCon.notify_all(); - }); - - mocks.OnCallFunc(NSSyncCallbackEmpty).Do( - [& type, this](NSSyncInfo * sync) - { - std::cout << "Income Notification : " << sync->messageId - << ", State : " << sync->state << std::endl; - type = sync->state; - responseCon.notify_all(); - }); + type = NS_SYNC_READ; g_providerSimul.notifyMessage(id, title, msg); { - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); + std::unique_lock< std::mutex > lock{ messageReceiveLock }; + messageReceive.wait_for(lock, g_waitForResponse); } g_providerSimul.sendDismiss(id); { - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); + std::unique_lock< std::mutex > lock{ syncReceiveLock }; + syncReceive.wait_for(lock, g_waitForResponse); } EXPECT_EQ(NS_SYNC_DELETED, type); @@ -465,30 +427,15 @@ TEST_F(NotificationConsumerTest, ExpectCallbackReadCheckWhenConsumerPostSync) uint64_t id = 14; std::string title = "title"; std::string msg = "msg"; - NSSyncType type = NS_SYNC_DELETED; - - mocks.OnCallFunc(NSNotificationReceivedCallbackEmpty).Do( - [this](NSMessage * message) - { - std::cout << "Income Notification : " << message->messageId << std::endl; - NSConsumerSendSyncInfo(message->providerId, message->messageId, NS_SYNC_READ); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); - }); - - mocks.OnCallFunc(NSSyncCallbackEmpty).Do( - [& type, this](NSSyncInfo * sync) - { - std::cout << "Income Notification : " << sync->messageId - << ", State : " << sync->state << std::endl; - type = sync->state; - responseCon.notify_all(); - }); + type = NS_SYNC_DELETED; g_providerSimul.notifyMessage(id, title, msg); + std::unique_lock< std::mutex > lock{ messageReceiveLock }; + messageReceive.wait_for(lock, g_waitForResponse); { - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); + NSConsumerSendSyncInfo(testProviderID.c_str(), revId, NS_SYNC_READ); + std::unique_lock< std::mutex > lock{ syncReceiveLock }; + syncReceive.wait_for(lock, g_waitForResponse); } EXPECT_EQ(NS_SYNC_READ, type); @@ -499,33 +446,18 @@ TEST_F(NotificationConsumerTest, ExpectCallbackDismissCheckWhenConsumerPostSync) uint64_t id = 15; std::string title = "title"; std::string msg = "msg"; - NSSyncType state = NS_SYNC_READ; - - mocks.OnCallFunc(NSNotificationReceivedCallbackEmpty).Do( - [this](NSMessage * message) - { - std::cout << "Income Notification : " << message->messageId << std::endl; - NSConsumerSendSyncInfo(message->providerId, message->messageId, NS_SYNC_DELETED); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); - }); - - mocks.OnCallFunc(NSSyncCallbackEmpty).Do( - [& state, this](NSSyncInfo * sync) - { - std::cout << "Income Notification : " << sync->messageId - << ", State : " << sync->state << std::endl; - state = sync->state; - responseCon.notify_all(); - }); + type = NS_SYNC_READ; g_providerSimul.notifyMessage(id, title, msg); + std::unique_lock< std::mutex > lock{ messageReceiveLock }; + messageReceive.wait_for(lock, g_waitForResponse); { - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); + NSConsumerSendSyncInfo(testProviderID.c_str(), revId, NS_SYNC_DELETED); + std::unique_lock< std::mutex > lock{ syncReceiveLock }; + syncReceive.wait_for(lock, g_waitForResponse); } - EXPECT_EQ(NS_SYNC_DELETED, state); + EXPECT_EQ(NS_SYNC_DELETED, type); } TEST_F(NotificationConsumerTest, ExpectGetProviderSuccessWithValidProviderId) @@ -556,18 +488,16 @@ TEST_F(NotificationConsumerTest, ExpectGetTopicListIsNULL) NSTopicLL * currentTopics = NSConsumerGetTopicList(g_provider->providerId); EXPECT_EQ(NULL, currentTopics); + + if (currentTopics) + { + removeTopics(currentTopics); + } } TEST_F(NotificationConsumerTest, ExpectCallbackTopicUpdated) { - NSProviderState revState = NS_STOPPED; - mocks.OnCallFunc(NSProviderChangedCallback).Do( - [this, & revState](NSProvider * , NSProviderState state) - { - std::cout << "Income Changed Callback : " << state << std::endl; - revState = state; - responseCon.notify_all(); - }); + revState = NS_STOPPED; NSProviderSimulator::NS_TopicList topics; topics.push_back("1"); @@ -576,10 +506,13 @@ TEST_F(NotificationConsumerTest, ExpectCallbackTopicUpdated) g_providerSimul.setTopics(topics); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); + expectedState = NS_TOPIC; + std::unique_lock< std::mutex > lock{ providerChangedLock }; + providerChanged.wait_for(lock, g_waitForResponse); EXPECT_EQ(NS_TOPIC, revState); + + expectedState = NS_STOPPED; } TEST_F(NotificationConsumerTest, ExpectEQTopicList) @@ -594,13 +527,17 @@ TEST_F(NotificationConsumerTest, ExpectEQTopicList) ASSERT_NE(nullptr, g_provider) << "error: discovery failure"; NSTopicLL * retTopic = NSConsumerGetTopicList(g_provider->providerId); + + NSTopicLL * iter = retTopic; std::for_each (topics.begin(), topics.end(), - [this, & retTopic, & isSame](const std::string & str) + [this, & iter, & isSame](const std::string & str) { - isSame = (str == std::string(retTopic->topicName)); - retTopic = retTopic->next; + isSame = (str == std::string(iter->topicName)); + iter = iter->next; }); + removeTopics(retTopic); + EXPECT_EQ(true, isSame); } @@ -609,31 +546,34 @@ TEST_F(NotificationConsumerTest, ExpectFailUpdateTopicOnConsumer) ASSERT_NE(nullptr, g_provider) << "error: discovery failure"; NSTopicLL * retTopic = NSConsumerGetTopicList(g_provider->providerId); - for (; retTopic; retTopic = retTopic->next) + + NSTopicLL * iter = retTopic; + for (; iter; iter = iter->next) { - retTopic->state = NS_TOPIC_SUBSCRIBED; + iter->state = NS_TOPIC_SUBSCRIBED; } NSResult ret = NSConsumerUpdateTopicList(g_provider->providerId, retTopic); + removeTopics(retTopic); + EXPECT_EQ(NS_ERROR, ret); } TEST_F(NotificationConsumerTest, ExpectCallbackDeletedProvider) { - NSProviderState type = NS_ALLOW; - mocks.OnCallFunc(NSProviderChangedCallback).Do( - [& type, this](NSProvider * , NSProviderState state) - { - std::cout << "Income Changed Callback : " << state << std::endl; - type = state; - responseCon.notify_all(); - }); + revState = NS_ALLOW; + expectedState = NS_STOPPED; g_providerSimul.deleteNotificationResource(); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, std::chrono::milliseconds(2000)); + std::unique_lock< std::mutex > lock{ providerChangedLock }; + providerChanged.wait_for(lock, g_waitForResponse); - EXPECT_EQ(type, NS_STOPPED); + EXPECT_EQ(revState, NS_STOPPED); NSStopConsumer(); + + if (g_provider) + { + free(g_provider); + } } diff --git a/service/notification/unittest/NSProviderSimulator.h b/service/notification/unittest/NSProviderSimulator.h index 2798e5d..31d4781 100644 --- a/service/notification/unittest/NSProviderSimulator.h +++ b/service/notification/unittest/NSProviderSimulator.h @@ -23,6 +23,7 @@ #include #include +#include #include "OCPlatform.h" #include "OCApi.h" @@ -79,7 +80,7 @@ public: NSProviderSimulator() : m_notificationHandle(), m_messageHandle(), m_syncHandle(), m_topicHandle(), m_syncRep(), m_messageRep(), m_accepter(0), - m_notificationUri(std::string("/notification")), + m_notificationUri(std::string("/notificationTest")), m_messageUri(std::string("/message")), m_syncUri(std::string("/sync")), m_topicUri(std::string("/topic")), @@ -324,9 +325,9 @@ public: { std::string providerId = "123456789012345678901234567890123456"; m_messageRep.setValue("messageid", id); - m_messageRep.setValue("title", title); - m_messageRep.setValue("contenttext", content); - m_messageRep.setValue("providerid", providerId); + m_messageRep.setValue("title", title); + m_messageRep.setValue("contenttext", content); + m_messageRep.setValue("providerid", providerId); } void setTopics(const NS_TopicList & topics) diff --git a/service/notification/unittest/NSProviderTest.cpp b/service/notification/unittest/NSProviderTest.cpp index dda37b9..929f0b6 100755 --- a/service/notification/unittest/NSProviderTest.cpp +++ b/service/notification/unittest/NSProviderTest.cpp @@ -19,7 +19,6 @@ //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #include -#include #include #include #include @@ -28,43 +27,65 @@ #include "NSProviderInterface.h" #include "NSConsumerSimulator.h" +#include "NSUnittestUtil.h" #include "NSCommon.h" namespace { std::atomic_bool g_isStartedStack(false); - std::chrono::milliseconds g_waitForResponse(500); + std::chrono::milliseconds g_waitForResponse(1000); - std::condition_variable responseCon; - std::mutex mutexForCondition; + std::condition_variable responseProviderSub; + std::mutex responseProviderSubLock; + + std::condition_variable responseProviderSync; + std::mutex responseProviderSyncLock; + + std::condition_variable responseConsumerMessage; + std::mutex responseConsumerMessageLock; + + std::condition_variable responseConsumerSync; + std::mutex responseConsumerSyncLock; NSConsumerSimulator g_consumerSimul; - char * g_consumerID; + char * g_consumerID = NULL; char g_title[100]; char g_body[100]; char g_sourceName[100]; -} -class TestWithMock: public testing::Test -{ -public: - MockRepository mocks; + int expectedMsgId; + int expectedSyncType = NS_SYNC_READ; -protected: - virtual ~TestWithMock() noexcept(noexcept(std::declval().~Test())) {} - - virtual void TearDown() { - try + static FILE* server_open(const char * path, const char * mode) + { + if (0 == strcmp(path, OC_SECURITY_DB_DAT_FILE_NAME)) { - mocks.VerifyAll(); + std::string file_name = "./oic_svr_db_ns.dat"; +#ifndef LOCAL_RUNNING + file_name = "./service/notification/unittest/oic_svr_db_ns.dat"; +#endif + return fopen(file_name.c_str(), mode); } - catch (...) + else { - mocks.reset(); - throw; + return fopen(path, mode); } } +} + +class TestWithMock: public testing::Test +{ +protected: + virtual ~TestWithMock() noexcept(noexcept(std::declval().~Test())) + { + + } + + virtual void TearDown() + { + + } }; class NotificationProviderTest : public TestWithMock @@ -73,21 +94,37 @@ public: NotificationProviderTest() = default; ~NotificationProviderTest() = default; - static void NSRequestedSubscribeCallbackEmpty(NSConsumer *) + static void NSRequestedSubscribeCallback(NSConsumer * consumer) { + if (g_consumerID) + { + free(g_consumerID); + } + g_consumerID = strdup(consumer->consumerId); + + responseProviderSub.notify_all(); } - static void NSSyncCallbackEmpty(NSSyncInfo *) + static void NSSyncCallback(NSSyncInfo * sync) { + expectedSyncType = sync->state; + expectedMsgId = sync->messageId; + free(sync); + responseProviderSync.notify_all(); } - static void NSMessageCallbackFromConsumerEmpty( - const int &, const std::string &, const std::string &, const std::string &) + static void NSMessageCallbackFromConsumer( + const int & id, const std::string &, const std::string &, const std::string &) { + expectedMsgId = id; + responseConsumerMessage.notify_all(); } - static void NSSyncCallbackFromConsumerEmpty(int, int) + static void NSSyncCallbackFromConsumer(const int type, const int syncId) { + expectedSyncType = type; + expectedMsgId = syncId; + responseConsumerSync.notify_all(); } protected: @@ -98,13 +135,16 @@ protected: if (g_isStartedStack == false) { + static OCPersistentStorage gps {server_open, fread, fwrite, fclose, unlink }; + OC::PlatformConfig cfg { OC::ServiceType::InProc, OC::ModeType::Both, "0.0.0.0", 0, - OC::QualityOfService::HighQos + OC::QualityOfService::HighQos, + &gps }; OC::OCPlatform::Configure(cfg); @@ -136,97 +176,74 @@ protected: TEST_F(NotificationProviderTest, StartProviderPositiveWithNSPolicyTrue) { NSProviderConfig config; - config.subRequestCallback = NSRequestedSubscribeCallbackEmpty; - config.syncInfoCallback = NSSyncCallbackEmpty; + config.subRequestCallback = NSRequestedSubscribeCallback; + config.syncInfoCallback = NSSyncCallback; config.subControllability = true; config.userInfo = strdup("user1"); + config.resourceSecurity = false; NSResult ret = NSStartProvider(config); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); - EXPECT_EQ(ret, NS_OK); + free(config.userInfo); + config.userInfo = NULL; } TEST_F(NotificationProviderTest, StopProviderPositive) { NSResult ret = NSStopProvider(); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); - EXPECT_EQ(ret, NS_OK); } TEST_F(NotificationProviderTest, StartProviderPositiveWithNSPolicyFalse) { NSProviderConfig config; - config.subRequestCallback = NSRequestedSubscribeCallbackEmpty; - config.syncInfoCallback = NSSyncCallbackEmpty; + config.subRequestCallback = NSRequestedSubscribeCallback; + config.syncInfoCallback = NSSyncCallback; config.subControllability = false; config.userInfo = NULL; + config.resourceSecurity = false; NSResult ret = NSStartProvider(config); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); g_consumerSimul.findProvider(); - responseCon.wait_for(lock, g_waitForResponse); NSStopProvider(); EXPECT_EQ(ret, NS_OK); } TEST_F(NotificationProviderTest, ExpectCallbackWhenReceiveSubscribeRequestWithAccepterProvider) { - g_consumerID = NULL; - mocks.OnCallFunc(NSRequestedSubscribeCallbackEmpty).Do( - [](NSConsumer * consumer) - { - g_consumerID = strdup(consumer->consumerId); - responseCon.notify_all(); - }); - NSProviderConfig config; - config.subRequestCallback = NSRequestedSubscribeCallbackEmpty; - config.syncInfoCallback = NSSyncCallbackEmpty; + config.subRequestCallback = NSRequestedSubscribeCallback; + config.syncInfoCallback = NSSyncCallback; config.subControllability = true; config.userInfo = NULL; + config.resourceSecurity = false; NSStartProvider(config); - { - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); - } - - g_consumerSimul.setCallback(NSMessageCallbackFromConsumerEmpty, - NSSyncCallbackFromConsumerEmpty); + g_consumerSimul.setCallback(NSMessageCallbackFromConsumer, + NSSyncCallbackFromConsumer); g_consumerSimul.findProvider(); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); + // maximum waiting time for subscription is 1.5 sec. + // usually maximum time is 1 sec. (g_waitForResponse = 1 sec.) + // but, in the secured case is need to more wait for processing. + std::chrono::milliseconds waitForSubscription(1500); + std::unique_lock< std::mutex > lock{ responseProviderSubLock }; + responseProviderSub.wait_for(lock, waitForSubscription); ASSERT_NE(nullptr, g_consumerID) << "error: discovery failure"; } TEST_F(NotificationProviderTest, NeverCallNotifyOnConsumerByAcceptIsFalse) { - bool expectTrue = true; int msgID; ASSERT_NE(nullptr, g_consumerID) << "error: discovery failure"; - mocks.OnCallFunc(NSMessageCallbackFromConsumerEmpty).Do( - [& expectTrue, &msgID](const int &id, const std::string&, const std::string&, const std::string&) - { - if (id == msgID) - { - expectTrue = false; - } - }); - NSAcceptSubscription(g_consumerID, false); NSMessage * msg = NSCreateMessage(); @@ -238,18 +255,20 @@ TEST_F(NotificationProviderTest, NeverCallNotifyOnConsumerByAcceptIsFalse) msg->sourceName = g_sourceName; NSSendMessage(msg); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); + std::unique_lock< std::mutex > lock{ responseConsumerMessageLock }; + responseConsumerMessage.wait_for(lock, g_waitForResponse); - EXPECT_EQ(expectTrue, true); + EXPECT_NE(expectedMsgId, msgID); NSAcceptSubscription(g_consumerID, true); - responseCon.wait_for(lock, g_waitForResponse); + responseConsumerMessage.wait_for(lock, g_waitForResponse); } else { - EXPECT_EQ(expectTrue, false); + EXPECT_EQ(expectedMsgId, msgID); } + + free(msg); } TEST_F(NotificationProviderTest, ExpectCallNotifyOnConsumerByAcceptIsTrue) @@ -258,15 +277,6 @@ TEST_F(NotificationProviderTest, ExpectCallNotifyOnConsumerByAcceptIsTrue) ASSERT_NE(nullptr, g_consumerID) << "error: discovery failure"; - mocks.ExpectCallFunc(NSMessageCallbackFromConsumerEmpty).Do( - [&msgID](const int &id, const std::string&, const std::string&, const std::string&) - { - if (id == msgID) - { - responseCon.notify_all(); - } - }); - NSMessage * msg = NSCreateMessage(); if(msg) { @@ -276,26 +286,21 @@ TEST_F(NotificationProviderTest, ExpectCallNotifyOnConsumerByAcceptIsTrue) msg->sourceName = g_sourceName; NSSendMessage(msg); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait(lock); + std::unique_lock< std::mutex > lock{ responseConsumerMessageLock }; + responseConsumerMessage.wait_for(lock, g_waitForResponse); + EXPECT_EQ(expectedMsgId, msgID); } + + free(msg); } TEST_F(NotificationProviderTest, ExpectCallbackSyncOnReadToConsumer) { int id; + int type = NS_SYNC_READ; ASSERT_NE(nullptr, g_consumerID) << "error: discovery failure"; - mocks.ExpectCallFunc(NSSyncCallbackFromConsumerEmpty).Do( - [& id](int & type, int &syncId) - { - if (syncId == id && type == NS_SYNC_READ) - { - responseCon.notify_all(); - } - }); - NSMessage * msg = NSCreateMessage(); if(msg) { @@ -305,27 +310,23 @@ TEST_F(NotificationProviderTest, ExpectCallbackSyncOnReadToConsumer) msg->sourceName = g_sourceName; NSProviderSendSyncInfo(msg->messageId, NS_SYNC_READ); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait(lock); + std::unique_lock< std::mutex > lock{ responseConsumerSyncLock }; + responseConsumerSync.wait_for(lock, g_waitForResponse); + + EXPECT_EQ(expectedMsgId, id); + EXPECT_EQ(expectedSyncType, type); } + + free(msg); } TEST_F(NotificationProviderTest, ExpectCallbackSyncOnReadFromConsumer) { - int type = NS_SYNC_READ; int id; + int type = NS_SYNC_READ; ASSERT_NE(nullptr, g_consumerID) << "error: discovery failure"; - mocks.ExpectCallFunc(NSSyncCallbackEmpty).Do( - [& id](NSSyncInfo * sync) - { - if ((int)sync->messageId == id && sync->state == NS_SYNC_READ) - { - responseCon.notify_all(); - } - }); - NSMessage * msg = NSCreateMessage(); if(msg) { @@ -335,9 +336,14 @@ TEST_F(NotificationProviderTest, ExpectCallbackSyncOnReadFromConsumer) msg->sourceName = g_sourceName; g_consumerSimul.syncToProvider(type, id, msg->providerId); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait(lock); + std::unique_lock< std::mutex > lock{ responseProviderSyncLock }; + responseProviderSync.wait_for(lock, g_waitForResponse); + + EXPECT_EQ(expectedMsgId, id); + EXPECT_EQ(expectedSyncType, type); } + + free(msg); } TEST_F(NotificationProviderTest, ExpectEqualAddedTopicsAndRegisteredTopics) @@ -366,6 +372,8 @@ TEST_F(NotificationProviderTest, ExpectEqualAddedTopicsAndRegisteredTopics) } } + removeTopics(topics); + NSProviderUnregisterTopic(str.c_str()); NSProviderUnregisterTopic(str2.c_str()); EXPECT_EQ(isSame, true); @@ -397,6 +405,8 @@ TEST_F(NotificationProviderTest, ExpectEqualUnregisteredTopicsAndRegisteredTopic } } + removeTopics(topics); + NSProviderUnregisterTopic(str.c_str()); EXPECT_EQ(isSame, true); } @@ -409,9 +419,6 @@ TEST_F(NotificationProviderTest, ExpectEqualSetConsumerTopicsAndGetConsumerTopic NSProviderRegisterTopic(str2.c_str()); NSProviderSetConsumerTopic(g_consumerID, str.c_str()); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); - bool isSame = false; NSTopicLL * topics = NSProviderGetConsumerTopics(g_consumerID); @@ -431,6 +438,8 @@ TEST_F(NotificationProviderTest, ExpectEqualSetConsumerTopicsAndGetConsumerTopic } } + removeTopics(topics); + NSProviderUnregisterTopic(str.c_str()); NSProviderUnregisterTopic(str2.c_str()); EXPECT_EQ(isSame, true); @@ -446,9 +455,6 @@ TEST_F(NotificationProviderTest, ExpectEqualUnSetConsumerTopicsAndGetConsumerTop NSProviderSetConsumerTopic(g_consumerID, str2.c_str()); NSProviderUnsetConsumerTopic(g_consumerID, str.c_str()); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, g_waitForResponse); - bool isSame = false; ASSERT_NE(nullptr, g_consumerID) << "error: discovery failure"; @@ -471,6 +477,8 @@ TEST_F(NotificationProviderTest, ExpectEqualUnSetConsumerTopicsAndGetConsumerTop } } + removeTopics(topics); + NSProviderUnregisterTopic(str.c_str()); NSProviderUnregisterTopic(str2.c_str()); EXPECT_EQ(isSame, true); @@ -562,8 +570,8 @@ TEST_F(NotificationProviderTest, CancelObserves) { bool ret = g_consumerSimul.cancelObserves(); - std::unique_lock< std::mutex > lock{ mutexForCondition }; - responseCon.wait_for(lock, std::chrono::milliseconds(3000)); + std::chrono::milliseconds waitForTerminate(1000); + std::this_thread::sleep_for(waitForTerminate); EXPECT_EQ(ret, true); } diff --git a/service/notification/unittest/NSUnittestUtil.h b/service/notification/unittest/NSUnittestUtil.h new file mode 100644 index 0000000..b3672e0 --- /dev/null +++ b/service/notification/unittest/NSUnittestUtil.h @@ -0,0 +1,85 @@ +//****************************************************************** +// +// Copyright 2016 Samsung Electronics 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. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License 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 "ocpayload.h" +#include "NSCommon.h" + +void removeMessage(NSMessage * msg) +{ + if (msg == NULL) + { + return; + } + + msg->messageId = 0; + if (msg->title != NULL) + { + free(msg->title); + } + if (msg->contentText != NULL) + { + free(msg->contentText); + } + if (msg->sourceName != NULL) + { + free(msg->sourceName); + } + if (msg->dateTime != NULL) + { + free(msg->dateTime); + } + if (msg->topic != NULL) + { + free(msg->topic); + } + + if (msg->mediaContents != NULL) + { + free(msg->mediaContents->iconImage); + free(msg->mediaContents); + } + + if (msg->extraInfo != NULL) + { + OCRepPayloadDestroy(msg->extraInfo); + msg->extraInfo = NULL; + } + + free(msg); +} + +void removeTopics(NSTopicLL * topics) +{ + NSTopicLL * iter = topics; + NSTopicLL * following = NULL; + + while (iter) + { + following = iter->next; + + free(iter->topicName); + iter->next = NULL; + + free(iter); + + iter = following; + } +} diff --git a/service/notification/unittest/SConscript b/service/notification/unittest/SConscript index e011ee6..9d6ccaa 100644 --- a/service/notification/unittest/SConscript +++ b/service/notification/unittest/SConscript @@ -21,9 +21,11 @@ ## # Notification Unit Test build script ## - +from tools.scons.RunTest import run_test Import('env') +import os + if env.get('RELEASE'): env.AppendUnique(CCFLAGS = ['-Os']) env.AppendUnique(CPPDEFINES = ['NDEBUG']) @@ -69,8 +71,8 @@ notification_test_env.AppendUnique(CPPPATH = ['../include']) if env.get('WITH_TCP') == True: notification_test_env.AppendUnique(CPPDEFINES = ['WITH_TCP']) - if env.get('SECURED') == '1': - notification_test_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) +if env.get('SECURED') == '1': + notification_test_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) ###################################################################### # Build Test @@ -92,18 +94,25 @@ notification_provider_test = notification_provider_test_env.Program('notificatio Alias("notification_provider_test", notification_provider_test) env.AppendTarget('notification_provider_test') +# TODO: Fix this test for MLK and remove commented lines if env.get('TEST') == '1': - if env.get('SECURED') != '1': -# TODO: fix this test on linux and remove this comment line - if target_os in []: - from tools.scons.RunTest import * - run_test(notification_consumer_test_env, -# 'service_notification_unittest_notification_consumer_test.memcheck', - '', - 'service/notification/unittest/notification_consumer_test', - notification_consumer_test) - run_test(notification_provider_test_env, -# 'service_notification_unittest_notification_provider_test.memcheck', - '', - 'service/notification/unittest/notification_provider_test', - notification_provider_test) + if target_os in ['linux'] and env.get('SECURED') != '1': + run_test(notification_consumer_test_env, +# 'service_notification_unittest_notification_consumer_test.memcheck', + '', + 'service/notification/unittest/notification_consumer_test') + run_test(notification_provider_test_env, +# 'service_notification_unittest_notification_provider_test.memcheck', + '', + 'service/notification/unittest/notification_provider_test') +else: + notification_consumer_test_env.AppendUnique(CPPDEFINES = ['LOCAL_RUNNING']) + notification_provider_test_env.AppendUnique(CPPDEFINES = ['LOCAL_RUNNING']) + src_dir = notification_consumer_test_env.get('SRC_DIR') + svr_db_src_dir = os.path.join(src_dir, 'service/notification/unittest/') + svr_db_build_dir = os.path.join(notification_consumer_test_env.get('BUILD_DIR'), + 'service', 'notification', 'unittest') + os.sep + notification_consumer_test_env.Alias("install", + notification_consumer_test_env.Install(svr_db_build_dir, + os.path.join(svr_db_src_dir, + 'oic_svr_db_ns.dat'))) diff --git a/service/notification/unittest/oic_svr_db_ns.dat b/service/notification/unittest/oic_svr_db_ns.dat new file mode 100644 index 0000000000000000000000000000000000000000..cbf9ef1169d140dc7406639eb1b52c402219c9f8 GIT binary patch literal 4991 zcmeHKy^_-~5KfpI7~X&zS}JBv8Q=-1XelUi9kR5J<=B>y1(sbqeL3v z3r3BQ35x1c@kW0;NY(%u#h^8v0D|Succ77KKs%~xqUx)JIml%zt2yQ9u! z9;3aTV=CgB?faG7$)?&+w^>u%dqs-&KIxxGaGc(u%Fsf3hr**~gMO6+YEk%v z4)r)xa-M*~6qmnv^SXF0kZimv9{N;!{@_-1KK`==qi`6#lS}b(ST`YhJbs|Z||*W zWLI|2W7BDE2V(bn-4||qLPlS>E%Lr_tJUu0h!XgOd8RMi@W$BRgzy^K--O&nwL^HS X-84>7xb^kSiEFh(^~`@$Ij{c$xsgzY literal 0 HcmV?d00001 diff --git a/service/notification/unittest/oic_svr_db_ns.json b/service/notification/unittest/oic_svr_db_ns.json new file mode 100644 index 0000000..0bd65b4 --- /dev/null +++ b/service/notification/unittest/oic_svr_db_ns.json @@ -0,0 +1,191 @@ +{ + "acl": { + "aclist": { + "aces": [ + { + "subjectuuid": "*", + "resources": [ + { + "href": "/oic/res", + "rel": "", + "rt": ["oic.wk.res"], + "if": ["oic.if.ll"] + }, + { + "href": "/oic/d", + "rel": "", + "rt": ["oic.wk.d"], + "if": ["oic.if.baseline", "oic.if.r"] + }, + { + "href": "/oic/p", + "rel": "", + "rt": ["oic.wk.p"], + "if": ["oic.if.baseline", "oic.if.r"] + }, + { + "href": "/oic/sec/acl", + "rel": "", + "rt": ["oic.r.acl"], + "if": ["oic.if.baseline"] + }, + { + "href": "/notification", + "rel": "", + "rt": ["oic.wk.notification"], + "if": ["oic.if.baseline"] + }, + { + "href": "/notification/message", + "rel": "", + "rt": ["oic.wk.notification.message"], + "if": ["oic.if.baseline"] + }, + { + "href": "/notification/sync", + "rel": "", + "rt": ["oic.wk.notification.sync"], + "if": ["oic.if.baseline"] + }, + { + "href": "/notification/topic", + "rel": "", + "rt": ["oic.wk.notification.topic"], + "if": ["oic.if.baseline"] + }, + { + "href": "/notificationTest", + "rel": "", + "rt": ["oic.wk.notification"], + "if": ["oic.if.baseline"] + }, + { + "href": "/notificationTest/message", + "rel": "", + "rt": ["oic.wk.notification.message"], + "if": ["oic.if.baseline"] + }, + { + "href": "/notificationTest/sync", + "rel": "", + "rt": ["oic.wk.notification.sync"], + "if": ["oic.if.baseline"] + }, + { + "href": "/notificationTest/topic", + "rel": "", + "rt": ["oic.wk.notification.topic"], + "if": ["oic.if.baseline"] + } + ], + "permission": 2 + }, + { + "subjectuuid": "*", + "resources": [ + { + "href": "/oic/sec/doxm", + "rel": "", + "rt": ["oic.r.doxm"], + "if": ["oic.if.baseline"] + }, + { + "href": "/oic/sec/pstat", + "rel": "", + "rt": ["oic.r.pstat"], + "if": ["oic.if.baseline"] + } + ], + "permission": 2 + }, + { + "subjectuuid": "*", + "resources": [ + { + "href": "/notification", + "rel": "", + "rt": ["oic.wk.notification"], + "if": ["oic.if.baseline"] + }, + { + "href": "/notification/message", + "rel": "", + "rt": ["oic.wk.notification.message"], + "if": ["oic.if.baseline"] + }, + { + "href": "/notification/sync", + "rel": "", + "rt": ["oic.wk.notification.sync"], + "if": ["oic.if.baseline"] + }, + { + "href": "/notification/topic", + "rel": "", + "rt": ["oic.wk.notification.topic"], + "if": ["oic.if.baseline"] + }, + { + "href": "/notificationTest", + "rel": "", + "rt": ["oic.wk.notification"], + "if": ["oic.if.baseline"] + }, + { + "href": "/notificationTest/message", + "rel": "", + "rt": ["oic.wk.notification.message"], + "if": ["oic.if.baseline"] + }, + { + "href": "/notificationTest/sync", + "rel": "", + "rt": ["oic.wk.notification.sync"], + "if": ["oic.if.baseline"] + }, + { + "href": "/notificationTest/topic", + "rel": "", + "rt": ["oic.wk.notification.topic"], + "if": ["oic.if.baseline"] + } + ], + "permission": 6 + } + ] + }, + "rowneruuid" : "32323232-3232-3232-3232-323232323232" + }, + "pstat": { + "isop": true, + "deviceuuid": "32323232-3232-3232-3232-323232323232", + "rowneruuid": "32323232-3232-3232-3232-323232323232", + "cm": 0, + "tm": 0, + "om": 4, + "sm": 4 + }, + "doxm": { + "oxms": [0], + "oxmsel": 0, + "sct": 1, + "owned": true, + "deviceuuid": "32323232-3232-3232-3232-323232323232", + "devowneruuid": "32323232-3232-3232-3232-323232323232", + "rowneruuid": "32323232-3232-3232-3232-323232323232" + }, + "cred": { + "creds": [ + { + "credid": 1, + "subjectuuid": "31313131-3131-3131-3131-313131313131", + "credtype": 1, + "privatedata": { + "data": "AAAAAAAAAAAAAAAA", + "encoding": "oic.sec.encoding.raw" + } + } + ], + "rowneruuid": "32323232-3232-3232-3232-323232323232" + } +} -- 2.7.4