json-test.c++ 39.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// Copyright (c) 2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#include "json.h"
#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 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
#include <kj/test.h>

namespace capnp {
namespace _ {  // private
namespace {

KJ_TEST("basic json encoding") {
  JsonCodec json;

  KJ_EXPECT(json.encode(VOID) == "null");
  KJ_EXPECT(json.encode(true) == "true");
  KJ_EXPECT(json.encode(false) == "false");
  KJ_EXPECT(json.encode(123) == "123");
  KJ_EXPECT(json.encode(-5.5) == "-5.5");
  KJ_EXPECT(json.encode(Text::Reader("foo")) == "\"foo\"");
  KJ_EXPECT(json.encode(Text::Reader("ab\"cd\\ef\x03")) == "\"ab\\\"cd\\\\ef\\u0003\"");
  KJ_EXPECT(json.encode(test::TestEnum::CORGE) == "\"corge\"");

  byte bytes[] = {12, 34, 56};
  KJ_EXPECT(json.encode(Data::Reader(bytes, 3)) == "[12,34,56]");

  json.setPrettyPrint(true);
  KJ_EXPECT(json.encode(Data::Reader(bytes, 3)) == "[12, 34, 56]");
}

const char ALL_TYPES_JSON[] =
    "{ \"voidField\": null,\n"
    "  \"boolField\": true,\n"
    "  \"int8Field\": -123,\n"
    "  \"int16Field\": -12345,\n"
    "  \"int32Field\": -12345678,\n"
    "  \"int64Field\": \"-123456789012345\",\n"
    "  \"uInt8Field\": 234,\n"
    "  \"uInt16Field\": 45678,\n"
    "  \"uInt32Field\": 3456789012,\n"
    "  \"uInt64Field\": \"12345678901234567890\",\n"
    "  \"float32Field\": 1234.5,\n"
    "  \"float64Field\": -1.23e47,\n"
    "  \"textField\": \"foo\",\n"
    "  \"dataField\": [98, 97, 114],\n"
    "  \"structField\": {\n"
    "    \"voidField\": null,\n"
    "    \"boolField\": true,\n"
    "    \"int8Field\": -12,\n"
    "    \"int16Field\": 3456,\n"
    "    \"int32Field\": -78901234,\n"
    "    \"int64Field\": \"56789012345678\",\n"
    "    \"uInt8Field\": 90,\n"
    "    \"uInt16Field\": 1234,\n"
    "    \"uInt32Field\": 56789012,\n"
    "    \"uInt64Field\": \"345678901234567890\",\n"
    "    \"float32Field\": -1.2499999646475857e-10,\n"
    "    \"float64Field\": 345,\n"
    "    \"textField\": \"baz\",\n"
    "    \"dataField\": [113, 117, 120],\n"
    "    \"structField\": {\n"
    "      \"voidField\": null,\n"
    "      \"boolField\": false,\n"
    "      \"int8Field\": 0,\n"
    "      \"int16Field\": 0,\n"
    "      \"int32Field\": 0,\n"
    "      \"int64Field\": \"0\",\n"
    "      \"uInt8Field\": 0,\n"
    "      \"uInt16Field\": 0,\n"
    "      \"uInt32Field\": 0,\n"
    "      \"uInt64Field\": \"0\",\n"
    "      \"float32Field\": 0,\n"
    "      \"float64Field\": 0,\n"
    "      \"textField\": \"nested\",\n"
    "      \"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"
    "      \"enumField\": \"foo\",\n"
    "      \"interfaceField\": null },\n"
    "    \"enumField\": \"baz\",\n"
    "    \"interfaceField\": null,\n"
    "    \"voidList\": [null, null, null],\n"
    "    \"boolList\": [false, true, false, true, true],\n"
    "    \"int8List\": [12, -34, -128, 127],\n"
    "    \"int16List\": [1234, -5678, -32768, 32767],\n"
    "    \"int32List\": [12345678, -90123456, -2147483648, 2147483647],\n"
    "    \"int64List\": [\"123456789012345\", \"-678901234567890\", \"-9223372036854775808\", \"9223372036854775807\"],\n"
    "    \"uInt8List\": [12, 34, 0, 255],\n"
    "    \"uInt16List\": [1234, 5678, 0, 65535],\n"
    "    \"uInt32List\": [12345678, 90123456, 0, 4294967295],\n"
    "    \"uInt64List\": [\"123456789012345\", \"678901234567890\", \"0\", \"18446744073709551615\"],\n"
    "    \"float32List\": [0, 1234567, 9.9999999338158125e36, -9.9999999338158125e36, 9.99999991097579e-38, -9.99999991097579e-38],\n"
    "    \"float64List\": [0, 123456789012345, 1e306, -1e306, 1e-306, -1e-306],\n"
    "    \"textList\": [\"quux\", \"corge\", \"grault\"],\n"
    "    \"dataList\": [[103, 97, 114, 112, 108, 121], [119, 97, 108, 100, 111], [102, 114, 101, 100]],\n"
    "    \"structList\": [\n"
    "      {\"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"
    "      {\"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"
    "      {\"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"
    "    \"enumList\": [\"qux\", \"bar\", \"grault\"] },\n"
    "  \"enumField\": \"corge\",\n"
    "  \"interfaceField\": null,\n"
    "  \"voidList\": [null, null, null, null, null, null],\n"
    "  \"boolList\": [true, false, false, true],\n"
    "  \"int8List\": [111, -111],\n"
    "  \"int16List\": [11111, -11111],\n"
    "  \"int32List\": [111111111, -111111111],\n"
    "  \"int64List\": [\"1111111111111111111\", \"-1111111111111111111\"],\n"
    "  \"uInt8List\": [111, 222],\n"
    "  \"uInt16List\": [33333, 44444],\n"
    "  \"uInt32List\": [3333333333],\n"
    "  \"uInt64List\": [\"11111111111111111111\"],\n"
133 134
    "  \"float32List\": [5555.5, \"Infinity\", \"-Infinity\", \"NaN\"],\n"
    "  \"float64List\": [7777.75, \"Infinity\", \"-Infinity\", \"NaN\"],\n"
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
    "  \"textList\": [\"plugh\", \"xyzzy\", \"thud\"],\n"
    "  \"dataList\": [[111, 111, 112, 115], [101, 120, 104, 97, 117, 115, 116, 101, 100], [114, 102, 99, 51, 48, 57, 50]],\n"
    "  \"structList\": [\n"
    "    {\"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"
    "    {\"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"
    "    {\"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"
    "  \"enumList\": [\"foo\", \"garply\"] }";

KJ_TEST("encode all types") {
  MallocMessageBuilder message;
  auto root = message.getRoot<TestAllTypes>();
  initTestMessage(root);

  JsonCodec json;
  json.setPrettyPrint(true);
  KJ_EXPECT(json.encode(root) == ALL_TYPES_JSON);

  // Verify that if we strip out the non-string spaces, we get the non-pretty-print version.
  kj::Vector<char> chars;
  bool inQuotes = false;
  for (char c: ALL_TYPES_JSON) {
    if (c == '\"') inQuotes = !inQuotes;

    if ((c == '\n' || c == ' ') && !inQuotes) {
      // skip space
    } else {
      chars.add(c);
    }
  }
  kj::String nospaces(chars.releaseAsArray());

  json.setPrettyPrint(false);
  KJ_EXPECT(json.encode(root) == nospaces);
}

KJ_TEST("encode union") {
  MallocMessageBuilder message;
  auto root = message.getRoot<test::TestUnnamedUnion>();

  root.setBefore("a");
  root.setMiddle(44);
  root.setAfter("c");

  JsonCodec json;

  root.setFoo(123);
  KJ_EXPECT(json.encode(root) == "{\"before\":\"a\",\"foo\":123,\"middle\":44,\"after\":\"c\"}");

  root.setBar(321);
  KJ_EXPECT(json.encode(root) == "{\"before\":\"a\",\"middle\":44,\"bar\":321,\"after\":\"c\"}");
}

187 188
KJ_TEST("decode all types") {
  JsonCodec json;
189 190 191
  json.setHasMode(HasMode::NON_DEFAULT);

#define CASE_MAYBE_ROUNDTRIP(s, f, roundtrip) \
192
  { \
193 194
    MallocMessageBuilder message; \
    auto root = message.initRoot<TestAllTypes>(); \
195 196 197 198 199
    kj::StringPtr input = s; \
    json.decode(input, root); \
    KJ_EXPECT((f), input, root); \
    auto reencoded = json.encode(root); \
    KJ_EXPECT(roundtrip == (input == reencoded), roundtrip, input, reencoded); \
200
  }
201 202
#define CASE_NO_ROUNDTRIP(s, f) CASE_MAYBE_ROUNDTRIP(s, f, false)
#define CASE(s, f) CASE_MAYBE_ROUNDTRIP(s, f, true)
203 204 205 206 207 208
#define CASE_THROW(s, errorMessage) \
  { \
    MallocMessageBuilder message; \
    auto root = message.initRoot<TestAllTypes>(); \
    KJ_EXPECT_THROW_MESSAGE(errorMessage, json.decode(s, root)); \
  }
209 210 211 212 213 214
#define CASE_THROW_RECOVERABLE(s, errorMessage) \
  { \
    MallocMessageBuilder message; \
    auto root = message.initRoot<TestAllTypes>(); \
    KJ_EXPECT_THROW_RECOVERABLE_MESSAGE(errorMessage, json.decode(s, root)); \
  }
215 216

  CASE(R"({})", root.getBoolField() == false);
217
  CASE_NO_ROUNDTRIP(R"({"unknownField":7})", root.getBoolField() == false);
218
  CASE(R"({"boolField":true})", root.getBoolField() == true);
219
  CASE(R"({"int8Field":-128})", root.getInt8Field() == -128);
220
  CASE_NO_ROUNDTRIP(R"({"int8Field":"127"})", root.getInt8Field() == 127);
221 222
  CASE_THROW_RECOVERABLE(R"({"int8Field":"-129"})", "Value out-of-range");
  CASE_THROW_RECOVERABLE(R"({"int8Field":128})", "Value out-of-range");
223
  CASE(R"({"int16Field":-32768})", root.getInt16Field() == -32768);
224
  CASE_NO_ROUNDTRIP(R"({"int16Field":"32767"})", root.getInt16Field() == 32767);
225 226
  CASE_THROW_RECOVERABLE(R"({"int16Field":"-32769"})", "Value out-of-range");
  CASE_THROW_RECOVERABLE(R"({"int16Field":32768})", "Value out-of-range");
227
  CASE(R"({"int32Field":-2147483648})", root.getInt32Field() == -2147483648);
228 229 230
  CASE_NO_ROUNDTRIP(R"({"int32Field":"2147483647"})", root.getInt32Field() == 2147483647);
  CASE_NO_ROUNDTRIP(R"({"int64Field":-9007199254740992})", root.getInt64Field() == -9007199254740992LL);
  CASE_NO_ROUNDTRIP(R"({"int64Field":9007199254740991})", root.getInt64Field() == 9007199254740991LL);
231
  CASE(R"({"int64Field":"-9223372036854775808"})", root.getInt64Field() == -9223372036854775808ULL);
232
  CASE(R"({"int64Field":"9223372036854775807"})", root.getInt64Field() == 9223372036854775807LL);
233 234
  CASE_THROW_RECOVERABLE(R"({"int64Field":"-9223372036854775809"})", "Value out-of-range");
  CASE_THROW_RECOVERABLE(R"({"int64Field":"9223372036854775808"})", "Value out-of-range");
235
  CASE(R"({"uInt8Field":255})", root.getUInt8Field() == 255);
236
  CASE_NO_ROUNDTRIP(R"({"uInt8Field":"0"})", root.getUInt8Field() == 0);
237 238
  CASE_THROW_RECOVERABLE(R"({"uInt8Field":"256"})", "Value out-of-range");
  CASE_THROW_RECOVERABLE(R"({"uInt8Field":-1})", "Value out-of-range");
239
  CASE(R"({"uInt16Field":65535})", root.getUInt16Field() == 65535);
240
  CASE_NO_ROUNDTRIP(R"({"uInt16Field":"0"})", root.getUInt16Field() == 0);
241 242
  CASE_THROW_RECOVERABLE(R"({"uInt16Field":"655356"})", "Value out-of-range");
  CASE_THROW_RECOVERABLE(R"({"uInt16Field":-1})", "Value out-of-range");
243
  CASE(R"({"uInt32Field":4294967295})", root.getUInt32Field() == 4294967295);
244
  CASE_NO_ROUNDTRIP(R"({"uInt32Field":"0"})", root.getUInt32Field() == 0);
245 246
  CASE_THROW_RECOVERABLE(R"({"uInt32Field":"42949672956"})", "Value out-of-range");
  CASE_THROW_RECOVERABLE(R"({"uInt32Field":-1})", "Value out-of-range");
247
  CASE_NO_ROUNDTRIP(R"({"uInt64Field":9007199254740991})", root.getUInt64Field() == 9007199254740991ULL);
248
  CASE(R"({"uInt64Field":"18446744073709551615"})", root.getUInt64Field() == 18446744073709551615ULL);
249
  CASE_NO_ROUNDTRIP(R"({"uInt64Field":"0"})", root.getUInt64Field() == 0);
250
  CASE_THROW_RECOVERABLE(R"({"uInt64Field":"18446744073709551616"})", "Value out-of-range");
251
  CASE_NO_ROUNDTRIP(R"({"float32Field":0})", root.getFloat32Field() == 0);
252
  CASE(R"({"float32Field":4.5})", root.getFloat32Field() == 4.5);
253 254 255
  CASE_NO_ROUNDTRIP(R"({"float32Field":null})", kj::isNaN(root.getFloat32Field()));
  CASE(R"({"float32Field":"NaN"})", kj::isNaN(root.getFloat32Field()));
  CASE_NO_ROUNDTRIP(R"({"float32Field":"nan"})", kj::isNaN(root.getFloat32Field()));
256 257
  CASE(R"({"float32Field":"Infinity"})", root.getFloat32Field() == kj::inf());
  CASE(R"({"float32Field":"-Infinity"})", root.getFloat32Field() == -kj::inf());
258 259 260 261
  CASE_NO_ROUNDTRIP(R"({"float32Field":"infinity"})", root.getFloat32Field() == kj::inf());
  CASE_NO_ROUNDTRIP(R"({"float32Field":"-infinity"})", root.getFloat32Field() == -kj::inf());
  CASE_NO_ROUNDTRIP(R"({"float32Field":"INF"})", root.getFloat32Field() == kj::inf());
  CASE_NO_ROUNDTRIP(R"({"float32Field":"-INF"})", root.getFloat32Field() == -kj::inf());
262 263
  CASE_NO_ROUNDTRIP(R"({"float32Field":1e39})", root.getFloat32Field() == kj::inf());
  CASE_NO_ROUNDTRIP(R"({"float32Field":-1e39})", root.getFloat32Field() == -kj::inf());
264
  CASE_NO_ROUNDTRIP(R"({"float64Field":0})", root.getFloat64Field() == 0);
265
  CASE(R"({"float64Field":4.5})", root.getFloat64Field() == 4.5);
266 267 268
  CASE_NO_ROUNDTRIP(R"({"float64Field":null})", kj::isNaN(root.getFloat64Field()));
  CASE(R"({"float64Field":"NaN"})", kj::isNaN(root.getFloat64Field()));
  CASE_NO_ROUNDTRIP(R"({"float64Field":"nan"})", kj::isNaN(root.getFloat64Field()));
269
  CASE(R"({"float64Field":"Infinity"})", root.getFloat64Field() == kj::inf());
270 271 272 273
  CASE_NO_ROUNDTRIP(R"({"float64Field":"infinity"})", root.getFloat64Field() == kj::inf());
  CASE_NO_ROUNDTRIP(R"({"float64Field":"-infinity"})", root.getFloat64Field() == -kj::inf());
  CASE_NO_ROUNDTRIP(R"({"float64Field":"INF"})", root.getFloat64Field() == kj::inf());
  CASE_NO_ROUNDTRIP(R"({"float64Field":"-INF"})", root.getFloat64Field() == -kj::inf());
274 275
  CASE_NO_ROUNDTRIP(R"({"float64Field":1e309})", root.getFloat64Field() == kj::inf());
  CASE_NO_ROUNDTRIP(R"({"float64Field":-1e309})", root.getFloat64Field() == -kj::inf());
276 277 278 279 280
  CASE(R"({"textField":"hello"})", kj::str("hello") == root.getTextField());
  CASE(R"({"dataField":[7,0,122]})",
      kj::heapArray<byte>({7,0,122}).asPtr() == root.getDataField());
  CASE(R"({"structField":{}})", root.hasStructField() == true);
  CASE(R"({"structField":{}})", root.getStructField().getBoolField() == false);
281
  CASE_NO_ROUNDTRIP(R"({"structField":{"boolField":false}})", root.getStructField().getBoolField() == false);
282 283 284
  CASE(R"({"structField":{"boolField":true}})", root.getStructField().getBoolField() == true);
  CASE(R"({"enumField":"bar"})", root.getEnumField() == TestEnum::BAR);

285
  CASE_NO_ROUNDTRIP(R"({"textField":"foo\u1234bar"})",
Kenton Varda's avatar
Kenton Varda committed
286
      kj::str(u8"foo\u1234bar") == root.getTextField());
287

288 289 290 291
  CASE_THROW_RECOVERABLE(R"({"structField":null})", "Expected object value");
  CASE_THROW_RECOVERABLE(R"({"structList":null})", "Expected list value");
  CASE_THROW_RECOVERABLE(R"({"boolList":null})", "Expected list value");
  CASE_THROW_RECOVERABLE(R"({"structList":[null]})", "Expected object value");
292 293 294
  CASE_THROW_RECOVERABLE(R"({"int64Field":"177a"})", "String does not contain valid");
  CASE_THROW_RECOVERABLE(R"({"uInt64Field":"177a"})", "String does not contain valid");
  CASE_THROW_RECOVERABLE(R"({"float64Field":"177a"})", "String does not contain valid");
295

296 297 298
  CASE(R"({})", root.hasBoolList() == false);
  CASE(R"({"boolList":[]})", root.hasBoolList() == true);
  CASE(R"({"boolList":[]})", root.getBoolList().size() == 0);
299
  CASE(R"({"boolList":[false]})", root.getBoolList().size() == 1);
300 301 302
  CASE(R"({"boolList":[false]})", root.getBoolList()[0] == false);
  CASE(R"({"boolList":[true]})", root.getBoolList()[0] == true);
  CASE(R"({"int8List":[7]})", root.getInt8List()[0] == 7);
303
  CASE_NO_ROUNDTRIP(R"({"int8List":["7"]})", root.getInt8List()[0] == 7);
304
  CASE(R"({"int16List":[7]})", root.getInt16List()[0] == 7);
305
  CASE_NO_ROUNDTRIP(R"({"int16List":["7"]})", root.getInt16List()[0] == 7);
306
  CASE(R"({"int32List":[7]})", root.getInt32List()[0] == 7);
307 308
  CASE_NO_ROUNDTRIP(R"({"int32List":["7"]})", root.getInt32List()[0] == 7);
  CASE_NO_ROUNDTRIP(R"({"int64List":[7]})", root.getInt64List()[0] == 7);
309 310
  CASE(R"({"int64List":["7"]})", root.getInt64List()[0] == 7);
  CASE(R"({"uInt8List":[7]})", root.getUInt8List()[0] == 7);
311
  CASE_NO_ROUNDTRIP(R"({"uInt8List":["7"]})", root.getUInt8List()[0] == 7);
312
  CASE(R"({"uInt16List":[7]})", root.getUInt16List()[0] == 7);
313
  CASE_NO_ROUNDTRIP(R"({"uInt16List":["7"]})", root.getUInt16List()[0] == 7);
314
  CASE(R"({"uInt32List":[7]})", root.getUInt32List()[0] == 7);
315 316
  CASE_NO_ROUNDTRIP(R"({"uInt32List":["7"]})", root.getUInt32List()[0] == 7);
  CASE_NO_ROUNDTRIP(R"({"uInt64List":[7]})", root.getUInt64List()[0] == 7);
317
  CASE(R"({"uInt64List":["7"]})", root.getUInt64List()[0] == 7);
318
  CASE(R"({"float32List":[4.5]})", root.getFloat32List()[0] == 4.5);
319 320 321 322 323
  CASE_NO_ROUNDTRIP(R"({"float32List":["4.5"]})", root.getFloat32List()[0] == 4.5);
  CASE_NO_ROUNDTRIP(R"({"float32List":[null]})", kj::isNaN(root.getFloat32List()[0]));
  CASE(R"({"float32List":["NaN"]})", kj::isNaN(root.getFloat32List()[0]));
  CASE(R"({"float32List":["Infinity"]})", root.getFloat32List()[0] == kj::inf());
  CASE(R"({"float32List":["-Infinity"]})", root.getFloat32List()[0] == -kj::inf());
324
  CASE(R"({"float64List":[4.5]})", root.getFloat64List()[0] == 4.5);
325 326 327 328 329
  CASE_NO_ROUNDTRIP(R"({"float64List":["4.5"]})", root.getFloat64List()[0] == 4.5);
  CASE_NO_ROUNDTRIP(R"({"float64List":[null]})", kj::isNaN(root.getFloat64List()[0]));
  CASE(R"({"float64List":["NaN"]})", kj::isNaN(root.getFloat64List()[0]));
  CASE(R"({"float64List":["Infinity"]})", root.getFloat64List()[0] == kj::inf());
  CASE(R"({"float64List":["-Infinity"]})", root.getFloat64List()[0] == -kj::inf());
330 331 332
  CASE(R"({"textList":["hello"]})", kj::str("hello") == root.getTextList()[0]);
  CASE(R"({"dataList":[[7,0,122]]})",
      kj::heapArray<byte>({7,0,122}).asPtr() == root.getDataList()[0]);
333
  CASE(R"({"structList":[{}]})", root.hasStructList() == true);
334
  CASE(R"({"structList":[{}]})", root.getStructList()[0].getBoolField() == false);
335
  CASE_NO_ROUNDTRIP(R"({"structList":[{"boolField":false}]})", root.getStructList()[0].getBoolField() == false);
336 337
  CASE(R"({"structList":[{"boolField":true}]})", root.getStructList()[0].getBoolField() == true);
  CASE(R"({"enumList":["bar"]})", root.getEnumList()[0] == TestEnum::BAR);
338 339
#undef CASE_MAYBE_ROUNDTRIP
#undef CASE_NO_ROUNDTRIP
340
#undef CASE
341
#undef CASE_THROW
342
#undef CASE_THROW_RECOVERABLE
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
}

KJ_TEST("decode test message") {
  MallocMessageBuilder message;
  auto root = message.getRoot<TestAllTypes>();
  initTestMessage(root);

  JsonCodec json;
  auto encoded = json.encode(root);

  MallocMessageBuilder decodedMessage;
  auto decodedRoot = decodedMessage.initRoot<TestAllTypes>();
  json.decode(encoded, decodedRoot);

  KJ_EXPECT(root.toString().flatten() == decodedRoot.toString().flatten());
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
KJ_TEST("basic json decoding") {
  // TODO(cleanup): this test is a mess!
  JsonCodec json;
  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();
    json.decodeRaw("null", root);

    KJ_EXPECT(root.which() == JsonValue::NULL_);
    KJ_EXPECT(root.getNull() == VOID);
  }

  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    json.decodeRaw("false", root);
    KJ_EXPECT(root.which() == JsonValue::BOOLEAN);
    KJ_EXPECT(root.getBoolean() == false);
  }

  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    json.decodeRaw("true", root);
    KJ_EXPECT(root.which() == JsonValue::BOOLEAN);
    KJ_EXPECT(root.getBoolean() == true);
  }

  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    json.decodeRaw("\"foo\"", root);
    KJ_EXPECT(root.which() == JsonValue::STRING);
    KJ_EXPECT(kj::str("foo") == root.getString());
  }

  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    json.decodeRaw(R"("\"")", root);
    KJ_EXPECT(root.which() == JsonValue::STRING);
    KJ_EXPECT(kj::str("\"") == root.getString());
  }

  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    json.decodeRaw(R"("\\abc\"d\\e")", root);
    KJ_EXPECT(root.which() == JsonValue::STRING);
    KJ_EXPECT(kj::str("\\abc\"d\\e") == root.getString());
  }

  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    json.decodeRaw(R"("\"\\\/\b\f\n\r\t\u0003abc\u0064\u0065f")", root);
    KJ_EXPECT(root.which() == JsonValue::STRING);
    KJ_EXPECT(kj::str("\"\\/\b\f\n\r\t\x03""abcdef") == root.getString(), root.getString());
  }
  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    json.decodeRaw("[]", root);
