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_unit_test/framework.h"
19
20 namespace {
21
22 using ::pw::async2::Context;
23 using ::pw::async2::Dispatcher;
24 using ::pw::async2::PendFuncTask;
25 using ::pw::async2::Pending;
26 using ::pw::async2::Poll;
27 using ::pw::async2::Ready;
28 using ::pw::async2::WaitReason;
29 using ::pw::async2::Waker;
30
TEST(PendFuncTask,PendDelegatesToFunc)31 TEST(PendFuncTask, PendDelegatesToFunc) {
32 Dispatcher dispatcher;
33
34 Waker waker;
35 int poll_count = 0;
36 bool allow_completion = false;
37
38 PendFuncTask func_task([&](Context& cx) -> Poll<> {
39 ++poll_count;
40 if (allow_completion) {
41 return Ready();
42 }
43 waker = cx.GetWaker(WaitReason::Unspecified());
44 return Pending();
45 });
46
47 dispatcher.Post(func_task);
48
49 EXPECT_EQ(poll_count, 0);
50 EXPECT_EQ(dispatcher.RunUntilStalled(), Pending());
51 EXPECT_EQ(poll_count, 1);
52
53 // Unwoken task is not polled.
54 EXPECT_EQ(dispatcher.RunUntilStalled(), Pending());
55 EXPECT_EQ(poll_count, 1);
56
57 std::move(waker).Wake();
58 allow_completion = true;
59 EXPECT_EQ(dispatcher.RunUntilStalled(), Ready());
60 EXPECT_EQ(poll_count, 2);
61 }
62
63 } // namespace
64