blob: 0d8a0593bf6df60a7bfebdfacf9ba01cd0bc1745 [file] [log] [blame]
Ewout van Bekkum126e0112021-03-12 10:59:49 -08001// Copyright 2020 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15#include "gtest/gtest.h"
16#include "pw_sync/interrupt_spin_lock.h"
17
18namespace pw::sync {
19namespace {
20
21extern "C" {
22
23// Functions defined in interrupt_spin_lock_facade_test_c.c which call the API
24// from C.
25void pw_sync_InterruptSpinLock_CallLock(
26 pw_sync_InterruptSpinLock* interrupt_spin_lock);
27bool pw_sync_InterruptSpinLock_CallTryLock(
28 pw_sync_InterruptSpinLock* interrupt_spin_lock);
29void pw_sync_InterruptSpinLock_CallUnlock(
30 pw_sync_InterruptSpinLock* interrupt_spin_lock);
31
32} // extern "C"
33
34TEST(InterruptSpinLock, LockUnlock) {
35 pw::sync::InterruptSpinLock interrupt_spin_lock;
36 interrupt_spin_lock.lock();
37 interrupt_spin_lock.unlock();
38}
39
40// TODO(pwbug/291): Add real concurrency tests once we have pw::thread.
41
42InterruptSpinLock static_interrupt_spin_lock;
43TEST(InterruptSpinLock, LockUnlockStatic) {
44 static_interrupt_spin_lock.lock();
45 // Ensure it fails to lock when already held.
46 EXPECT_FALSE(static_interrupt_spin_lock.try_lock());
47 static_interrupt_spin_lock.unlock();
48}
49
50TEST(InterruptSpinLock, TryLockUnlock) {
51 pw::sync::InterruptSpinLock interrupt_spin_lock;
Ewout van Bekkumcc9ef832021-04-08 08:51:16 -070052 const bool locked = interrupt_spin_lock.try_lock();
53 EXPECT_TRUE(locked);
54 if (locked) {
55 // Ensure it fails to lock when already held.
56 EXPECT_FALSE(interrupt_spin_lock.try_lock());
57 interrupt_spin_lock.unlock();
58 }
Ewout van Bekkum126e0112021-03-12 10:59:49 -080059}
60
61TEST(InterruptSpinLock, LockUnlockInC) {
62 pw::sync::InterruptSpinLock interrupt_spin_lock;
63 pw_sync_InterruptSpinLock_CallLock(&interrupt_spin_lock);
64 pw_sync_InterruptSpinLock_CallUnlock(&interrupt_spin_lock);
65}
66
67TEST(InterruptSpinLock, TryLockUnlockInC) {
68 pw::sync::InterruptSpinLock interrupt_spin_lock;
69 ASSERT_TRUE(pw_sync_InterruptSpinLock_CallTryLock(&interrupt_spin_lock));
70 // Ensure it fails to lock when already held.
71 EXPECT_FALSE(pw_sync_InterruptSpinLock_CallTryLock(&interrupt_spin_lock));
72 pw_sync_InterruptSpinLock_CallUnlock(&interrupt_spin_lock);
73}
74
75} // namespace
76} // namespace pw::sync