json-test.c++ 30.3 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 <kj/debug.h>
26
#include <kj/string.h>
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
#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"
132 133
    "  \"float32List\": [5555.5, \"Infinity\", \"-Infinity\", \"NaN\"],\n"
    "  \"float64List\": [7777.75, \"Infinity\", \"-Infinity\", \"NaN\"],\n"
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
    "  \"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\"}");
}

186 187 188 189
KJ_TEST("decode all types") {
  JsonCodec json;
#define CASE(s, f) \
  { \
190 191
    MallocMessageBuilder message; \
    auto root = message.initRoot<TestAllTypes>(); \
192 193 194
    json.decode(s, root); \
    KJ_EXPECT((f)) \
  }
195 196 197 198 199 200
#define CASE_THROW(s, errorMessage) \
  { \
    MallocMessageBuilder message; \
    auto root = message.initRoot<TestAllTypes>(); \
    KJ_EXPECT_THROW_MESSAGE(errorMessage, json.decode(s, root)); \
  }
201 202 203 204 205 206
#define CASE_THROW_RECOVERABLE(s, errorMessage) \
  { \
    MallocMessageBuilder message; \
    auto root = message.initRoot<TestAllTypes>(); \
    KJ_EXPECT_THROW_RECOVERABLE_MESSAGE(errorMessage, json.decode(s, root)); \
  }
207 208 209 210

  CASE(R"({})", root.getBoolField() == false);
  CASE(R"({"unknownField":7})", root.getBoolField() == false);
  CASE(R"({"boolField":true})", root.getBoolField() == true);
211 212
  CASE(R"({"int8Field":-128})", root.getInt8Field() == -128);
  CASE(R"({"int8Field":"127"})", root.getInt8Field() == 127);
213 214
  CASE_THROW_RECOVERABLE(R"({"int8Field":"-129"})", "Value out-of-range");
  CASE_THROW_RECOVERABLE(R"({"int8Field":128})", "Value out-of-range");
215 216
  CASE(R"({"int16Field":-32768})", root.getInt16Field() == -32768);
  CASE(R"({"int16Field":"32767"})", root.getInt16Field() == 32767);
217 218
  CASE_THROW_RECOVERABLE(R"({"int16Field":"-32769"})", "Value out-of-range");
  CASE_THROW_RECOVERABLE(R"({"int16Field":32768})", "Value out-of-range");
219 220 221 222
  CASE(R"({"int32Field":-2147483648})", root.getInt32Field() == -2147483648);
  CASE(R"({"int32Field":"2147483647"})", root.getInt32Field() == 2147483647);
  CASE(R"({"int64Field":-9007199254740992})", root.getInt64Field() == -9007199254740992LL);
  CASE(R"({"int64Field":9007199254740991})", root.getInt64Field() == 9007199254740991LL);
223
  CASE(R"({"int64Field":"-9223372036854775808"})", root.getInt64Field() == -9223372036854775808ULL);
224
  CASE(R"({"int64Field":"9223372036854775807"})", root.getInt64Field() == 9223372036854775807LL);
225 226
  CASE_THROW_RECOVERABLE(R"({"int64Field":"-9223372036854775809"})", "Value out-of-range");
  CASE_THROW_RECOVERABLE(R"({"int64Field":"9223372036854775808"})", "Value out-of-range");
227 228
  CASE(R"({"uInt8Field":255})", root.getUInt8Field() == 255);
  CASE(R"({"uInt8Field":"0"})", root.getUInt8Field() == 0);
229 230
  CASE_THROW_RECOVERABLE(R"({"uInt8Field":"256"})", "Value out-of-range");
  CASE_THROW_RECOVERABLE(R"({"uInt8Field":-1})", "Value out-of-range");
231 232
  CASE(R"({"uInt16Field":65535})", root.getUInt16Field() == 65535);
  CASE(R"({"uInt16Field":"0"})", root.getUInt16Field() == 0);
233 234
  CASE_THROW_RECOVERABLE(R"({"uInt16Field":"655356"})", "Value out-of-range");
  CASE_THROW_RECOVERABLE(R"({"uInt16Field":-1})", "Value out-of-range");
235 236
  CASE(R"({"uInt32Field":4294967295})", root.getUInt32Field() == 4294967295);
  CASE(R"({"uInt32Field":"0"})", root.getUInt32Field() == 0);
237 238
  CASE_THROW_RECOVERABLE(R"({"uInt32Field":"42949672956"})", "Value out-of-range");
  CASE_THROW_RECOVERABLE(R"({"uInt32Field":-1})", "Value out-of-range");
239 240
  CASE(R"({"uInt64Field":9007199254740991})", root.getUInt64Field() == 9007199254740991ULL);
  CASE(R"({"uInt64Field":"18446744073709551615"})", root.getUInt64Field() == 18446744073709551615ULL);
241
  CASE(R"({"uInt64Field":"0"})", root.getUInt64Field() == 0);
242
  CASE_THROW_RECOVERABLE(R"({"uInt64Field":"18446744073709551616"})", "Value out-of-range");
243 244 245 246 247 248 249 250 251 252 253 254 255 256
  CASE(R"({"float32Field":0})", root.getFloat32Field() == 0);
  CASE(R"({"float32Field":4.5})", root.getFloat32Field() == 4.5);
  CASE(R"({"float32Field":null})", kj::isNaN(root.getFloat32Field()));
  CASE(R"({"float32Field":"nan"})", kj::isNaN(root.getFloat32Field()));
  CASE(R"({"float32Field":"nan"})", kj::isNaN(root.getFloat32Field()));
  CASE(R"({"float32Field":"Infinity"})", root.getFloat32Field() == kj::inf());
  CASE(R"({"float32Field":"-Infinity"})", root.getFloat32Field() == -kj::inf());
  CASE(R"({"float64Field":0})", root.getFloat64Field() == 0);
  CASE(R"({"float64Field":4.5})", root.getFloat64Field() == 4.5);
  CASE(R"({"float64Field":null})", kj::isNaN(root.getFloat64Field()));
  CASE(R"({"float64Field":"nan"})", kj::isNaN(root.getFloat64Field()));
  CASE(R"({"float64Field":"nan"})", kj::isNaN(root.getFloat64Field()));
  CASE(R"({"float64Field":"Infinity"})", root.getFloat64Field() == kj::inf());
  CASE(R"({"float64Field":"-Infinity"})", root.getFloat64Field() == -kj::inf());
257 258 259 260 261 262 263 264 265 266
  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":null})", root.hasStructField() == false);
  CASE(R"({"structField":{}})", root.hasStructField() == true);
  CASE(R"({"structField":{}})", root.getStructField().getBoolField() == false);
  CASE(R"({"structField":{"boolField":false}})", root.getStructField().getBoolField() == false);
  CASE(R"({"structField":{"boolField":true}})", root.getStructField().getBoolField() == true);
  CASE(R"({"enumField":"bar"})", root.getEnumField() == TestEnum::BAR);

