aboutsummaryrefslogtreecommitdiff
path: root/lib/std/json/stringify_test.zig
blob: d2c4104316b7a61d2a5d5a6a090ed6b13dca5231 (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
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
const std = @import("std");
const builtin = @import("builtin");
const mem = std.mem;
const testing = std.testing;

const ObjectMap = @import("dynamic.zig").ObjectMap;
const Value = @import("dynamic.zig").Value;

const StringifyOptions = @import("stringify.zig").StringifyOptions;
const stringify = @import("stringify.zig").stringify;
const stringifyMaxDepth = @import("stringify.zig").stringifyMaxDepth;
const stringifyArbitraryDepth = @import("stringify.zig").stringifyArbitraryDepth;
const stringifyAlloc = @import("stringify.zig").stringifyAlloc;
const writeStream = @import("stringify.zig").writeStream;
const writeStreamMaxDepth = @import("stringify.zig").writeStreamMaxDepth;
const writeStreamArbitraryDepth = @import("stringify.zig").writeStreamArbitraryDepth;

test "json write stream" {
    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;

    var out_buf: [1024]u8 = undefined;
    var slice_stream = std.io.fixedBufferStream(&out_buf);
    const out = slice_stream.writer();

    {
        var w = writeStream(out, .{ .whitespace = .indent_2 });
        try testBasicWriteStream(&w, &slice_stream);
    }

    {
        var w = writeStreamMaxDepth(out, .{ .whitespace = .indent_2 }, 8);
        try testBasicWriteStream(&w, &slice_stream);
    }

    {
        var w = writeStreamMaxDepth(out, .{ .whitespace = .indent_2 }, null);
        try testBasicWriteStream(&w, &slice_stream);
    }

    {
        var w = writeStreamArbitraryDepth(testing.allocator, out, .{ .whitespace = .indent_2 });
        defer w.deinit();
        try testBasicWriteStream(&w, &slice_stream);
    }
}

fn testBasicWriteStream(w: anytype, slice_stream: anytype) !void {
    slice_stream.reset();

    try w.beginObject();

    try w.objectField("object");
    var arena_allocator = std.heap.ArenaAllocator.init(testing.allocator);
    defer arena_allocator.deinit();
    try w.write(try getJsonObject(arena_allocator.allocator()));

    try w.objectField("string");
    try w.write("This is a string");

    try w.objectField("array");
    try w.beginArray();
    try w.write("Another string");
    try w.write(@as(i32, 1));
    try w.write(@as(f32, 3.5));
    try w.endArray();

    try w.objectField("int");
    try w.write(@as(i32, 10));

    try w.objectField("float");
    try w.write(@as(f32, 3.5));

    try w.endObject();

    const result = slice_stream.getWritten();
    const expected =
        \\{
        \\  "object": {
        \\    "one": 1,
        \\    "two": 2.0e+00
        \\  },
        \\  "string": "This is a string",
        \\  "array": [
        \\    "Another string",
        \\    1,
        \\    3.5e+00
        \\  ],
        \\  "int": 10,
        \\  "float": 3.5e+00
        \\}
    ;
    try std.testing.expectEqualStrings(expected, result);
}

fn getJsonObject(allocator: std.mem.Allocator) !Value {
    var value = Value{ .object = ObjectMap.init(allocator) };
    try value.object.put("one", Value{ .integer = @as(i64, @intCast(1)) });
    try value.object.put("two", Value{ .float = 2.0 });
    return value;
}

test "stringify null optional fields" {
    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;

    const MyStruct = struct {
        optional: ?[]const u8 = null,
        required: []const u8 = "something",
        another_optional: ?[]const u8 = null,
        another_required: []const u8 = "something else",
    };
    try testStringify(
        \\{"optional":null,"required":"something","another_optional":null,"another_required":"something else"}
    ,
        MyStruct{},
        .{},
    );
    try testStringify(
        \\{"required":"something","another_required":"something else"}
    ,
        MyStruct{},
        .{ .emit_null_optional_fields = false },
    );
}

test "stringify basic types" {
    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;

    try testStringify("false", false, .{});
    try testStringify("true", true, .{});
    try testStringify("null", @as(?u8, null), .{});
    try testStringify("null", @as(?*u32, null), .{});
    try testStringify("42", 42, .{});
    try testStringify("4.2e+01", 42.0, .{});
    try testStringify("42", @as(u8, 42), .{});
    try testStringify("42", @as(u128, 42), .{});
    try testStringify("9999999999999999", 9999999999999999, .{});
    try testStringify("4.2e+01", @as(f32, 42), .{});
    try testStringify("4.2e+01", @as(f64, 42), .{});
    try testStringify("\"ItBroke\"", @as(anyerror, error.ItBroke), .{});
    try testStringify("\"ItBroke\"", error.ItBroke, .{});
}

test "stringify string" {
    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;

    try testStringify("\"hello\"", "hello", .{});
    try testStringify("\"with\\nescapes\\r\"", "with\nescapes\r", .{});
    try testStringify("\"with\\nescapes\\r\"", "with\nescapes\r", .{ .escape_unicode = true });
    try testStringify("\"with unicode\\u0001\"", "with unicode\u{1}", .{});
    try testStringify("\"with unicode\\u0001\"", "with unicode\u{1}", .{ .escape_unicode = true });
    try testStringify("\"with unicode\u{80}\"", "with unicode\u{80}", .{});
    try testStringify("\"with unicode\\u0080\"", "with unicode\u{80}", .{ .escape_unicode = true });
    try testStringify("\"with unicode\u{FF}\"", "with unicode\u{FF}", .{});
    try testStringify("\"with unicode\\u00ff\"", "with unicode\u{FF}", .{ .escape_unicode = true });
    try testStringify("\"with unicode\u{100}\"", "with unicode\u{100}", .{});
    try testStringify("\"with unicode\\u0100\"", "with unicode\u{100}", .{ .escape_unicode = true });
    try testStringify("\"with unicode\u{800}\"", "with unicode\u{800}", .{});
    try testStringify("\"with unicode\\u0800\"", "with unicode\u{800}", .{ .escape_unicode = true });
    try testStringify("\"with unicode\u{8000}\"", "with unicode\u{8000}", .{});
    try testStringify("\"with unicode\\u8000\"", "with unicode\u{8000}", .{ .escape_unicode = true });
    try testStringify("\"with unicode\u{D799}\"", "with unicode\u{D799}", .{});
    try testStringify("\"with unicode\\ud799\"", "with unicode\u{D799}", .{ .escape_unicode = true });
    try testStringify("\"with unicode\u{10000}\"", "with unicode\u{10000}", .{});
    try testStringify("\"with unicode\\ud800\\udc00\"", "with unicode\u{10000}", .{ .escape_unicode = true });
    try testStringify("\"with unicode\u{10FFFF}\"", "with unicode\u{10FFFF}", .{});
    try testStringify("\"with unicode\\udbff\\udfff\"", "with unicode\u{10FFFF}", .{ .escape_unicode = true });
}

test "stringify many-item sentinel-terminated string" {
    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;

    try testStringify("\"hello\"", @as([*:0]const u8, "hello"), .{});
    try testStringify("\"with\\nescapes\\r\"", @as([*:0]const u8, "with\nescapes\r"), .{ .escape_unicode = true });
    try testStringify("\"with unicode\\u0001\"", @as([*:0]const u8, "with unicode\u{1}"), .{ .escape_unicode = true });
}

test "stringify enums" {
    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;

    const E = enum {
        foo,
        bar,
    };
    try testStringify("\"foo\"", E.foo, .{});
    try testStringify("\"bar\"", E.bar, .{});
}

test "stringify enum literals" {
    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;

    try testStringify("\"foo\"", .foo, .{});
    try testStringify("\"bar\"", .bar, .{});
}

test "stringify tagged unions" {
    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;

    const T = union(enum) {
        nothing,
        foo: u32,
        bar: bool,
    };
    try testStringify("{\"nothing\":{}}", T{ .nothing = {} }, .{});
    try testStringify("{\"foo\":42}", T{ .foo = 42 }, .{});
    try testStringify("{\"bar\":true}", T{ .bar = true }, .{});
}

test "stringify struct" {
    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;

    try testStringify("{\"foo\":42}", struct {
        foo: u32,
    }{ .foo = 42 }, .{});
}

test "emit_strings_as_arrays" {
    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;

    // Should only affect string values, not object keys.
    try testStringify("{\"foo\":\"bar\"}", .{ .foo = "bar" }, .{});
    try testStringify("{\"foo\":[98,97,114]}", .{ .foo = "bar" }, .{ .emit_strings_as_arrays = true });
    // Should *not* affect these types:
    try testStringify("\"foo\"", @as(enum { foo, bar }, .foo), .{ .emit_strings_as_arrays = true });
    try testStringify("\"ItBroke\"", error.ItBroke, .{ .emit_strings_as_arrays = true });
    // Should work on these:
    try testStringify("\"bar\"", @Vector(3, u8){ 'b', 'a', 'r' }, .{});
    try testStringify("[98,97,114]", @Vector(3, u8){ 'b', 'a', 'r' }, .{ .emit_strings_as_arrays = true });
    try testStringify("\"bar\"", [3]u8{ 'b', 'a', 'r' }, .{});
    try testStringify("[98,97,114]", [3]u8{ 'b', 'a', 'r' }, .{ .emit_strings_as_arrays = true });
}

test "stringify struct with indentation" {
    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;

    try testStringify(
        \\{
        \\    "foo": 42,
        \\    "bar": [
        \\        1,
        \\        2,
        \\        3
        \\    ]
        \\}
    ,
        struct {
            foo: u32,
            bar: [3]u32,
        }{
            .foo = 42,
            .bar = .{ 1, 2, 3 },
        },
        .{ .whitespace = .indent_4 },
    );
    try testStringify(
        "{\n\t\"foo\": 42,\n\t\"bar\": [\n\t\t1,\n\t\t2,\n\t\t3\n\t]\n}",
        struct {
            foo: u32,
            bar: [3]u32,
        }{
            .foo = 42,
            .bar = .{ 1, 2, 3 },
        },
        .{ .whitespace = .indent_tab },
    );
    try testStringify(
        \\{"foo":42,"bar":[1,2,3]}
    ,
        struct {
            foo: u32,
            bar: [3]u32,
        }{
            .foo = 42,
            .bar = .{ 1, 2, 3 },
        },
        .{ .whitespace = .minified },
    );
}

test "stringify struct with void field" {
    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;

    try testStringify("{\"foo\":42}", struct {
        foo: u32,
        bar: void = {},
    }{ .foo = 42 }, .{});
}

test "stringify array of structs" {
    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;

    const MyStruct = struct {
        foo: u32,
    };
    try testStringify("[{\"foo\":42},{\"foo\":100},{\"foo\":1000}]", [_]MyStruct{
        MyStruct{ .foo = 42 },
        MyStruct{ .foo = 100 },
        MyStruct{ .foo = 1000 },
    }, .{});
}

test "stringify struct with custom stringifier" {
    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;

    try testStringify("[\"something special\",42]", struct {
        foo: u32,
        const Self = @This();
        pub fn jsonStringify(value: @This(), jws: anytype) !void {
            _ = value;
            try jws.beginArray();
            try jws.write("something special");
            try jws.write(42);
            try jws.endArray();
        }
    }{ .foo = 42 }, .{});
}

test "stringify vector" {
    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;

    try testStringify("[1,1]", @as(@Vector(2, u32), @splat(1)), .{});
    try testStringify("\"AA\"", @as(@Vector(2, u8), @splat('A')), .{});
    try testStringify("[65,65]", @as(@Vector(2, u8), @splat('A')), .{ .emit_strings_as_arrays = true });
}

test "stringify tuple" {
    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;

    try testStringify("[\"foo\",42]", std.meta.Tuple(&.{ []const u8, usize }){ "foo", 42 }, .{});
}

fn testStringify(expected: []const u8, value: anytype, options: StringifyOptions) !void {
    const ValidationWriter = struct {
        const Self = @This();
        pub const Writer = std.io.Writer(*Self, Error, write);
        pub const Error = error{
            TooMuchData,
            DifferentData,
        };

        expected_remaining: []const u8,

        fn init(exp: []const u8) Self {
            return .{ .expected_remaining = exp };
        }

        pub fn writer(self: *Self) Writer {
            return .{ .context = self };
        }

        fn write(self: *Self, bytes: []const u8) Error!usize {
            if (self.expected_remaining.len < bytes.len) {
                std.debug.print(
                    \\====== expected this output: =========
                    \\{s}
                    \\======== instead found this: =========
                    \\{s}
                    \\======================================
                , .{
                    self.expected_remaining,
                    bytes,
                });
                return error.TooMuchData;
            }
            if (!mem.eql(u8, self.expected_remaining[0..bytes.len], bytes)) {
                std.debug.print(
                    \\====== expected this output: =========
                    \\{s}
                    \\======== instead found this: =========
                    \\{s}
                    \\======================================
                , .{
                    self.expected_remaining[0..bytes.len],
                    bytes,
                });
                return error.DifferentData;
            }
            self.expected_remaining = self.expected_remaining[bytes.len..];
            return bytes.len;
        }
    };

    var vos = ValidationWriter.init(expected);
    try stringifyArbitraryDepth(testing.allocator, value, options, vos.writer());
    if (vos.expected_remaining.len > 0) return error.NotEnoughData;

    // Also test with safety disabled.
    try testStringifyMaxDepth(expected, value, options, null);
    try testStringifyArbitraryDepth(expected, value, options);
}

fn testStringifyMaxDepth(expected: []const u8, value: anytype, options: StringifyOptions, comptime max_depth: ?usize) !void {
    var out_buf: [1024]u8 = undefined;
    var slice_stream = std.io.fixedBufferStream(&out_buf);
    const out = slice_stream.writer();

    try stringifyMaxDepth(value, options, out, max_depth);
    const got = slice_stream.getWritten();

    try testing.expectEqualStrings(expected, got);
}

fn testStringifyArbitraryDepth(expected: []const u8, value: anytype, options: StringifyOptions) !void {
    var out_buf: [1024]u8 = undefined;
    var slice_stream = std.io.fixedBufferStream(&out_buf);
    const out = slice_stream.writer();

    try stringifyArbitraryDepth(testing.allocator, value, options, out);
    const got = slice_stream.getWritten();

    try testing.expectEqualStrings(expected, got);
}

test "stringify alloc" {
    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;

    const allocator = std.testing.allocator;
    const expected =
        \\{"foo":"bar","answer":42,"my_friend":"sammy"}
    ;
    const actual = try stringifyAlloc(allocator, .{ .foo = "bar", .answer = 42, .my_friend = "sammy" }, .{});
    defer allocator.free(actual);

    try std.testing.expectEqualStrings(expected, actual);
}

test "comptime stringify" {
    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;

    comptime testStringifyMaxDepth("false", false, .{}, null) catch unreachable;
    comptime testStringifyMaxDepth("false", false, .{}, 0) catch unreachable;
    comptime testStringifyArbitraryDepth("false", false, .{}) catch unreachable;

    const MyStruct = struct {
        foo: u32,
    };
    comptime testStringifyMaxDepth("[{\"foo\":42},{\"foo\":100},{\"foo\":1000}]", [_]MyStruct{
        MyStruct{ .foo = 42 },
        MyStruct{ .foo = 100 },
        MyStruct{ .foo = 1000 },
    }, .{}, null) catch unreachable;
    comptime testStringifyMaxDepth("[{\"foo\":42},{\"foo\":100},{\"foo\":1000}]", [_]MyStruct{
        MyStruct{ .foo = 42 },
        MyStruct{ .foo = 100 },
        MyStruct{ .foo = 1000 },
    }, .{}, 8) catch unreachable;
}

test "print" {
    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;

    var out_buf: [1024]u8 = undefined;
    var slice_stream = std.io.fixedBufferStream(&out_buf);
    const out = slice_stream.writer();

    var w = writeStream(out, .{ .whitespace = .indent_2 });
    defer w.deinit();

    try w.beginObject();
    try w.objectField("a");
    try w.print("[  ]", .{});
    try w.objectField("b");
    try w.beginArray();
    try w.print("[{s}] ", .{"[]"});
    try w.print("  {}", .{12345});
    try w.endArray();
    try w.endObject();

    const result = slice_stream.getWritten();
    const expected =
        \\{
        \\  "a": [  ],
        \\  "b": [
        \\    [[]] ,
        \\      12345
        \\  ]
        \\}
    ;
    try std.testing.expectEqualStrings(expected, result);
}

test "nonportable numbers" {
    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;

    try testStringify("9999999999999999", 9999999999999999, .{});
    try testStringify("\"9999999999999999\"", 9999999999999999, .{ .emit_nonportable_numbers_as_strings = true });
}