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