aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/json/writer/json_ut.cpp
blob: 9980555683f411040dc089c62b4d4f2179005cd0 (plain) (blame)
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
#include <library/cpp/testing/unittest/registar.h>
#include <util/system/sanitizers.h>

#include "json.h"
#include <library/cpp/json/json_value.h>

#include <limits>

Y_UNIT_TEST_SUITE(JsonWriter) {
    Y_UNIT_TEST(Struct) {
        NJsonWriter::TBuf w;
        w.BeginList();
        w.BeginObject()
            .WriteKey("key")
            .WriteString("value")
            .UnsafeWritePair("\"xk\":13")
            .WriteKey("key2")
            .BeginList()
            .BeginObject()
            .EndObject()
            .BeginObject()
            .EndObject()
            .EndList()
            .EndObject();
        w.WriteInt(43);
        w.UnsafeWriteValue("\"x\"");
        w.WriteString("...");
        w.EndList();
        const char* exp = "[{\"key\":\"value\",\"xk\":13,\"key2\":[{},{}]},43,\"x\",\"...\"]";
        UNIT_ASSERT_EQUAL(w.Str(), exp);
    }
    Y_UNIT_TEST(EscapedString) {
        NJsonWriter::TBuf w(NJsonWriter::HEM_ESCAPE_HTML);
        w.WriteString(" \n \r \t \007 \b \f ' <tag> &ent; \"txt\" ");
        TString ws = w.Str();
        const char* exp = "\" \\n \\r \\t \\u0007 \\b \\f &#39; &lt;tag&gt; &amp;ent; &quot;txt&quot; \"";
        UNIT_ASSERT_STRINGS_EQUAL(ws.c_str(), exp);
    }
    Y_UNIT_TEST(UnescapedString) {
        NJsonWriter::TBuf w;
        w.WriteString(" \n \r \t \b \f '; -- <tag> &ent; \"txt\"", NJsonWriter::HEM_DONT_ESCAPE_HTML);
        TString ws = w.Str();
        const char* exp = "\" \\n \\r \\t \\b \\f \\u0027; -- \\u003Ctag\\u003E &ent; \\\"txt\\\"\"";
        UNIT_ASSERT_STRINGS_EQUAL(ws.c_str(), exp);
    }
    Y_UNIT_TEST(UnescapedChaining) {
        NJsonWriter::TBuf w(NJsonWriter::HEM_DONT_ESCAPE_HTML);
        w.UnsafeWriteRawBytes("(", 1);
        w.BeginList().WriteString("<>&'\\").BeginList();
        w.EndList().EndList();
        TString ws = w.Str();
        const char* exp = "([\"\\u003C\\u003E&\\u0027\\\\\",[]]";
        UNIT_ASSERT_STRINGS_EQUAL(ws.c_str(), exp);
    }
    Y_UNIT_TEST(Utf8) {
        TString ws = NJsonWriter::TBuf().WriteString("яЯ σΣ ש א").Str();
        const char* exp = "\"яЯ σΣ ש א\"";
        UNIT_ASSERT_STRINGS_EQUAL(ws.c_str(), exp);
    }
    Y_UNIT_TEST(WrongObject) {
        NJsonWriter::TBuf w;
        w.BeginObject();
        UNIT_ASSERT_EXCEPTION(w.WriteString("hehe"), NJsonWriter::TError);
    }
    Y_UNIT_TEST(WrongList) {
        NJsonWriter::TBuf w;
        w.BeginList();
        UNIT_ASSERT_EXCEPTION(w.WriteKey("hehe"), NJsonWriter::TError);
    }
    Y_UNIT_TEST(Incomplete) {
        NJsonWriter::TBuf w;
        w.BeginList();
        UNIT_ASSERT_EXCEPTION(w.Str(), NJsonWriter::TError);
    }
    Y_UNIT_TEST(BareKey) {
        NJsonWriter::TBuf w;
        w.BeginObject()
            .CompatWriteKeyWithoutQuotes("p")
            .WriteInt(1)
            .CompatWriteKeyWithoutQuotes("n")
            .WriteInt(0)
            .EndObject();
        TString ws = w.Str();
        const char* exp = "{p:1,n:0}";
        UNIT_ASSERT_STRINGS_EQUAL(ws.c_str(), exp);
    }
    Y_UNIT_TEST(UnescapedStringInObject) {
        NJsonWriter::TBuf w(NJsonWriter::HEM_DONT_ESCAPE_HTML);
        w.BeginObject().WriteKey("key").WriteString("</&>'").EndObject();
        TString ws = w.Str();
        const char* exp = "{\"key\":\"\\u003C\\/&\\u003E\\u0027\"}";
        UNIT_ASSERT_STRINGS_EQUAL(ws.c_str(), exp);
    }
    Y_UNIT_TEST(ForeignStreamStr) {
        NJsonWriter::TBuf w(NJsonWriter::HEM_DONT_ESCAPE_HTML, &Cerr);
        UNIT_ASSERT_EXCEPTION(w.Str(), NJsonWriter::TError);
    }
    Y_UNIT_TEST(ForeignStreamValue) {
        TStringStream ss;
        NJsonWriter::TBuf w(NJsonWriter::HEM_DONT_ESCAPE_HTML, &ss);
        w.WriteInt(1543);
        UNIT_ASSERT_STRINGS_EQUAL(ss.Str(), "1543");
    }
    Y_UNIT_TEST(Indentation) {
        NJsonWriter::TBuf w(NJsonWriter::HEM_DONT_ESCAPE_HTML);
        w.SetIndentSpaces(2);
        w.BeginList()
            .WriteInt(1)
            .WriteString("hello")
            .BeginObject()
            .WriteKey("abc")
            .WriteInt(3)
            .WriteKey("def")
            .WriteInt(4)
            .EndObject()
            .EndList();
        const char* exp = "[\n"
                          "  1,\n"
                          "  \"hello\",\n"
                          "  {\n"
                          "    \"abc\":3,\n"
                          "    \"def\":4\n"
                          "  }\n"
                          "]";
        UNIT_ASSERT_STRINGS_EQUAL(exp, w.Str());
    }
    Y_UNIT_TEST(WriteJsonValue) {
        using namespace NJson;
        TJsonValue val;
        val.AppendValue(1);
        val.AppendValue("2");
        val.AppendValue(3.5);
        TJsonValue obj;
        obj.InsertValue("key", TJsonValue("value"));

        val.AppendValue(obj);
        val.AppendValue(TJsonValue(JSON_NULL));

        NJsonWriter::TBuf w(NJsonWriter::HEM_DONT_ESCAPE_HTML);
        w.WriteJsonValue(&val);

        const char exp[] = "[1,\"2\",3.5,{\"key\":\"value\"},null]";
        UNIT_ASSERT_STRINGS_EQUAL(exp, w.Str());
    }
    Y_UNIT_TEST(WriteJsonValueSorted) {
        using namespace NJson;
        TJsonValue val;
        val.InsertValue("1", TJsonValue(1));
        val.InsertValue("2", TJsonValue(2));

        TJsonValue obj;
        obj.InsertValue("zero", TJsonValue(0));
        obj.InsertValue("succ", TJsonValue(1));
        val.InsertValue("0", obj);

        NJsonWriter::TBuf w(NJsonWriter::HEM_DONT_ESCAPE_HTML);
        w.WriteJsonValue(&val, true);

        const char exp[] = "{\"0\":{\"succ\":1,\"zero\":0},\"1\":1,\"2\":2}";
        UNIT_ASSERT_STRINGS_EQUAL(exp, w.Str());
    }
    Y_UNIT_TEST(Unescaped) {
        NJsonWriter::TBuf buf(NJsonWriter::HEM_UNSAFE);
        buf.WriteString("</security>'");
        UNIT_ASSERT_STRINGS_EQUAL("\"</security>'\"", buf.Str());
    }
    Y_UNIT_TEST(LittleBobbyJsonp) {
        NJsonWriter::TBuf buf;
        buf.WriteString("hello\xe2\x80\xa8\xe2\x80\xa9stranger");
        UNIT_ASSERT_STRINGS_EQUAL("\"hello\\u2028\\u2029stranger\"", buf.Str());
    }
    Y_UNIT_TEST(LittleBobbyInvalid) {
        NJsonWriter::TBuf buf;
        TStringBuf incomplete("\xe2\x80\xa8", 2);
        buf.WriteString(incomplete);
        // garbage in - garbage out
        UNIT_ASSERT_STRINGS_EQUAL("\"\xe2\x80\"", buf.Str());
    }
    Y_UNIT_TEST(OverlyZealous) {
        NJsonWriter::TBuf buf;
        buf.WriteString("—");
        UNIT_ASSERT_STRINGS_EQUAL("\"\"", buf.Str());
    }
    Y_UNIT_TEST(RelaxedEscaping) {
        NJsonWriter::TBuf buf(NJsonWriter::HEM_RELAXED);
        buf.WriteString("</>");
        UNIT_ASSERT_STRINGS_EQUAL("\"\\u003C/\\u003E\"", buf.Str());
    }

    Y_UNIT_TEST(FloatFormatting) {
        NJsonWriter::TBuf buf(NJsonWriter::HEM_DONT_ESCAPE_HTML);
        buf.BeginList()
            .WriteFloat(0.12345678987654321f)
            .WriteDouble(0.12345678987654321)
            .WriteFloat(0.315501, PREC_NDIGITS, 3)
            .WriteFloat(244.13854, PREC_NDIGITS, 4)
            .WriteFloat(10385.8324, PREC_POINT_DIGITS, 2)
            .BeginObject()
            .WriteKey("1")
            .WriteDouble(1111.71, PREC_POINT_DIGITS, 0)
            .WriteKey("2")
            .WriteDouble(1111.71, PREC_NDIGITS, 1)
            .EndObject()
            .EndList();
        const char exp[] = "[0.123457,0.1234567899,0.316,244.1,10385.83,{\"1\":1112,\"2\":1e+03}]";
        UNIT_ASSERT_STRINGS_EQUAL(exp, buf.Str());
    }

    Y_UNIT_TEST(NanFormatting) {
        {
            NJsonWriter::TBuf buf;
            buf.BeginObject();
            buf.WriteKey("nanvalue");
            UNIT_ASSERT_EXCEPTION(buf.WriteFloat(std::numeric_limits<double>::quiet_NaN()), yexception);
        }

        {
            NJsonWriter::TBuf buf;
            buf.BeginObject();
            buf.WriteKey("infvalue");
            UNIT_ASSERT_EXCEPTION(buf.WriteFloat(std::numeric_limits<double>::infinity()), yexception);
        }

        {
            NJsonWriter::TBuf buf;
            buf.BeginList();
            UNIT_ASSERT_EXCEPTION(buf.WriteFloat(std::numeric_limits<double>::quiet_NaN()), yexception);
        }

        {
            NJsonWriter::TBuf buf;
            buf.BeginList();
            UNIT_ASSERT_EXCEPTION(buf.WriteFloat(std::numeric_limits<double>::infinity()), yexception);
        }

        {
            NJsonWriter::TBuf buf;
            buf.SetWriteNanAsString();

            buf.BeginObject()
                .WriteKey("nanvalue")
                .WriteFloat(std::numeric_limits<double>::quiet_NaN())
                .WriteKey("infvalue")
                .WriteFloat(std::numeric_limits<double>::infinity())
                .WriteKey("minus_infvalue")
                .WriteFloat(-std::numeric_limits<float>::infinity())
                .WriteKey("l")
                .BeginList()
                .WriteFloat(std::numeric_limits<float>::quiet_NaN())
                .EndList()
                .EndObject();

            UNIT_ASSERT_STRINGS_EQUAL(buf.Str(), R"raw_json({"nanvalue":"nan","infvalue":"inf","minus_infvalue":"-inf","l":["nan"]})raw_json");
        }

        {
            NJsonWriter::TBuf buf;
            buf.BeginObject()
                .WriteKey("<>&")
                .WriteString("Ololo")
                .UnsafeWriteKey("<>&")
                .WriteString("Ololo2")
                .EndObject();

            UNIT_ASSERT_STRINGS_EQUAL(buf.Str(), R"({"\u003C\u003E&":"Ololo","<>&":"Ololo2"})");
        }
    }

    Y_UNIT_TEST(WriteUninitializedBoolDoesntCrashProgram) {
        // makes sense only in release build w/ address sanitizer
        //
        // passing uninitialized boolean into WriteBool can make cleverly optimized code which is emitted by compiler crash program
        // https://stackoverflow.com/questions/54120862/does-the-c-standard-allow-for-an-uninitialized-bool-to-crash-a-program

        // looks like compiler can detect UB at compile time in simple cases, but not in this one
        class  TSensorConf {
        public:
            class TAggrRuleItem {
            public:
                TVector<TString> Cond;
                TVector<TString> Target;
            };

            TString ToString() const {
                NJson::TJsonValue jsonValue;
                NJsonWriter::TBuf jsonOutput;
                jsonOutput.BeginObject()
                    .WriteKey("rawDataMemOnly").WriteBool(RawDataMemOnly)
                    .WriteKey("aggrRules").BeginList();

                jsonOutput.EndList()
                    .EndObject();

                return jsonOutput.Str();
            }

            TVector<TAggrRuleItem> AggrRules;
            bool RawDataMemOnly;
        };

        TSensorConf s;
        NSan::Unpoison(&s.RawDataMemOnly, sizeof(s.RawDataMemOnly));
        auto p = s.ToString();
        // doesn't really matter
        UNIT_ASSERT(!p.empty());
    }
}