Make OCProcessEvent method.
[platform/upstream/iotivity.git] / resource / c_common / ocevent / test / eventtest.cpp
1 /* *****************************************************************
2  *
3  * Copyright 2017 Microsoft
4  *
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  ******************************************************************/
19
20 /**
21  * @file
22  *
23  * This file implement tests for the Event object.
24  */
25
26 #include "ocevent.h"
27 #include "gtest/gtest.h"
28 #include <limits.h>
29 #include <thread>
30
31 class EventTester : public testing::Test
32 {
33   protected:
34     virtual void SetUp()
35     {
36         m_event = oc_event_new();
37         ASSERT_TRUE(nullptr != m_event);
38     }
39     virtual void TearDown()
40     {
41         oc_event_free(m_event);
42     }
43     void TestSignalBeforeWait(uint32_t timeout);
44     oc_event m_event;
45 };
46
47 void EventTester::TestSignalBeforeWait(uint32_t timeout)
48 {
49     std::thread thread([this]()
50     {
51         oc_event_signal(m_event);
52     });
53
54     // Make sure the signal occurs before the wait.
55     thread.join();
56
57     if (UINT_MAX == timeout)
58     {
59         oc_event_wait(m_event);
60     }
61     else
62     {
63         EXPECT_EQ(OC_WAIT_SUCCESS, oc_event_wait_for(m_event, timeout));
64     }
65 }
66
67 TEST_F(EventTester, InfiniteTimeout_SignaledAfterWait)
68 {
69     std::thread thread([this]()
70     {
71         // This sleep allows the main thread to enter the wait state before the signal.
72         std::this_thread::sleep_for(std::chrono::milliseconds(10));
73         oc_event_signal(m_event);
74     });
75     oc_event_wait(m_event);
76     thread.join();
77 }
78
79 TEST_F(EventTester, InfiniteTimeout_SignaledBeforeWait)
80 {
81     TestSignalBeforeWait(UINT_MAX);
82 }
83
84 TEST_F(EventTester, ZeroTimeout_NotSignaled)
85 {
86     EXPECT_EQ(OC_WAIT_TIMEDOUT, oc_event_wait_for(m_event, 0));
87 }
88
89 TEST_F(EventTester, ZeroTimeout_Signaled)
90 {
91     TestSignalBeforeWait(0);
92 }
93
94 TEST_F(EventTester, TimedOut)
95 {
96     EXPECT_EQ(OC_WAIT_TIMEDOUT, oc_event_wait_for(m_event, 10));
97 }