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