2 * Copyright 2015 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 * Licensed to the Apache Software Foundation (ASF) under one
18 * or more contributor license agreements. See the NOTICE file
19 * distributed with this work for additional information
20 * regarding copyright ownership. The ASF licenses this file
21 * to you under the Apache License, Version 2.0 (the
22 * "License"); you may not use this file except in compliance
23 * with the License. You may obtain a copy of the License at
25 * http://www.apache.org/licenses/LICENSE-2.0
27 * Unless required by applicable law or agreed to in writing,
28 * software distributed under the License is distributed on an
29 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
30 * KIND, either express or implied. See the License for the
31 * specific language governing permissions and limitations
35 #include <folly/io/async/EventBaseLocal.h>
36 #include <folly/io/async/test/Util.h>
37 #include <gtest/gtest.h>
40 Foo(int n, std::function<void()> dtorFn):
41 n(n), dtorFn(std::move(dtorFn)) {}
45 std::function<void()> dtorFn;
48 TEST(EventBaseLocalTest, Basic) {
50 folly::EventBase evb1;
53 folly::EventBaseLocal<Foo> foo;
55 EXPECT_EQ(foo.get(evb1), nullptr);
57 foo.emplace(evb1, new Foo(5, [&] () { ++dtorCnt; }));
59 EXPECT_EQ(foo.get(evb1)->n, 5);
62 folly::EventBase evb2;
63 foo.emplace(evb2, new Foo(6, [&] () { ++dtorCnt; }));
64 EXPECT_EQ(foo.get(evb2)->n, 6);
66 EXPECT_EQ(dtorCnt, 1); // should dtor a Foo when we erase
67 EXPECT_EQ(foo.get(evb2), nullptr);
68 foo.emplace(evb2, 7, [&] () { ++dtorCnt; });
69 EXPECT_EQ(foo.get(evb2)->n, 7);
72 EXPECT_EQ(dtorCnt, 2); // should dtor a Foo when evb2 destructs
75 EXPECT_EQ(dtorCnt, 3); // should dtor a Foo when foo destructs
78 TEST(EventBaseLocalTest, getOrCreate) {
79 folly::EventBase evb1;
80 folly::EventBaseLocal<int> ints;
82 EXPECT_EQ(ints.getOrCreate(evb1), 0);
83 EXPECT_EQ(ints.getOrCreate(evb1, 5), 0);
85 folly::EventBase evb2;
86 EXPECT_EQ(ints.getOrCreate(evb2, 5), 5);
88 auto creator = []() { return new int(4); };
89 EXPECT_EQ(ints.getOrCreateFn(evb2, creator), 4);