vec: merge ws/data (codecs/Xml, codecs/Json)

This commit is contained in:
4DBug committed 2026-10-31 08:45:48 -05:00
commit c371839331
20 files changed
+3708 -3

No files matched your search

+210
View File
@@ -0,0 +1,210 @@
-- 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()
+197
View File
@@ -0,0 +1,197 @@
-- codecs/Xml tests: random documents (namespaces, escapes, CDATA, comments, PIs, DOCTYPE entities, UTF-16, Latin-1)
-- against Python's ElementTree trees; encode -> decode round trips; well-formedness verdicts against expat
-- (hand-written cases and random mutations); events, helpers, options, error codes; the fuzz pass.
-- Fixtures: tools/fixtures/xml.py.
local T = require("@tests/T")
local Xml = require("@formats/codecs/Xml")
local Types = require("@formats/Types")
local Err = require("@formats/core/Err")
local Docs = require("@tests/gen/xml_docs")
local Wf = require("@tests/gen/xml_wf")
local t = T.suite("xml")
-- ElementTree's view of an element (tools/fixtures/xml.py canon): Clark names, xmlns attributes dropped, text / tail
local function s(x: string?): string
x = x or ""
return #(x :: string) .. ":" .. (x :: string)
end
local function canon(e: any, tail: string?): string
local out = { "(" .. s(Xml.clark(e)) }
local keys = {}
local vals = {}
for _, k in Types.keys(e.attrs) do
if k ~= "xmlns" and string.sub(k, 1, 6) ~= "xmlns:" then
local ck = Xml.clark(e, k)
table.insert(keys, ck)
vals[ck] = e.attrs[k]
end
end
table.sort(keys)
for _, k in keys do
table.insert(out, "|" .. s(k) .. "=" .. s(vals[k]))
end
-- text: strings before the first element child; each child's tail: strings after it
local text = {}
local i = 1
local ch = e.children
while i <= #ch and (type(ch[i]) == "string" or ch[i].name == "#cdata") do
table.insert(text, Xml.text(ch[i]))
i += 1
end
table.insert(out, "|t" .. s(table.concat(text)))
while i <= #ch do
local c = ch[i]
i += 1
local tl = {}
while i <= #ch and (type(ch[i]) == "string" or ch[i].name == "#cdata") do
table.insert(tl, Xml.text(ch[i]))
i += 1
end
table.insert(out, canon(c, table.concat(tl)))
end
return table.concat(out) .. ")t" .. s(tail)
end
-- 1. documents vs ElementTree, and round trips
for i, d in Docs do
local doc, err = Xml.decode(d.data, { whitespace = true })
t:check(doc, "doc " .. i .. ": " .. tostring(err))
t:eq(canon((doc :: any).root), d.canon, "doc " .. i .. ": tree")
-- keep everything, encode, decode again: the same tree
local full = Xml.decode(d.data, { whitespace = true, comments = true, cdata = true, pi = true }) :: any
local out, eerr = Xml.encode(full)
t:check(out, "doc " .. i .. ": encodes (" .. tostring(eerr) .. ")")
local again, aerr = Xml.decode(out :: string, { whitespace = true })
t:check(again, "doc " .. i .. ": re-decodes (" .. tostring(aerr) .. ")")
t:eq(canon((again :: any).root), d.canon, "doc " .. i .. ": round trip")
local pretty = Xml.encode(full, { indent = 2 }) :: string
t:check(Xml.decode(pretty), "doc " .. i .. ": pretty output parses")
-- the namespace option agrees with the clark helper
local nsdoc = Xml.decode(d.data, { namespaces = true }) :: any
local root = nsdoc.root
local want = string.match(Xml.clark(root), "^{([^}]*)}")
t:eq(root.ns, want, "doc " .. i .. ": node.ns")
end
-- 2. well-formedness against expat
local agree, total, accepted, rejected = 0, 0, 0, 0
for i, c in Wf do
local doc = Xml.decode(c.data)
local ok = doc ~= nil
total += 1
if ok == c.ok then
agree += 1
elseif i <= 60 then
t:check(false, "wf case " .. i .. " " .. string.format("%q", c.data) .. ": expat says " .. tostring(c.ok))
end
if c.ok then
accepted += 1
else
rejected += 1
end
end
t:note("well-formedness: %d of %d verdicts agree with expat (%d well-formed, %d not)", agree, total, accepted, rejected)
t:check(agree >= total * 0.99, "well-formedness agreement >= 99%")
-- 3. API details
do
local src = '<?xml version="1.0"?>\n<!DOCTYPE r [<!ENTITY e "E&#38;#38;">]>\n<!--c--><r xmlns="urn:d" xmlns:p="urn:p" z="1" a="2"><p:x p:k="v">t<![CDATA[<c>]]>u</p:x><?go now?><y/>\n</r>'
local doc = Xml.decode(src, { comments = true, cdata = true, pi = true, namespaces = true }) :: any
t:eq(doc.declaration.version, "1.0", "declaration")
t:eq(doc.doctype.name, "r", "doctype name")
t:eq(doc.doctype.entities.e, "E&#38;", "doctype entities (char refs expanded once)")
t:eq(doc.children[1].name, "#comment", "prolog comment kept")
local r = doc.root
t:eq(table.concat(Types.keys(r.attrs), ","), "xmlns,xmlns:p,z,a", "attribute order")
t:eq(r.ns, "urn:d", "default namespace")
local x = Xml.child(r, "x") :: any
t:eq(x.name, "p:x", "child by local name")
t:eq(x.ns, "urn:p", "prefixed namespace")
t:eq(Xml.clark(x, "p:k"), "{urn:p}k", "attribute clark")
t:eq(x.children[2].name, "#cdata", "cdata node")
t:eq(Xml.text(x), "t<c>u", "text with cdata")
t:eq(r.children[2].name, "#pi", "pi node")
t:eq(r.children[2].target .. "|" .. r.children[2].text, "go|now", "pi target / data")
t:eq(#Xml.children(r), 2, "element children")
t:eq(#Xml.descendants(doc), 3, "descendants")
t:eq(x.parent, r, "parent link")
t:eq(Xml.decode("<a>&e;</a>") == nil, true, "undefined entity")
local d2 = Xml.decode('<!DOCTYPE r [<!ENTITY e "E&#38;#38;">]><r a="&e;">&e;</r>') :: any
t:eq(d2.root.attrs.a, "E&", "entity in attribute")
t:eq(Xml.text(d2.root), "E&", "entity in text")
-- whitespace handling
local w = Xml.decode("<a>\n <b> x </b>\n <c xml:space='preserve'> </c>\n</a>") :: any
t:eq(#w.root.children, 2, "whitespace-only text dropped")
t:eq(Xml.text(w.root.children[1]), " x ", "other text kept as is")
t:eq(w.root.children[2].children[1], " ", "xml:space preserve")
t:eq(#(Xml.decode("<a>\n <b/>\n</a>", { whitespace = true }) :: any).root.children, 3, "opts.whitespace")
-- attribute normalization and line endings
local n = Xml.decode("<a b='x\ty\r\nz&#10;'>l1\r\nl2\rl3</a>") :: any
t:eq(n.root.attrs.b, "x y z\n", "attribute value normalization")
t:eq(Xml.text(n.root), "l1\nl2\nl3", "line endings")
-- builders and encode
local e = Xml.element("svg", { width = "10", height = "5" }, { Xml.element("rect", { x = "1" }), "a<b & \"c\"" })
Xml.setAttr(e, "id", "q\"\n")
t:eq(Xml.encode(e), '<svg height="5" width="10" id="q&quot;&#10;"><rect x="1"/>a&lt;b &amp; "c"</svg>', "encode element")
local d3 = Xml.document(Xml.element("r", nil, { Xml.element("a"), Xml.element("b", nil, { "t" }) }))
t:eq(Xml.encode(d3, { indent = 2 }), '<?xml version="1.0" encoding="UTF-8"?>\n<r>\n <a/>\n <b>t</b>\n</r>\n', "pretty document")
t:eq(Xml.encode(Xml.element("a"), { selfClose = false }), "<a></a>", "selfClose false")
local _, be = Xml.encode(Xml.element("1bad"))
t:eq(be and be.code, Err.ARG, "bad name on encode")
local cyc = Xml.element("a")
table.insert(cyc.children, cyc)
local _, ce = Xml.encode(cyc)
t:eq(ce and ce.code, Err.ARG, "cycle on encode")
t:eq(Xml.encode({ name = "#cdata", attrs = Types.object(), children = {}, text = "a]]>b" } :: any), "<![CDATA[a]]]]><![CDATA[>b]]>", "cdata split")
-- events
local evs = {}
for ev, a in Xml.events("<a x='1'><b>t</b><!--c--></a>") do
table.insert(evs, ev .. (if type(a) == "string" then ":" .. a else ""))
end
t:eq(table.concat(evs, " "), "start:a start:b text:t end:b comment:c end:a", "events")
local last
for ev, a in Xml.events("<a><b></a>") do
last = { ev, a }
end
t:eq(last[1], "error", "events error")
t:eq(last[2].code, Err.CORRUPT, "events error code")
-- UTF-16 without BOM and encodings
local u16 = buffer.create(8)
for k, ch in { 60, 0, 97, 0, 47, 0, 62, 0 } do
buffer.writeu8(u16, k - 1, ch)
end
t:eq((Xml.decode(u16) :: any).root.name, "a", "UTF-16LE without BOM")
local _, ue = Xml.decode("<?xml version='1.0' encoding='EBCDIC'?><a/>")
t:eq(ue and ue.code, Err.UNSUPPORTED, "unsupported encoding")
end
-- 4. errors and limits
local function code(src: string, opts: any?): string?
local _, e = Xml.decode(src, opts)
return e and e.code
end
t:eq(code("<a><b>"), Err.TRUNCATED, "unclosed")
t:eq(code("<a></b>"), Err.CORRUPT, "mismatch")
t:eq(code("<a b='1' b='2'/>"), Err.CORRUPT, "duplicate attribute")
t:eq(code(string.rep("<a>", 60) .. string.rep("</a>", 60), { maxDepth = 50 }), Err.LIMIT, "maxDepth")
t:eq(code('<!DOCTYPE r [<!ENTITY a "aaaaaaaaaa"><!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;"><!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;"><!ENTITY d "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;"><!ENTITY e "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">]><r>&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;</r>', { maxExpansion = 100000 }), Err.LIMIT, "billion laughs")
t:eq(code('<!DOCTYPE r [<!ENTITY a "&a;">]><r>&a;</r>'), Err.CORRUPT, "recursive entity")
t:eq(code('<!DOCTYPE r [<!ENTITY x SYSTEM "file.xml">]><r>&x;</r>'), Err.UNSUPPORTED, "external entity")
t:eq(code("<p:a/>", { namespaces = true }), Err.CORRUPT, "undeclared prefix")
local _, ae = Xml.decode(5 :: any)
t:eq(ae and ae.code, Err.ARG, "bad argument")
-- 5. fuzz
local samples = {}
for i = 1, 40 do
table.insert(samples, Docs[i].data)
end
t:fuzz("decode", function(b: buffer)
return Xml.decode(b, { comments = true, namespaces = true })
end, samples)
t:fuzz("encode(decode)", function(b: buffer)
local d = Xml.decode(b, { comments = true, cdata = true, pi = true })
return d and Xml.encode(d, { indent = 1 })
end, samples, { garbage = 20 })
t:done()
+86
View File
@@ -0,0 +1,86 @@
-- tests/data/Canon: the canonical text of a decoded data value, the same as tools/fixtures/_data_common.py canon() on
-- Python's parse: null n, true t, false f, numbers #%d (integral under 2^53) or #%.17g, strings s<len>:<bytes>,
-- buffers b<len>:<bytes>, arrays [x,...], objects {k=v,...} sorted by key text, dates d<rfc3339>. A module the data
-- tests require (running it alone does nothing).
local Types = require("@formats/Types")
local Canon = {}
local function num(x: number): string
if x ~= x then
return "#nan"
elseif x == math.huge then
return "#inf"
elseif x == -math.huge then
return "#-inf"
elseif x == math.floor(x) and math.abs(x) < 2 ^ 53 then
return string.format("#%d", x)
end
return "#" .. string.format("%.17g", x)
end
local function isArray(t: { [any]: any }): boolean
if Types.isObject(t) then
return false
end
local n = #t
local c = 0
for _ in next, t do
c += 1
end
return c == n
end
local function canon(v: any, out: { string })
local tv = type(v)
if v == Types.null then
table.insert(out, "n")
elseif tv == "boolean" then
table.insert(out, if v then "t" else "f")
elseif tv == "number" then
table.insert(out, num(v))
elseif tv == "string" then
table.insert(out, "s" .. #v .. ":" .. v)
elseif tv == "buffer" then
table.insert(out, "b" .. buffer.len(v) .. ":" .. buffer.tostring(v))
elseif tv == "table" and Types.Date.is(v) then
table.insert(out, "d" .. tostring(v))
elseif tv == "table" then
if isArray(v) then
table.insert(out, "[")
for i = 1, #v do
canon(v[i], out)
table.insert(out, ",")
end
table.insert(out, "]")
else
local items = {}
for k, x in next, v do
local ko = {}
canon(k, ko)
table.insert(items, { table.concat(ko), x })
end
table.sort(items, function(a, b)
return a[1] < b[1]
end)
table.insert(out, "{")
for _, it in items do
table.insert(out, it[1] .. "=")
canon(it[2], out)
table.insert(out, ",")
end
table.insert(out, "}")
end
else
table.insert(out, "?" .. tv)
end
end
-- of(v) -> the canonical text
function Canon.of(v: any): string
local out = {}
canon(v, out)
return table.concat(out)
end
return Canon
+71
View File
@@ -0,0 +1,71 @@
-- 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()
+49
View File
@@ -0,0 +1,49 @@
-- data/xml tests: the contract, the format through the API (F.load / F.save / sniffing), documents from Python's
-- ElementTree fixtures decoded and re-encoded through the format, and the fuzz pass. The codec itself is tested in
-- tests/codecs/xml.luau. Fixtures: tools/fixtures/xml.py.
local T = require("@tests/T")
local F = require("@formats")
local XmlF = require("@formats/data/xml")
local Xml = require("@formats/codecs/Xml")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Docs = require("@tests/gen/xml_docs")
local t = T.suite("data/xml")
t:eq(XmlF.name, "xml", "name")
t:eq(XmlF.category, "data", "category")
t:check(XmlF.caps.decode and XmlF.caps.encode, "caps")
for i = 1, 60 do
local d = Docs[i]
local doc, err = XmlF.decode(Bytes.reader(buffer.fromstring(d.data)), { comments = true, cdata = true, whitespace = true })
t:check(doc ~= nil, "doc " .. i .. ": " .. tostring(err))
local b, eerr = XmlF.encode(doc :: any)
t:check(b ~= nil, "doc " .. i .. ": encode " .. tostring(eerr))
local again = XmlF.decode(Bytes.reader(b :: buffer), { comments = true, cdata = true, whitespace = true })
t:check(again ~= nil, "doc " .. i .. ": re-decode")
t:eq(Xml.text((again :: any).root), Xml.text((doc :: any).root), "doc " .. i .. ": same text")
end
do
local doc, err = F.load(buffer.fromstring('<?xml version="1.0"?><r><a k="v">t</a></r>'))
t:check(doc ~= nil, "F.load sniffs xml: " .. tostring(err))
t:eq(doc.root.name, "r", "root")
local s = F.saveString(doc, { format = "xml" })
t:eq(s, '<?xml version="1.0" encoding="UTF-8"?>\n<r><a k="v">t</a></r>', "F.saveString")
local _, e = XmlF.encode(5 :: any)
t:eq(e and e.code, Err.ARG, "encode argument check")
local _, e2 = F.load(buffer.fromstring("<r><a></r>"), { format = "xml" })
t:eq(e2 and e2.code, Err.CORRUPT, "error through the API")
t:eq(e2 and e2.format, "xml", "error tagged with the format")
end
local samples = {}
for i = 1, 30 do
table.insert(samples, Docs[i].data)
end
t:fuzz("decode", function(b: buffer)
return XmlF.decode(Bytes.reader(b))
end, samples)
t:done()