1 // Copyright 2022 The 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 <memory>
16
17 #include "gtest/gtest.h"
18
19 #include <grpc/event_engine/event_engine.h>
20 #include <grpc/grpc.h>
21 #include <grpc/support/port_platform.h>
22
23 #include "src/core/lib/event_engine/default_event_engine.h"
24 #include "test/core/event_engine/util/aborting_event_engine.h"
25 #include "test/core/util/test_config.h"
26
27 namespace {
28 using ::grpc_event_engine::experimental::AbortingEventEngine;
29 using ::grpc_event_engine::experimental::EventEngine;
30 using ::grpc_event_engine::experimental::EventEngineFactoryReset;
31 using ::grpc_event_engine::experimental::GetDefaultEventEngine;
32 using ::grpc_event_engine::experimental::SetEventEngineFactory;
33
34 class EventEngineFactoryTest : public testing::Test {
35 public:
36 EventEngineFactoryTest() = default;
~EventEngineFactoryTest()37 ~EventEngineFactoryTest() override { EventEngineFactoryReset(); }
38 };
39
TEST_F(EventEngineFactoryTest,CustomFactoryIsUsed)40 TEST_F(EventEngineFactoryTest, CustomFactoryIsUsed) {
41 int counter{0};
42 SetEventEngineFactory([&counter] {
43 ++counter;
44 return std::make_unique<AbortingEventEngine>();
45 });
46 auto ee1 = GetDefaultEventEngine();
47 ASSERT_EQ(counter, 1);
48 auto ee2 = GetDefaultEventEngine();
49 ASSERT_EQ(counter, 1);
50 ASSERT_EQ(ee1, ee2);
51 }
52
TEST_F(EventEngineFactoryTest,FactoryResetWorks)53 TEST_F(EventEngineFactoryTest, FactoryResetWorks) {
54 int counter{0};
55 SetEventEngineFactory([&counter]() -> std::unique_ptr<EventEngine> {
56 // this factory should only be used twice;
57 EXPECT_LE(++counter, 2);
58 return std::make_unique<AbortingEventEngine>();
59 });
60 auto custom_ee = GetDefaultEventEngine();
61 ASSERT_EQ(counter, 1);
62 auto same_ee = GetDefaultEventEngine();
63 ASSERT_EQ(custom_ee, same_ee);
64 ASSERT_EQ(counter, 1);
65 EventEngineFactoryReset();
66 auto default_ee = GetDefaultEventEngine();
67 ASSERT_NE(custom_ee, default_ee);
68 }
69 } // namespace
70
main(int argc,char ** argv)71 int main(int argc, char** argv) {
72 testing::InitGoogleTest(&argc, argv);
73 grpc::testing::TestEnvironment env(&argc, argv);
74 grpc_init();
75 auto result = RUN_ALL_TESTS();
76 grpc_shutdown();
77 return result;
78 }
79