Kenton Varda's avatar
Kenton Varda committed
430
    KJ_EXPECT(root.which() == JsonValue::ARRAY, (uint)root.which());
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 466
    KJ_EXPECT(root.getArray().size() == 0);
  }

  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    json.decodeRaw("[true]", root);
    KJ_EXPECT(root.which() == JsonValue::ARRAY);
    auto array = root.getArray();
    KJ_EXPECT(array.size() == 1, array.size());
    KJ_EXPECT(root.getArray()[0].which() == JsonValue::BOOLEAN);
    KJ_EXPECT(root.getArray()[0].getBoolean() == true);
  }

  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    json.decodeRaw("  [  true  , false\t\n , null]", root);
    KJ_EXPECT(root.which() == JsonValue::ARRAY);
    auto array = root.getArray();
    KJ_EXPECT(array.size() == 3);
    KJ_EXPECT(array[0].which() == JsonValue::BOOLEAN);
    KJ_EXPECT(array[0].getBoolean() == true);
    KJ_EXPECT(array[1].which() == JsonValue::BOOLEAN);
    KJ_EXPECT(array[1].getBoolean() == false);
    KJ_EXPECT(array[2].which() == JsonValue::NULL_);
    KJ_EXPECT(array[2].getNull() == VOID);
  }

  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    json.decodeRaw("{}", root);
