blob: 652cd9ed1a2aaa5637e532813ef8bc1e7216e266 [file] [log] [blame]
brians343bc112013-02-10 01:53:46 +00001#include "aos/common/mutex.h"
2
Brian Silvermand41b4422013-09-01 14:02:33 -07003#include <sched.h>
4#include <math.h>
5#include <pthread.h>
6#ifdef __VXWORKS__
7#include <taskLib.h>
8#endif
9
brians343bc112013-02-10 01:53:46 +000010#include "gtest/gtest.h"
11
Brian Silverman08661c72013-09-01 17:24:38 -070012#include "aos/atom_code/ipc_lib/aos_sync.h"
Brian Silvermand41b4422013-09-01 14:02:33 -070013
brians343bc112013-02-10 01:53:46 +000014namespace aos {
15namespace testing {
16
17class MutexTest : public ::testing::Test {
18 public:
19 Mutex test_mutex;
20};
21
22typedef MutexTest MutexDeathTest;
23
24TEST_F(MutexTest, TryLock) {
25 EXPECT_TRUE(test_mutex.TryLock());
26 EXPECT_FALSE(test_mutex.TryLock());
27}
28
29TEST_F(MutexTest, Lock) {
30 test_mutex.Lock();
31 EXPECT_FALSE(test_mutex.TryLock());
32}
33
34TEST_F(MutexTest, Unlock) {
35 test_mutex.Lock();
36 EXPECT_FALSE(test_mutex.TryLock());
37 test_mutex.Unlock();
38 EXPECT_TRUE(test_mutex.TryLock());
39}
40
41#ifndef __VXWORKS__
42// Sees what happens with multiple unlocks.
43TEST_F(MutexDeathTest, RepeatUnlock) {
44 test_mutex.Lock();
45 test_mutex.Unlock();
46 EXPECT_DEATH(test_mutex.Unlock(), ".*multiple unlock.*");
47}
48
49// Sees what happens if you unlock without ever locking (or unlocking) it.
50TEST_F(MutexDeathTest, NeverLock) {
51 EXPECT_DEATH(test_mutex.Unlock(), ".*multiple unlock.*");
52}
53#endif
54
55TEST_F(MutexTest, MutexLocker) {
56 {
57 aos::MutexLocker locker(&test_mutex);
58 EXPECT_FALSE(test_mutex.TryLock());
59 }
60 EXPECT_TRUE(test_mutex.TryLock());
61}
Brian Silverman797e71e2013-09-06 17:29:39 -070062
Brian Silvermand41b4422013-09-01 14:02:33 -070063TEST_F(MutexTest, MutexUnlocker) {
64 test_mutex.Lock();
65 {
66 aos::MutexUnlocker unlocker(&test_mutex);
67 // If this fails, then something weird is going on and the next line might
Brian Silverman797e71e2013-09-06 17:29:39 -070068 // hang, so fail immediately.
Brian Silvermand41b4422013-09-01 14:02:33 -070069 ASSERT_TRUE(test_mutex.TryLock());
70 test_mutex.Unlock();
71 }
Brian Silverman08661c72013-09-01 17:24:38 -070072 EXPECT_FALSE(test_mutex.TryLock());
Brian Silvermand41b4422013-09-01 14:02:33 -070073}
74
brians343bc112013-02-10 01:53:46 +000075} // namespace testing
76} // namespace aos