-- codecs/Json tests: the JSONTestSuite parsing corpus (y_ must parse to Python's value, n_ must fail, i_ must not -- throw), Python json.dumps output in four styles parsed and reproduced byte for byte (compact sorted, ordered, -- indent 2, ensure_ascii), events / lines / decodeAt / writer, options, error codes, and the fuzz pass. -- Fixtures: tools/fixtures/json.py. local T = require("@tests/T") local Json = require("@formats/codecs/Json") local Types = require("@formats/Types") local Err = require("@formats/core/Err") local Canon = require("@tests/data/Canon") local Suite = require("@tests/gen/json_suite") local Corpus = require("@tests/gen/json_corpus") local t = T.suite("json") -- events() rebuilt into a value (checks the pull tokenizer agrees with decode) local function fromEvents(s: string): (any, any) local stack, keys = {}, {} local top: any = nil local key: any = nil local function add(v: any) local cur = stack[#stack] if cur == nil then top = v elseif keys[#stack] ~= false then cur[key] = v else table.insert(cur, v) end end for ev, v in Json.events(s) do if ev == "error" then return nil, v elseif ev == "object" or ev == "array" then local tbl = if ev == "object" then Types.object() else {} add(tbl) table.insert(stack, tbl) keys[#stack] = if ev == "object" then true else false elseif ev == "endObject" or ev == "endArray" then keys[#stack] = nil table.remove(stack) elseif ev == "key" then key = v else add(v) end end return top, nil end -- 1. JSONTestSuite local counts = { y = 0, n = 0, i = 0, iok = 0 } for _, c in Suite do local v, err = Json.decode(c.data) local ev, everr = fromEvents(c.data) if c.expect == "y" then t:check(v ~= nil, c.name .. ": parses (" .. tostring(err) .. ")") t:eq(Canon.of(v), c.canon, c.name .. ": value") t:check(ev ~= nil, c.name .. ": events parse (" .. tostring(everr) .. ")") t:eq(Canon.of(ev), c.canon, c.name .. ": events value") -- and our output reads back the same local s = Json.encode(v) t:check(s ~= nil, c.name .. ": encodes") t:eq(Canon.of(Json.decode(s :: string)), c.canon, c.name .. ": round trip") elseif c.expect == "n" then t:check(v == nil and Err.is(err), c.name .. ": rejected") t:check(ev == nil, c.name .. ": events reject") else counts.iok += if v ~= nil then 1 else 0 end counts[c.expect] += 1 end t:note("JSONTestSuite: %d y_ accepted, %d n_ rejected, %d of %d i_ accepted", counts.y, counts.n, counts.iok, counts.i) -- 2. Python's json.dumps output: parse, compare, re-encode byte for byte for i, c in Corpus do local v, err = Json.decode(c.compact) t:check(v ~= nil, "corpus " .. i .. ": " .. tostring(err)) t:eq(Canon.of(v), c.canon, "corpus " .. i .. ": value") t:eq(Json.encode(v), c.compact, "corpus " .. i .. ": compact text") t:eq(Json.encode(v, { indent = 2 }), c.pretty, "corpus " .. i .. ": indent 2 text") t:eq(Json.encode(v, { ascii = true }), c.ascii, "corpus " .. i .. ": ensure_ascii text") local o = Json.decode(c.ordered, { ordered = true }) t:eq(Json.encode(o), c.ordered, "corpus " .. i .. ": ordered text") t:eq(Canon.of(Json.decode(c.ascii)), c.canon, "corpus " .. i .. ": ascii parse") t:eq(Canon.of(Json.decode(c.pretty)), c.canon, "corpus " .. i .. ": pretty parse") end -- 3. options and API do local v = Json.decode('[12345678901234567890, -9007199254740993, 9007199254740991, 1.5e300]', { bigInts = "string" }) t:eq(v[1], "12345678901234567890", "bigInts string") t:eq(v[2], "-9007199254740993", "bigInts negative") t:eq(v[3], 9007199254740991, "2^53 - 1 stays a number") t:eq(v[4], 1.5e300, "floats stay numbers") t:eq(Json.decode("[null]", { null = false })[1], false, "opts.null") t:eq(Json.decode("null"), Types.null, "top-level null") t:eq(Json.decode("\239\187\191[1]")[1], 1, "BOM skipped") t:eq(Json.decode(buffer.fromstring(" 7 ")), 7, "buffer input") local e = Json.decode('{"b":1,"a":{},"c":[]}') t:eq(Json.encode(e), '{"a":{},"b":1,"c":[]}', "empty object stays an object") local o = Json.decode('{"z":1,"a":2,"m":{"y":1,"b":2}}', { ordered = true }) t:eq(Json.encode(o), '{"z":1,"a":2,"m":{"y":1,"b":2}}', "ordered keys") Types.set(o, "b", 3) o.a = nil t:eq(Json.encode(o), '{"z":1,"m":{"y":1,"b":2},"b":3}', "ordered set / remove") t:eq(Json.encode({}, { emptyTable = "object" }), "{}", "emptyTable object") t:eq(Json.encode({ [1] = "a", [3] = "c" }), '{"1":"a","3":"c"}', "sparse array -> object") t:eq(Json.encode({ 1, 2, x = 1 }), '{"1":1,"2":2,"x":1}', "mixed table -> object") t:eq(Json.encode("a/b", { escapeSlash = true }), '"a\\/b"', "escapeSlash") t:eq(Json.encode(0 / 0, { nan = "null" }), "null", "nan null") local _, ne = Json.encode(math.huge) t:eq(ne and ne.code, Err.ARG, "inf is an error") local cyc = {} cyc.self = cyc local _, ce = Json.encode(cyc) t:eq(ce and ce.code, Err.ARG, "cycle is an error") local _, fe = Json.encode({ f = print }) t:eq(fe and fe.code, Err.ARG, "function is an error") t:eq(Json.encode(Types.Date.parse("1979-05-27T07:32:00Z")), '"1979-05-27T07:32:00Z"', "dates as strings") for _, x in { 0.1, 1 / 3, -2.5e-8, 1e300, 123456789012345, 2 ^ 53, 5e-324, 1.7976931348623157e308 } do t:eq(Json.decode(Json.encode(x) :: string), x, "number round trip " .. string.format("%.17g", x)) end end -- 4. streaming: lines, decodeAt, writer do local got = {} for _, v in Json.lines('{"a":1}\n[2]\n"x"\n 3 ') do table.insert(got, (Json.encode(v))) end t:eq(table.concat(got, "|"), '{"a":1}|[2]|"x"|3', "lines") local n, last = 0, nil for _, v, e in Json.lines("1 2 [") do if e then last = e else n += 1 end end t:eq(n, 2, "lines stop at the bad value") t:eq(last and last.code, Err.TRUNCATED, "lines report the error") local v, p = Json.decodeAt("[1] [2]", 1) t:eq(v[1], 1, "decodeAt value") t:eq(p, 4, "decodeAt next") t:eq(Json.decodeAt(" ", 1), nil, "decodeAt at the end") local w = Json.writer({ indent = 2 }) w:beginObject():key("a"):value({ 1, 2 }):key("b"):beginArray():value("x"):beginObject():endObject():endArray():endObject() local s = w:tostring() t:eq(s, Json.encode(Json.decode('{"a":[1,2],"b":["x",{}]}', { ordered = true }), { indent = 2 }), "writer pretty") local w2 = Json.writer() w2:beginArray() local parts = {} for i = 1, 5 do w2:value(i) table.insert(parts, w2:flush()) end w2:endArray() table.insert(parts, w2:flush()) t:eq(table.concat(parts), "[1,2,3,4,5]", "writer flush chunks") t:eq(w2:tostring(), "[1,2,3,4,5]", "writer tostring after flushes") local w3 = Json.writer() w3:beginArray():key("x") t:check(w3.err ~= nil, "writer: key in array") local w4 = Json.writer() w4:beginObject():value(1) t:check(w4.err ~= nil, "writer: value without key") local w5 = Json.writer() w5:beginObject() t:check(w5:tostring() == nil, "writer: unclosed") end -- 5. errors local function code(s: string, opts: any?): string? local _, e = Json.decode(s, opts) return e and e.code end t:eq(code('{"a":'), Err.TRUNCATED, "truncated object") t:eq(code('"abc'), Err.TRUNCATED, "truncated string") t:eq(code("[1 2]"), Err.CORRUPT, "missing comma") t:eq(code("[1] x"), Err.CORRUPT, "trailing data") t:eq(code(string.rep("[", 50) .. string.rep("]", 50), { maxDepth = 10 }), Err.LIMIT, "maxDepth") t:eq(code(string.rep("[", 100000)), Err.LIMIT, "100000 opening brackets") t:eq(code(""), Err.TRUNCATED, "empty input") local _, ae = Json.decode(42 :: any) t:eq(ae and ae.code, Err.ARG, "bad argument") do local _, e = Json.decode('{"a": tru}') t:eq(e and e.offset, 6, "error offset") end -- 6. fuzz local samples = {} for i = 1, 40 do table.insert(samples, Corpus[i].compact) end for _, c in Suite do if #samples < 120 and c.expect == "y" and #c.data < 200 then table.insert(samples, c.data) end end t:fuzz("decode", function(b: buffer) return Json.decode(b) end, samples) t:fuzz("events", function(b: buffer) for _ in Json.events(b) do end return nil end, samples, { garbage = 50 }) t:done()