Kenton Varda's avatar
Kenton Varda committed
467
    KJ_EXPECT(root.which() == JsonValue::OBJECT, (uint)root.which());
468 469 470
    KJ_EXPECT(root.getObject().size() == 0);
  }

471 472 473 474 475 476 477 478 479
  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    json.decodeRaw("\r\n\t {\r\n\t }\r\n\t ", root);
    KJ_EXPECT(root.which() == JsonValue::OBJECT, (uint)root.which());
    KJ_EXPECT(root.getObject().size() == 0);
  }

480 481 482 483 484
  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    json.decodeRaw(R"({"some": null})", root);
Kenton Varda's avatar
Kenton Varda committed
485
    KJ_EXPECT(root.which() == JsonValue::OBJECT, (uint)root.which());
486 487 488 489 490 491 492 493 494 495 496
    auto object = root.getObject();
    KJ_EXPECT(object.size() == 1);
    KJ_EXPECT(kj::str("some") == object[0].getName());
    KJ_EXPECT(object[0].getValue().which() == JsonValue::NULL_);
  }

  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    json.decodeRaw(R"({"foo\n\tbaz": "a val", "bar": ["a", -5.5e11,  { "z": {}}]})", root);
Kenton Varda's avatar
Kenton Varda committed
497
    KJ_EXPECT(root.which() == JsonValue::OBJECT, (uint)root.which());
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
    auto object = root.getObject();
    KJ_EXPECT(object.size() == 2);
    KJ_EXPECT(kj::str("foo\n\tbaz") == object[0].getName());
    KJ_EXPECT(object[0].getValue().which() == JsonValue::STRING);
    KJ_EXPECT(kj::str("a val") == object[0].getValue().getString());

    KJ_EXPECT(kj::str("bar") == object[1].getName());
    KJ_EXPECT(object[1].getValue().which() == JsonValue::ARRAY);
    auto array = object[1].getValue().getArray();
    KJ_EXPECT(array.size() == 3, array.size());
    KJ_EXPECT(array[0].which() == JsonValue::STRING);
    KJ_EXPECT(kj::str("a") == array[0].getString());
    KJ_EXPECT(array[1].which() == JsonValue::NUMBER);
    KJ_EXPECT(array[1].getNumber() == -5.5e11);
    KJ_EXPECT(array[2].which() == JsonValue::OBJECT);
    KJ_EXPECT(array[2].getObject().size() == 1);
    KJ_EXPECT(array[2].getObject()[0].getValue().which() == JsonValue::OBJECT);
    KJ_EXPECT(array[2].getObject()[0].getValue().getObject().size() == 0);
  }

  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    json.decodeRaw("123", root);
    KJ_EXPECT(root.which() == JsonValue::NUMBER);
    KJ_EXPECT(root.getNumber() == 123);
  }

  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
    KJ_EXPECT_THROW_MESSAGE("input", json.decodeRaw("z", root));
  }

  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    // Leading + not allowed in numbers.
    KJ_EXPECT_THROW_MESSAGE("Unexpected", json.decodeRaw("+123", root));
  }

  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    KJ_EXPECT_THROW_MESSAGE("Unexpected", json.decodeRaw("[00]", root));
    KJ_EXPECT_THROW_MESSAGE("Unexpected", json.decodeRaw("[01]", root));
  }

  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

