jsonxx_test.cc 19 KB
Newer Older
Swann Perarnau's avatar
Swann Perarnau committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 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 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 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 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
// -*- mode: c++; c-basic-offset: 4; -*-

// Author: Hong Jiang <hong@hjiang.net>
// Include a few sanity tests from https://github.com/isubiker/mljson/
// Include a few samples from http://www.json.org

#include <cassert>
#include <sstream>
#include <string>
#include <iostream>
#include <fstream>

#include "jsonxx.h"

namespace jsonxx {
    extern bool parse_string(std::istream& input, String& value);
    extern bool parse_number(std::istream& input, Number& value);
    extern bool match(const char* pattern, std::istream& input);
}

bool is_asserting() {
    bool asserting = false;
    JSONXX_ASSERT( asserting |= true );
    return asserting;
}

struct custom_type {};      // Used in a test elsewhere

int main(int argc, const char **argv) {

    if( !is_asserting() ) {
        std::cout << "JSONXX_ASSERT(...) is not working. Assertions are disabled somehow. Tests aborted." << std::endl;
        return -1;
    }

    bool verbose = false;
    if( argc > 1 && (std::string(argv[1]) == "-v")) {
        verbose = true;
    }

#   define TEST_ARRAY(...)  TEST( Array().parse(istringstream(#__VA_ARGS__).str()) )
#   define TEST_OBJECT(...) TEST( Object().parse(istringstream(#__VA_ARGS__).str()) )
#   define TEST(...) do { JSONXX_ASSERT( __VA_ARGS__ ); \
    if( verbose ) std::cout << "[OK] " #__VA_ARGS__ << std::endl; \
    } while(0)

    using namespace jsonxx;
    using namespace std;
    {
        string teststr("\"field1\"");
        string value;
        istringstream input(teststr);
        TEST(parse_string(input, value));
        TEST(value == "field1");
    }
    if( Parser != Strict )
    {
        string teststr("'field1'");
        string value;
        istringstream input(teststr);
        TEST(parse_string(input, value));
        TEST(value == "field1");
    }
    {
        string teststr("\"  field1\"");
        string value;
        istringstream input(teststr);
        TEST(parse_string(input, value));
        TEST(value == "  field1");
    }
    if( Parser != Strict )
    {
        string teststr("'  field1'");
        string value;
        istringstream input(teststr);
        TEST(parse_string(input, value));
        TEST(value == "  field1");
    }
    {
        string teststr("  \"field1\"");
        string value;
        istringstream input(teststr);
        TEST(parse_string(input, value));
        TEST(value == "field1");
    }
    if( Parser != Strict )
    {
        string teststr("  'field1'");
        string value;
        istringstream input(teststr);
        TEST(parse_string(input, value));
        TEST(value == "field1");
    }
    {
        // 'escaped text to unescaped text' test
        string teststr("\"\\b\\f\\n\\r\\t\\u0014\\u0002\"");
        string value;
        istringstream input(teststr);
        TEST(parse_string(input, value));
        TEST( value == "\b\f\n\r\t\xe\x2" );
    }
    {
        string teststr("6");
        istringstream input(teststr);
        Number value;
        TEST(parse_number(input, value));
        TEST(value == 6);
    }
    {
        string teststr(" }");
        istringstream input(teststr);
        TEST(match("}", input));
    }
    {
        string teststr("{ \"field1\" : 6 }");
        if(UnquotedKeys == Enabled) {
            teststr = "{ field1 : 6 }";
        }
        istringstream input(teststr);
        Object o;
        TEST(o.parse(input));
    }
    {
        string teststr("{ \"field1 : 6 }");
        istringstream input(teststr);
        Object o;
        TEST(!o.parse(input));
    }
    {
        string teststr("6");
        istringstream input(teststr);
        Value v;
        TEST(v.parse(input));
        TEST(v.is<Number>());
        TEST(v.get<Number>() == 6);
    }
    {
        string teststr("+6");
        istringstream input(teststr);
        Value v;
        TEST(v.parse(input));
        TEST(v.is<Number>());
        TEST(v.get<Number>() == 6);
    }
    {
        string teststr("-6");
        istringstream input(teststr);
        Value v;
        TEST(v.parse(input));
        TEST(v.is<Number>());
        TEST(v.get<Number>() == -6);
    }
    {
        string teststr("asdf");
        istringstream input(teststr);
        Value v;
        TEST(!v.parse(input));
    }
    {
        string teststr("true");
        istringstream input(teststr);
        Value v;
        TEST(v.parse(input));
        TEST(v.is<Boolean>());
        TEST(v.get<Boolean>());
    }
    {
        string teststr("false");
        istringstream input(teststr);
        Value v;
        TEST(v.parse(input));
        TEST(v.is<Boolean>());
        TEST(!v.get<Boolean>());
    }
    {
        string teststr("null");
        istringstream input(teststr);
        Value v;
        TEST(v.parse(input));
        TEST(v.is<Null>());
        TEST(!v.is<Boolean>());
    }
    {
        string teststr("\"field1\"");
        istringstream input(teststr);
        Value v;
        TEST(v.parse(input));
        TEST(v.is<String>());
        TEST("field1" == v.get<String>());
        ostringstream stream;
        stream << v;
        TEST(stream.str() == "\"field1\"");
    }
    if( Parser != Strict )
    {
        string teststr("'field1'");
        istringstream input(teststr);
        Value v;
        TEST(v.parse(input));
        TEST(v.is<String>());
        TEST("field1" == v.get<String>());
        ostringstream stream;
        stream << v;
        TEST(stream.str() == "\"field1\"");
    }
    {
        string teststr("[\"field1\", 6]");
        istringstream input(teststr);
        Array a;
        TEST(a.parse(input));
        TEST(a.has<String>(0));
        TEST("field1" == a.get<String>(0));
        TEST(a.has<Number>(1));
        TEST(6 == a.get<Number>(1));
        TEST(!a.has<Boolean>(2));
    }
    {
        string teststr(
                "{"
                "  \"foo\" : 1,"
                "  \"bar\" : false,"
                "  \"person\" : {\"name\" : \"GWB\", \"age\" : 60},"
                "  \"data\": [\"abcd\", 42, 54.7]"
                "}"
                );
        if(UnquotedKeys == Enabled) {
            teststr = 
                    "{"
                    "  foo : 1,"
                    "  bar : false,"
                    "  person : {name : \"GWB\", age : 60},"
                    "  data: [\"abcd\", 42, 54.7]"
                    "}";
        }
        istringstream input(teststr);
        Object o;
        TEST(o.parse(input));
        TEST(1 == o.get<Number>("foo"));
        TEST(o.has<Boolean>("bar"));
        TEST(o.has<Object>("person"));
        TEST(o.get<Object>("person").has<Number>("age"));
        TEST(o.has<Array>("data"));
        TEST(o.get<Array>("data").get<Number>(1) == 42);
        TEST(o.get<Array>("data").get<String>(0) == "abcd");
        TEST(o.get<Array>("data").get<Number>(2) - 54.7 < 1e-6 ||
                - o.get<Array>("data").get<Number>(2) + 54.7 < 1e-6 );
        TEST(!o.has<Number>("data"));
    }
    {
        string teststr("{\"bar\": \"a\\rb\\nc\\td\", \"foo\": true}");
        if(UnquotedKeys == Enabled) {
            teststr = "{bar: \"a\\rb\\nc\\td\", foo: true}";
        }
        istringstream input(teststr);
        Object o;
        TEST(o.parse(input));
        TEST(o.has<String>("bar"));
        TEST(o.get<String>("bar") == "a\rb\nc\td");
        TEST(o.has<Boolean>("foo"));
        TEST(o.get<Boolean>("foo") == true);
    }
    {
        string teststr("[ ]");
        istringstream input(teststr);
        ostringstream output;
        Array root;
        TEST(root.parse(input));
        output << root;
    }

    {
        string teststr("{}");
        istringstream input(teststr);
        Object o;
        TEST(o.parse(input));
    }

    {
        string teststr("{\"attrs\":{}}");
        if(UnquotedKeys == Enabled) {
            teststr = "{attrs:{}}";
        }
        istringstream input(teststr);
        Object o;
        TEST(o.parse(input));
        TEST(o.has<Object>("attrs"));
    }

    {
        string teststr("{\"place\":{\"full_name\":\"Limburg, The Netherlands\""
                       ",\"attributes\":{},\"name\":\"Limburg\","
                       "\"place_type\":\"admin\",\"bounding_box\":{"
                       "\"type\":\"Polygon\",\"coordinates\":"
                       "[[[5.5661376,50.750449],[6.2268848,50.750449],"
                       "[6.2268848,51.7784841],[5.5661376,51.7784841]]]},"
                       "\"url\":\"http:\\/\\/api.twitter.com\\/1\\/geo\\/id\\/"
                       "4ef0c00cbdff9ac8.json\",\"country_code\":\"NL\","
                       "\"id\":\"4ef0c00cbdff9ac8\","
                       "\"country\":\"The Netherlands\"}}");
        if(UnquotedKeys == Enabled) {
            teststr = "{place:{full_name:\"Limburg, The Netherlands\""
                           ",attributes:{},name:\"Limburg\","
                           "place_type:\"admin\",bounding_box:{"
                           "type:\"Polygon\",coordinates:"
                           "[[[5.5661376,50.750449],[6.2268848,50.750449],"
                           "[6.2268848,51.7784841],[5.5661376,51.7784841]]]},"
                           "url:\"http:\\/\\/api.twitter.com\\/1\\/geo\\/id\\/"
                           "4ef0c00cbdff9ac8.json\",country_code:\"NL\","
                           "id:\"4ef0c00cbdff9ac8\","
                           "country:\"The Netherlands\"}}";
        }

        istringstream input(teststr);
        Object o;
        TEST(o.parse(input));
        TEST(o.has<Object>("place"));
        TEST(o.get<Object>("place").has<Object>("attributes"));
    }


    {
        string teststr("{\"file\": \"test.txt\", \"types\": {\"one\": 1, \"two\": 2},"
                       "\"list\": [\"string\", 10]}");
        if(UnquotedKeys == Enabled) {
            teststr = "{file: \"test.txt\", types: {one: 1, two: 2},"
                           "list: [\"string\", 10]}";
        }
        istringstream input(teststr);
        Object o;
        TEST(o.parse(input));
        TEST(o.has<String>("file"));
        TEST(o.has<Object>("types"));
        TEST(o.get<String>("file", "lol.txt") == "test.txt");
        TEST(o.get<Object>("types").has<Number>("one"));
        TEST(!o.get<Object>("types").has<Number>("three"));
        TEST(o.get<Object>("types").get<Number>("three", 3) == 3);
        TEST(o.has<Array>("list"));
        TEST(o.get<Array>("list").has<String>(0));
        TEST(!o.get<Array>("list").has<String>(2));
        TEST(o.get<Array>("list").get<String>(0) == "string");
        TEST(o.get<Array>("list").get<String>(2, "test") == "test");
    }

    if( Parser != Strict && UnquotedKeys == Disabled /* '/' not supported as an identifier */ ) 
    {
        #define QUOTE(...) #__VA_ARGS__
        string input = QUOTE(
        {
          "name/surname":"John Smith",
          'alias': 'Joe',
          "address": {
            "streetAddress": "21 2nd Street",
            "city": "New York",
            "state": "NY",
            "postal-code": 10021,
          },
          "phoneNumbers": [
            "212 555-1111",
            "212 555-2222",
          ],
          "additionalInfo": null,
          "remote": false,
          "height": 62.4,
          "ficoScore": " > 640",
        }
        );

        string sample_output = QUOTE(
        <?xml version="1.0" encoding="UTF-8"?>
        <json:object xsi:schemaLocation="http://www.datapower.com/schemas/json jsonx.xsd"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:json="http://www.ibm.com/xmlns/prod/2009/jsonx">
          <json:string name="name/surname">John Smith</json:string>
          <json:string name="alias">Joe</json:string>
          <json:object name="address">
            <json:string name="streetAddress">21 2nd Street</json:string>
            <json:string name="city">New York</json:string>
            <json:string name="state">NY</json:string>
            <json:number name="postal-code">10021</json:number>
          </json:object>
          <json:array name="phoneNumbers">
            <json:string>212 555-1111</json:string>
            <json:string>212 555-2222</json:string>
          </json:array>
          <json:null name="additionalInfo" />
          <json:boolean name="remote">false</json:boolean>
          <json:number name="height">62.4</json:number>
          <json:string name="ficoScore">&gt; 640</json:string>
        </json:object>
        );

        Object o;
        if( o.parse(input) ) {
            if( verbose ) {
                cout << o.xml(JSONx) << endl;            // XML output, JSONx flavor
                cout << o.xml(JXML) << endl;             // XML output, JXML flavor
                cout << o.xml(JXMLex) << endl;           // XML output, JXMLex flavor
                cout << o.xml(TaggedXML) << endl;        // XML output, tagged XML flavor
            }
        } else {
            TEST( !"provided JSON is valid. jsonxx::Object::operator<<() is broken!" );
        }

        TEST( jsonxx::validate(input) );
    }

    if(UnquotedKeys == Enabled) {
        cout << "Some of tests with 'UnquotedKeys = Enabled' ok." << endl;
        return 0;
    }

    // Four samples from www.json.org
    TEST_OBJECT( {
        "name": "Jack (\"Bee\") Nimble",
        "format": {
            "type":       "rect",
            "width":      1920,
            "height":     1080,
            "interlace":  false,
            "frame rate": 24
        }
    } );
    TEST_OBJECT( { "color": "blue", "closed": true, "points": [[10,10], [20,10], [20,20], [10,20]] } );
    TEST_ARRAY( [ [0, -1, 0], [1, 0, 0], [0, 0, 1] ] );
    TEST_ARRAY( ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] );

    // Empty/raw datatypes
    TEST_ARRAY( [true, false, null, [], {}] );

    // Various numbers
    TEST_ARRAY( [[-1], [1.2]] );

    // General array with all data types
    TEST_ARRAY( ["hello", 0, [], {}, null, false, true] );

    // Nested objects
    TEST_OBJECT( {"foo":1, "bar":{"baz":2, "yaz":3}} );

    // Nested objects with trailing key/value
    TEST_OBJECT( {"foo":1, "em":{"a":"b"}, "bar":"aa"} );

    // Nested arrays
    TEST_ARRAY( [1, 2, 3, [4, 5, [7, 8, 9], 6]] );

    // Nested arrays with trailing values
    TEST_ARRAY( [1, 2, 3, [4, 5, [7, 8, 9], 6], 10] );

    // UTF-8
    TEST_OBJECT( {"text":"は 2010/11/4 at 5:50 AM に 6'45\"/km のペースで 8.42 km を走りました http://go.nike.com/9rlcovd"} );
    
    // Escaped UTF-8
    TEST_OBJECT( {"text":"\u3050\u3089\u307e\u3041\u3067\u3061\u3085\u306d\u2665\u304a\u306f\u3088\u3046\u3067\u3059\uff01"} );

    // Empty values
    TEST_OBJECT( {"foo":"", "bar":""} );

    // Escaped quotes
    TEST_OBJECT( {"foo":"\"bar\""} );

    // Newline
    TEST_OBJECT( {"foo":"bar\nbaz"} );

    // Could use more tests around escaping odd characters in key names that can't be used as an element name
    // Escaping invalid xml element names
    TEST_OBJECT( {"f•o":"bar"} );

    // Escaping our invalid xml element name escaping
    TEST_OBJECT( {"_foo":"bar"} );

    // Empty key name (about to check in a fix)
    TEST_OBJECT( {"":"bar"} );

    // Trailing commas (if permissive mode is enabled)
    if( Parser != Strict ) {
        TEST_ARRAY( [ true, 42, 54.7, ] );
        TEST_OBJECT( { "hello": "world",} );
    }

    // Single-quoted strings (if permissive mode is enabled)
    if( Parser != Strict ) {
        TEST_OBJECT( { 'single-quoted-strings': 'are "handy"' } );
    }

    {
        jsonxx::Array a;
        a << true;
        a << false;
        a << 'A';
        a << 65;
        a << 65L;
        a << 65LL;
        a << 65U;
        a << 65UL;
        a << 65ULL;
        a << 65.f;
        a << 65.0;
        a << jsonxx::Value( "hello world" );
        a << std::string("hello world");
        a << "hello world";

        TEST( jsonxx::Array().parse( a.json() ) );   // self-evaluation
        TEST( validate( a.json() ) );                // self-evaluation
    }

    {
        jsonxx::Object o;
        o << "hello" << "world";
        o << "hola" << "mundo";
        TEST( o.get<String>("hello") == "world" );
        TEST( o.get<String>("hola") == "mundo" );
        o << "hello" << "mundo";
        o << "hola" << "world";
        TEST( o.get<String>("hello") == "mundo" );
        TEST( o.get<String>("hola") == "world" );
    }

    {
        // Generate JSON document dinamically
        jsonxx::Array a;
        a << jsonxx::Null();           // C++11: 'a << nullptr' is preferred
        a << 123;
        a << "hello \"world\"";
        a << 3.1415;
        a << 99.95f;
        a << 'h';

        jsonxx::Object o;
        o << "key1" << "value";
        o << "key2" << 123;
        o << "key3" << a;

        a << o;

        TEST( jsonxx::Array().parse( a.json() ) );   // self-evaluation
        TEST( validate( a.json() ) );                // self-evaluation
    }

    {
        // Generate JSON document dinamically
        jsonxx::Object o1;
        o1 << "key1" << "value 1";
        o1 << "key2" << 123;

        jsonxx::Object o2;
        o2 << "key3" << "value 2";
        o2 << "key4" << 456;

        o1 << "key3" << o2;

        TEST( jsonxx::Object().parse( o1.json() ) );  // self-evaluation
        TEST( validate( o1.json() ) );                // self-evaluation
    }

    {
        jsonxx::Array a;
        a << true;
        a << false;

        jsonxx::Object o;
        o << "number" << 123;
        o << "string" << "hello world";
        o << "boolean" << false;
        o << "null" << NULL;
        o << "array" << a;
        o << "object" << jsonxx::Object("child", "object");
        o << "undefined" << custom_type();

        if( verbose ) {
            cout << o.write(JSON) << std::endl;        // same than o.json()
            cout << o.write(JSONx) << std::endl;       // same than o.xml()
            cout << o.write(JXML) << std::endl;        // same than o.xml(JXML)
            cout << o.write(JXMLex) << std::endl;      // same than o.xml(JXMLex)
        }

        TEST( jsonxx::Object().parse( o.json() ) );   // self-evaluation
        TEST( validate( o.json() ) );                 // self-evaluation
    }

    {
        // recursion test
        jsonxx::Array a;
        a << 123;
        a << "hello world";
        a << a;
        TEST( a.size() == 4 );
    }

    {
        // recursion test
        jsonxx::Object o;
        o << "number" << 123;
        o << "string" << "world";
        o << "recursion" << o;
        TEST( o.size() == 3 );
    }

    if( Parser != Strict )
    {
        // C++ style comments test
        string teststr(
                "//this is comment #1 {\n"
                "{"
                "  \"foo\" : 1,"
                "  \"bar\" : false, //this is comment #2\n"
                "  \"person\" : {\"name //this shall not be removed\" : \"GWB\", \"age\" : 60},"
                "  \"data\": [\"abcd\", 42, 54.7]"
                "} //this is comment #3"
       );
        jsonxx::Object o;
        TEST( o.parse(teststr) );
    }

    if( argc > 1 )
    {
        std::ifstream ifs( argv[1] );

        if( ifs.good() ) {
            std::string read = jsonxx::reformat(ifs);
            TEST( read.size() );
            cout << read << endl;
        } else {
            cout << "Cant find '" << argv[1] << "'" << endl;
        }
    }

    cout << "All tests ok." << endl;
    return 0;
}