2 * Copyright 2017 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/Optional.h>
18 #include <folly/Portability.h>
19 #include <folly/ScopeGuard.h>
20 #include <folly/portability/GTest.h>
22 #if FOLLY_HAS_COROUTINES
23 using folly::Optional;
28 Optional<double> f2(int x) {
33 Optional<std::unique_ptr<int>> f3(int x, double y) {
34 return std::make_unique<int>((int)(x + y));
37 TEST(Optional, CoroutineSuccess) {
38 auto r0 = []() -> Optional<int> {
39 auto x = co_await f1();
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);
47 EXPECT_TRUE(r0.hasValue());
51 Optional<int> f4(int, double) {
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);
63 EXPECT_TRUE(!r1.hasValue());
66 Optional<int> throws() {
70 TEST(Optional, CoroutineException) {
72 auto r2 = []() -> Optional<int> {
73 auto x = co_await throws();
79 } catch (/* nolint */ int i) {
86 // this test makes sure that the coroutine is destroyed properly
87 TEST(Optional, CoroutineCleanedUp) {
89 auto r = [&]() -> Optional<int> {
93 auto x = co_await folly::Optional<int>();
94 ADD_FAILURE() << "Should not be resuming";
97 EXPECT_FALSE(r.hasValue());
98 EXPECT_EQ(1, count_dest);