xref: /aosp_15_r20/external/pigweed/pw_async2/pend_func_task_test.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2023 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 "pw_async2/pend_func_task.h"
16 
17 #include "pw_async2/dispatcher.h"
18 #include "pw_function/function.h"
19 #include "pw_unit_test/framework.h"
20 
21 namespace {
22 
23 using ::pw::Function;
24 using ::pw::async2::Context;
25 using ::pw::async2::Dispatcher;
26 using ::pw::async2::PendFuncTask;
27 using ::pw::async2::Pending;
28 using ::pw::async2::Poll;
29 using ::pw::async2::Ready;
30 using ::pw::async2::Waker;
31 
TEST(PendFuncTask,PendDelegatesToFunc)32 TEST(PendFuncTask, PendDelegatesToFunc) {
33   Dispatcher dispatcher;
34 
35   Waker waker;
36   int poll_count = 0;
37   bool allow_completion = false;
38 
39   PendFuncTask func_task([&](Context& cx) -> Poll<> {
40     ++poll_count;
41     if (allow_completion) {
42       return Ready();
43     }
44     PW_ASYNC_STORE_WAKER(cx, waker, "func_task is waiting for waker");
45     return Pending();
46   });
47 
48   dispatcher.Post(func_task);
49 
50   EXPECT_EQ(poll_count, 0);
51   EXPECT_EQ(dispatcher.RunUntilStalled(), Pending());
52   EXPECT_EQ(poll_count, 1);
53 
54   // Unwoken task is not polled.
55   EXPECT_EQ(dispatcher.RunUntilStalled(), Pending());
56   EXPECT_EQ(poll_count, 1);
57 
58   std::move(waker).Wake();
59   allow_completion = true;
60   EXPECT_EQ(dispatcher.RunUntilStalled(), Ready());
61   EXPECT_EQ(poll_count, 2);
62 }
63 
TEST(PendFuncTask,HoldsCallableByDefault)64 TEST(PendFuncTask, HoldsCallableByDefault) {
65   auto callable = [](Context&) -> Poll<> { return Ready(); };
66   PendFuncTask func_task(std::move(callable));
67   static_assert(std::is_same<decltype(func_task),
68                              PendFuncTask<decltype(callable)>>::value);
69 }
70 
TEST(PendFuncTask,HoldsPwFunctionWithEmptyTypeList)71 TEST(PendFuncTask, HoldsPwFunctionWithEmptyTypeList) {
72   PendFuncTask<> func_task([](Context&) -> Poll<> { return Ready(); });
73   static_assert(std::is_same<decltype(func_task),
74                              PendFuncTask<Function<Poll<>(Context&)>>>::value);
75 }
76 
77 }  // namespace
78