267 268 269
  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");
270

271 272 273 274
  CASE(R"({})", root.hasBoolList() == false);
  CASE(R"({"boolList":null})", root.hasBoolList() == false);
  CASE(R"({"boolList":[]})", root.hasBoolList() == true);
  CASE(R"({"boolList":[]})", root.getBoolList().size() == 0);
275
  CASE(R"({"boolList":[false]})", root.getBoolList().size() == 1);
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
  CASE(R"({"boolList":[false]})", root.getBoolList()[0] == false);
  CASE(R"({"boolList":[true]})", root.getBoolList()[0] == true);
  CASE(R"({"int8List":[7]})", root.getInt8List()[0] == 7);
  CASE(R"({"int8List":["7"]})", root.getInt8List()[0] == 7);
  CASE(R"({"int16List":[7]})", root.getInt16List()[0] == 7);
  CASE(R"({"int16List":["7"]})", root.getInt16List()[0] == 7);
  CASE(R"({"int32List":[7]})", root.getInt32List()[0] == 7);
  CASE(R"({"int32List":["7"]})", root.getInt32List()[0] == 7);
  CASE(R"({"int64List":[7]})", root.getInt64List()[0] == 7);
  CASE(R"({"int64List":["7"]})", root.getInt64List()[0] == 7);
  CASE(R"({"uInt8List":[7]})", root.getUInt8List()[0] == 7);
  CASE(R"({"uInt8List":["7"]})", root.getUInt8List()[0] == 7);
  CASE(R"({"uInt16List":[7]})", root.getUInt16List()[0] == 7);
  CASE(R"({"uInt16List":["7"]})", root.getUInt16List()[0] == 7);
  CASE(R"({"uInt32List":[7]})", root.getUInt32List()[0] == 7);
  CASE(R"({"uInt32List":["7"]})", root.getUInt32List()[0] == 7);
  CASE(R"({"uInt64List":[7]})", root.getUInt64List()[0] == 7);
  CASE(R"({"uInt64List":["7"]})", root.getUInt64List()[0] == 7);
294 295 296 297 298 299 300 301 302 303 304 305
  CASE(R"({"float32List":[4.5]})", root.getFloat32List()[0] == 4.5);
  CASE(R"({"float32List":["4.5"]})", root.getFloat32List()[0] == 4.5);
  CASE(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());
  CASE(R"({"float64List":[4.5]})", root.getFloat64List()[0] == 4.5);
  CASE(R"({"float64List":["4.5"]})", root.getFloat64List()[0] == 4.5);
  CASE(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());
