support using co_await with folly::Optional when it is available
[folly.git] / folly / test / OptionalCoroutinesTest.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/Optional.h>
18 #include <folly/Portability.h>
19 #include <folly/portability/GTest.h>
20
21 #if FOLLY_HAS_COROUTINES
22 using folly::Optional;
23
24 Optional<int> f1() {
25   return 7;
26 }
27 Optional<double> f2(int x) {
28   return 2.0 * x;
29 }
30 Optional<int> f3(int x, double y) {
31   return (int)(x + y);
32 }
33
34 TEST(Optional, CoroutineSuccess) {
35   auto r0 = []() -> Optional<int> {
36     auto x = co_await f1();
37     EXPECT_EQ(7, x);
38     auto y = co_await f2(x);
39     EXPECT_EQ(2.0 * 7, y);
40     auto z = co_await f3(x, y);
41     EXPECT_EQ((int)(2.0 * 7 + 7), z);
42     co_return z;
43   }();
44   EXPECT_TRUE(r0.hasValue());
45   EXPECT_EQ(21, *r0);
46 }
47
48 Optional<int> f4(int, double) {
49   return folly::none;
50 }
51
52 TEST(Optional, CoroutineFailure) {
53   auto r1 = []() -> Optional<int> {
54     auto x = co_await f1();
55     auto y = co_await f2(x);
56     auto z = co_await f4(x, y);
57     EXPECT_FALSE(true);
58     co_return z;
59   }();
60   EXPECT_TRUE(!r1.hasValue());
61 }
62
63 Optional<int> throws() {
64   throw 42;
65 }
66
67 TEST(Optional, CoroutineException) {
68   try {
69     auto r2 = []() -> Optional<int> {
70       auto x = co_await throws();
71       EXPECT_FALSE(true);
72       co_return x;
73     }();
74     EXPECT_FALSE(true);
75   } catch (/* nolint */ int i) {
76     EXPECT_EQ(42, i);
77   } catch (...) {
78     EXPECT_FALSE(true);
79   }
80 }
81 #endif