xref: /aosp_15_r20/external/grpc-grpc/test/core/promise/context_test.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 // Copyright 2021 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/context.h"
16 
17 #include <memory>
18 
19 #include "gtest/gtest.h"
20 
21 namespace grpc_core {
22 
23 struct TestContext {
24   bool done = false;
25 };
26 
27 template <>
28 struct ContextType<TestContext> {};
29 
TEST(Context,WithContext)30 TEST(Context, WithContext) {
31   EXPECT_FALSE(HasContext<TestContext>());
32   TestContext test;
33   EXPECT_FALSE(HasContext<TestContext>());
34   EXPECT_FALSE(test.done);
35   WithContext(
36       []() {
37         EXPECT_TRUE(HasContext<TestContext>());
38         GetContext<TestContext>()->done = true;
39       },
40       &test)();
41   EXPECT_FALSE(HasContext<TestContext>());
42   EXPECT_TRUE(test.done);
43 }
44 
45 class BaseContext {
46  public:
47   virtual int Answer() = 0;
48 
49  protected:
50   ~BaseContext() = default;
51 };
52 
53 class CorrectContext final : public BaseContext {
54  public:
Answer()55   int Answer() override { return 42; }
56 };
57 
58 class IncorrectContext final : public BaseContext {
59  public:
Answer()60   int Answer() override { return 0; }
61 };
62 
63 template <>
64 struct ContextType<BaseContext> {};
65 template <>
66 struct ContextSubclass<CorrectContext> {
67   using Base = BaseContext;
68 };
69 template <>
70 struct ContextSubclass<IncorrectContext> {
71   using Base = BaseContext;
72 };
73 
TEST(Context,ContextSubclass)74 TEST(Context, ContextSubclass) {
75   CorrectContext correct;
76   IncorrectContext incorrect;
77   EXPECT_EQ(42,
78             WithContext([]() { return GetContext<BaseContext>()->Answer(); },
79                         &correct)());
80   EXPECT_EQ(0, WithContext([]() { return GetContext<BaseContext>()->Answer(); },
81                            &incorrect)());
82 }
83 
84 }  // namespace grpc_core
85 
main(int argc,char ** argv)86 int main(int argc, char** argv) {
87   ::testing::InitGoogleTest(&argc, argv);
88   return RUN_ALL_TESTS();
89 }
90