1/*
2 * Copyright 2016-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/executors/InlineExecutor.h>
18#include <folly/futures/Future.h>
19#include <folly/portability/GTest.h>
20
21using namespace folly;
22
23TEST(SelfDestruct, then) {
24 auto* p = new Promise<int>();
25 auto future = p->getFuture().thenValue([p](int x) {
26 delete p;
27 return x + 1;
28 });
29 p->setValue(123);
30 EXPECT_EQ(124, std::move(future).get());
31}
32
33TEST(SelfDestruct, ensure) {
34 auto* p = new Promise<int>();
35 auto future = p->getFuture().ensure([p] { delete p; });
36 p->setValue(123);
37 EXPECT_EQ(123, std::move(future).get());
38}
39
40class ThrowingExecutorError : public std::runtime_error {
41 public:
42 using std::runtime_error::runtime_error;
43};
44
45class ThrowingExecutor : public folly::Executor {
46 public:
47 void add(folly::Func) override {
48 throw ThrowingExecutorError("ThrowingExecutor::add");
49 }
50};
51
52TEST(SelfDestruct, throwingExecutor) {
53 ThrowingExecutor executor;
54 auto* p = new Promise<int>();
55 auto future =
56 p->getFuture().via(&executor).onError([p](ThrowingExecutorError const&) {
57 delete p;
58 return 456;
59 });
60 p->setValue(123);
61 EXPECT_EQ(456, std::move(future).get());
62}
63
64TEST(SelfDestruct, throwingInlineExecutor) {
65 InlineExecutor executor;
66
67 auto* p = new Promise<int>();
68 auto future = p->getFuture()
69 .via(&executor)
70 .thenValue([p](auto &&) -> int {
71 delete p;
72 throw ThrowingExecutorError("callback throws");
73 })
74 .onError([](ThrowingExecutorError const&) { return 456; });
75 p->setValue(123);
76 EXPECT_EQ(456, std::move(future).get());
77}
78