554
    KJ_EXPECT_THROW_MESSAGE("ends prematurely", json.decodeRaw("-", root));
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
  }

  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    json.decodeRaw("-5", root);
    KJ_EXPECT(root.which() == JsonValue::NUMBER);
    KJ_EXPECT(root.getNumber() == -5);
  }

  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    json.decodeRaw("-5.5", root);
    KJ_EXPECT(root.which() == JsonValue::NUMBER);
    KJ_EXPECT(root.getNumber() == -5.5);
  }
574 575 576 577 578 579 580 581

  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("a", root));
    KJ_EXPECT_THROW_MESSAGE("ends prematurely", json.decodeRaw("[", root));
    KJ_EXPECT_THROW_MESSAGE("ends prematurely", json.decodeRaw("{", root));
582
    KJ_EXPECT_THROW_MESSAGE("ends prematurely", json.decodeRaw("\"\\u\"", root));
583 584 585 586 587
    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("[}", root));
    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("{]", root));
    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("[}]", root));
    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("[1, , ]", root));
    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("[,]", root));
588
    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("[true,]", root));
589
    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("[, 1]", root));
590 591 592
    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("[1\"\"]", root));
    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("[1,, \"\"]", root));
    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("{\"a\"1: 0}", root));
593
    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw(R"({"some": null,})", root));
