fix a multiline comment warning
[folly.git] / folly / test / OptionalCoroutinesTest.cpp
1 /*
2  * Copyright 2017-present 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/ScopeGuard.h>
20 #include <folly/portability/GTest.h>
21
22 #if FOLLY_HAS_COROUTINES
23 using folly::Optional;
24
25 Optional<int> f1() {
26   return 7;
27 }
28 Optional<double> f2(int x) {
29   return 2.0 * x;
30 }
31
32 // move-only type
33 Optional<std::unique_ptr<int>> f3(int x, double y) {
34   return std::make_unique<int>((int)(x + y));
35 }
36
37 TEST(Optional, CoroutineSuccess) {
38   auto r0 = []() -> Optional<int> {
39     auto x = co_await f1();
40     EXPECT_EQ(7, x);
41     auto y = co_await f2(x);
42     EXPECT_EQ(2.0 * 7, y);
43     auto z = co_await f3(x, y);
44     EXPECT_EQ((int)(2.0 * 7 + 7), *z);
45     co_return* z;
46   }();
47   EXPECT_TRUE(r0.hasValue());
48   EXPECT_EQ(21, *r0);
49 }
50
51 Optional<int> f4(int, double) {
52   return folly::none;
53 }
54
55 TEST(Optional, CoroutineFailure) {
56   auto r1 = []() -> Optional<int> {
57     auto x = co_await f1();
58     auto y = co_await f2(x);
59     auto z = co_await f4(x, y);
60     ADD_FAILURE();
61     co_return z;
62   }();
63   EXPECT_TRUE(!r1.hasValue());
64 }
65
66 Optional<int> throws() {
67   throw 42;
68 }
69
70 TEST(Optional, CoroutineException) {
71   try {
72     auto r2 = []() -> Optional<int> {
73       auto x = co_await throws();
74       ADD_FAILURE();
75       co_return x;
76     }();
77     (void)r2;
78     ADD_FAILURE();
79   } catch (/* nolint */ int i) {
80     EXPECT_EQ(42, i);
81   } catch (...) {
82     ADD_FAILURE();
83   }
84 }
85
86 // this test makes sure that the coroutine is destroyed properly
87 TEST(Optional, CoroutineCleanedUp) {
88   int count_dest = 0;
89   auto r = [&]() -> Optional<int> {
90     SCOPE_EXIT {
91       ++count_dest;
92     };
93     auto x = co_await folly::Optional<int>();
94     ADD_FAILURE() << "Should not be resuming";
95     co_return x;
96   }();
97   EXPECT_FALSE(r.hasValue());
98   EXPECT_EQ(1, count_dest);
99 }
100
101 #endif