2 * Copyright 2016-present 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/futures/Future.h>
18 #include <folly/portability/GTest.h>
20 using namespace folly;
22 TEST(NonCopyableLambda, basic) {
24 Future<int> future = promise.getFuture();
26 Future<Unit>().then(std::bind(
27 [](Promise<int>& p2) mutable { p2.setValue(123); },
30 // The previous statement can be simplified in C++14:
31 // Future<Unit>().then([promise = std::move(promise)]() mutable {
32 // promise.setValue(123);
35 EXPECT_TRUE(future.isReady());
36 EXPECT_EQ(future.get(), 123);
39 TEST(NonCopyableLambda, unique_ptr) {
40 Promise<Unit> promise;
41 auto int_ptr = std::make_unique<int>(1);
43 EXPECT_EQ(*int_ptr, 1);
45 auto future = promise.getFuture().then(std::bind(
46 [](std::unique_ptr<int>& p) mutable {
52 // The previous statement can be simplified in C++14:
54 // promise.getFuture().then([int_ptr = std::move(int_ptr)]() mutable {
56 // return std::move(int_ptr);
59 EXPECT_FALSE(future.isReady());
61 EXPECT_TRUE(future.isReady());
62 EXPECT_EQ(*future.get(), 2);
65 TEST(NonCopyableLambda, Function) {
68 Function<int(int)> callback = [](int x) { return x + 1; };
70 auto future = promise.getFuture().then(std::move(callback));
71 EXPECT_THROW(callback(0), std::bad_function_call);
73 EXPECT_FALSE(future.isReady());
74 promise.setValue(100);
75 EXPECT_TRUE(future.isReady());
76 EXPECT_EQ(future.get(), 101);
79 TEST(NonCopyableLambda, FunctionConst) {
82 Function<int(int) const> callback = [](int x) { return x + 1; };
84 auto future = promise.getFuture().then(std::move(callback));
85 EXPECT_THROW(callback(0), std::bad_function_call);
87 EXPECT_FALSE(future.isReady());
88 promise.setValue(100);
89 EXPECT_TRUE(future.isReady());
90 EXPECT_EQ(future.get(), 101);