306 307 308 309 310 311 312 313 314 315 316
  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]);
  CASE(R"({"structList":null})", root.hasStructList() == false);
  CASE(R"({"structList":[null]})", root.hasStructList() == true);
  CASE(R"({"structList":[null]})", root.getStructList()[0].getBoolField() == false);
  CASE(R"({"structList":[{}]})", root.getStructList()[0].getBoolField() == false);
  CASE(R"({"structList":[{"boolField":false}]})", root.getStructList()[0].getBoolField() == false);
  CASE(R"({"structList":[{"boolField":true}]})", root.getStructList()[0].getBoolField() == true);
  CASE(R"({"enumList":["bar"]})", root.getEnumList()[0] == TestEnum::BAR);
#undef CASE
317
#undef CASE_THROW
318
#undef CASE_THROW_RECOVERABLE
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
}

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());
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
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
406
    KJ_EXPECT(root.which() == JsonValue::ARRAY, (uint)root.which());
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
    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
443
    KJ_EXPECT(root.which() == JsonValue::OBJECT, (uint)root.which());
444 445 446
    KJ_EXPECT(root.getObject().size() == 0);
  }

447 448 449 450 451 452 453 454 455
  {
    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);
  }

456 457 458 459 460
  {
    MallocMessageBuilder message;
    auto root = message.initRoot<JsonValue>();

    json.decodeRaw(R"({"some": null})", root);
Kenton Varda's avatar
Kenton Varda committed
461
    KJ_EXPECT(root.which() == JsonValue::OBJECT, (uint)root.which());
462 463 464 465 466 467 468 469 470 471 472
    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
473
    KJ_EXPECT(root.which() == JsonValue::OBJECT, (uint)root.which());
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
    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>();

507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
    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("Overflow", json.decodeRaw("1e1024", root));
  }

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

    KJ_EXPECT_THROW_MESSAGE("Underflow", json.decodeRaw("1e-1023", 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>();

544
    KJ_EXPECT_THROW_MESSAGE("ends prematurely", json.decodeRaw("-", root));
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
  }

  {
    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);
  }
564 565 566 567 568 569 570 571

  {
    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));
572
    KJ_EXPECT_THROW_MESSAGE("ends prematurely", json.decodeRaw("\"\\u\"", root));
573 574 575 576 577
    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));
578
    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("[true,]", root));
579
    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("[, 1]", root));
580 581 582
    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));
583
    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw(R"({"some": null,})", root));
584
    KJ_EXPECT_THROW_MESSAGE("Input remains", json.decodeRaw("11a", root));
585 586
    KJ_EXPECT_THROW_MESSAGE("Invalid escape", json.decodeRaw(R"("\z")", root));
    KJ_EXPECT_THROW_MESSAGE("Invalid escape", json.decodeRaw(R"("\z")", root));
587 588 589 590 591 592
    {
      // 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());
    }
593
    KJ_EXPECT_THROW_MESSAGE("Invalid hex", json.decodeRaw(R"("\u12zz")", root));
594 595
    KJ_EXPECT_THROW_MESSAGE("ends prematurely", json.decodeRaw("-", root));
    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("--", root));
596 597
    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("\f{}", root));
    KJ_EXPECT_THROW_MESSAGE("Unexpected input", json.decodeRaw("{\v}", root));
598
  }
599 600
}

601 602 603 604 605 606 607 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
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);
  }
}

640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
class TestHandler: public JsonCodec::Handler<Text> {
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");
  }
};

KJ_TEST("register handler") {
  MallocMessageBuilder message;
  auto root = message.getRoot<test::TestOldVersion>();

  TestHandler handler;
  JsonCodec json;
  json.addTypeHandler(handler);

  root.setOld1(123);
  root.setOld2("foo");
  KJ_EXPECT(json.encode(root) == "{\"old1\":\"123\",\"old2\":Frob(123,\"foo\")}");
}

KJ_TEST("register field handler") {
  MallocMessageBuilder message;
  auto root = message.getRoot<test::TestOutOfOrder>();

  TestHandler handler;
  JsonCodec json;
  json.addFieldHandler(StructSchema::from<test::TestOutOfOrder>().getFieldByName("corge"),
                       handler);

  root.setBaz("abcd");
  root.setCorge("efg");
  KJ_EXPECT(json.encode(root) == "{\"corge\":Frob(123,\"efg\"),\"baz\":\"abcd\"}");
}

684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
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);
}

706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
class TestDynamicStructHandler: public JsonCodec::Handler<DynamicStruct> {
public:
  void encode(const JsonCodec& codec, DynamicStruct::Reader input,
              JsonValue::Builder output) const override {
    KJ_UNIMPLEMENTED("TestDynamicStructHandler::encode");
  }

  void decode(const JsonCodec& codec, JsonValue::Reader input,
              DynamicStruct::Builder output) const override {
    KJ_UNIMPLEMENTED("TestDynamicStructHandler::decode");
  }
};


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

  TestDynamicStructHandler handler;
  JsonCodec json;
  json.addTypeHandler(Schema::from<TestAllTypes>(), handler);
}

729 730 731
}  // namespace
}  // namespace _ (private)
}  // namespace capnp