594
    KJ_EXPECT_THROW_MESSAGE("Input remains", json.decodeRaw("11a", root));
595 596
    KJ_EXPECT_THROW_MESSAGE("Invalid escape", json.decodeRaw(R"("\z")", root));
    KJ_EXPECT_THROW_MESSAGE("Invalid escape", json.decodeRaw(R"("\z")", root));
597 598 599 600 601 602
    {
      // TODO(msvc):  This raw string literal currently confuses MSVC's preprocessor, so I hoisted
      // it outside the macro.
      auto f = [&] { json.decodeRaw(R"(["\n\", 3])", root); };
      KJ_EXPECT_THROW_MESSAGE("ends prematurely", f());
    }
603
    KJ_EXPECT_THROW_MESSAGE("Invalid hex", json.decodeRaw(R"("\u12zz")", root));
604 605
    KJ_EXPECT_THROW_MESSAGE("ends prematurely", json.decodeRaw("-", root));
    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("--", root));
606 607
    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("\f{}", root));
    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("{\v}", root));
608
  }
609 610
}

611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
KJ_TEST("maximum nesting depth") {
  JsonCodec json;
  auto input = kj::str(R"({"foo": "a", "bar": ["b", { "baz": [-5.5e11] }, [ [ 1 ], {  "z": 2 }]]})");
  // `input` has a maximum nesting depth of 4, reached 3 times.

  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    json.decodeRaw(input, root);
  }

  {
    json.setMaxNestingDepth(0);
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    KJ_EXPECT_THROW_MESSAGE("nest",
        json.decodeRaw(input, root));
  }

  {
    json.setMaxNestingDepth(3);
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    KJ_EXPECT_THROW_MESSAGE("nest",
        json.decodeRaw(input, root));
  }

  {
    json.setMaxNestingDepth(4);
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    json.decodeRaw(input, root);
  }
}

