72 lines
2.5 KiB
Luau
72 lines
2.5 KiB
Luau
-- data/json tests: the contract, the format through the API (F.load / F.save / sniffing), JSON Lines, Python's
|
|
-- json.dumps corpus through the format, and the fuzz pass. The codec itself is tested in tests/codecs/json.luau.
|
|
-- Fixtures: tools/fixtures/json.py.
|
|
local T = require("@tests/T")
|
|
local F = require("@formats")
|
|
local JsonF = require("@formats/data/json")
|
|
local Bytes = require("@formats/core/Bytes")
|
|
local Err = require("@formats/core/Err")
|
|
local Canon = require("@tests/data/Canon")
|
|
local Corpus = require("@tests/gen/json_corpus")
|
|
|
|
local t = T.suite("data/json")
|
|
|
|
t:eq(JsonF.name, "json", "name")
|
|
t:eq(JsonF.category, "data", "category")
|
|
t:check(JsonF.caps.decode and JsonF.caps.encode, "caps")
|
|
|
|
local function dec(s: string, opts: any?): (any, any)
|
|
return JsonF.decode(Bytes.reader(buffer.fromstring(s)), opts)
|
|
end
|
|
|
|
for i, c in Corpus do
|
|
local v, err = dec(c.pretty)
|
|
t:check(v ~= nil, "corpus " .. i .. ": " .. tostring(err))
|
|
t:eq(Canon.of(v), c.canon, "corpus " .. i)
|
|
local b = JsonF.encode(v, { indent = 2 }) :: buffer
|
|
t:eq(buffer.tostring(b), c.pretty .. "\n", "corpus " .. i .. ": encode")
|
|
end
|
|
|
|
-- through the API: sniffed, by name, saved
|
|
do
|
|
local v, err = F.load(buffer.fromstring('{"a": [1, 2], "b": null}'))
|
|
t:check(v ~= nil, "F.load sniffs json: " .. tostring(err))
|
|
t:eq(v.b, F.null, "F.null")
|
|
local v2 = F.load(buffer.fromstring("[1, 2]"), { format = "json" })
|
|
t:eq(v2[2], 2, "F.load format = json")
|
|
local s = F.saveString({ x = 1, y = { true, false } }, { format = "json" })
|
|
t:eq(s, '{"x":1,"y":[true,false]}', "F.saveString json")
|
|
local back = F.data.load(buffer.fromstring(s :: string), { format = "json" })
|
|
t:eq(back.y[1], true, "F.data.load")
|
|
end
|
|
|
|
-- JSON Lines
|
|
do
|
|
local v = dec('{"a":1}\n{"a":2}\n\n[3]\n', { lines = true })
|
|
t:eq(#v, 3, "lines decode count")
|
|
t:eq(v[2].a, 2, "lines decode value")
|
|
local b = JsonF.encode({ { a = 1 }, { 2, 3 } }, { lines = true }) :: buffer
|
|
t:eq(buffer.tostring(b), '{"a":1}\n[2,3]\n', "lines encode")
|
|
local _, e = dec("1\n[", { lines = true })
|
|
t:eq(e and e.code, Err.TRUNCATED, "lines error")
|
|
end
|
|
|
|
-- reader range: the data inside a bigger buffer
|
|
do
|
|
local big = buffer.fromstring("xx[1,2,3]yy")
|
|
local v = JsonF.decode(Bytes.reader(big, 2, 7))
|
|
t:eq(#v, 3, "reader range")
|
|
end
|
|
|
|
t:eq(JsonF.sniff(Bytes.reader(buffer.fromstring(' {"a":1}'))), 0.6, "sniff object")
|
|
t:eq(JsonF.sniff(Bytes.reader(buffer.fromstring("hello"))), 0, "sniff text")
|
|
|
|
local samples = {}
|
|
for i = 1, 30 do
|
|
table.insert(samples, Corpus[i].pretty)
|
|
end
|
|
t:fuzz("decode", function(b: buffer)
|
|
return JsonF.decode(Bytes.reader(b))
|
|
end, samples)
|
|
t:done()
|