suppress warnings in tests for deprecated functions
[folly.git] / folly / futures / test / NonCopyableLambdaTest.cpp
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/futures/Future.h>
18 #include <folly/portability/GTest.h>
19
20 using namespace folly;
21
22 TEST(NonCopyableLambda, basic) {
23   Promise<int> promise;
24   Future<int> future = promise.getFuture();
25
26   Future<Unit>().then(std::bind(
27       [](Promise<int>& p2) mutable { p2.setValue(123); },
28       std::move(promise)));
29
30   // The previous statement can be simplified in C++14:
31   //  Future<Unit>().then([promise = std::move(promise)]() mutable {
32   //    promise.setValue(123);
33   //  });
34
35   EXPECT_TRUE(future.isReady());
36   EXPECT_EQ(future.get(), 123);
37 }
38
39 TEST(NonCopyableLambda, unique_ptr) {
40   Promise<Unit> promise;
41   auto int_ptr = std::make_unique<int>(1);
42
43   EXPECT_EQ(*int_ptr, 1);
44
45   auto future = promise.getFuture().then(std::bind(
46       [](std::unique_ptr<int>& p) mutable {
47         ++*p;
48         return std::move(p);
49       },
50       std::move(int_ptr)));
51
52   // The previous statement can be simplified in C++14:
53   //  auto future =
54   //      promise.getFuture().then([int_ptr = std::move(int_ptr)]() mutable {
55   //        ++*int_ptr;
56   //        return std::move(int_ptr);
57   //      });
58
59   EXPECT_FALSE(future.isReady());
60   promise.setValue();
61   EXPECT_TRUE(future.isReady());
62   EXPECT_EQ(*future.get(), 2);
63 }
64
65 TEST(NonCopyableLambda, Function) {
66   Promise<int> promise;
67
68   Function<int(int)> callback = [](int x) { return x + 1; };
69
70   auto future = promise.getFuture().then(std::move(callback));
71   EXPECT_THROW(callback(0), std::bad_function_call);
72
73   EXPECT_FALSE(future.isReady());
74   promise.setValue(100);
75   EXPECT_TRUE(future.isReady());
76   EXPECT_EQ(future.get(), 101);
77 }
78
79 TEST(NonCopyableLambda, FunctionConst) {
80   Promise<int> promise;
81
82   Function<int(int) const> callback = [](int x) { return x + 1; };
83
84   auto future = promise.getFuture().then(std::move(callback));
85   EXPECT_THROW(callback(0), std::bad_function_call);
86
87   EXPECT_FALSE(future.isReady());
88   promise.setValue(100);
89   EXPECT_TRUE(future.isReady());
90   EXPECT_EQ(future.get(), 101);
91 }