Codemod folly::make_unique to std::make_unique
[folly.git] / folly / test / TryTest.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/Memory.h>
18 #include <folly/Try.h>
19 #include <folly/portability/GTest.h>
20
21 using namespace folly;
22
23 TEST(Try, basic) {
24   class A {
25    public:
26     A(int x) : x_(x) {}
27
28     int x() const {
29       return x_;
30     }
31    private:
32     int x_;
33   };
34
35   A a(5);
36   Try<A> t_a(std::move(a));
37
38   Try<Unit> t_void;
39
40   EXPECT_EQ(5, t_a.value().x());
41 }
42
43 // Make sure we can copy Trys for copyable types
44 TEST(Try, copy) {
45   Try<int> t;
46   auto t2 = t;
47 }
48
49 // But don't choke on move-only types
50 TEST(Try, moveOnly) {
51   Try<std::unique_ptr<int>> t;
52   std::vector<Try<std::unique_ptr<int>>> v;
53   v.reserve(10);
54 }
55
56 TEST(Try, makeTryWith) {
57   auto func = []() {
58     return std::make_unique<int>(1);
59   };
60
61   auto result = makeTryWith(func);
62   EXPECT_TRUE(result.hasValue());
63   EXPECT_EQ(*result.value(), 1);
64 }
65
66 TEST(Try, makeTryWithThrow) {
67   auto func = []() -> std::unique_ptr<int> {
68     throw std::runtime_error("Runtime");
69   };
70
71   auto result = makeTryWith(func);
72   EXPECT_TRUE(result.hasException<std::runtime_error>());
73 }
74
75 TEST(Try, makeTryWithVoid) {
76   auto func = []() {
77     return;
78   };
79
80   auto result = makeTryWith(func);
81   EXPECT_TRUE(result.hasValue());
82 }
83
84 TEST(Try, makeTryWithVoidThrow) {
85   auto func = []() {
86     throw std::runtime_error("Runtime");
87   };
88
89   auto result = makeTryWith(func);
90   EXPECT_TRUE(result.hasException<std::runtime_error>());
91 }