Repository navigation
Expand file tree
/
Copy pathgtest_json.cpp
More file actions
465 lines (396 loc) · 14.3 KB
/
Copy pathgtest_json.cpp
File metadata and controls
465 lines (396 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
#include "behaviortree_cpp/basic_types.h"
#include "behaviortree_cpp/blackboard.h"
#include "behaviortree_cpp/json_export.h"
#include <gtest/gtest.h>
//----------- Custom types ----------
namespace TestTypes
{
struct Vector3D
{
double x = 0;
double y = 0;
double z = 0;
bool operator==(const Vector3D& other) const
{
return x == other.x && y == other.y && z == other.z;
}
};
struct Quaternion3D
{
double w = 1;
double x = 0;
double y = 0;
double z = 0;
bool operator==(const Quaternion3D& other) const
{
return w == other.w && x == other.x && y == other.y && z == other.z;
}
};
struct Pose3D
{
Vector3D pos;
Quaternion3D rot;
bool operator==(const Pose3D& other) const
{
return pos == other.pos && rot == other.rot;
}
};
struct Time
{
uint32_t sec;
uint32_t nsec;
};
struct Temperature
{
double celsius = 0;
};
// NOLINTBEGIN(misc-use-internal-linkage)
BT_JSON_CONVERTER(Vector3D, v)
{
add_field("x", &v.x);
add_field("y", &v.y);
add_field("z", &v.z);
}
BT_JSON_CONVERTER(Quaternion3D, v)
{
add_field("w", &v.w);
add_field("x", &v.x);
add_field("y", &v.y);
add_field("z", &v.z);
}
BT_JSON_CONVERTER(Pose3D, v)
{
add_field("pos", &v.pos);
add_field("rot", &v.rot);
}
// specialized functions
inline void jsonFromTime(const Time& t, nlohmann::json& j)
{
j["stamp"] = double(t.sec) + 1e-9 * double(t.nsec);
}
inline void jsonToTime(const nlohmann::json& j, Time& t)
{
double sec = j["stamp"];
t.sec = static_cast<uint32_t>(sec);
t.nsec = static_cast<uint32_t>((sec - t.sec) * 1e9);
}
inline void jsonFromTemperature(const Temperature& t, nlohmann::json& j)
{
j["celsius"] = t.celsius;
}
inline void jsonToTemperature(const nlohmann::json& j, Temperature& t)
{
t.celsius = j["celsius"];
}
// NOLINTEND(misc-use-internal-linkage)
} // namespace TestTypes
//----------- JSON specialization ----------
class JsonTest : public testing::Test
{
protected:
JsonTest()
{
BT::JsonExporter& exporter = BT::JsonExporter::get();
exporter.addConverter<TestTypes::Pose3D>();
exporter.addConverter<TestTypes::Vector3D>();
exporter.addConverter<TestTypes::Quaternion3D>();
exporter.addConverter<TestTypes::Time>(TestTypes::jsonFromTime);
exporter.addConverter<TestTypes::Time>(TestTypes::jsonToTime);
}
};
TEST_F(JsonTest, TwoWaysConversion)
{
BT::JsonExporter& exporter = BT::JsonExporter::get();
TestTypes::Pose3D pose = { { 1, 2, 3 }, { 4, 5, 6, 7 } };
nlohmann::json json;
exporter.toJson(BT::Any(69), json["int"]);
exporter.toJson(BT::Any(3.14), json["real"]);
exporter.toJson(BT::Any(pose), json["pose"]);
std::cout << json.dump(2) << std::endl;
ASSERT_EQ(json["int"], 69);
ASSERT_EQ(json["real"], 3.14);
ASSERT_EQ(json["pose"]["__type"], "Pose3D");
ASSERT_EQ(json["pose"]["pos"]["x"], 1);
ASSERT_EQ(json["pose"]["pos"]["y"], 2);
ASSERT_EQ(json["pose"]["pos"]["z"], 3);
ASSERT_EQ(json["pose"]["rot"]["w"], 4);
ASSERT_EQ(json["pose"]["rot"]["x"], 5);
ASSERT_EQ(json["pose"]["rot"]["y"], 6);
ASSERT_EQ(json["pose"]["rot"]["z"], 7);
auto num_result = exporter.fromJson(json["int"]);
ASSERT_TRUE(num_result) << num_result.error();
auto num = num_result->first.cast<int>();
ASSERT_EQ(num, 69);
auto real_result = exporter.fromJson(json["real"]);
ASSERT_TRUE(real_result) << real_result.error();
auto real = real_result->first.cast<double>();
ASSERT_EQ(real, 3.14);
auto pose_result = exporter.fromJson(json["pose"]);
ASSERT_TRUE(pose_result) << pose_result.error();
auto pose_out = pose_result->first.cast<TestTypes::Pose3D>();
ASSERT_EQ(pose.pos, pose_out.pos);
ASSERT_EQ(pose.rot, pose_out.rot);
}
TEST_F(JsonTest, CustomTime)
{
BT::JsonExporter& exporter = BT::JsonExporter::get();
TestTypes::Time stamp = { 3, 8000000 };
nlohmann::json json;
exporter.toJson(BT::Any(stamp), json);
std::cout << json.dump() << std::endl;
{
auto res = exporter.fromJson(json, typeid(TestTypes::Time));
ASSERT_TRUE(res);
auto stamp_out = res->first.cast<TestTypes::Time>();
ASSERT_EQ(stamp.sec, stamp_out.sec);
ASSERT_EQ(stamp.nsec, stamp_out.nsec);
}
{
auto res = exporter.fromJson(json);
ASSERT_TRUE(res);
auto stamp_out = res->first.cast<TestTypes::Time>();
ASSERT_EQ(stamp.sec, stamp_out.sec);
ASSERT_EQ(stamp.nsec, stamp_out.nsec);
}
{
auto stamp_out = exporter.fromJson<TestTypes::Time>(json);
ASSERT_TRUE(stamp_out);
ASSERT_EQ(stamp.sec, stamp_out->sec);
ASSERT_EQ(stamp.nsec, stamp_out->nsec);
}
}
// Issue #877: the name stored in "__type" can be chosen when registering lambdas
TEST_F(JsonTest, CustomTypeName)
{
BT::JsonExporter& exporter = BT::JsonExporter::get();
const std::string name = "Temperature";
// a string literal as second argument is the type name, not add_type
using TestTypes::Temperature;
exporter.addConverter<Temperature>(TestTypes::jsonFromTemperature, "Temperature");
exporter.addConverter<TestTypes::Temperature>(TestTypes::jsonToTemperature, name);
TestTypes::Temperature temp = { 21.5 };
nlohmann::json json;
ASSERT_TRUE(exporter.toJson(BT::Any(temp), json));
ASSERT_EQ(json["__type"], name);
auto res = exporter.fromJson<TestTypes::Temperature>(json);
ASSERT_TRUE(res) << res.error();
ASSERT_EQ(res->celsius, 21.5);
// the demangled name is still accepted
json["__type"] = BT::demangle(typeid(TestTypes::Temperature));
ASSERT_TRUE(exporter.fromJson<TestTypes::Temperature>(json));
// vectors use the same name
std::vector<TestTypes::Temperature> temps = { { 1.5 }, { 2.5 } };
nlohmann::json json_vec;
ASSERT_TRUE(exporter.toJson(BT::Any(temps), json_vec));
ASSERT_EQ(json_vec[1]["__type"], name);
auto res_vec = exporter.fromJson<std::vector<TestTypes::Temperature>>(json_vec);
ASSERT_TRUE(res_vec) << res_vec.error();
ASSERT_EQ(res_vec->size(), 2u);
ASSERT_EQ((*res_vec)[1].celsius, 2.5);
// without a name, the demangled name of the type is used
TestTypes::Time stamp = { 3, 8000000 };
ASSERT_TRUE(exporter.toJson(BT::Any(stamp), json));
ASSERT_EQ(json["__type"], BT::demangle(typeid(TestTypes::Time)));
}
TEST_F(JsonTest, ConvertFromString)
{
TestTypes::Vector3D vect;
auto const test_json = R"(json:{"x":2.1, "y":4.2, "z":6.3})";
ASSERT_NO_THROW(vect = BT::convertFromString<TestTypes::Vector3D>(test_json));
ASSERT_EQ(vect.x, 2.1);
ASSERT_EQ(vect.y, 4.2);
ASSERT_EQ(vect.z, 6.3);
}
TEST_F(JsonTest, BlackboardInOut)
{
auto bb_in = BT::Blackboard::create();
bb_in->set("int", 42);
bb_in->set("real", 3.14);
bb_in->set("vect", TestTypes::Vector3D{ 1.1, 2.2, 3.3 });
auto json = ExportBlackboardToJSON(*bb_in);
std::cout << json.dump(2) << std::endl;
auto bb_out = BT::Blackboard::create();
ImportBlackboardFromJSON(json, *bb_out);
ASSERT_EQ(bb_out->get<int>("int"), 42);
ASSERT_EQ(bb_out->get<double>("real"), 3.14);
auto vect_out = bb_out->get<TestTypes::Vector3D>("vect");
ASSERT_EQ(vect_out.x, 1.1);
ASSERT_EQ(vect_out.y, 2.2);
ASSERT_EQ(vect_out.z, 3.3);
}
TEST_F(JsonTest, LargeIntegerPreserved)
{
BT::JsonExporter& exporter = BT::JsonExporter::get();
// Values outside the int32 range used to be silently wrapped by get<int>().
{
auto json = nlohmann::json::parse(R"({"a": 2147483648, "b": 5000000000,
"c": 4294967296})");
auto bb = BT::Blackboard::create();
ImportBlackboardFromJSON(json, *bb);
ASSERT_EQ(bb->get<int64_t>("a"), 2147483648LL);
ASSERT_EQ(bb->get<int64_t>("b"), 5000000000LL);
ASSERT_EQ(bb->get<int64_t>("c"), 4294967296LL);
}
// Negative values below the int32 minimum are preserved too.
{
auto res = exporter.fromJson(nlohmann::json(int64_t(-5000000000LL)));
ASSERT_TRUE(res) << res.error();
ASSERT_EQ(res->first.cast<int64_t>(), -5000000000LL);
}
// Values that fit keep the int type, unchanged from before.
{
auto res = exporter.fromJson(nlohmann::json(100));
ASSERT_TRUE(res) << res.error();
ASSERT_EQ(res->first.cast<int>(), 100);
}
// An int64_t entry survives an Export/Import round-trip.
{
auto bb_in = BT::Blackboard::create();
bb_in->set("big", int64_t(5000000000LL));
auto bb_out = BT::Blackboard::create();
ImportBlackboardFromJSON(ExportBlackboardToJSON(*bb_in), *bb_out);
ASSERT_EQ(bb_out->get<int64_t>("big"), 5000000000LL);
}
}
TEST_F(JsonTest, VectorInteger)
{
BT::JsonExporter& exporter = BT::JsonExporter::get();
std::vector<int> vec = { 1, 2, 3 };
nlohmann::json json;
exporter.toJson(BT::Any(vec), json["vec"]);
std::cout << json.dump(2) << std::endl;
ASSERT_EQ(json["vec"][0], 1);
ASSERT_EQ(json["vec"][1], 2);
ASSERT_EQ(json["vec"][2], 3);
auto result = exporter.fromJson(json["vec"]);
ASSERT_TRUE(result) << result.error();
auto vec_out = result->first.cast<std::vector<int>>();
ASSERT_EQ(vec.size(), vec_out.size());
for(size_t i = 0; i < vec.size(); ++i)
{
ASSERT_EQ(vec[i], vec_out[i]);
}
}
TEST_F(JsonTest, IntegerValuesAreRangeChecked)
{
using nlohmann::json;
BT::JsonExporter& exporter = BT::JsonExporter::get();
ASSERT_EQ(BT::details::JsonToInteger<int>(json(-7)), -7);
ASSERT_EQ(BT::details::JsonToInteger<uint16_t>(json(65535)), 65535);
ASSERT_EQ(BT::details::JsonToInteger<int64_t>(json(INT64_MIN)), INT64_MIN);
ASSERT_EQ(BT::details::JsonToInteger<uint64_t>(json(UINT64_MAX)), UINT64_MAX);
ASSERT_THROW(std::ignore = BT::details::JsonToInteger<uint16_t>(json(65536)),
BT::RuntimeError);
ASSERT_THROW(std::ignore = BT::details::JsonToInteger<uint16_t>(json(-1)),
BT::RuntimeError);
ASSERT_THROW(std::ignore = BT::details::JsonToInteger<int>(json(2.5)),
BT::RuntimeError);
ASSERT_THROW(std::ignore = BT::details::JsonToInteger<int>(json(1e300)),
BT::RuntimeError);
ASSERT_THROW(std::ignore = BT::details::JsonToInteger<int>(json(true)),
BT::RuntimeError);
ASSERT_THROW(std::ignore = BT::details::JsonToInteger<int>(json(std::nan(""))),
BT::RuntimeError);
// A floating point value with no fractional part converts, like Any::cast<int>()
ASSERT_EQ(BT::details::JsonToInteger<int>(json(100.0)), 100);
ASSERT_EQ(BT::details::JsonToInteger<int>(json(-3.0)), -3);
ASSERT_THROW(std::ignore = BT::details::JsonToInteger<uint16_t>(json(65536.0)),
BT::RuntimeError);
{
auto result = exporter.fromJson(json::parse("[1, 2.0]"));
ASSERT_TRUE(result);
ASSERT_EQ(result->first.cast<std::vector<int>>(), (std::vector<int>{ 1, 2 }));
}
// The type of the array is taken from the first element. The other elements
// used to be truncated, wrapped, or cast out of range (undefined behavior).
for(const char* text :
{ "[1, 2.5]", "[1, 1e300]", "[1, 5000000000]", "[1, -3000000000]" })
{
ASSERT_THROW(std::ignore = exporter.fromJson(json::parse(text)), BT::RuntimeError)
<< text;
auto bb = BT::Blackboard::create();
ASSERT_THROW(BT::ImportBlackboardFromJSON(
json::parse(R"({"v":)" + std::string(text) + "}"), *bb),
BT::RuntimeError)
<< text;
}
auto result = exporter.fromJson(json::parse("[1, -2, 2147483647]"));
ASSERT_TRUE(result) << result.error();
ASSERT_EQ(result->first.cast<std::vector<int>>(),
(std::vector<int>{ 1, -2, 2147483647 }));
// Same for the "json:" prefix of a std::vector<int> port
ASSERT_EQ(BT::convertFromString<std::vector<int>>("json:[3, -4]"),
(std::vector<int>{ 3, -4 }));
ASSERT_THROW(std::ignore = BT::convertFromString<std::vector<int>>("json:[1e300]"),
BT::RuntimeError);
ASSERT_THROW(std::ignore = BT::convertFromString<std::vector<int>>("json:[1.5]"),
BT::RuntimeError);
ASSERT_THROW(std::ignore = BT::convertFromString<std::vector<int>>("json:[4294967297]"),
BT::RuntimeError);
ASSERT_THROW(std::ignore = BT::convertFromString<std::vector<int>>("json:{\"a\":1}"),
BT::RuntimeError);
}
TEST_F(JsonTest, VectorSring)
{
BT::JsonExporter& exporter = BT::JsonExporter::get();
std::vector<std::string> vec = { "hello", "world" };
nlohmann::json json;
exporter.toJson(BT::Any(vec), json["vec"]);
std::cout << json.dump(2) << std::endl;
ASSERT_EQ(json["vec"][0], "hello");
ASSERT_EQ(json["vec"][1], "world");
auto result = exporter.fromJson(json["vec"]);
ASSERT_TRUE(result) << result.error();
auto vec_out = result->first.cast<std::vector<std::string>>();
ASSERT_EQ(vec.size(), vec_out.size());
for(size_t i = 0; i < vec.size(); ++i)
{
ASSERT_EQ(vec[i], vec_out[i]);
}
// check the two-ways transform, i.e. "from_json"
auto result2 = exporter.fromJson(json["vec"]);
ASSERT_TRUE(result2) << result2.error();
auto vec_out2 = result2->first.cast<std::vector<std::string>>();
ASSERT_EQ(vec.size(), vec_out2.size());
for(size_t i = 0; i < vec.size(); ++i)
{
ASSERT_EQ(vec[i], vec_out2[i]);
}
}
TEST_F(JsonTest, VectorOfCustomTypes)
{
BT::JsonExporter& exporter = BT::JsonExporter::get();
std::vector<TestTypes::Pose3D> poses(2);
poses[0].pos = { 1, 2, 3 };
poses[0].rot = { 4, 5, 6, 7 };
poses[1].pos = { 8, 9, 10 };
poses[1].rot = { 11, 12, 13, 14 };
nlohmann::json json;
exporter.toJson(BT::Any(poses), json["poses"]);
std::cout << json.dump(2) << std::endl;
ASSERT_EQ(json["poses"][0]["__type"], "Pose3D");
ASSERT_EQ(json["poses"][0]["pos"]["x"], 1);
ASSERT_EQ(json["poses"][0]["pos"]["y"], 2);
ASSERT_EQ(json["poses"][0]["pos"]["z"], 3);
ASSERT_EQ(json["poses"][0]["rot"]["w"], 4);
ASSERT_EQ(json["poses"][0]["rot"]["x"], 5);
ASSERT_EQ(json["poses"][0]["rot"]["y"], 6);
ASSERT_EQ(json["poses"][0]["rot"]["z"], 7);
ASSERT_EQ(json["poses"][1]["__type"], "Pose3D");
ASSERT_EQ(json["poses"][1]["pos"]["x"], 8);
ASSERT_EQ(json["poses"][1]["pos"]["y"], 9);
ASSERT_EQ(json["poses"][1]["pos"]["z"], 10);
ASSERT_EQ(json["poses"][1]["rot"]["w"], 11);
ASSERT_EQ(json["poses"][1]["rot"]["x"], 12);
ASSERT_EQ(json["poses"][1]["rot"]["y"], 13);
ASSERT_EQ(json["poses"][1]["rot"]["z"], 14);
// check the two-ways transform, i.e. "from_json"
auto result = exporter.fromJson(json["poses"]);
ASSERT_TRUE(result) << result.error();
auto poses_out = result->first.cast<std::vector<TestTypes::Pose3D>>();
ASSERT_EQ(poses.size(), poses_out.size());
ASSERT_EQ(poses[0].pos, poses_out[0].pos);
ASSERT_EQ(poses[0].rot, poses_out[0].rot);
ASSERT_EQ(poses[1].pos, poses_out[1].pos);
ASSERT_EQ(poses[1].rot, poses_out[1].rot);
}