650
class TestCallHandler: public JsonCodec::Handler<Text> {
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
public:
  void encode(const JsonCodec& codec, Text::Reader input,
              JsonValue::Builder output) const override {
    auto call = output.initCall();
    call.setFunction("Frob");
    auto params = call.initParams(2);
    params[0].setNumber(123);
    params[1].setString(input);
  }

  Orphan<Text> decode(const JsonCodec& codec, JsonValue::Reader input,
                      Orphanage orphanage) const override {
    KJ_UNIMPLEMENTED("TestHandler::decode");
  }
};

667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
class TestDynamicStructHandler: public JsonCodec::Handler<DynamicStruct> {
public:
  void encode(const JsonCodec& codec, DynamicStruct::Reader input,
              JsonValue::Builder output) const override {
    auto fields = input.getSchema().getFields();
    auto items = output.initArray(fields.size());
    for (auto field: fields) {
      KJ_REQUIRE(field.getIndex() < items.size());
      auto item = items[field.getIndex()];
      if (input.has(field)) {
        codec.encode(input.get(field), field.getType(), item);
      } else {
        item.setNull();
      }
    }
  }

  void decode(const JsonCodec& codec, JsonValue::Reader input,
              DynamicStruct::Builder output) const override {
    auto orphanage = Orphanage::getForMessageContaining(output);
    auto fields = output.getSchema().getFields();
    auto items = input.getArray();
    for (auto field: fields) {
      KJ_REQUIRE(field.getIndex() < items.size());
      auto item = items[field.getIndex()];
      if (!item.isNull()) {
        output.adopt(field, codec.decode(item, field.getType(), orphanage));
      }
    }
  }
};

