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