Debian Codegraph @

src/capnp/compat/json-test.c++

raw
1 // Copyright (c) 2015 Sandstorm Development Group, Inc. and contributors
2 // Licensed under the MIT License:
3 //
4 // Permission is hereby granted, free of charge, to any person obtaining a copy
5 // of this software and associated documentation files (the "Software"), to deal
6 // in the Software without restriction, including without limitation the rights
7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 // copies of the Software, and to permit persons to whom the Software is
9 // furnished to do so, subject to the following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included in
12 // all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 // THE SOFTWARE.
21
22 #include "json.h"
23 #include <capnp/test-util.h>
24 #include <capnp/compat/json.capnp.h>
25 #include <capnp/compat/json-test.capnp.h>
26 #include <kj/debug.h>
27 #include <kj/string.h>
28 #include <kj/test.h>
29
30 namespace capnp {
31 namespace _ { // private
32 namespace {
33
34 KJ_TEST("basic json encoding") {
35 JsonCodec json;
36
37 KJ_EXPECT(json.encode(VOID) == "null");
38 KJ_EXPECT(json.encode(true) == "true");
39 KJ_EXPECT(json.encode(false) == "false");
40 KJ_EXPECT(json.encode(123) == "123");
41 KJ_EXPECT(json.encode(-5.5) == "-5.5");
42 KJ_EXPECT(json.encode(Text::Reader("foo")) == "\"foo\"");
43 KJ_EXPECT(json.encode(Text::Reader("ab\"cd\\ef\x03")) == "\"ab\\\"cd\\\\ef\\u0003\"");
44 KJ_EXPECT(json.encode(test::TestEnum::CORGE) == "\"corge\"");
45
46 byte bytes[] = {12, 34, 56};
47 KJ_EXPECT(json.encode(Data::Reader(bytes, 3)) == "[12,34,56]");
48
49 json.setPrettyPrint(true);
50 KJ_EXPECT(json.encode(Data::Reader(bytes, 3)) == "[12, 34, 56]");
51 }
52
53 KJ_TEST("raw encoding") {
54 JsonCodec json;
55
56 auto text = kj::str("{\"field\":\"value\"}");
57 MallocMessageBuilder message;
58 auto value = message.initRoot<JsonValue>();
59 value.setRaw(text);
60
61 KJ_EXPECT(json.encodeRaw(value) == text);
62 }
63
64 const char ALL_TYPES_JSON[] =
65 "{ \"voidField\": null,\n"
66 " \"boolField\": true,\n"
67 " \"int8Field\": -123,\n"
68 " \"int16Field\": -12345,\n"
69 " \"int32Field\": -12345678,\n"
70 " \"int64Field\": \"-123456789012345\",\n"
71 " \"uInt8Field\": 234,\n"
72 " \"uInt16Field\": 45678,\n"
73 " \"uInt32Field\": 3456789012,\n"
74 " \"uInt64Field\": \"12345678901234567890\",\n"
75 " \"float32Field\": 1234.5,\n"
76 " \"float64Field\": -1.23e47,\n"
77 " \"textField\": \"foo\",\n"
78 " \"dataField\": [98, 97, 114],\n"
79 " \"structField\": {\n"
80 " \"voidField\": null,\n"
81 " \"boolField\": true,\n"
82 " \"int8Field\": -12,\n"
83 " \"int16Field\": 3456,\n"
84 " \"int32Field\": -78901234,\n"
85 " \"int64Field\": \"56789012345678\",\n"
86 " \"uInt8Field\": 90,\n"
87 " \"uInt16Field\": 1234,\n"
88 " \"uInt32Field\": 56789012,\n"
89 " \"uInt64Field\": \"345678901234567890\",\n"
90 " \"float32Field\": -1.2499999646475857e-10,\n"
91 " \"float64Field\": 345,\n"
92 " \"textField\": \"baz\",\n"
93 " \"dataField\": [113, 117, 120],\n"
94 " \"structField\": {\n"
95 " \"voidField\": null,\n"
96 " \"boolField\": false,\n"
97 " \"int8Field\": 0,\n"
98 " \"int16Field\": 0,\n"
99 " \"int32Field\": 0,\n"
100 " \"int64Field\": \"0\",\n"
101 " \"uInt8Field\": 0,\n"
102 " \"uInt16Field\": 0,\n"
103 " \"uInt32Field\": 0,\n"
104 " \"uInt64Field\": \"0\",\n"
105 " \"float32Field\": 0,\n"
106 " \"float64Field\": 0,\n"
107 " \"textField\": \"nested\",\n"
108 " \"structField\": {\"voidField\": null, \"boolField\": false, \"int8Field\": 0, \"int16Field\": 0, \"int32Field\": 0, \"int64Field\": \"0\", \"uInt8Field\": 0, \"uInt16Field\": 0, \"uInt32Field\": 0, \"uInt64Field\": \"0\", \"float32Field\": 0, \"float64Field\": 0, \"textField\": \"really nested\", \"enumField\": \"foo\", \"interfaceField\": null},\n"
109 " \"enumField\": \"foo\",\n"
110 " \"interfaceField\": null },\n"
111 " \"enumField\": \"baz\",\n"
112 " \"interfaceField\": null,\n"
113 " \"voidList\": [null, null, null],\n"
114 " \"boolList\": [false, true, false, true, true],\n"
115 " \"int8List\": [12, -34, -128, 127],\n"
116 " \"int16List\": [1234, -5678, -32768, 32767],\n"
117 " \"int32List\": [12345678, -90123456, -2147483648, 2147483647],\n"
118 " \"int64List\": [\"123456789012345\", \"-678901234567890\", \"-9223372036854775808\", \"9223372036854775807\"],\n"
119 " \"uInt8List\": [12, 34, 0, 255],\n"
120 " \"uInt16List\": [1234, 5678, 0, 65535],\n"
121 " \"uInt32List\": [12345678, 90123456, 0, 4294967295],\n"
122 " \"uInt64List\": [\"123456789012345\", \"678901234567890\", \"0\", \"18446744073709551615\"],\n"
123 " \"float32List\": [0, 1234567, 9.9999999338158125e36, -9.9999999338158125e36, 9.99999991097579e-38, -9.99999991097579e-38],\n"
124 " \"float64List\": [0, 123456789012345, 1e306, -1e306, 1e-306, -1e-306],\n"
125 " \"textList\": [\"quux\", \"corge\", \"grault\"],\n"
126 " \"dataList\": [[103, 97, 114, 112, 108, 121], [119, 97, 108, 100, 111], [102, 114, 101, 100]],\n"
127 " \"structList\": [\n"
128 " {\"voidField\": null, \"boolField\": false, \"int8Field\": 0, \"int16Field\": 0, \"int32Field\": 0, \"int64Field\": \"0\", \"uInt8Field\": 0, \"uInt16Field\": 0, \"uInt32Field\": 0, \"uInt64Field\": \"0\", \"float32Field\": 0, \"float64Field\": 0, \"textField\": \"x structlist 1\", \"enumField\": \"foo\", \"interfaceField\": null},\n"
129 " {\"voidField\": null, \"boolField\": false, \"int8Field\": 0, \"int16Field\": 0, \"int32Field\": 0, \"int64Field\": \"0\", \"uInt8Field\": 0, \"uInt16Field\": 0, \"uInt32Field\": 0, \"uInt64Field\": \"0\", \"float32Field\": 0, \"float64Field\": 0, \"textField\": \"x structlist 2\", \"enumField\": \"foo\", \"interfaceField\": null},\n"
130 " {\"voidField\": null, \"boolField\": false, \"int8Field\": 0, \"int16Field\": 0, \"int32Field\": 0, \"int64Field\": \"0\", \"uInt8Field\": 0, \"uInt16Field\": 0, \"uInt32Field\": 0, \"uInt64Field\": \"0\", \"float32Field\": 0, \"float64Field\": 0, \"textField\": \"x structlist 3\", \"enumField\": \"foo\", \"interfaceField\": null} ],\n"
131 " \"enumList\": [\"qux\", \"bar\", \"grault\"] },\n"
132 " \"enumField\": \"corge\",\n"
133 " \"interfaceField\": null,\n"
134 " \"voidList\": [null, null, null, null, null, null],\n"
135 " \"boolList\": [true, false, false, true],\n"
136 " \"int8List\": [111, -111],\n"
137 " \"int16List\": [11111, -11111],\n"
138 " \"int32List\": [111111111, -111111111],\n"
139 " \"int64List\": [\"1111111111111111111\", \"-1111111111111111111\"],\n"
140 " \"uInt8List\": [111, 222],\n"
141 " \"uInt16List\": [33333, 44444],\n"
142 " \"uInt32List\": [3333333333],\n"
143 " \"uInt64List\": [\"11111111111111111111\"],\n"
144 " \"float32List\": [5555.5, \"Infinity\", \"-Infinity\", \"NaN\"],\n"
145 " \"float64List\": [7777.75, \"Infinity\", \"-Infinity\", \"NaN\"],\n"
146 " \"textList\": [\"plugh\", \"xyzzy\", \"thud\"],\n"
147 " \"dataList\": [[111, 111, 112, 115], [101, 120, 104, 97, 117, 115, 116, 101, 100], [114, 102, 99, 51, 48, 57, 50]],\n"
148 " \"structList\": [\n"
149 " {\"voidField\": null, \"boolField\": false, \"int8Field\": 0, \"int16Field\": 0, \"int32Field\": 0, \"int64Field\": \"0\", \"uInt8Field\": 0, \"uInt16Field\": 0, \"uInt32Field\": 0, \"uInt64Field\": \"0\", \"float32Field\": 0, \"float64Field\": 0, \"textField\": \"structlist 1\", \"enumField\": \"foo\", \"interfaceField\": null},\n"
150 " {\"voidField\": null, \"boolField\": false, \"int8Field\": 0, \"int16Field\": 0, \"int32Field\": 0, \"int64Field\": \"0\", \"uInt8Field\": 0, \"uInt16Field\": 0, \"uInt32Field\": 0, \"uInt64Field\": \"0\", \"float32Field\": 0, \"float64Field\": 0, \"textField\": \"structlist 2\", \"enumField\": \"foo\", \"interfaceField\": null},\n"
151 " {\"voidField\": null, \"boolField\": false, \"int8Field\": 0, \"int16Field\": 0, \"int32Field\": 0, \"int64Field\": \"0\", \"uInt8Field\": 0, \"uInt16Field\": 0, \"uInt32Field\": 0, \"uInt64Field\": \"0\", \"float32Field\": 0, \"float64Field\": 0, \"textField\": \"structlist 3\", \"enumField\": \"foo\", \"interfaceField\": null} ],\n"
152 " \"enumList\": [\"foo\", \"garply\"] }";
153
154 KJ_TEST("encode all types") {
155 MallocMessageBuilder message;
156 auto root = message.getRoot<TestAllTypes>();
157 initTestMessage(root);
158
159 JsonCodec json;
160 json.setPrettyPrint(true);
161 KJ_EXPECT(json.encode(root) == ALL_TYPES_JSON);
162
163 // Verify that if we strip out the non-string spaces, we get the non-pretty-print version.
164 kj::Vector<char> chars;
165 bool inQuotes = false;
166 for (char c: ALL_TYPES_JSON) {
167 if (c == '\"') inQuotes = !inQuotes;
168
169 if ((c == '\n' || c == ' ') && !inQuotes) {
170 // skip space
171 } else {
172 chars.add(c);
173 }
174 }
175 kj::String nospaces(chars.releaseAsArray());
176
177 json.setPrettyPrint(false);
178 KJ_EXPECT(json.encode(root) == nospaces);
179 }
180
181 KJ_TEST("encode union") {
182 MallocMessageBuilder message;
183 auto root = message.getRoot<test::TestUnnamedUnion>();
184
185 root.setBefore("a");
186 root.setMiddle(44);
187 root.setAfter("c");
188
189 JsonCodec json;
190
191 root.setFoo(123);
192 KJ_EXPECT(json.encode(root) == "{\"before\":\"a\",\"foo\":123,\"middle\":44,\"after\":\"c\"}");
193
194 root.setBar(321);
195 KJ_EXPECT(json.encode(root) == "{\"before\":\"a\",\"middle\":44,\"bar\":321,\"after\":\"c\"}");
196 }
197
198 KJ_TEST("decode all types") {
199 JsonCodec json;
200 json.setHasMode(HasMode::NON_DEFAULT);
201
202 #define CASE_MAYBE_ROUNDTRIP(s, f, roundtrip) \
203 { \
204 MallocMessageBuilder message; \
205 auto root = message.initRoot<TestAllTypes>(); \
206 kj::StringPtr input = s; \
207 json.decode(input, root); \
208 KJ_EXPECT((f), input, root); \
209 auto reencoded = json.encode(root); \
210 KJ_EXPECT(roundtrip == (input == reencoded), roundtrip, input, reencoded); \
211 }
212 #define CASE_NO_ROUNDTRIP(s, f) CASE_MAYBE_ROUNDTRIP(s, f, false)
213 #define CASE(s, f) CASE_MAYBE_ROUNDTRIP(s, f, true)
214 #define CASE_THROW(s, errorMessage) \
215 { \
216 MallocMessageBuilder message; \
217 auto root = message.initRoot<TestAllTypes>(); \
218 KJ_EXPECT_THROW_MESSAGE(errorMessage, json.decode(s, root)); \
219 }
220 #define CASE_THROW_RECOVERABLE(s, errorMessage) \
221 { \
222 MallocMessageBuilder message; \
223 auto root = message.initRoot<TestAllTypes>(); \
224 KJ_EXPECT_THROW_RECOVERABLE_MESSAGE(errorMessage, json.decode(s, root)); \
225 }
226
227 CASE(R"({})", root.getBoolField() == false);
228 CASE_NO_ROUNDTRIP(R"({"unknownField":7})", root.getBoolField() == false);
229 CASE(R"({"boolField":true})", root.getBoolField() == true);
230 CASE(R"({"int8Field":-128})", root.getInt8Field() == -128);
231 CASE_NO_ROUNDTRIP(R"({"int8Field":"127"})", root.getInt8Field() == 127);
232 CASE_THROW_RECOVERABLE(R"({"int8Field":"-129"})", "Value out-of-range");
233 CASE_THROW_RECOVERABLE(R"({"int8Field":128})", "Value out-of-range");
234 CASE(R"({"int16Field":-32768})", root.getInt16Field() == -32768);
235 CASE_NO_ROUNDTRIP(R"({"int16Field":"32767"})", root.getInt16Field() == 32767);
236 CASE_THROW_RECOVERABLE(R"({"int16Field":"-32769"})", "Value out-of-range");
237 CASE_THROW_RECOVERABLE(R"({"int16Field":32768})", "Value out-of-range");
238 CASE(R"({"int32Field":-2147483648})", root.getInt32Field() == -2147483648);
239 CASE_NO_ROUNDTRIP(R"({"int32Field":"2147483647"})", root.getInt32Field() == 2147483647);
240 CASE_NO_ROUNDTRIP(R"({"int64Field":-9007199254740992})", root.getInt64Field() == -9007199254740992LL);
241 CASE_NO_ROUNDTRIP(R"({"int64Field":9007199254740991})", root.getInt64Field() == 9007199254740991LL);
242 CASE(R"({"int64Field":"-9223372036854775808"})", root.getInt64Field() == -9223372036854775808ULL);
243 CASE(R"({"int64Field":"9223372036854775807"})", root.getInt64Field() == 9223372036854775807LL);
244 CASE_THROW_RECOVERABLE(R"({"int64Field":"-9223372036854775809"})", "Value out-of-range");
245 CASE_THROW_RECOVERABLE(R"({"int64Field":"9223372036854775808"})", "Value out-of-range");
246 CASE(R"({"uInt8Field":255})", root.getUInt8Field() == 255);
247 CASE_NO_ROUNDTRIP(R"({"uInt8Field":"0"})", root.getUInt8Field() == 0);
248 CASE_THROW_RECOVERABLE(R"({"uInt8Field":"256"})", "Value out-of-range");
249 CASE_THROW_RECOVERABLE(R"({"uInt8Field":-1})", "Value out-of-range");
250 CASE(R"({"uInt16Field":65535})", root.getUInt16Field() == 65535);
251 CASE_NO_ROUNDTRIP(R"({"uInt16Field":"0"})", root.getUInt16Field() == 0);
252 CASE_THROW_RECOVERABLE(R"({"uInt16Field":"655356"})", "Value out-of-range");
253 CASE_THROW_RECOVERABLE(R"({"uInt16Field":-1})", "Value out-of-range");
254 CASE(R"({"uInt32Field":4294967295})", root.getUInt32Field() == 4294967295);
255 CASE_NO_ROUNDTRIP(R"({"uInt32Field":"0"})", root.getUInt32Field() == 0);
256 CASE_THROW_RECOVERABLE(R"({"uInt32Field":"42949672956"})", "Value out-of-range");
257 CASE_THROW_RECOVERABLE(R"({"uInt32Field":-1})", "Value out-of-range");
258 CASE_NO_ROUNDTRIP(R"({"uInt64Field":9007199254740991})", root.getUInt64Field() == 9007199254740991ULL);
259 CASE(R"({"uInt64Field":"18446744073709551615"})", root.getUInt64Field() == 18446744073709551615ULL);
260 CASE_NO_ROUNDTRIP(R"({"uInt64Field":"0"})", root.getUInt64Field() == 0);
261 CASE_THROW_RECOVERABLE(R"({"uInt64Field":"18446744073709551616"})", "Value out-of-range");
262 CASE_NO_ROUNDTRIP(R"({"float32Field":0})", root.getFloat32Field() == 0);
263 CASE(R"({"float32Field":4.5})", root.getFloat32Field() == 4.5);
264 CASE_NO_ROUNDTRIP(R"({"float32Field":null})", kj::isNaN(root.getFloat32Field()));
265 CASE(R"({"float32Field":"NaN"})", kj::isNaN(root.getFloat32Field()));
266 CASE_NO_ROUNDTRIP(R"({"float32Field":"nan"})", kj::isNaN(root.getFloat32Field()));
267 CASE(R"({"float32Field":"Infinity"})", root.getFloat32Field() == kj::inf());
268 CASE(R"({"float32Field":"-Infinity"})", root.getFloat32Field() == -kj::inf());
269 CASE_NO_ROUNDTRIP(R"({"float32Field":"infinity"})", root.getFloat32Field() == kj::inf());
270 CASE_NO_ROUNDTRIP(R"({"float32Field":"-infinity"})", root.getFloat32Field() == -kj::inf());
271 CASE_NO_ROUNDTRIP(R"({"float32Field":"INF"})", root.getFloat32Field() == kj::inf());
272 CASE_NO_ROUNDTRIP(R"({"float32Field":"-INF"})", root.getFloat32Field() == -kj::inf());
273 CASE_NO_ROUNDTRIP(R"({"float32Field":1e39})", root.getFloat32Field() == kj::inf());
274 CASE_NO_ROUNDTRIP(R"({"float32Field":-1e39})", root.getFloat32Field() == -kj::inf());
275 CASE_NO_ROUNDTRIP(R"({"float64Field":0})", root.getFloat64Field() == 0);
276 CASE(R"({"float64Field":4.5})", root.getFloat64Field() == 4.5);
277 CASE_NO_ROUNDTRIP(R"({"float64Field":null})", kj::isNaN(root.getFloat64Field()));
278 CASE(R"({"float64Field":"NaN"})", kj::isNaN(root.getFloat64Field()));
279 CASE_NO_ROUNDTRIP(R"({"float64Field":"nan"})", kj::isNaN(root.getFloat64Field()));
280 CASE(R"({"float64Field":"Infinity"})", root.getFloat64Field() == kj::inf());
281 CASE_NO_ROUNDTRIP(R"({"float64Field":"infinity"})", root.getFloat64Field() == kj::inf());
282 CASE_NO_ROUNDTRIP(R"({"float64Field":"-infinity"})", root.getFloat64Field() == -kj::inf());
283 CASE_NO_ROUNDTRIP(R"({"float64Field":"INF"})", root.getFloat64Field() == kj::inf());
284 CASE_NO_ROUNDTRIP(R"({"float64Field":"-INF"})", root.getFloat64Field() == -kj::inf());
285 CASE_NO_ROUNDTRIP(R"({"float64Field":1e309})", root.getFloat64Field() == kj::inf());
286 CASE_NO_ROUNDTRIP(R"({"float64Field":-1e309})", root.getFloat64Field() == -kj::inf());
287 CASE(R"({"textField":"hello"})", kj::str("hello") == root.getTextField());
288 CASE(R"({"dataField":[7,0,122]})",
289 kj::heapArray<byte>({7,0,122}).asPtr() == root.getDataField());
290 CASE(R"({"structField":{}})", root.hasStructField() == true);
291 CASE(R"({"structField":{}})", root.getStructField().getBoolField() == false);
292 CASE_NO_ROUNDTRIP(R"({"structField":{"boolField":false}})", root.getStructField().getBoolField() == false);
293 CASE(R"({"structField":{"boolField":true}})", root.getStructField().getBoolField() == true);
294 CASE(R"({"enumField":"bar"})", root.getEnumField() == TestEnum::BAR);
295
296 CASE_NO_ROUNDTRIP(R"({"textField":"foo\u1234bar"})",
297 kj::str(u8"foo\u1234bar") == root.getTextField());
298
299 CASE_THROW_RECOVERABLE(R"({"structField":null})", "Expected object value");
300 CASE_THROW_RECOVERABLE(R"({"structList":null})", "Expected list value");
301 CASE_THROW_RECOVERABLE(R"({"boolList":null})", "Expected list value");
302 CASE_THROW_RECOVERABLE(R"({"structList":[null]})", "Expected object value");
303 CASE_THROW_RECOVERABLE(R"({"int64Field":"177a"})", "String does not contain valid");
304 CASE_THROW_RECOVERABLE(R"({"uInt64Field":"177a"})", "String does not contain valid");
305 CASE_THROW_RECOVERABLE(R"({"float64Field":"177a"})", "String does not contain valid");
306
307 CASE(R"({})", root.hasBoolList() == false);
308 CASE(R"({"boolList":[]})", root.hasBoolList() == true);
309 CASE(R"({"boolList":[]})", root.getBoolList().size() == 0);
310 CASE(R"({"boolList":[false]})", root.getBoolList().size() == 1);
311 CASE(R"({"boolList":[false]})", root.getBoolList()[0] == false);
312 CASE(R"({"boolList":[true]})", root.getBoolList()[0] == true);
313 CASE(R"({"int8List":[7]})", root.getInt8List()[0] == 7);
314 CASE_NO_ROUNDTRIP(R"({"int8List":["7"]})", root.getInt8List()[0] == 7);
315 CASE(R"({"int16List":[7]})", root.getInt16List()[0] == 7);
316 CASE_NO_ROUNDTRIP(R"({"int16List":["7"]})", root.getInt16List()[0] == 7);
317 CASE(R"({"int32List":[7]})", root.getInt32List()[0] == 7);
318 CASE_NO_ROUNDTRIP(R"({"int32List":["7"]})", root.getInt32List()[0] == 7);
319 CASE_NO_ROUNDTRIP(R"({"int64List":[7]})", root.getInt64List()[0] == 7);
320 CASE(R"({"int64List":["7"]})", root.getInt64List()[0] == 7);
321 CASE(R"({"uInt8List":[7]})", root.getUInt8List()[0] == 7);
322 CASE_NO_ROUNDTRIP(R"({"uInt8List":["7"]})", root.getUInt8List()[0] == 7);
323 CASE(R"({"uInt16List":[7]})", root.getUInt16List()[0] == 7);
324 CASE_NO_ROUNDTRIP(R"({"uInt16List":["7"]})", root.getUInt16List()[0] == 7);
325 CASE(R"({"uInt32List":[7]})", root.getUInt32List()[0] == 7);
326 CASE_NO_ROUNDTRIP(R"({"uInt32List":["7"]})", root.getUInt32List()[0] == 7);
327 CASE_NO_ROUNDTRIP(R"({"uInt64List":[7]})", root.getUInt64List()[0] == 7);
328 CASE(R"({"uInt64List":["7"]})", root.getUInt64List()[0] == 7);
329 CASE(R"({"float32List":[4.5]})", root.getFloat32List()[0] == 4.5);
330 CASE_NO_ROUNDTRIP(R"({"float32List":["4.5"]})", root.getFloat32List()[0] == 4.5);
331 CASE_NO_ROUNDTRIP(R"({"float32List":[null]})", kj::isNaN(root.getFloat32List()[0]));
332 CASE(R"({"float32List":["NaN"]})", kj::isNaN(root.getFloat32List()[0]));
333 CASE(R"({"float32List":["Infinity"]})", root.getFloat32List()[0] == kj::inf());
334 CASE(R"({"float32List":["-Infinity"]})", root.getFloat32List()[0] == -kj::inf());
335 CASE(R"({"float64List":[4.5]})", root.getFloat64List()[0] == 4.5);
336 CASE_NO_ROUNDTRIP(R"({"float64List":["4.5"]})", root.getFloat64List()[0] == 4.5);
337 CASE_NO_ROUNDTRIP(R"({"float64List":[null]})", kj::isNaN(root.getFloat64List()[0]));
338 CASE(R"({"float64List":["NaN"]})", kj::isNaN(root.getFloat64List()[0]));
339 CASE(R"({"float64List":["Infinity"]})", root.getFloat64List()[0] == kj::inf());
340 CASE(R"({"float64List":["-Infinity"]})", root.getFloat64List()[0] == -kj::inf());
341 CASE(R"({"textList":["hello"]})", kj::str("hello") == root.getTextList()[0]);
342 CASE(R"({"dataList":[[7,0,122]]})",
343 kj::heapArray<byte>({7,0,122}).asPtr() == root.getDataList()[0]);
344 CASE(R"({"structList":[{}]})", root.hasStructList() == true);
345 CASE(R"({"structList":[{}]})", root.getStructList()[0].getBoolField() == false);
346 CASE_NO_ROUNDTRIP(R"({"structList":[{"boolField":false}]})", root.getStructList()[0].getBoolField() == false);
347 CASE(R"({"structList":[{"boolField":true}]})", root.getStructList()[0].getBoolField() == true);
348 CASE(R"({"enumList":["bar"]})", root.getEnumList()[0] == TestEnum::BAR);
349 #undef CASE_MAYBE_ROUNDTRIP
350 #undef CASE_NO_ROUNDTRIP
351 #undef CASE
352 #undef CASE_THROW
353 #undef CASE_THROW_RECOVERABLE
354 }
355
356 KJ_TEST("decode test message") {
357 MallocMessageBuilder message;
358 auto root = message.getRoot<TestAllTypes>();
359 initTestMessage(root);
360
361 JsonCodec json;
362 auto encoded = json.encode(root);
363
364 MallocMessageBuilder decodedMessage;
365 auto decodedRoot = decodedMessage.initRoot<TestAllTypes>();
366 json.decode(encoded, decodedRoot);
367
368 KJ_EXPECT(root.toString().flatten() == decodedRoot.toString().flatten());
369 }
370
371 KJ_TEST("basic json decoding") {
372 // TODO(cleanup): this test is a mess!
373 JsonCodec json;
374 {
375 MallocMessageBuilder message;
376 auto root = message.initRoot<JsonValue>();
377 json.decodeRaw("null", root);
378
379 KJ_EXPECT(root.which() == JsonValue::NULL_);
380 KJ_EXPECT(root.getNull() == VOID);
381 }
382
383 {
384 MallocMessageBuilder message;
385 auto root = message.initRoot<JsonValue>();
386
387 json.decodeRaw("false", root);
388 KJ_EXPECT(root.which() == JsonValue::BOOLEAN);
389 KJ_EXPECT(root.getBoolean() == false);
390 }
391
392 {
393 MallocMessageBuilder message;
394 auto root = message.initRoot<JsonValue>();
395
396 json.decodeRaw("true", root);
397 KJ_EXPECT(root.which() == JsonValue::BOOLEAN);
398 KJ_EXPECT(root.getBoolean() == true);
399 }
400
401 {
402 MallocMessageBuilder message;
403 auto root = message.initRoot<JsonValue>();
404
405 json.decodeRaw("\"foo\"", root);
406 KJ_EXPECT(root.which() == JsonValue::STRING);
407 KJ_EXPECT(kj::str("foo") == root.getString());
408 }
409
410 {
411 MallocMessageBuilder message;
412 auto root = message.initRoot<JsonValue>();
413
414 json.decodeRaw(R"("\"")", root);
415 KJ_EXPECT(root.which() == JsonValue::STRING);
416 KJ_EXPECT(kj::str("\"") == root.getString());
417 }
418
419 {
420 MallocMessageBuilder message;
421 auto root = message.initRoot<JsonValue>();
422
423 json.decodeRaw(R"("\\abc\"d\\e")", root);
424 KJ_EXPECT(root.which() == JsonValue::STRING);
425 KJ_EXPECT(kj::str("\\abc\"d\\e") == root.getString());
426 }
427
428 {
429 MallocMessageBuilder message;
430 auto root = message.initRoot<JsonValue>();
431
432 json.decodeRaw(R"("\"\\\/\b\f\n\r\t\u0003abc\u0064\u0065f")", root);
433 KJ_EXPECT(root.which() == JsonValue::STRING);
434 KJ_EXPECT(kj::str("\"\\/\b\f\n\r\t\x03""abcdef") == root.getString(), root.getString());
435 }
436 {
437 MallocMessageBuilder message;
438 auto root = message.initRoot<JsonValue>();
439
440 json.decodeRaw("[]", root);
441 KJ_EXPECT(root.which() == JsonValue::ARRAY, (uint)root.which());
442 KJ_EXPECT(root.getArray().size() == 0);
443 }
444
445 {
446 MallocMessageBuilder message;
447 auto root = message.initRoot<JsonValue>();
448
449 json.decodeRaw("[true]", root);
450 KJ_EXPECT(root.which() == JsonValue::ARRAY);
451 auto array = root.getArray();
452 KJ_EXPECT(array.size() == 1, array.size());
453 KJ_EXPECT(root.getArray()[0].which() == JsonValue::BOOLEAN);
454 KJ_EXPECT(root.getArray()[0].getBoolean() == true);
455 }
456
457 {
458 MallocMessageBuilder message;
459 auto root = message.initRoot<JsonValue>();
460
461 json.decodeRaw(" [ true , false\t\n , null]", root);
462 KJ_EXPECT(root.which() == JsonValue::ARRAY);
463 auto array = root.getArray();
464 KJ_EXPECT(array.size() == 3);
465 KJ_EXPECT(array[0].which() == JsonValue::BOOLEAN);
466 KJ_EXPECT(array[0].getBoolean() == true);
467 KJ_EXPECT(array[1].which() == JsonValue::BOOLEAN);
468 KJ_EXPECT(array[1].getBoolean() == false);
469 KJ_EXPECT(array[2].which() == JsonValue::NULL_);
470 KJ_EXPECT(array[2].getNull() == VOID);
471 }
472
473 {
474 MallocMessageBuilder message;
475 auto root = message.initRoot<JsonValue>();
476
477 json.decodeRaw("{}", root);
478 KJ_EXPECT(root.which() == JsonValue::OBJECT, (uint)root.which());
479 KJ_EXPECT(root.getObject().size() == 0);
480 }
481
482 {
483 MallocMessageBuilder message;
484 auto root = message.initRoot<JsonValue>();
485
486 json.decodeRaw("\r\n\t {\r\n\t }\r\n\t ", root);
487 KJ_EXPECT(root.which() == JsonValue::OBJECT, (uint)root.which());
488 KJ_EXPECT(root.getObject().size() == 0);
489 }
490
491 {
492 MallocMessageBuilder message;
493 auto root = message.initRoot<JsonValue>();
494
495 json.decodeRaw(R"({"some": null})", root);
496 KJ_EXPECT(root.which() == JsonValue::OBJECT, (uint)root.which());
497 auto object = root.getObject();
498 KJ_EXPECT(object.size() == 1);
499 KJ_EXPECT(kj::str("some") == object[0].getName());
500 KJ_EXPECT(object[0].getValue().which() == JsonValue::NULL_);
501 }
502
503 {
504 MallocMessageBuilder message;
505 auto root = message.initRoot<JsonValue>();
506
507 json.decodeRaw(R"({"foo\n\tbaz": "a val", "bar": ["a", -5.5e11, { "z": {}}]})", root);
508 KJ_EXPECT(root.which() == JsonValue::OBJECT, (uint)root.which());
509 auto object = root.getObject();
510 KJ_EXPECT(object.size() == 2);
511 KJ_EXPECT(kj::str("foo\n\tbaz") == object[0].getName());
512 KJ_EXPECT(object[0].getValue().which() == JsonValue::STRING);
513 KJ_EXPECT(kj::str("a val") == object[0].getValue().getString());
514
515 KJ_EXPECT(kj::str("bar") == object[1].getName());
516 KJ_EXPECT(object[1].getValue().which() == JsonValue::ARRAY);
517 auto array = object[1].getValue().getArray();
518 KJ_EXPECT(array.size() == 3, array.size());
519 KJ_EXPECT(array[0].which() == JsonValue::STRING);
520 KJ_EXPECT(kj::str("a") == array[0].getString());
521 KJ_EXPECT(array[1].which() == JsonValue::NUMBER);
522 KJ_EXPECT(array[1].getNumber() == -5.5e11);
523 KJ_EXPECT(array[2].which() == JsonValue::OBJECT);
524 KJ_EXPECT(array[2].getObject().size() == 1);
525 KJ_EXPECT(array[2].getObject()[0].getValue().which() == JsonValue::OBJECT);
526 KJ_EXPECT(array[2].getObject()[0].getValue().getObject().size() == 0);
527 }
528
529 {
530 MallocMessageBuilder message;
531 auto root = message.initRoot<JsonValue>();
532
533 json.decodeRaw("123", root);
534 KJ_EXPECT(root.which() == JsonValue::NUMBER);
535 KJ_EXPECT(root.getNumber() == 123);
536 }
537
538 {
539 MallocMessageBuilder message;
540 auto root = message.initRoot<JsonValue>();
541
542 KJ_EXPECT_THROW_MESSAGE("input", json.decodeRaw("z", root));
543 }
544
545 {
546 MallocMessageBuilder message;
547 auto root = message.initRoot<JsonValue>();
548
549 // Leading + not allowed in numbers.
550 KJ_EXPECT_THROW_MESSAGE("Unexpected", json.decodeRaw("+123", root));
551 }
552
553 {
554 MallocMessageBuilder message;
555 auto root = message.initRoot<JsonValue>();
556
557 KJ_EXPECT_THROW_MESSAGE("Unexpected", json.decodeRaw("[00]", root));
558 KJ_EXPECT_THROW_MESSAGE("Unexpected", json.decodeRaw("[01]", root));
559 }
560
561 {
562 MallocMessageBuilder message;
563 auto root = message.initRoot<JsonValue>();
564
565 KJ_EXPECT_THROW_MESSAGE("ends prematurely", json.decodeRaw("-", root));
566 }
567
568 {
569 MallocMessageBuilder message;
570 auto root = message.initRoot<JsonValue>();
571
572 json.decodeRaw("-5", root);
573 KJ_EXPECT(root.which() == JsonValue::NUMBER);
574 KJ_EXPECT(root.getNumber() == -5);
575 }
576
577 {
578 MallocMessageBuilder message;
579 auto root = message.initRoot<JsonValue>();
580
581 json.decodeRaw("-5.5", root);
582 KJ_EXPECT(root.which() == JsonValue::NUMBER);
583 KJ_EXPECT(root.getNumber() == -5.5);
584 }
585
586 {
587 MallocMessageBuilder message;
588 auto root = message.initRoot<JsonValue>();
589
590 KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("a", root));
591 KJ_EXPECT_THROW_MESSAGE("ends prematurely", json.decodeRaw("[", root));
592 KJ_EXPECT_THROW_MESSAGE("ends prematurely", json.decodeRaw("{", root));
593 KJ_EXPECT_THROW_MESSAGE("ends prematurely", json.decodeRaw("\"\\u\"", root));
594 KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("[}", root));
595 KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("{]", root));
596 KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("[}]", root));
597 KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("[1, , ]", root));
598 KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("[,]", root));
599 KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("[true,]", root));
600 KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("[, 1]", root));
601 KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("[1\"\"]", root));
602 KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("[1,, \"\"]", root));
603 KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("{\"a\"1: 0}", root));
604 KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw(R"({"some": null,})", root));
605 KJ_EXPECT_THROW_MESSAGE("Input remains", json.decodeRaw("11a", root));
606 KJ_EXPECT_THROW_MESSAGE("Invalid escape", json.decodeRaw(R"("\z")", root));
607 KJ_EXPECT_THROW_MESSAGE("Invalid escape", json.decodeRaw(R"("\z")", root));
608 {
609 // TODO(msvc): This raw string literal currently confuses MSVC's preprocessor, so I hoisted
610 // it outside the macro.
611 auto f = [&] { json.decodeRaw(R"(["\n\", 3])", root); };
612 KJ_EXPECT_THROW_MESSAGE("ends prematurely", f());
613 }
614 KJ_EXPECT_THROW_MESSAGE("Invalid hex", json.decodeRaw(R"("\u12zz")", root));
615 KJ_EXPECT_THROW_MESSAGE("ends prematurely", json.decodeRaw("-", root));
616 KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("--", root));
617 KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("\f{}", root));
618 KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("{\v}", root));
619 }
620
621 {
622 MallocMessageBuilder message;
623 auto root = message.initRoot<JsonValue>();
624
625 json.decodeRaw(R"("\u007f")", root);
626 KJ_EXPECT(root.which() == JsonValue::STRING);
627
628 char utf_buffer[] = {127, 0};
629 KJ_EXPECT(kj::str(utf_buffer) == root.getString());
630 }
631 }
632
633 KJ_TEST("maximum nesting depth") {
634 JsonCodec json;
635 auto input = kj::str(R"({"foo": "a", "bar": ["b", { "baz": [-5.5e11] }, [ [ 1 ], { "z": 2 }]]})");
636 // `input` has a maximum nesting depth of 4, reached 3 times.
637
638 {
639 MallocMessageBuilder message;
640 auto root = message.initRoot<JsonValue>();
641
642 json.decodeRaw(input, root);
643 }
644
645 {
646 json.setMaxNestingDepth(0);
647 MallocMessageBuilder message;
648 auto root = message.initRoot<JsonValue>();
649
650 KJ_EXPECT_THROW_MESSAGE("nest",
651 json.decodeRaw(input, root));
652 }
653
654 {
655 json.setMaxNestingDepth(3);
656 MallocMessageBuilder message;
657 auto root = message.initRoot<JsonValue>();
658
659 KJ_EXPECT_THROW_MESSAGE("nest",
660 json.decodeRaw(input, root));
661 }
662
663 {
664 json.setMaxNestingDepth(4);
665 MallocMessageBuilder message;
666 auto root = message.initRoot<JsonValue>();
667
668 json.decodeRaw(input, root);
669 }
670 }
671
672 KJ_TEST("unknown fields") {
673 JsonCodec json;
674 MallocMessageBuilder message;
675 auto root = message.initRoot<TestJsonAnnotations2>();
676 auto valid = R"({"foo": "a"})"_kj;
677 auto unknown = R"({"foo": "a", "unknown-field": "b"})"_kj;
678 json.decode(valid, root);
679 json.decode(unknown, root);
680 json.setRejectUnknownFields(true);
681 json.decode(valid, root);
682 KJ_EXPECT_THROW_MESSAGE("Unknown field", json.decode(unknown, root));
683
684 // Verify unknown field rejection still works when handling by annotation.
685 json.handleByAnnotation<TestJsonAnnotations2>();
686 KJ_EXPECT_THROW_MESSAGE("Unknown field", json.decode(unknown, root));
687 }
688
689 class TestCallHandler: public JsonCodec::Handler<Text> {
690 public:
691 void encode(const JsonCodec& codec, Text::Reader input,
692 JsonValue::Builder output) const override {
693 auto call = output.initCall();
694 call.setFunction("Frob");
695 auto params = call.initParams(2);
696 params[0].setNumber(123);
697 params[1].setString(input);
698 }
699
700 Orphan<Text> decode(const JsonCodec& codec, JsonValue::Reader input,
701 Orphanage orphanage) const override {
702 KJ_UNIMPLEMENTED("TestHandler::decode");
703 }
704 };
705
706 class TestDynamicStructHandler: public JsonCodec::Handler<DynamicStruct> {
707 public:
708 void encode(const JsonCodec& codec, DynamicStruct::Reader input,
709 JsonValue::Builder output) const override {
710 auto fields = input.getSchema().getFields();
711 auto items = output.initArray(fields.size());
712 for (auto field: fields) {
713 KJ_REQUIRE(field.getIndex() < items.size());
714 auto item = items[field.getIndex()];
715 if (input.has(field)) {
716 codec.encode(input.get(field), field.getType(), item);
717 } else {
718 item.setNull();
719 }
720 }
721 }
722
723 void decode(const JsonCodec& codec, JsonValue::Reader input,
724 DynamicStruct::Builder output) const override {
725 auto orphanage = Orphanage::getForMessageContaining(output);
726 auto fields = output.getSchema().getFields();
727 auto items = input.getArray();
728 for (auto field: fields) {
729 KJ_REQUIRE(field.getIndex() < items.size());
730 auto item = items[field.getIndex()];
731 if (!item.isNull()) {
732 output.adopt(field, codec.decode(item, field.getType(), orphanage));
733 }
734 }
735 }
736 };
737
738 class TestStructHandler: public JsonCodec::Handler<test::TestOldVersion> {
739 public:
740 void encode(const JsonCodec& codec, test::TestOldVersion::Reader input, JsonValue::Builder output) const override {
741 dynamicHandler.encode(codec, input, output);
742 }
743
744 void decode(const JsonCodec& codec, JsonValue::Reader input, test::TestOldVersion::Builder output) const override {
745 dynamicHandler.decode(codec, input, output);
746 }
747
748 private:
749 TestDynamicStructHandler dynamicHandler;
750 };
751
752 KJ_TEST("register custom encoding handlers") {
753 JsonCodec json;
754
755 TestStructHandler structHandler;
756 json.addTypeHandler(structHandler);
757
758 // JSON decoder can't parse calls back, so test only encoder here
759 TestCallHandler callHandler;
760 json.addTypeHandler(callHandler);
761
762 MallocMessageBuilder message;
763 auto root = message.getRoot<test::TestOldVersion>();
764 root.setOld1(123);
765 root.setOld2("foo");
766
767 KJ_EXPECT(json.encode(root) == "[\"123\",Frob(123,\"foo\"),null]");
768 }
769
770 KJ_TEST("register custom roundtrip handler") {
771 for (auto i = 1; i <= 2; i++) {
772 JsonCodec json;
773 TestStructHandler staticHandler;
774 TestDynamicStructHandler dynamicHandler;
775 kj::String encoded;
776
777 if (i == 1) {
778 // first iteration: test with explicit struct handler
779 json.addTypeHandler(staticHandler);
780 } else {
781 // second iteration: same checks, but with DynamicStruct handler
782 json.addTypeHandler(StructSchema::from<test::TestOldVersion>(), dynamicHandler);
783 }
784
785 {
786 MallocMessageBuilder message;
787 auto root = message.getRoot<test::TestOldVersion>();
788 root.setOld1(123);
789 root.initOld3().setOld2("foo");
790
791 encoded = json.encode(root);
792
793 KJ_EXPECT(encoded == "[\"123\",null,[\"0\",\"foo\",null]]");
794 }
795
796 {
797 MallocMessageBuilder message;
798 auto root = message.getRoot<test::TestOldVersion>();
799 json.decode(encoded, root);
800
801 KJ_EXPECT(root.getOld1() == 123);
802 KJ_EXPECT(!root.hasOld2());
803 auto nested = root.getOld3();
804 KJ_EXPECT(nested.getOld1() == 0);
805 KJ_EXPECT("foo" == nested.getOld2());
806 KJ_EXPECT(!nested.hasOld3());
807 }
808 }
809 }
810
811 KJ_TEST("register field handler") {
812 TestStructHandler handler;
813 JsonCodec json;
814 json.addFieldHandler(StructSchema::from<test::TestOldVersion>().getFieldByName("old3"),
815 handler);
816
817 kj::String encoded;
818
819 {
820 MallocMessageBuilder message;
821 auto root = message.getRoot<test::TestOldVersion>();
822 root.setOld1(123);
823 root.setOld2("foo");
824 auto nested = root.initOld3();
825 nested.setOld2("bar");
826
827 encoded = json.encode(root);
828
829 KJ_EXPECT(encoded == "{\"old1\":\"123\",\"old2\":\"foo\",\"old3\":[\"0\",\"bar\",null]}")
830 }
831
832 {
833 MallocMessageBuilder message;
834 auto root = message.getRoot<test::TestOldVersion>();
835 json.decode(encoded, root);
836
837 KJ_EXPECT(root.getOld1() == 123);
838 KJ_EXPECT("foo" == root.getOld2());
839 auto nested = root.getOld3();
840 KJ_EXPECT(nested.getOld1() == 0);
841 KJ_EXPECT("bar" == nested.getOld2());
842 KJ_EXPECT(!nested.hasOld3());
843 }
844 }
845
846 class TestCapabilityHandler: public JsonCodec::Handler<test::TestInterface> {
847 public:
848 void encode(const JsonCodec& codec, test::TestInterface::Client input,
849 JsonValue::Builder output) const override {
850 KJ_UNIMPLEMENTED("TestCapabilityHandler::encode");
851 }
852
853 test::TestInterface::Client decode(
854 const JsonCodec& codec, JsonValue::Reader input) const override {
855 return nullptr;
856 }
857 };
858
859 KJ_TEST("register capability handler") {
860 // This test currently only checks that this compiles, which at one point wasn't the caes.
861 // TODO(test): Actually run some code here.
862
863 TestCapabilityHandler handler;
864 JsonCodec json;
865 json.addTypeHandler(handler);
866 }
867
868 static constexpr kj::StringPtr GOLDEN_ANNOTATED =
869 R"({ "names-can_contain!anything Really": "foo",
870 "flatFoo": 123,
871 "flatBar": "abc",
872 "renamed-flatBaz": {"hello": true},
873 "flatQux": "cba",
874 "pfx.foo": "this is a long string in order to force multi-line pretty printing",
875 "pfx.renamed-bar": 321,
876 "pfx.baz": {"hello": true},
877 "pfx.xfp.qux": "fed",
878 "union-type": "renamed-bar",
879 "barMember": 789,
880 "multiMember": "ghi",
881 "dependency": {"renamed-foo": "corge"},
882 "simpleGroup": {"renamed-grault": "garply"},
883 "enums": ["qux", "renamed-bar", "foo", "renamed-baz"],
884 "innerJson": [123, "hello", {"object": true}],
885 "customFieldHandler": "add-prefix-waldo",
886 "testBase64": "ZnJlZA==",
887 "testHex": "706c756768",
888 "bUnion": "renamed-bar",
889 "bValue": 678,
890 "externalUnion": {"type": "bar", "value": "cba"},
891 "unionWithVoid": {"type": "voidValue"} })"_kj;
892
893 static constexpr kj::StringPtr GOLDEN_ANNOTATED_REVERSE =
894 R"({
895 "unionWithVoid": {"type": "voidValue"},
896 "externalUnion": {"type": "bar", "value": "cba"},
897 "bValue": 678,
898 "bUnion": "renamed-bar",
899 "testHex": "706c756768",
900 "testBase64": "ZnJlZA==",
901 "customFieldHandler": "add-prefix-waldo",
902 "innerJson": [123, "hello", {"object": true}],
903 "enums": ["qux", "renamed-bar", "foo", "renamed-baz"],
904 "simpleGroup": { "renamed-grault": "garply" },
905 "dependency": { "renamed-foo": "corge" },
906 "multiMember": "ghi",
907 "barMember": 789,
908 "union-type": "renamed-bar",
909 "pfx.xfp.qux": "fed",
910 "pfx.baz": {"hello": true},
911 "pfx.renamed-bar": 321,
912 "pfx.foo": "this is a long string in order to force multi-line pretty printing",
913 "flatQux": "cba",
914 "renamed-flatBaz": {"hello": true},
915 "flatBar": "abc",
916 "flatFoo": 123,
917 "names-can_contain!anything Really": "foo"
918 })"_kj;
919
920 class PrefixAdder: public JsonCodec::Handler<capnp::Text> {
921 public:
922 void encode(const JsonCodec& codec, capnp::Text::Reader input, JsonValue::Builder output) const {
923 output.setString(kj::str("add-prefix-", input));
924 }
925
926 Orphan<capnp::Text> decode(const JsonCodec& codec, JsonValue::Reader input,
927 Orphanage orphanage) const {
928 return orphanage.newOrphanCopy(capnp::Text::Reader(input.getString().slice(11)));
929 }
930 };
931
932 KJ_TEST("rename fields") {
933 JsonCodec json;
934 json.handleByAnnotation<TestJsonAnnotations>();
935 json.setPrettyPrint(true);
936
937 PrefixAdder customHandler;
938 json.addFieldHandler(Schema::from<TestJsonAnnotations>().getFieldByName("customFieldHandler"),
939 customHandler);
940
941 kj::String goldenText;
942
943 {
944 MallocMessageBuilder message;
945 auto root = message.getRoot<TestJsonAnnotations>();
946 root.setSomeField("foo");
947
948 auto aGroup = root.getAGroup();
949 aGroup.setFlatFoo(123);
950 aGroup.setFlatBar("abc");
951 aGroup.getFlatBaz().setHello(true);
952 aGroup.getDoubleFlat().setFlatQux("cba");
953
954 auto prefixedGroup = root.getPrefixedGroup();
955 prefixedGroup.setFoo("this is a long string in order to force multi-line pretty printing");
956 prefixedGroup.setBar(321);
957 prefixedGroup.getBaz().setHello(true);
958 prefixedGroup.getMorePrefix().setQux("fed");
959
960 auto unionBar = root.getAUnion().initBar();
961 unionBar.setBarMember(789);
962 unionBar.setMultiMember("ghi");
963
964 root.initDependency().setFoo("corge");
965 root.initSimpleGroup().setGrault("garply");
966
967 root.setEnums({
968 TestJsonAnnotatedEnum::QUX,
969 TestJsonAnnotatedEnum::BAR,
970 TestJsonAnnotatedEnum::FOO,
971 TestJsonAnnotatedEnum::BAZ
972 });
973
974 auto val = root.initInnerJson();
975 auto arr = val.initArray(3);
976 arr[0].setNumber(123);
977 arr[1].setString("hello");
978 auto field = arr[2].initObject(1)[0];
979 field.setName("object");
980 field.initValue().setBoolean(true);
981
982 root.setCustomFieldHandler("waldo");
983
984 root.setTestBase64("fred"_kj.asBytes());
985 root.setTestHex("plugh"_kj.asBytes());
986
987 root.getBUnion().setBar(678);
988
989 root.initExternalUnion().initBar().setValue("cba");
990
991 root.initUnionWithVoid().setVoidValue();
992
993 auto encoded = json.encode(root.asReader());
994 KJ_EXPECT(encoded == GOLDEN_ANNOTATED, encoded);
995
996 goldenText = kj::str(root);
997 }
998
999 {
1000 MallocMessageBuilder message;
1001 auto root = message.getRoot<TestJsonAnnotations>();
1002 json.decode(GOLDEN_ANNOTATED, root);
1003
1004 KJ_EXPECT(kj::str(root) == goldenText, root, goldenText);
1005 }
1006
1007 {
1008 // Try parsing in reverse, mostly to test that union tags can come after content.
1009 MallocMessageBuilder message;
1010 auto root = message.getRoot<TestJsonAnnotations>();
1011 json.decode(GOLDEN_ANNOTATED_REVERSE, root);
1012
1013 KJ_EXPECT(kj::str(root) == goldenText, root, goldenText);
1014 }
1015 }
1016
1017 KJ_TEST("base64 union encoded correctly") {
1018 // At one point field handlers were not correctly applied when the field was a member of a union
1019 // in a type that was handled by annotation.
1020
1021 JsonCodec json;
1022 json.handleByAnnotation<TestBase64Union>();
1023 json.setPrettyPrint(true);
1024
1025 MallocMessageBuilder message;
1026 auto root = message.getRoot<TestBase64Union>();
1027 root.initFoo(5);
1028
1029 KJ_EXPECT(json.encode(root) == "{\"foo\": \"AAAAAAA=\"}", json.encode(root));
1030 }
1031
1032 } // namespace
1033 } // namespace _ (private)
1034 } // namespace capnp