53b15b1b899877e5b166bb8bc7073c8b268d12aa
[folly.git] / folly / futures / test / ConversionTest.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 <type_traits>
21
22 using namespace folly;
23
24 class A {
25  public:
26   virtual ~A() {}
27 };
28
29 class B : public A {
30  public:
31   explicit B(std::string msg) : msg_(msg) {}
32
33   const std::string& getMsg() { return msg_; }
34   std::string msg_;
35 };
36
37 TEST(Convert, subclassConstruct) {
38   Future<std::unique_ptr<A>> future =
39       makeFuture<std::unique_ptr<B>>(folly::make_unique<B>("hello world"));
40   std::unique_ptr<A> a = future.get();
41   A* aptr = a.get();
42   B* b = dynamic_cast<B*>(aptr);
43   EXPECT_NE(nullptr, b);
44   EXPECT_EQ("hello world", b->getMsg());
45 }
46
47 TEST(Convert, subclassAssign) {
48   Future<std::unique_ptr<B>> f1 =
49       makeFuture<std::unique_ptr<B>>(folly::make_unique<B>("hello world"));
50   Future<std::unique_ptr<A>> f2 = std::move(f1);
51   std::unique_ptr<A> a = f2.get();
52   A* aptr = a.get();
53   B* b = dynamic_cast<B*>(aptr);
54   EXPECT_NE(nullptr, b);
55   EXPECT_EQ("hello world", b->getMsg());
56 }
57
58 TEST(Convert, ConversionTests) {
59   static_assert(std::is_convertible<Future<std::unique_ptr<B>>,
60                                     Future<std::unique_ptr<A>>>::value,
61                 "Unique ptr not convertible");
62   static_assert(!std::is_convertible<Future<std::unique_ptr<A>>,
63                                      Future<std::unique_ptr<B>>>::value,
64                 "Underlying types are not convertible");
65   static_assert(!std::is_convertible<Future<B>, Future<A>>::value,
66                 "Underlying types are not the same size");
67   static_assert(sizeof(detail::Core<std::unique_ptr<A>>) ==
68                     sizeof(detail::Core<std::unique_ptr<B>>),
69                 "Sizes of types are not the same");
70 }