1 /*
2  * Copyright (c) Facebook, Inc. and its affiliates.
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 <thrift/test/reflection/gen-cpp2/reflection_for_each_field.h>
18 #include <thrift/test/reflection/gen-cpp2/reflection_visit_by_thrift_field_metadata.h> // @manual
19 
20 #include <folly/Overload.h>
21 #include <folly/portability/GTest.h>
22 
23 #include <typeindex>
24 
25 namespace test_cpp2 {
26 namespace cpp_reflection {
27 namespace {
28 template <class T>
idToThriftField(int32_t id)29 auto idToThriftField(int32_t id) {
30   apache::thrift::metadata::ThriftField field;
31   apache::thrift::for_each_field(T{}, [&](auto&& meta, auto&&) {
32     if (meta.id_ref() == id) {
33       field = meta;
34     }
35   });
36   return field;
37 }
38 
TEST(struct1,modify_field)39 TEST(struct1, modify_field) {
40   struct1 s;
41   s.field4_ref().emplace().set_us("foo");
42   s.field5_ref().emplace().set_us_2("bar");
43   auto run = folly::overload(
44       [](union1& ref) {
45         EXPECT_EQ(ref.get_us(), "foo");
46         ref.set_ui(20);
47       },
48       [](auto&) { EXPECT_TRUE(false) << "type mismatch"; });
49   auto meta = idToThriftField<struct1>(16);
50   apache::thrift::visit_by_thrift_field_metadata(s, meta, [run](auto&& ref) {
51     EXPECT_TRUE(ref.has_value());
52     run(*ref);
53   });
54   EXPECT_EQ(s.field4_ref()->ui_ref(), 20);
55   EXPECT_EQ(s.field5_ref()->us_2_ref(), "bar");
56 
57   meta.id_ref() = 123456;
58   EXPECT_THROW(
59       apache::thrift::visit_by_thrift_field_metadata(s, meta, [](auto&&...) {}),
60       apache::thrift::InvalidThriftId);
61 }
62 } // namespace
63 } // namespace cpp_reflection
64 } // namespace test_cpp2
65