2 * Copyright 2016 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/MapUtil.h>
20 #include <gtest/gtest.h>
22 using namespace folly;
24 TEST(MapUtil, get_default) {
27 EXPECT_EQ(2, get_default(m, 1, 42));
28 EXPECT_EQ(42, get_default(m, 2, 42));
29 EXPECT_EQ(0, get_default(m, 3));
32 TEST(MapUtil, get_default_function) {
35 EXPECT_EQ(2, get_default(m, 1, [] { return 42; }));
36 EXPECT_EQ(42, get_default(m, 2, [] { return 42; }));
37 EXPECT_EQ(0, get_default(m, 3));
40 TEST(MapUtil, get_or_throw) {
43 EXPECT_EQ(2, get_or_throw(m, 1));
44 EXPECT_THROW(get_or_throw(m, 2), std::out_of_range);
45 EXPECT_EQ(&m[1], &get_or_throw(m, 1));
46 get_or_throw(m, 1) = 3;
47 EXPECT_EQ(3, get_or_throw(m, 1));
49 EXPECT_EQ(&m[1], &get_or_throw(cm, 1));
50 EXPECT_EQ(3, get_or_throw(cm, 1));
51 EXPECT_THROW(get_or_throw(cm, 2), std::out_of_range);
54 TEST(MapUtil, get_or_throw_specified) {
57 EXPECT_EQ(2, get_or_throw<std::runtime_error>(m, 1));
58 EXPECT_THROW(get_or_throw<std::runtime_error>(m, 2), std::runtime_error);
61 TEST(MapUtil, get_optional) {
64 EXPECT_TRUE(get_optional(m, 1).hasValue());
65 EXPECT_EQ(2, get_optional(m, 1).value());
66 EXPECT_FALSE(get_optional(m, 2).hasValue());
69 TEST(MapUtil, get_ref_default) {
73 EXPECT_EQ(2, get_ref_default(m, 1, i));
74 EXPECT_EQ(42, get_ref_default(m, 2, i));
75 EXPECT_EQ(std::addressof(i), std::addressof(get_ref_default(m, 2, i)));
78 TEST(MapUtil, get_ref_default_function) {
82 EXPECT_EQ(2, get_ref_default(m, 1, [&i]() -> const int& { return i; }));
83 EXPECT_EQ(42, get_ref_default(m, 2, [&i]() -> const int& { return i; }));
87 get_ref_default(m, 2, [&i]() -> const int& { return i; })));
88 // statically disallowed:
89 // get_ref_default(m, 2, [] { return 7; });
92 TEST(MapUtil, get_ptr) {
95 EXPECT_EQ(2, *get_ptr(m, 1));
96 EXPECT_TRUE(get_ptr(m, 2) == nullptr);
98 EXPECT_EQ(4, m.at(1));