2 * Copyright 2016 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 <gtest/gtest.h>
19 #include <folly/futures/Future.h>
21 using namespace folly;
23 TEST(NonCopyableLambda, basic) {
25 Future<int> future = promise.getFuture();
27 Future<Unit>().then(std::bind(
28 [](Promise<int>& promise) mutable { promise.setValue(123); },
31 // The previous statement can be simplified in C++14:
32 // Future<Unit>().then([promise = std::move(promise)]() mutable {
33 // promise.setValue(123);
36 EXPECT_TRUE(future.isReady());
37 EXPECT_EQ(future.get(), 123);
40 TEST(NonCopyableLambda, unique_ptr) {
41 Promise<Unit> promise;
42 auto int_ptr = folly::make_unique<int>(1);
44 EXPECT_EQ(*int_ptr, 1);
46 auto future = promise.getFuture().then(std::bind(
47 [](std::unique_ptr<int>& int_ptr) mutable {
49 return std::move(int_ptr);
53 // The previous statement can be simplified in C++14:
55 // promise.getFuture().then([int_ptr = std::move(int_ptr)]() mutable {
57 // return std::move(int_ptr);
60 EXPECT_FALSE(future.isReady());
62 EXPECT_TRUE(future.isReady());
63 EXPECT_EQ(*future.get(), 2);
66 TEST(NonCopyableLambda, Function) {
69 Function<int(int)> callback = [](int x) { return x + 1; };
71 auto future = promise.getFuture().then(std::move(callback));
72 EXPECT_THROW(callback(0), std::bad_function_call);
74 EXPECT_FALSE(future.isReady());
75 promise.setValue(100);
76 EXPECT_TRUE(future.isReady());
77 EXPECT_EQ(future.get(), 101);
80 TEST(NonCopyableLambda, FunctionConst) {
83 Function<int(int) const> callback = [](int x) { return x + 1; };
85 auto future = promise.getFuture().then(std::move(callback));
86 EXPECT_THROW(callback(0), std::bad_function_call);
88 EXPECT_FALSE(future.isReady());
89 promise.setValue(100);
90 EXPECT_TRUE(future.isReady());
91 EXPECT_EQ(future.get(), 101);