3f6ea12ba170709e33e960084732ead9e40853c9
[folly.git] / folly / futures / exercises / 01-Values.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 #include "Koan.h"
17 #include <folly/futures/Future.h>
18
19 using folly::Future;
20 using folly::makeFuture;
21
22 #if 0 // compilation cursor
23
24 TEST(Values, canonicalForm) {
25   // The canonical way to make a Future from an immediate value is with the
26   // Future constructor.
27   Future<int> answer(__);
28   EXPECT_EQ(42, answer.get());
29 }
30
31 TEST(Values, typeDeduction) {
32   // If you use makeFuture, the compiler will deduce the type.
33   auto answer = makeFuture(__);
34   EXPECT_EQ(42, answer.get());
35 }
36
37 TEST(Values, exceptionNeedsType) {
38   // To create a Future holding an exception, you must
39   // use makeFuture with the type
40   std::runtime_error err("Don't Panic");
41   auto question = __(err);
42   // not
43   //auto question = makeFuture(err);
44   EXPECT_THROW(question.get(), std::runtime_error);
45 }
46
47 TEST(Values, typeConversion) {
48   // Sometimes it's cleaner to give the type and let the compiler do implicit
49   // type conversion
50   __ answer(42);
51   // not
52   //auto answer = makeFuture((double)42);
53   EXPECT_EQ(__, answer.get());
54 }
55
56 using folly::Try;
57
58 TEST(Values, tryInside) {
59   // Futures hold either a Value or Exception. This is accomplished under the
60   // covers with Try
61   Try<int> t = makeFuture(42).__();
62   EXPECT_TRUE(t.hasValue());
63   EXPECT_EQ(42, t.value());
64
65   t = Future<int>(std::runtime_error("Don't Panic")).__();
66   EXPECT_TRUE(t.hasException());
67   EXPECT_THROW(t.value(), std::runtime_error);
68 }
69
70 #endif