xref: /aosp_15_r20/external/grpc-grpc/test/core/promise/promise_mutex_test.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 // Copyright 2023 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://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,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "src/core/lib/promise/promise_mutex.h"
16 
17 #include <memory>
18 #include <optional>
19 
20 #include "absl/status/status.h"
21 #include "gtest/gtest.h"
22 
23 #include "src/core/lib/promise/activity.h"
24 #include "src/core/lib/promise/join.h"
25 #include "src/core/lib/promise/promise.h"
26 #include "src/core/lib/promise/seq.h"
27 #include "test/core/promise/test_wakeup_schedulers.h"
28 
29 namespace grpc_core {
30 namespace {
31 
TEST(PromiseMutexTest,Basic)32 TEST(PromiseMutexTest, Basic) {
33   PromiseMutex<int> mutex{1};
34   bool done = false;
35   MakeActivity(
36       [&]() {
37         return Seq(Join(Seq(mutex.Acquire(),
38                             [](PromiseMutex<int>::Lock l) {
39                               EXPECT_EQ(*l, 1);
40                               *l = 2;
41                               return Empty{};
42                             }),
43                         Seq(mutex.Acquire(),
44                             [](PromiseMutex<int>::Lock l) {
45                               EXPECT_EQ(*l, 2);
46                               *l = 3;
47                               return Empty{};
48                             }),
49                         Seq(mutex.Acquire(),
50                             [](PromiseMutex<int>::Lock l) {
51                               EXPECT_EQ(*l, 3);
52                               return Empty{};
53                             })),
54                    []() { return absl::OkStatus(); });
55       },
56       InlineWakeupScheduler(),
57       [&done](absl::Status status) {
58         EXPECT_TRUE(status.ok());
59         done = true;
60       });
61   EXPECT_TRUE(done);
62   EXPECT_EQ(**NowOrNever(mutex.Acquire()), 3);
63 }
64 
65 }  // namespace
66 }  // namespace grpc_core
67 
main(int argc,char ** argv)68 int main(int argc, char** argv) {
69   ::testing::InitGoogleTest(&argc, argv);
70   return RUN_ALL_TESTS();
71 }
72