aboutsummaryrefslogtreecommitdiff
path: root/kernel/kapi/tracked_mutex.tests.cpp
blob: 37493a1bc815ad43bca0d3a880518200409ce1be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <kapi/tracked_mutex.hpp>

#include <kernel/test_support/cpu.hpp>

#include <kstd/mutex.hpp>

#include <catch2/catch_test_macros.hpp>

SCENARIO("Tracked mutex single threaded")
{
  GIVEN("a tracked mutex")
  {
    auto mutex = kapi::tracked_mutex{};

    WHEN("the current thread hasn't locked the mutex")
    {
      THEN("unlocking the mutex panics")
      {
        REQUIRE_THROWS_AS(mutex.unlock(), kernel::tests::cpu::halt);
      }

      THEN("locking the mutex succeeds")
      {
        mutex.lock();
      }

      THEN("locking the mutex using try_lock succeeds")
      {
        REQUIRE(mutex.try_lock());
      }
    }

    WHEN("the current thread has locked the mutex")
    {
      mutex.lock();

      THEN("unlocking the mutex succeeds")
      {
        mutex.unlock();
      }

      THEN("locking the mutex panics")
      {
        REQUIRE_THROWS_AS(mutex.lock(), kernel::tests::cpu::halt);
      }

      THEN("locking the mutex using try_lock fails")
      {
        REQUIRE_FALSE(mutex.try_lock());
      }
    }
  }
}

SCENARIO("Tracked mutex as a lockable for lock_guard")
{
  GIVEN("a tracked mutex")
  {
    auto mutex = kapi::tracked_mutex{};

    WHEN("the current thread hasn't locked the mutex")
    {
      THEN("it can be locked using a lock_guard")
      {
        auto guard = kstd::lock_guard{mutex};
      }
    }

    WHEN("the current thread has locked the mutex")
    {
      mutex.lock();

      THEN("it can be adopted by a lock_guard")
      {
        auto guard = kstd::lock_guard{mutex, kstd::adopt_lock};
      }
    }
  }
}