summaryrefslogtreecommitdiff
path: root/test/test-json.cc
blob: 9344837c38bdfbc0eedb92514fbad72077f2cacc (plain)
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
#include "common.hh"

#include <iostream>

#include "json.hh"

using namespace stuff;

namespace {

bool test_equal(const std::string& test, const std::string& value,
                const std::string& expected) {
    if (value == expected) return true;
    std::cerr << test << ": got '" << value <<
        "' expected '" << expected << "'" << std::endl;
    return false;
}

bool test_equal(const std::string& test, const std::string& value,
                const std::string& expected1,
                const std::string& expected2) {
    if (value == expected1 || value == expected2) return true;
    std::cerr << test << ": got '" << value <<
        "' expected '" << expected1 << "' or '" <<
        expected2 << "'" << std::endl;
    return false;
}

bool test_simple() {
    auto obj = JsonObject::create();
    if (!test_equal("simple", obj->str(), "{}"))
        return false;
    obj->put("foo", "bar");
    obj->put("value", static_cast<int64_t>(12));
    if (!test_equal("simple", obj->str(),
                    "{\"foo\":\"bar\",\"value\":12}",
                    "{\"value\":12,\"foo\":\"bar\"}"))
        return false;
    auto arr = JsonArray::create();
    if (!test_equal("simple", arr->str(), "[]"))
        return false;
    arr->put(0, static_cast<int64_t>(42));
    if (!test_equal("simple", arr->str(), "[42]"))
        return false;
    arr->put(1, static_cast<int64_t>(1234567));
    obj->put("test", arr);
    obj->erase("foo");
    if (!test_equal("simple", obj->str(),
                    "{\"value\":12,\"test\":[42,1234567]}",
                    "{\"test\":[42,1234567],\"value\":12}"))
        return false;
    return true;
}

bool test_quote() {
    auto obj = JsonObject::create();
    obj->put("foo", "");
    if (!test_equal("quote", obj->str(), "{\"foo\":\"\"}"))
        return false;
    obj->put("foo", "\"bar\"");
    if (!test_equal("quote", obj->str(), "{\"foo\":\"\\\"bar\\\"\"}"))
        return false;
    obj->put("foo", " ");
    if (!test_equal("quote", obj->str(), "{\"foo\":\" \"}"))
        return false;
    obj->put("foo", "\\\"");
    if (!test_equal("quote", obj->str(), "{\"foo\":\"\\\\\\\"\"}"))
        return false;
    obj->put("foo", "\n");
    if (!test_equal("quote", obj->str(), "{\"foo\":\"\\n\"}"))
        return false;
    return true;
}

}  // namespace

int main() {
    unsigned int ok = 0, tot = 0;

    tot++; if (test_simple()) ok++;
    tot++; if (test_quote()) ok++;

    std::cout << "OK " << ok << "/" << tot << std::endl;
    return ok == tot ? EXIT_SUCCESS : EXIT_FAILURE;
}