Refactor duplicated SCons/Python test run code.
[platform/upstream/iotivity.git] / resource / csdk / connectivity / test / camutex_tests.cpp
1 //******************************************************************
2 //
3 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20 //
21 //
22 //*********************************************************************
23
24 // Defining _POSIX_C_SOURCE macro with 200809L (or greater) as value
25 // causes header files to expose definitions
26 // corresponding to the POSIX.1-2008 base
27 // specification (excluding the XSI extension).
28 // For POSIX.1-2008 base specification,
29 // Refer http://pubs.opengroup.org/stage7tc1/
30 //
31 // For this specific file, see use of usleep
32 #ifndef _POSIX_C_SOURCE
33 #define _POSIX_C_SOURCE 200809L
34 #endif // _POSIX_C_SOURCE
35
36 #include "gtest/gtest.h"
37
38 #include <camutex.h>
39 #include <cathreadpool.h>
40
41 #include <time.h>
42 #include <sys/time.h>
43 #include <unistd.h>
44
45 //#define DEBUG_VERBOSE 1
46
47 // The debug print lines are left in for now since the output can be
48 // helpful for developers trying to debug or extend the tests.
49 // However, by default they are #defined out so as not to get in
50 // the way of normal test runs.
51 #ifdef DEBUG_VERBOSE
52 #define DBG_printf(...) printf(__VA_ARGS__)
53 #else
54 #define DBG_printf(...)
55 #endif
56
57 static const uint64_t USECS_PER_SEC = 1000000;
58
59 static const uint64_t USECS_PER_MSEC = 1000;
60
61 static const int MINIMAL_LOOP_SLEEP = 20;
62 static const int MINIMAL_EXTRA_SLEEP = 25;
63
64 uint64_t getAbsTime()
65 {
66     uint64_t currentTime=0;
67 #if _POSIX_TIMERS > 0
68     struct timespec ts;
69     clock_gettime(CLOCK_MONOTONIC, &ts);
70     currentTime = ts.tv_sec * USECS_PER_SEC + ts.tv_nsec / 1000;
71 #else
72     struct timeval tv;
73     gettimeofday(&tv, NULL);
74     currentTime = tv.tv_sec * USECS_PER_SEC + tv.tv_usec;
75 #endif
76     return currentTime;
77 }
78
79 TEST(MutexTests, TC_01_CREATE)
80 {
81     ca_mutex mymutex = ca_mutex_new();
82
83     EXPECT_TRUE(mymutex != NULL);
84     if (mymutex != NULL)
85     {
86         ca_mutex_free(mymutex);
87     }
88 }
89
90 TEST(MutexTests, TC_02_TRY_LOCK)
91 {
92     ca_mutex mymutex = ca_mutex_new();
93
94     EXPECT_TRUE(mymutex != NULL);
95     if (mymutex != NULL)
96     {
97         EXPECT_TRUE(ca_mutex_trylock(mymutex)); // acquire it
98
99         ca_mutex_unlock(mymutex); // release it
100
101         ca_mutex_lock(mymutex); // acquire it
102
103         EXPECT_FALSE(ca_mutex_trylock(mymutex)); // he should be lock
104
105         EXPECT_FALSE(ca_mutex_trylock(NULL));
106
107         ca_mutex_unlock(mymutex); // release it
108         ca_mutex_free(mymutex);
109
110         EXPECT_FALSE(ca_mutex_trylock(NULL));
111     }
112 }
113
114 typedef struct _tagFunc1
115 {
116     ca_mutex mutex;
117     volatile bool thread_up;
118     volatile bool finished;
119 } _func1_struct;
120
121 void mutexFunc(void *context)
122 {
123     _func1_struct* pData = (_func1_struct*) context;
124
125     DBG_printf("Thread: trying to lock\n");
126
127     // setting the flag must be done before lock attempt, as the test
128     // thread starts off with the mutex locked
129     pData->thread_up = true;
130     ca_mutex_lock(pData->mutex);
131
132     DBG_printf("Thread: got lock\n");
133     usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
134     DBG_printf("Thread: releasing\n");
135
136     pData->finished = true; // assignment guarded by lock
137
138     ca_mutex_unlock(pData->mutex);
139 }
140
141 TEST(MutexTests, TC_03_THREAD_LOCKING)
142 {
143     ca_thread_pool_t mythreadpool;
144
145     EXPECT_EQ(CA_STATUS_OK, ca_thread_pool_init(3, &mythreadpool));
146
147     _func1_struct pData = {};
148
149     pData.mutex = ca_mutex_new();
150
151     EXPECT_TRUE(pData.mutex != NULL);
152     if (pData.mutex != NULL)
153     {
154         DBG_printf("test: Holding mutex in test\n");
155         ca_mutex_lock(pData.mutex);
156
157         DBG_printf("test: starting thread\n");
158         //start thread
159         EXPECT_EQ(CA_STATUS_OK,
160                   ca_thread_pool_add_task(mythreadpool, mutexFunc, &pData));
161
162         DBG_printf("test: waiting for thread to be up.\n");
163
164         while (!pData.thread_up)
165         {
166             usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
167         }
168         // At this point the thread is running and close to trying to lock.
169         // For test purposes only, use of condition variables is being avoided,
170         // so a minor sleep is used.
171         usleep(MINIMAL_EXTRA_SLEEP * USECS_PER_MSEC);
172
173         DBG_printf("test: unlocking\n");
174
175         ca_mutex_unlock(pData.mutex);
176
177         DBG_printf("test: waiting for thread to release\n");
178         while (!pData.finished)
179         {
180             usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
181         }
182
183         ca_mutex_lock(pData.mutex);
184
185         // Cleanup Everything
186
187         ca_mutex_unlock(pData.mutex);
188         ca_mutex_free(pData.mutex);
189     }
190
191     ca_thread_pool_free(mythreadpool);
192 }
193
194 TEST(ConditionTests, TC_01_CREATE)
195 {
196     ca_cond mycond = ca_cond_new();
197
198     EXPECT_TRUE(mycond != NULL);
199     if (mycond != NULL)
200     {
201         ca_cond_free(mycond);
202     }
203 }
204
205 // Normally we would use one pair of mutex/cond-var communicating to the
206 // worker threads and one pair back to the main thread. However since
207 // testing the ca_cond itself is the point, only one pair is used here.
208 typedef struct _tagFunc2
209 {
210     int id;
211     ca_mutex mutex;
212     ca_cond condition;
213     volatile bool thread_up;
214     volatile bool finished;
215 } _func2_struct;
216
217 void condFunc(void *context)
218 {
219     _func2_struct* pData = (_func2_struct*) context;
220
221     DBG_printf("Thread_%d: waiting on condition\n", pData->id);
222
223     ca_mutex_lock(pData->mutex);
224
225     pData->thread_up = true;
226
227     ca_cond_wait(pData->condition, pData->mutex);
228
229     pData->finished = true; // assignment guarded by lock
230
231     ca_mutex_unlock(pData->mutex);
232
233     DBG_printf("Thread_%d: completed.\n", pData->id);
234 }
235
236 TEST(ConditionTests, TC_02_SIGNAL)
237 {
238     const int MAX_WAIT_MS = 2000;
239     ca_thread_pool_t mythreadpool;
240
241     EXPECT_EQ(CA_STATUS_OK, ca_thread_pool_init(3, &mythreadpool));
242
243     ca_mutex sharedMutex = ca_mutex_new();
244     ca_cond sharedCond = ca_cond_new();
245
246     _func2_struct pData1 =
247     { 1, sharedMutex, sharedCond, false, false };
248     _func2_struct pData2 =
249     { 2, sharedMutex, sharedCond, false, false };
250
251     EXPECT_TRUE(pData1.mutex != NULL);
252     if (pData1.mutex != NULL)
253     {
254         DBG_printf("starting thread\n");
255         // start threads
256         EXPECT_EQ(CA_STATUS_OK,
257                   ca_thread_pool_add_task(mythreadpool, condFunc, &pData1));
258         EXPECT_EQ(CA_STATUS_OK,
259                   ca_thread_pool_add_task(mythreadpool, condFunc, &pData2));
260
261         DBG_printf("test    : sleeping\n");
262
263         while (!pData1.thread_up || !pData2.thread_up)
264         {
265             // For test purposes only, use of condition variables is being
266             // avoided, so a minor sleep is used.
267             usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
268         }
269         // At this point the threads are running and both have locked. One
270         // has already started waiting on the condition and the other is at
271         // least close.
272
273         ca_mutex_lock(sharedMutex);
274         // once the lock is acquired it means both threads were waiting.
275         DBG_printf("test    : signaling first thread\n");
276         ca_cond_signal(sharedCond);
277         ca_mutex_unlock(sharedMutex);
278
279         // At this point either of the child threads might lock the mutex in
280         // their cond_wait call, or this test thread might lock it again if
281         // mutex_lock gets executed before the child threads can react to
282         // the signaling. Thus we wait on their flag variables
283         int waitCount = 1; // start with 1 for minumum targetWait value.
284         while (!pData1.finished && !pData2.finished)
285         {
286             usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
287             waitCount++;
288         }
289
290         // As a rough hueristic wait twice as long for the second to possibly
291         // finish:
292         int targetWait = waitCount * 2;
293         for (int i = 0;
294              (i < targetWait) && (!pData1.finished && !pData2.finished); i++)
295         {
296             usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
297         }
298         usleep(MINIMAL_EXTRA_SLEEP);
299
300         // only one should be finished
301         ca_mutex_lock(sharedMutex);
302         EXPECT_NE(pData1.finished, pData2.finished);
303         ca_mutex_unlock(sharedMutex);
304
305         DBG_printf("test    : signaling another thread\n");
306
307         ca_mutex_lock(sharedMutex);
308         ca_cond_signal(sharedCond);
309         ca_mutex_unlock(sharedMutex);
310
311         waitCount = 0;
312         while ((!pData1.finished || !pData2.finished)
313                && ((waitCount * MINIMAL_EXTRA_SLEEP) < MAX_WAIT_MS))
314         {
315             usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
316             waitCount++;
317         }
318
319         // both should finally be finished
320         EXPECT_TRUE(pData1.finished);
321         EXPECT_TRUE(pData2.finished);
322
323         // Cleanup Everything
324
325         ca_mutex_free(pData1.mutex);
326     }
327
328     ca_cond_free(pData1.condition);
329
330     ca_thread_pool_free(mythreadpool);
331 }
332
333 TEST(ConditionTests, TC_03_BROADCAST)
334 {
335     const int MAX_WAIT_MS = 2000;
336     ca_thread_pool_t mythreadpool;
337
338     EXPECT_EQ(CA_STATUS_OK, ca_thread_pool_init(3, &mythreadpool));
339
340     ca_mutex sharedMutex = ca_mutex_new();
341     ca_cond sharedCond = ca_cond_new();
342
343     _func2_struct pData1 =
344     { 1, sharedMutex, sharedCond, false, false };
345     _func2_struct pData2 =
346     { 2, sharedMutex, sharedCond, false, false };
347
348     EXPECT_TRUE(pData1.mutex != NULL);
349     if (pData1.mutex != NULL)
350     {
351         DBG_printf("starting thread\n");
352         // start threads
353         EXPECT_EQ(CA_STATUS_OK,
354                   ca_thread_pool_add_task(mythreadpool, condFunc, &pData1));
355         EXPECT_EQ(CA_STATUS_OK,
356                   ca_thread_pool_add_task(mythreadpool, condFunc, &pData2));
357
358         DBG_printf("test    : sleeping\n");
359
360         while (!pData1.thread_up || !pData2.thread_up)
361         {
362             // For test purposes only, use of condition variables is being
363             // avoided, so a minor sleep is used.
364             usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
365         }
366         // At this point the threads are running and both have locked. One
367         // has already started waiting on the condition and the other is at
368         // least close.
369
370         DBG_printf("test    : signaling all threads\n");
371
372         ca_mutex_lock(sharedMutex);
373         // once the lock is acquired it means both threads were waiting.
374         ca_cond_broadcast(sharedCond);
375         ca_mutex_unlock(sharedMutex);
376
377         int waitCount = 0;
378         while ((!pData1.finished || !pData2.finished)
379                && ((waitCount * MINIMAL_EXTRA_SLEEP) < MAX_WAIT_MS))
380         {
381             usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
382             waitCount++;
383         }
384
385         // both should finally be finished
386         EXPECT_TRUE(pData1.finished);
387         EXPECT_TRUE(pData2.finished);
388
389         // Cleanup Everything
390
391         ca_mutex_free(sharedMutex);
392     }
393
394     ca_cond_free(sharedCond);
395
396     ca_thread_pool_free(mythreadpool);
397 }
398
399 TEST(CondTests, TC_04_TIMECHECK)
400 {
401     uint64_t begin = getAbsTime();
402
403     usleep(1);
404
405     uint64_t end = getAbsTime();
406
407     EXPECT_LT(begin, end); // should never be the same value
408 }
409
410 void timedFunc(void *context)
411 {
412     _func2_struct* pData = (_func2_struct*) context;
413
414     DBG_printf("Thread_%d: waiting for timeout \n", pData->id);
415
416     ca_mutex_lock(pData->mutex);
417
418     uint64_t abs = USECS_PER_SEC / 2; // 1/2 seconds
419
420     // test UTIMEDOUT
421     CAWaitResult_t ret = ca_cond_wait_for(pData->condition,
422                                           pData->mutex, abs);
423     EXPECT_EQ(CA_WAIT_TIMEDOUT, ret);
424
425     pData->thread_up = true;
426
427     DBG_printf("Thread_%d: waiting for signal \n", pData->id);
428
429     abs = 5 * USECS_PER_SEC; // 5 seconds
430
431     // test signal
432     ret = ca_cond_wait_for(pData->condition, pData->mutex, abs);
433     EXPECT_EQ(CA_WAIT_SUCCESS, ret);
434
435     pData->finished = true; // assignment guarded by lock
436
437     ca_mutex_unlock(pData->mutex);
438
439     DBG_printf("Thread_%d: stopping\n", pData->id);
440 }
441
442 TEST(ConditionTests, TC_05_WAIT)
443 {
444     const int MAX_WAIT_MS = 5000;
445     ca_thread_pool_t mythreadpool;
446
447     EXPECT_EQ(CA_STATUS_OK, ca_thread_pool_init(3, &mythreadpool));
448
449     ca_mutex sharedMutex = ca_mutex_new();
450     ca_cond sharedCond = ca_cond_new();
451
452     _func2_struct pData1 =
453     { 1, sharedMutex, sharedCond, false, false };
454
455     EXPECT_TRUE(sharedMutex != NULL);
456     if (sharedMutex != NULL)
457     {
458         DBG_printf("test    : starting thread\n");
459         //start thread
460         EXPECT_EQ(CA_STATUS_OK,
461                   ca_thread_pool_add_task(mythreadpool, timedFunc, &pData1));
462
463         DBG_printf("test    : waiting for thread to timeout once.\n");
464
465         while (!pData1.thread_up)
466         {
467             // For test purposes only, use of condition variables is being
468             // avoided, so a minor sleep is used.
469             usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
470         }
471
472
473         DBG_printf("test    : signaling first thread\n");
474
475         ca_mutex_lock(sharedMutex);
476         ca_cond_signal(sharedCond);
477         ca_mutex_unlock(sharedMutex);
478
479         int waitCount = 0;
480         while (!pData1.finished
481                && ((waitCount * MINIMAL_EXTRA_SLEEP) < MAX_WAIT_MS))
482         {
483             usleep(MINIMAL_LOOP_SLEEP * USECS_PER_MSEC);
484             waitCount++;
485         }
486
487         EXPECT_TRUE(pData1.finished); // thread should finally be finished
488
489         // Cleanup Everything
490
491         ca_mutex_free(sharedMutex);
492     }
493
494     ca_cond_free(sharedCond);
495
496     ca_thread_pool_free(mythreadpool);
497 }
498
499 // Disabled because this should no longer be a valid test
500 TEST(ConditionTests, DISABLED_TC_06_INVALIDWAIT)
501 {
502
503     ca_mutex sharedMutex = ca_mutex_new();
504     ca_cond sharedCond = ca_cond_new();
505
506     ca_mutex_lock(sharedMutex);
507
508     int ret = ca_cond_wait_for(NULL, sharedMutex, 5000);
509     EXPECT_EQ(CA_WAIT_INVAL,ret);
510
511     ret = ca_cond_wait_for(sharedCond, NULL, 5000);
512     EXPECT_EQ(CA_WAIT_INVAL,ret);
513
514     ret = ca_cond_wait_for(NULL, NULL, 5000);
515     EXPECT_EQ(CA_WAIT_INVAL,ret);
516
517     ca_mutex_unlock(sharedMutex);
518
519     // Cleanup Everything
520
521     ca_mutex_free(sharedMutex);
522
523     ca_cond_free(sharedCond);
524 }
525
526 TEST(ConditionTests, TC_07_WAITDURATION)
527 {
528     const double TARGET_WAIT = 1.125;
529
530     ca_mutex sharedMutex = ca_mutex_new();
531     ca_cond sharedCond = ca_cond_new();
532
533     ca_mutex_lock(sharedMutex);
534
535     uint64_t beg = getAbsTime();
536
537     CAWaitResult_t ret = ca_cond_wait_for(sharedCond, sharedMutex,
538                                           TARGET_WAIT * USECS_PER_SEC);
539     EXPECT_EQ(CA_WAIT_TIMEDOUT,ret);
540
541     uint64_t end = getAbsTime();
542
543     double secondsDiff = (end - beg) / (double) USECS_PER_SEC;
544
545     EXPECT_NEAR(TARGET_WAIT, secondsDiff, 0.05);
546
547     ca_mutex_unlock(sharedMutex);
548
549     // Cleanup Everything
550
551     ca_mutex_free(sharedMutex);
552
553     ca_cond_free(sharedCond);
554 }