1 // Copyright by Contributors
2
3 #include <unordered_map>
4 #include <vector>
5 #include <string>
6 #include <memory>
7 #include <dmlc/any.h>
8 #include <dmlc/json.h>
9 #include <gtest/gtest.h>
10
11
TEST(Any,basics)12 TEST(Any, basics) {
13 std::unordered_map<std::string, dmlc::any> dict;
14 dict["1"] = 1;
15 dict["vec"] = std::vector<int>{1,2,3};
16 dict["shapex"] = std::string("xtyz");
17 std::unordered_map<std::string, dmlc::any> dict2(std::move(dict));
18 dmlc::get<int>(dict2["1"]) += 1;
19
20 CHECK_EQ(dmlc::get<int>(dict2["1"]), 2);
21 CHECK_EQ(dmlc::get<std::vector<int> >(dict2["vec"])[1], 2);
22 }
23
TEST(Any,cover)24 TEST(Any, cover) {
25 dmlc::any a = std::string("abc");
26 dmlc::any b = 1;
27
28 CHECK_EQ(dmlc::get<std::string>(a), "abc");
29 a = std::move(b);
30 CHECK(b.empty());
31 CHECK_EQ(dmlc::get<int>(a), 1);
32
33 std::shared_ptr<int> x = std::make_shared<int>(10);
34 {
35 dmlc::any aa(x);
36 CHECK_EQ(*dmlc::get<std::shared_ptr<int> >(aa), 10);
37 }
38 // aa must be destructed.
39 CHECK(x.unique());
40 }
41
42 DMLC_JSON_ENABLE_ANY(std::vector<int>, IntVector);
43 DMLC_JSON_ENABLE_ANY(int, Int);
44
TEST(Any,json)45 TEST(Any, json) {
46 std::unordered_map<std::string, dmlc::any> x;
47 x["vec"] = std::vector<int>{1, 2, 3};
48 x["int"] = 300;
49
50 #ifndef _LIBCPP_SGX_NO_IOSTREAMS
51 std::ostringstream os;
52 #else
53 std::string os;
54 #endif
55 {
56 std::unordered_map<std::string, dmlc::any> temp(x);
57 dmlc::JSONWriter writer(&os);
58 writer.Write(temp);
59 temp.clear();
60 }
61 #ifndef _LIBCPP_SGX_NO_IOSTREAMS
62 std::string json = os.str();
63 std::istringstream is(json);
64 #else
65 std::string json = os;
66 std::string is(json);
67 #endif
68 LOG(INFO) << json;
69
70 dmlc::JSONReader reader(&is);
71 std::unordered_map<std::string, dmlc::any> copy_data;
72 reader.Read(©_data);
73
74 ASSERT_EQ(dmlc::get<std::vector<int> >(x["vec"]),
75 dmlc::get<std::vector<int> >(copy_data["vec"]));
76 ASSERT_EQ(dmlc::get<int>(x["int"]),
77 dmlc::get<int>(copy_data["int"]));
78 }
79