06484cfc3edbefb90c14e57a726b7c45acbcf14b
[folly.git] / folly / executors / test / GlobalExecutorTest.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/executors/GlobalExecutor.h>
18 #include <folly/executors/IOExecutor.h>
19 #include <gtest/gtest.h>
20
21 using namespace folly;
22
23 TEST(GlobalExecutorTest, GlobalCPUExecutor) {
24   class DummyExecutor : public folly::Executor {
25    public:
26     void add(Func f) override {
27       f();
28       count++;
29     }
30     int count{0};
31   };
32
33   // The default CPU executor is a synchronous inline executor, lets verify
34   // that work we add is executed
35   auto count = 0;
36   auto f = [&]() { count++; };
37
38   // Don't explode, we should create the default global CPUExecutor lazily here.
39   getCPUExecutor()->add(f);
40   EXPECT_EQ(1, count);
41
42   {
43     auto dummy = std::make_shared<DummyExecutor>();
44     setCPUExecutor(dummy);
45     getCPUExecutor()->add(f);
46     // Make sure we were properly installed.
47     EXPECT_EQ(1, dummy->count);
48     EXPECT_EQ(2, count);
49   }
50
51   // Don't explode, we should restore the default global CPUExecutor because our
52   // weak reference to dummy has expired
53   getCPUExecutor()->add(f);
54   EXPECT_EQ(3, count);
55 }
56
57 TEST(GlobalExecutorTest, GlobalIOExecutor) {
58   class DummyExecutor : public IOExecutor {
59    public:
60     void add(Func) override {
61       count++;
62     }
63     folly::EventBase* getEventBase() override {
64       return nullptr;
65     }
66     int count{0};
67   };
68
69   auto f = []() {};
70
71   // Don't explode, we should create the default global IOExecutor lazily here.
72   getIOExecutor()->add(f);
73
74   {
75     auto dummy = std::make_shared<DummyExecutor>();
76     setIOExecutor(dummy);
77     getIOExecutor()->add(f);
78     // Make sure we were properly installed.
79     EXPECT_EQ(1, dummy->count);
80   }
81
82   // Don't explode, we should restore the default global IOExecutor because our
83   // weak reference to dummy has expired
84   getIOExecutor()->add(f);
85 }