class TestStructHandler: public JsonCodec::Handler<test::TestOldVersion> {
public:
  void encode(const JsonCodec& codec, test::TestOldVersion::Reader input, JsonValue::Builder output) const override {
    dynamicHandler.encode(codec, input, output);
  }

  void decode(const JsonCodec& codec, JsonValue::Reader input, test::TestOldVersion::Builder output) const override {
    dynamicHandler.decode(codec, input, output);
  }

private:
  TestDynamicStructHandler dynamicHandler;
};
712

713
KJ_TEST("register custom encoding handlers") {
714 715
  JsonCodec json;

716 717 718 719 720 721 722 723 724
  TestStructHandler structHandler;
  json.addTypeHandler(structHandler);

  // JSON decoder can't parse calls back, so test only encoder here
  TestCallHandler callHandler;
  json.addTypeHandler(callHandler);

  MallocMessageBuilder message;
  auto root = message.getRoot<test::TestOldVersion>();
725 726
  root.setOld1(123);
  root.setOld2("foo");
727 728

  KJ_EXPECT(json.encode(root) == "[\"123\",Frob(123,\"foo\"),null]");
729 730
}

731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
KJ_TEST("register custom roundtrip handler") {
  for (auto i = 1; i <= 2; i++) {
    JsonCodec json;
    TestStructHandler staticHandler;
    TestDynamicStructHandler dynamicHandler;
    kj::String encoded;

    if (i == 1) {
      // first iteration: test with explicit struct handler
      json.addTypeHandler(staticHandler);
    } else {
      // second iteration: same checks, but with DynamicStruct handler
      json.addTypeHandler(StructSchema::from<test::TestOldVersion>(), dynamicHandler);
    }

    {
      MallocMessageBuilder message;
      auto root = message.getRoot<test::TestOldVersion>();
      root.setOld1(123);
      root.initOld3().setOld2("foo");

      encoded = json.encode(root);

      KJ_EXPECT(encoded == "[\"123\",null,[\"0\",\"foo\",null]]");
    }
756

757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
    {
      MallocMessageBuilder message;
      auto root = message.getRoot<test::TestOldVersion>();
      json.decode(encoded, root);

      KJ_EXPECT(root.getOld1() == 123);
      KJ_EXPECT(!root.hasOld2());
      auto nested = root.getOld3();
      KJ_EXPECT(nested.getOld1() == 0);
      KJ_EXPECT("foo" == nested.getOld2());
      KJ_EXPECT(!nested.hasOld3());
    }
  }
}

KJ_TEST("register field handler") {
  TestStructHandler handler;
774
  JsonCodec json;
775
  json.addFieldHandler(StructSchema::from<test::TestOldVersion>().getFieldByName("old3"),
776 777
                       handler);

778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
  kj::String encoded;

  {
    MallocMessageBuilder message;
    auto root = message.getRoot<test::TestOldVersion>();
    root.setOld1(123);
    root.setOld2("foo");
    auto nested = root.initOld3();
    nested.setOld2("bar");

    encoded = json.encode(root);

    KJ_EXPECT(encoded == "{\"old1\":\"123\",\"old2\":\"foo\",\"old3\":[\"0\",\"bar\",null]}")
  }

  {
    MallocMessageBuilder message;
    auto root = message.getRoot<test::TestOldVersion>();
    json.decode(encoded, root);

    KJ_EXPECT(root.getOld1() == 123);
    KJ_EXPECT("foo" == root.getOld2());
    auto nested = root.getOld3();
    KJ_EXPECT(nested.getOld1() == 0);
    KJ_EXPECT("bar" == nested.getOld2());
    KJ_EXPECT(!nested.hasOld3());
  }
805 806
}

807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
class TestCapabilityHandler: public JsonCodec::Handler<test::TestInterface> {
public:
  void encode(const JsonCodec& codec, test::TestInterface::Client input,
              JsonValue::Builder output) const override {
    KJ_UNIMPLEMENTED("TestCapabilityHandler::encode");
  }

  test::TestInterface::Client decode(
      const JsonCodec& codec, JsonValue::Reader input) const override {
    return nullptr;
  }
};

KJ_TEST("register capability handler") {
  // This test currently only checks that this compiles, which at one point wasn't the caes.
  // TODO(test): Actually run some code here.

  TestCapabilityHandler handler;
  JsonCodec json;
  json.addTypeHandler(handler);
}

829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
static constexpr kj::StringPtr GOLDEN_ANNOTATED =
R"({ "names-can_contain!anything Really": "foo",
  "flatFoo": 123,
  "flatBar": "abc",
  "renamed-flatBaz": {"hello": true},
  "flatQux": "cba",
  "pfx.foo": "this is a long string in order to force multi-line pretty printing",
  "pfx.renamed-bar": 321,
  "pfx.baz": {"hello": true},
  "pfx.xfp.qux": "fed",
  "union-type": "renamed-bar",
  "barMember": 789,
  "multiMember": "ghi",
  "dependency": {"renamed-foo": "corge"},
  "simpleGroup": {"renamed-grault": "garply"},
844
  "enums": ["qux", "renamed-bar", "foo", "renamed-baz"],
845
  "innerJson": [123, "hello", {"object": true}],
