2 * Copyright 2004-present Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <folly/io/async/EventBaseLocal.h>
18 #include <folly/portability/GTest.h>
21 Foo(int n, std::function<void()> dtorFn):
22 n(n), dtorFn(std::move(dtorFn)) {}
26 std::function<void()> dtorFn;
29 TEST(EventBaseLocalTest, Basic) {
31 folly::EventBase evb1;
34 folly::EventBaseLocal<Foo> foo;
36 EXPECT_EQ(foo.get(evb1), nullptr);
38 foo.emplace(evb1, new Foo(5, [&] () { ++dtorCnt; }));
40 EXPECT_EQ(foo.get(evb1)->n, 5);
43 folly::EventBase evb2;
44 foo.emplace(evb2, new Foo(6, [&] () { ++dtorCnt; }));
45 EXPECT_EQ(foo.get(evb2)->n, 6);
47 EXPECT_EQ(dtorCnt, 1); // should dtor a Foo when we erase
48 EXPECT_EQ(foo.get(evb2), nullptr);
49 foo.emplace(evb2, 7, [&] () { ++dtorCnt; });
50 EXPECT_EQ(foo.get(evb2)->n, 7);
53 EXPECT_EQ(dtorCnt, 2); // should dtor a Foo when evb2 destructs
56 EXPECT_EQ(dtorCnt, 2); // should schedule Foo destructor, when foo destructs
58 EXPECT_EQ(dtorCnt, 3); // Foo will be destroyed in EventBase loop
61 TEST(EventBaseLocalTest, getOrCreate) {
62 folly::EventBase evb1;
63 folly::EventBaseLocal<int> ints;
65 EXPECT_EQ(ints.getOrCreate(evb1), 0);
66 EXPECT_EQ(ints.getOrCreate(evb1, 5), 0);
68 folly::EventBase evb2;
69 EXPECT_EQ(ints.getOrCreate(evb2, 5), 5);
71 auto creator = []() { return new int(4); };
72 EXPECT_EQ(ints.getOrCreateFn(evb2, creator), 4);
75 using IntPtr = std::unique_ptr<int>;
77 TEST(EventBaseLocalTest, getOrCreateNoncopyable) {
78 folly::EventBase evb1;
79 folly::EventBaseLocal<IntPtr> ints;
81 EXPECT_EQ(ints.getOrCreate(evb1), IntPtr());
82 EXPECT_EQ(ints.getOrCreate(evb1, std::make_unique<int>(5)), IntPtr());
84 folly::EventBase evb2;
85 EXPECT_EQ(*ints.getOrCreate(evb2, std::make_unique<int>(5)), 5);
88 TEST(EventBaseLocalTest, emplaceNoncopyable) {
90 folly::EventBaseLocal<IntPtr> ints;
91 ints.emplace(evb, std::make_unique<int>(42));
92 EXPECT_EQ(42, **ints.get(evb));