blob: f946dfa315045668e065d615d09321ab18f820df [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 Silverman14fd0fb2014-01-14 21:42:01 -080012#include "aos/linux_code/ipc_lib/aos_sync.h"
Brian Silverman8d2e56e2013-09-23 17:55:03 -070013#include "aos/common/die.h"
Brian Silvermand41b4422013-09-01 14:02:33 -070014
brians343bc112013-02-10 01:53:46 +000015namespace aos {
16namespace testing {
17
18class MutexTest : public ::testing::Test {
19 public:
20 Mutex test_mutex;
Brian Silverman8d2e56e2013-09-23 17:55:03 -070021
22 protected:
23 void SetUp() override {
24 SetDieTestMode(true);
25 }
brians343bc112013-02-10 01:53:46 +000026};
27
28typedef MutexTest MutexDeathTest;
29
30TEST_F(MutexTest, TryLock) {
31 EXPECT_TRUE(test_mutex.TryLock());
32 EXPECT_FALSE(test_mutex.TryLock());
33}
34
35TEST_F(MutexTest, Lock) {
36 test_mutex.Lock();
37 EXPECT_FALSE(test_mutex.TryLock());
38}
39
40TEST_F(MutexTest, Unlock) {
41 test_mutex.Lock();
42 EXPECT_FALSE(test_mutex.TryLock());
43 test_mutex.Unlock();
44 EXPECT_TRUE(test_mutex.TryLock());
45}
46
47#ifndef __VXWORKS__
48// Sees what happens with multiple unlocks.
49TEST_F(MutexDeathTest, RepeatUnlock) {
50 test_mutex.Lock();
51 test_mutex.Unlock();
52 EXPECT_DEATH(test_mutex.Unlock(), ".*multiple unlock.*");
53}
54
55// Sees what happens if you unlock without ever locking (or unlocking) it.
56TEST_F(MutexDeathTest, NeverLock) {
57 EXPECT_DEATH(test_mutex.Unlock(), ".*multiple unlock.*");
58}
59#endif
60
61TEST_F(MutexTest, MutexLocker) {
62 {
63 aos::MutexLocker locker(&test_mutex);
64 EXPECT_FALSE(test_mutex.TryLock());
65 }
66 EXPECT_TRUE(test_mutex.TryLock());
67}
Brian Silverman797e71e2013-09-06 17:29:39 -070068
Brian Silvermand41b4422013-09-01 14:02:33 -070069TEST_F(MutexTest, MutexUnlocker) {
70 test_mutex.Lock();
71 {
72 aos::MutexUnlocker unlocker(&test_mutex);
73 // If this fails, then something weird is going on and the next line might
Brian Silverman797e71e2013-09-06 17:29:39 -070074 // hang, so fail immediately.
Brian Silvermand41b4422013-09-01 14:02:33 -070075 ASSERT_TRUE(test_mutex.TryLock());
76 test_mutex.Unlock();
77 }
Brian Silverman08661c72013-09-01 17:24:38 -070078 EXPECT_FALSE(test_mutex.TryLock());
Brian Silvermand41b4422013-09-01 14:02:33 -070079}
80
brians343bc112013-02-10 01:53:46 +000081} // namespace testing
82} // namespace aos