846 847
  "customFieldHandler": "add-prefix-waldo",
  "testBase64": "ZnJlZA==",
848 849
  "testHex": "706c756768",
  "bUnion": "renamed-bar",
850
  "bValue": 678,
851 852
  "externalUnion": {"type": "bar", "value": "cba"},
  "unionWithVoid": {"type": "voidValue"} })"_kj;
853 854 855

static constexpr kj::StringPtr GOLDEN_ANNOTATED_REVERSE =
R"({
856
  "unionWithVoid": {"type": "voidValue"},
857
  "externalUnion": {"type": "bar", "value": "cba"},
858
  "bValue": 678,
859
  "bUnion": "renamed-bar",
860 861
  "testHex": "706c756768",
  "testBase64": "ZnJlZA==",
862
  "customFieldHandler": "add-prefix-waldo",
863
  "innerJson": [123, "hello", {"object": true}],
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
  "enums": ["qux", "renamed-bar", "foo", "renamed-baz"],
  "simpleGroup": { "renamed-grault": "garply" },
  "dependency": { "renamed-foo": "corge" },
  "multiMember": "ghi",
  "barMember": 789,
  "union-type": "renamed-bar",
  "pfx.xfp.qux": "fed",
  "pfx.baz": {"hello": true},
  "pfx.renamed-bar": 321,
  "pfx.foo": "this is a long string in order to force multi-line pretty printing",
  "flatQux": "cba",
  "renamed-flatBaz": {"hello": true},
  "flatBar": "abc",
  "flatFoo": 123,
  "names-can_contain!anything Really": "foo"
})"_kj;

881 882 883 884 885 886 887 888 889 890 891 892
class PrefixAdder: public JsonCodec::Handler<capnp::Text> {
public:
  void encode(const JsonCodec& codec, capnp::Text::Reader input, JsonValue::Builder output) const {
    output.setString(kj::str("add-prefix-", input));
  }

  Orphan<capnp::Text> decode(const JsonCodec& codec, JsonValue::Reader input,
                             Orphanage orphanage) const {
    return orphanage.newOrphanCopy(capnp::Text::Reader(input.getString().slice(11)));
  }
};

893 894 895 896 897
KJ_TEST("rename fields") {
  JsonCodec json;
  json.handleByAnnotation<TestJsonAnnotations>();
  json.setPrettyPrint(true);

898 899 900 901
  PrefixAdder customHandler;
  json.addFieldHandler(Schema::from<TestJsonAnnotations>().getFieldByName("customFieldHandler"),
                       customHandler);

902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
  kj::String goldenText;

  {
    MallocMessageBuilder message;
    auto root = message.getRoot<TestJsonAnnotations>();
    root.setSomeField("foo");

    auto aGroup = root.getAGroup();
    aGroup.setFlatFoo(123);
    aGroup.setFlatBar("abc");
    aGroup.getFlatBaz().setHello(true);
    aGroup.getDoubleFlat().setFlatQux("cba");

    auto prefixedGroup = root.getPrefixedGroup();
    prefixedGroup.setFoo("this is a long string in order to force multi-line pretty printing");
    prefixedGroup.setBar(321);
    prefixedGroup.getBaz().setHello(true);
    prefixedGroup.getMorePrefix().setQux("fed");

    auto unionBar = root.getAUnion().initBar();
    unionBar.setBarMember(789);
    unionBar.setMultiMember("ghi");

    root.initDependency().setFoo("corge");
    root.initSimpleGroup().setGrault("garply");

    root.setEnums({
      TestJsonAnnotatedEnum::QUX,
      TestJsonAnnotatedEnum::BAR,
      TestJsonAnnotatedEnum::FOO,
      TestJsonAnnotatedEnum::BAZ
    });

935 936 937 938 939 940 941 942
    auto val = root.initInnerJson();
    auto arr = val.initArray(3);
    arr[0].setNumber(123);
    arr[1].setString("hello");
    auto field = arr[2].initObject(1)[0];
    field.setName("object");
    field.initValue().setBoolean(true);

943 944
    root.setCustomFieldHandler("waldo");

945 946 947
    root.setTestBase64("fred"_kj.asBytes());
    root.setTestHex("plugh"_kj.asBytes());

948
    root.getBUnion().setBar(678);
949

950 951
    root.initExternalUnion().initBar().setValue("cba");

952 953
    root.initUnionWithVoid().setVoidValue();

954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
    auto encoded = json.encode(root.asReader());
    KJ_EXPECT(encoded == GOLDEN_ANNOTATED, encoded);

    goldenText = kj::str(root);
  }

  {
    MallocMessageBuilder message;
    auto root = message.getRoot<TestJsonAnnotations>();
    json.decode(GOLDEN_ANNOTATED, root);

    KJ_EXPECT(kj::str(root) == goldenText, root, goldenText);
  }

  {
    // Try parsing in reverse, mostly to test that union tags can come after content.
    MallocMessageBuilder message;
    auto root = message.getRoot<TestJsonAnnotations>();
    json.decode(GOLDEN_ANNOTATED_REVERSE, root);

    KJ_EXPECT(kj::str(root) == goldenText, root, goldenText);
  }
}

978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
KJ_TEST("base64 union encoded correctly") {
  // At one point field handlers were not correctly applied when the field was a member of a union
  // in a type that was handled by annotation.

  JsonCodec json;
  json.handleByAnnotation<TestBase64Union>();
  json.setPrettyPrint(true);

  MallocMessageBuilder message;
  auto root = message.getRoot<TestBase64Union>();
  root.initFoo(5);

  KJ_EXPECT(json.encode(root) == "{\"foo\": \"AAAAAAA=\"}", json.encode(root));
}

993 994 995
}  // namespace
}  // namespace _ (private)
}  // namespace capnp