merge ws/data: codecs Json/Xml, data json xml csv ini toml yaml msgpack cbor plist
This commit is contained in:
commit
e8d2ba81c2
49 files changed
+10395
-3
No files matched your search
@@ -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()
|
||||
@@ -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;">]>\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&", "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;">]><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 '>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" "><rect x="1"/>a<b & "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()
|
||||
@@ -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
|
||||
@@ -0,0 +1,121 @@
|
||||
-- data/cbor tests: the RFC 8949 Appendix A examples and random items encoded by Python's cbor2 decode to cbor2's
|
||||
-- values (canonical form), re-encode to the same bytes, big integers as doubles and exact text, indefinite lengths,
|
||||
-- tags / simple values / undefined, half floats, sequences, options, error codes, and the fuzz pass.
|
||||
-- Fixtures: tools/fixtures/cbor.py.
|
||||
local T = require("@tests/T")
|
||||
local Cbor = require("@formats/data/cbor")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Canon = require("@tests/data/Canon")
|
||||
local Fx = require("@tests/gen/cbor")
|
||||
|
||||
local t = T.suite("data/cbor")
|
||||
|
||||
t:eq(Cbor.name, "cbor", "name")
|
||||
t:check(Cbor.caps.decode and Cbor.caps.encode, "caps")
|
||||
|
||||
local function dec(s: string | buffer, opts: any?): (any, any)
|
||||
local b = if type(s) == "string" then buffer.fromstring(s) else s
|
||||
return Cbor.decode(Bytes.reader(b), opts)
|
||||
end
|
||||
|
||||
-- the fixture's view of tags / simple values / undefined
|
||||
local function plain(v: any): any
|
||||
if v == Cbor.undefined then
|
||||
return { "undefined" }
|
||||
elseif Cbor.isSimple(v) then
|
||||
return { "simple", v.value }
|
||||
elseif Cbor.isTagged(v) then
|
||||
return { "tag", v.tag, plain(v.value) }
|
||||
elseif type(v) == "table" and not Types.Date.is(v) and v ~= Types.null then
|
||||
local o = if Types.isObject(v) then Types.object() else {}
|
||||
for k, x in next, v do
|
||||
o[plain(k)] = plain(x)
|
||||
end
|
||||
return o
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
local nApp = 0
|
||||
for _, c in Fx.appendix do
|
||||
local v, err = dec(c.data)
|
||||
if c.error then
|
||||
t:check(v == nil and err ~= nil, c.hex .. ": rejected like cbor2")
|
||||
else
|
||||
t:check(v ~= nil or err == nil, c.hex .. ": " .. tostring(err))
|
||||
t:eq(Canon.of(plain(v)), c.canon, c.hex .. ": value")
|
||||
t:eq(Canon.of(plain(dec(c.data, { bigInts = "string" }))), c.canonStr, c.hex .. ": exact")
|
||||
t:eq(Canon.of(plain(dec(Cbor.encode(v) :: buffer))), c.canon, c.hex .. ": round trip")
|
||||
t:eq(Canon.of(plain(dec(Cbor.encode(v, { compactFloats = true }) :: buffer))), c.canon, c.hex .. ": compact round trip")
|
||||
end
|
||||
nApp += 1
|
||||
end
|
||||
t:note("RFC 8949 appendix A: %d examples", nApp)
|
||||
|
||||
for i, c in Fx.safe do
|
||||
local v, err = dec(c.data)
|
||||
t:check(v ~= nil, "safe " .. i .. ": " .. tostring(err))
|
||||
t:eq(Canon.of(plain(v)), c.canon, "safe " .. i .. ": value")
|
||||
local b = Cbor.encode(v) :: buffer
|
||||
t:check(b and buffer.tostring(b) == c.data, "safe " .. i .. ": same bytes")
|
||||
end
|
||||
for i, c in Fx.wide do
|
||||
local v, err = dec(c.data)
|
||||
t:check(v ~= nil, "wide " .. i .. ": " .. tostring(err))
|
||||
t:eq(Canon.of(plain(v)), c.canon, "wide " .. i .. ": value")
|
||||
t:eq(Canon.of(plain(dec(c.data, { bigInts = "string" }))), c.canonStr, "wide " .. i .. ": exact")
|
||||
end
|
||||
|
||||
-- details
|
||||
do
|
||||
local function hex(b: buffer): string
|
||||
return (string.gsub(buffer.tostring(b), ".", function(ch)
|
||||
return string.format("%02x", string.byte(ch))
|
||||
end))
|
||||
end
|
||||
t:eq(hex(Cbor.encode(1.5, { compactFloats = true }) :: buffer), "f93e00", "half float")
|
||||
t:eq(hex(Cbor.encode(100000.0 + 0.5, { compactFloats = true }) :: buffer), "fa47c35040", "single float")
|
||||
t:eq(hex(Cbor.encode(1.1) :: buffer), "fb3ff199999999999a", "double float")
|
||||
t:eq(hex(Cbor.encode(-0.0, { compactFloats = true }) :: buffer), "f98000", "negative zero")
|
||||
t:eq(hex(Cbor.encode(0 / 0, { compactFloats = true }) :: buffer), "f97e00", "nan")
|
||||
t:eq(hex(Cbor.encode(-2 ^ 64) :: buffer), "3bffffffffffffffff", "-2^64")
|
||||
t:eq(hex(Cbor.encode(Cbor.tagged(32, "x")) :: buffer), "d8206178", "tagged")
|
||||
t:eq(hex(Cbor.encode(Cbor.simple(255)) :: buffer), "f8ff", "simple")
|
||||
t:eq(hex(Cbor.encode(Cbor.undefined) :: buffer), "f7", "undefined")
|
||||
t:eq(hex(Cbor.encode(Types.Date.parse("2013-03-21T20:04:00Z")) :: buffer), "c074323031332d30332d32315432303a30343a30305a", "date tag 0")
|
||||
t:eq(hex(Cbor.encode(Types.Date.parse("2013-03-21T20:04:00Z"), { dates = "epoch" }) :: buffer), "c11a514b67b0", "date tag 1")
|
||||
t:eq(hex(Cbor.encode({ 1 }, { selfDescribe = true }) :: buffer), "d9d9f78101", "self-describe")
|
||||
t:eq(dec("\217\217\247\1"), 1, "self-describe stripped")
|
||||
t:eq(Cbor.sniff(Bytes.reader(buffer.fromstring("\217\217\247\1"))), 1, "sniff self-describe")
|
||||
t:eq(#dec("\1\2\3", { all = true }), 3, "sequence")
|
||||
t:eq(hex(Cbor.encode({ 1, "a" }, { all = true }) :: buffer), "016161", "encode sequence")
|
||||
local function code(s: string): string?
|
||||
local _, e = dec(s)
|
||||
return e and e.code
|
||||
end
|
||||
t:eq(code("\x9b\xff\xff\xff\xff\xff\xff\xff\xff"), Err.TRUNCATED, "huge array count")
|
||||
t:eq(code("\x5f\x61\x61\xff"), Err.CORRUPT, "text chunk in a byte string")
|
||||
t:eq(code("\xff"), Err.CORRUPT, "lone break")
|
||||
t:eq(code("\x1c"), Err.CORRUPT, "reserved additional info")
|
||||
t:eq(code("\x62\xc3\x28"), Err.CORRUPT, "invalid UTF-8")
|
||||
t:eq(code("\x01\x02"), Err.CORRUPT, "trailing data")
|
||||
t:eq(code("\xc0\x01"), Err.CORRUPT, "tag 0 on a number")
|
||||
t:eq(code(string.rep("\x81", 600) .. "\x01"), Err.LIMIT, "depth")
|
||||
t:eq(code("\x9f\x01"), Err.TRUNCATED, "unterminated indefinite array")
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for _, c in Fx.appendix do
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
for i = 1, 40 do
|
||||
if #Fx.safe[i].data < 3000 then
|
||||
table.insert(samples, Fx.safe[i].data)
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Cbor.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 4 })
|
||||
t:done()
|
||||
@@ -0,0 +1,76 @@
|
||||
-- data/csv tests: tables written by Python's csv.writer / DictWriter (every delimiter, quotes, line breaks inside
|
||||
-- fields, empty fields) read back as csv.reader does, re-encoded byte for byte, keyed rows with a header, options,
|
||||
-- error codes, and the fuzz pass. Fixtures: tools/fixtures/csv.py.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Csv = require("@formats/data/csv")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Canon = require("@tests/data/Canon")
|
||||
local Fx = require("@tests/gen/csv")
|
||||
|
||||
local t = T.suite("data/csv")
|
||||
|
||||
t:eq(Csv.name, "csv", "name")
|
||||
t:check(Csv.caps.decode and Csv.caps.encode, "caps")
|
||||
|
||||
local function dec(s: string, opts: any?): (any, any)
|
||||
return Csv.decode(Bytes.reader(buffer.fromstring(s)), opts)
|
||||
end
|
||||
|
||||
for i, c in Fx do
|
||||
local rows, err = dec(c.data, { delimiter = c.delimiter })
|
||||
t:check(rows ~= nil, "case " .. i .. ": " .. tostring(err))
|
||||
t:eq(Canon.of(rows), Canon.of(c.rows), "case " .. i .. ": rows")
|
||||
local b = Csv.encode(rows, { delimiter = c.delimiter, newline = c.newline }) :: buffer
|
||||
t:eq(buffer.tostring(b), c.data, "case " .. i .. ": same text")
|
||||
if c.delimiter ~= "," or i % 3 == 0 then
|
||||
local auto = dec(c.data, { delimiter = "auto" })
|
||||
if c.rows[1] and #c.rows[1] > 1 and auto then
|
||||
-- auto only has the first line to go on; it must at least split like the real delimiter there
|
||||
t:check(#auto[1] >= 1, "case " .. i .. ": auto")
|
||||
end
|
||||
end
|
||||
if c.keyed then
|
||||
local keyed = dec(c.data, { header = true }) :: any
|
||||
t:eq(#keyed, #c.rows - 1, "case " .. i .. ": keyed row count")
|
||||
t:eq(table.concat(Types.keys(keyed[1]), "|"), table.concat(c.rows[1], "|"), "case " .. i .. ": column order")
|
||||
local kb = Csv.encode(keyed) :: buffer
|
||||
t:eq(buffer.tostring(kb), c.data, "case " .. i .. ": keyed re-encode (DictWriter text)")
|
||||
end
|
||||
end
|
||||
|
||||
-- details
|
||||
do
|
||||
t:eq(Canon.of(dec("a,b\n\n1,2\r\n3,4\r5,6")), Canon.of({ { "a", "b" }, { "1", "2" }, { "3", "4" }, { "5", "6" } }), "line ends, blank lines")
|
||||
t:eq(Canon.of(dec('"a""b",c"d,"e"x')), Canon.of({ { 'a"b', 'c"d', "ex" } }), "lenient quotes like Python")
|
||||
t:eq(Canon.of(dec("a;b|c", { delimiter = "auto" })), Canon.of({ { "a", "b|c" } }), "auto delimiter")
|
||||
t:eq(Canon.of(dec("x,1.5,-2,1e3,abc, 7 ", { numbers = true })), Canon.of({ { "x", 1.5, -2, 1000, "abc", 7 } }), "numbers")
|
||||
t:eq(Canon.of(dec("a,b,c\n1,2")[1]), Canon.of({ "a", "b", "c" }), "ragged rows kept")
|
||||
local k = dec("a,b\n1,2,3\n4", { header = true })
|
||||
t:eq(k[1].b, "2", "keyed")
|
||||
t:eq(k[2].b, nil, "short keyed row")
|
||||
t:eq(buffer.tostring(Csv.encode({ { 1, true, F.null, 0.5 } }) :: buffer), "1,true,,0.5\r\n", "field types")
|
||||
t:eq(buffer.tostring(Csv.encode({ { "a", "b" } }, { quoteAll = true, newline = "\n" }) :: buffer), '"a","b"\n', "quoteAll")
|
||||
t:eq(buffer.tostring(Csv.encode({ { "" } }) :: buffer), '""\r\n', "single empty field quoted")
|
||||
local _, e = dec('a,"b')
|
||||
t:eq(e and e.code, Err.TRUNCATED, "unterminated quote")
|
||||
local _, e2 = dec("a", { delimiter = "ab" })
|
||||
t:eq(e2 and e2.code, Err.ARG, "bad delimiter")
|
||||
local _, e3 = Csv.encode({ { {} } })
|
||||
t:eq(e3 and e3.code, Err.ARG, "bad field")
|
||||
local _, e4 = dec("1\n2\n3", { maxRows = 2 })
|
||||
t:eq(e4 and e4.code, Err.LIMIT, "maxRows")
|
||||
local v = F.load(buffer.fromstring("a,b\r\n1,2\r\n"), { format = "csv", header = true })
|
||||
t:eq(v[1].a, "1", "through the API")
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for i = 1, 40 do
|
||||
table.insert(samples, Fx[i].data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Csv.decode(Bytes.reader(b), { delimiter = "auto", header = true, numbers = true })
|
||||
end, samples)
|
||||
t:done()
|
||||
@@ -0,0 +1,71 @@
|
||||
-- data/ini tests: configs written by Python's configparser read back to configparser's values and re-encoded byte for
|
||||
-- byte, messy hand-written files read as configparser(strict = false) reads them, options (inline comments, keys
|
||||
-- without values, types, strict), top-level keys, error codes, and the fuzz pass. Fixtures: tools/fixtures/ini.py.
|
||||
local T = require("@tests/T")
|
||||
local Ini = require("@formats/data/ini")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Canon = require("@tests/data/Canon")
|
||||
local Fx = require("@tests/gen/ini")
|
||||
|
||||
local t = T.suite("data/ini")
|
||||
|
||||
t:eq(Ini.name, "ini", "name")
|
||||
t:check(Ini.caps.decode and Ini.caps.encode, "caps")
|
||||
|
||||
local function dec(s: string, opts: any?): (any, any)
|
||||
return Ini.decode(Bytes.reader(buffer.fromstring(s)), opts)
|
||||
end
|
||||
|
||||
for i, c in Fx.written do
|
||||
local v, err = dec(c.data)
|
||||
t:check(v ~= nil, "written " .. i .. ": " .. tostring(err))
|
||||
t:eq(Canon.of(v), c.canon, "written " .. i .. ": values")
|
||||
t:eq(buffer.tostring(Ini.encode(v) :: buffer), c.data, "written " .. i .. ": same text")
|
||||
end
|
||||
for i, c in Fx.read do
|
||||
local v, err = dec(c.data)
|
||||
t:check(v ~= nil, "messy " .. i .. ": " .. tostring(err))
|
||||
t:eq(Canon.of(v), c.canon, "messy " .. i .. ": values")
|
||||
end
|
||||
|
||||
do
|
||||
local v = dec("top = 1\n[s]\na = 2 ; c\nflag\nn = 0x10\nb = Yes\n", { inlineComments = true, allowNoValue = true, types = true })
|
||||
t:eq(v.top, 1, "top-level key, typed")
|
||||
t:eq(v.s.a, 2, "inline comment stripped")
|
||||
t:eq(v.s.flag, true, "key without value")
|
||||
t:eq(v.s.n, 16, "hex number")
|
||||
t:eq(v.s.b, true, "yes -> true")
|
||||
t:eq(table.concat(Types.keys(v), ","), "top,s", "order")
|
||||
local o = Types.object()
|
||||
Types.set(o, "name", "x")
|
||||
local sub = Types.object()
|
||||
Types.set(sub, "k", "multi\nline")
|
||||
Types.set(sub, "inner", { z = 1 })
|
||||
Types.set(o, "sec", sub)
|
||||
t:eq(buffer.tostring(Ini.encode(o) :: buffer), "name = x\n\n[sec]\nk = multi\n\tline\n\n[sec.inner]\nz = 1\n\n", "encode nested")
|
||||
local function code(s: string, opts: any?): string?
|
||||
local _, e = dec(s, opts)
|
||||
return e and e.code
|
||||
end
|
||||
t:eq(code("[a]\njunk line\n"), Err.CORRUPT, "line without delimiter")
|
||||
t:eq(code("[a]\nk=1\nk=2\n", { strict = true }), Err.CORRUPT, "strict duplicate key")
|
||||
t:eq(code("[a]\n[a]\n", { strict = true }), Err.CORRUPT, "strict duplicate section")
|
||||
t:eq(code("[a]\n= v\n"), Err.CORRUPT, "empty key")
|
||||
local _, ee = Ini.encode({ ["bad=key"] = "v" })
|
||||
t:eq(ee and ee.code, Err.ARG, "unwritable key")
|
||||
t:eq(Ini.sniff(Bytes.reader(buffer.fromstring("; c\n[section]\nk=v"))), 0.2, "sniff")
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for _, c in Fx.read do
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
for i = 1, 20 do
|
||||
table.insert(samples, Fx.written[i].data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Ini.decode(Bytes.reader(b), { types = true, inlineComments = true })
|
||||
end, samples)
|
||||
t:done()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,96 @@
|
||||
-- data/msgpack tests: values packed by Python's msgpack decode to msgpack's own values (canonical form), re-encode to
|
||||
-- the same bytes, 64-bit integers as doubles and as exact strings, timestamps / ext, streams, options, error codes,
|
||||
-- and the fuzz pass. Fixtures: tools/fixtures/msgpack.py.
|
||||
local T = require("@tests/T")
|
||||
local Mp = require("@formats/data/msgpack")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Canon = require("@tests/data/Canon")
|
||||
local Fx = require("@tests/gen/msgpack")
|
||||
|
||||
local t = T.suite("data/msgpack")
|
||||
|
||||
t:eq(Mp.name, "msgpack", "name")
|
||||
t:check(Mp.caps.decode and Mp.caps.encode, "caps")
|
||||
|
||||
local function dec(s: string | buffer, opts: any?): (any, any)
|
||||
local b = if type(s) == "string" then buffer.fromstring(s) else s
|
||||
return Mp.decode(Bytes.reader(b), opts)
|
||||
end
|
||||
|
||||
-- ext values canonicalise like the fixture's ["ext", code, data]
|
||||
local function plain(v: any): any
|
||||
if Mp.isExt(v) then
|
||||
return { "ext", v.type, v.data }
|
||||
elseif type(v) == "table" and not Types.Date.is(v) and v ~= Types.null then
|
||||
local o = if Types.isObject(v) then Types.object() else {}
|
||||
for k, x in next, v do
|
||||
o[k] = plain(x)
|
||||
end
|
||||
return o
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
for i, c in Fx.safe do
|
||||
local v, err = dec(c.data)
|
||||
t:check(v ~= nil, "safe " .. i .. ": " .. tostring(err))
|
||||
t:eq(Canon.of(plain(v)), c.canon, "safe " .. i .. ": value")
|
||||
local b = Mp.encode(v) :: buffer
|
||||
t:check(b and buffer.tostring(b) == c.data, "safe " .. i .. ": same bytes")
|
||||
end
|
||||
for i, c in Fx.wide do
|
||||
local v, err = dec(c.data)
|
||||
t:check(v ~= nil, "wide " .. i .. ": " .. tostring(err))
|
||||
t:eq(Canon.of(plain(v)), c.canon, "wide " .. i .. ": value")
|
||||
local vs = dec(c.data, { bigInts = "string" })
|
||||
t:eq(Canon.of(plain(vs)), c.canonStr, "wide " .. i .. ": exact big integers")
|
||||
t:eq(Canon.of(plain(dec(Mp.encode(v) :: buffer))), c.canon, "wide " .. i .. ": round trip")
|
||||
end
|
||||
|
||||
-- details
|
||||
do
|
||||
t:eq(Mp.isExt(dec("\xd4\x05\x07")), true, "fixext1")
|
||||
local d = dec("\xd6\xff\x00\x00\x00\x00")
|
||||
t:check(Types.Date.is(d) and tostring(d) == "1970-01-01T00:00:00Z", "timestamp32")
|
||||
t:eq(dec("\xcf\xff\xff\xff\xff\xff\xff\xff\xff", { bigInts = "string" }), "18446744073709551615", "u64 max text")
|
||||
t:eq(dec("\xd3\x80\x00\x00\x00\x00\x00\x00\x00", { bigInts = "string" }), "-9223372036854775808", "i64 min text")
|
||||
t:eq(dec("\xd3\xff\xff\xff\xff\xff\xff\xff\xff"), -1, "i64 -1")
|
||||
t:eq(buffer.tostring(Mp.encode(-2 ^ 40) :: buffer), "\xd3\xff\xff\xff\x00\x00\x00\x00\x00", "encode i64")
|
||||
t:eq(buffer.tostring(Mp.encode(1.5, { float32 = true }) :: buffer), "\xca\x3f\xc0\x00\x00", "float32")
|
||||
t:eq(buffer.tostring(Mp.encode({}) :: buffer), "\x90", "empty table = array")
|
||||
t:eq(buffer.tostring(Mp.encode({}, { emptyTable = "map" }) :: buffer), "\x80", "emptyTable map")
|
||||
t:eq(buffer.tostring(Mp.encode(Types.object()) :: buffer), "\x80", "Types.object = map")
|
||||
t:eq(buffer.tostring(Mp.encode({ b = 1, a = 2 }) :: buffer), "\x82\xa1a\x02\xa1b\x01", "plain keys sorted")
|
||||
t:eq(buffer.tostring(Mp.encode("ab", { stringsAsBin = true }) :: buffer), "\xc4\x02ab", "stringsAsBin")
|
||||
t:eq(buffer.tostring(Mp.encode(Mp.ext(3, buffer.fromstring("xyz"))) :: buffer), "\xc7\x03\x03xyz", "ext8")
|
||||
local all = dec("\x01\x02\xa1x", { all = true })
|
||||
t:eq(#all, 3, "stream")
|
||||
t:eq(buffer.tostring(Mp.encode({ 1, "x" }, { all = true }) :: buffer), "\x01\xa1x", "encode stream")
|
||||
t:eq(dec("\xc0"), Types.null, "nil -> null")
|
||||
local cyc = {}
|
||||
cyc[1] = cyc
|
||||
local _, ce = Mp.encode(cyc)
|
||||
t:eq(ce and ce.code, Err.ARG, "cycle")
|
||||
local function code(s: string, o: any?): string?
|
||||
local _, e = dec(s, o)
|
||||
return e and e.code
|
||||
end
|
||||
t:eq(code("\xdd\xff\xff\xff\xff"), Err.TRUNCATED, "huge array count")
|
||||
t:eq(code("\xa5ab"), Err.TRUNCATED, "short string")
|
||||
t:eq(code("\xc1"), Err.CORRUPT, "reserved byte")
|
||||
t:eq(code("\x01\x02"), Err.CORRUPT, "trailing data")
|
||||
t:eq(code(string.rep("\x91", 600) .. "\x01"), Err.LIMIT, "depth")
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for i = 5, 60 do
|
||||
if #Fx.safe[i].data < 3000 then
|
||||
table.insert(samples, Fx.safe[i].data)
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Mp.decode(Bytes.reader(b))
|
||||
end, samples)
|
||||
t:done()
|
||||
@@ -0,0 +1,86 @@
|
||||
-- data/plist tests: values written by Python's plistlib as XML and binary decode to plistlib's values; our XML writer
|
||||
-- reproduces plistlib's XML byte for byte; binary-only values (UIDs, 64-bit integers); a hand-written XML plist;
|
||||
-- error codes; the fuzz pass (XML and binary). Fixtures: tools/fixtures/plist.py.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Plist = require("@formats/data/plist")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Canon = require("@tests/data/Canon")
|
||||
local Fx = require("@tests/gen/plist")
|
||||
|
||||
local t = T.suite("data/plist")
|
||||
|
||||
t:eq(Plist.name, "plist", "name")
|
||||
t:check(Plist.caps.decode and Plist.caps.encode, "caps")
|
||||
|
||||
local function dec(s: string, opts: any?): (any, any)
|
||||
return Plist.decode(Bytes.reader(buffer.fromstring(s)), opts)
|
||||
end
|
||||
local function plain(v: any): any
|
||||
if Plist.isUid(v) then
|
||||
return { "uid", v.uid }
|
||||
elseif type(v) == "table" and not Types.Date.is(v) then
|
||||
local o = if Types.isObject(v) then Types.object() else {}
|
||||
for k, x in next, v do
|
||||
o[k] = plain(x)
|
||||
end
|
||||
return o
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
for i, c in Fx.cases do
|
||||
local v, err = dec(c.xml)
|
||||
t:check(v ~= nil, "xml " .. i .. ": " .. tostring(err))
|
||||
t:eq(Canon.of(v), c.canon, "xml " .. i .. ": value")
|
||||
local vb, berr = dec(c.binary)
|
||||
t:check(vb ~= nil, "binary " .. i .. ": " .. tostring(berr))
|
||||
t:eq(Canon.of(vb), c.canon, "binary " .. i .. ": value")
|
||||
t:eq(buffer.tostring(Plist.encode(v) :: buffer), c.xml, "xml " .. i .. ": same text as plistlib")
|
||||
end
|
||||
for i, c in Fx.wide do
|
||||
local v, err = dec(c.binary)
|
||||
t:check(v ~= nil, "wide " .. i .. ": " .. tostring(err))
|
||||
t:eq(Canon.of(plain(v)), c.canon, "wide " .. i .. ": value")
|
||||
end
|
||||
do
|
||||
local v = dec(Fx.extra)
|
||||
t:eq(Canon.of(v), Fx.extraCanon, "hand-written plist")
|
||||
t:eq(v.hex, 31, "hex integer")
|
||||
local f = F.load(buffer.fromstring(Fx.cases[1].binary))
|
||||
t:check(f ~= nil, "F.load sniffs binary plists")
|
||||
local fx = F.load(buffer.fromstring(Fx.cases[1].xml))
|
||||
t:eq(Canon.of(fx), Fx.cases[1].canon, "F.load sniffs XML plists over plain XML")
|
||||
t:eq(dec("<plist><string>x</string></plist>"), "x", "bare root value")
|
||||
local function code(s: string): string?
|
||||
local _, e = dec(s)
|
||||
return e and e.code
|
||||
end
|
||||
t:eq(code("<plist><dict><key>a</key></dict></plist>"), Err.CORRUPT, "key without value")
|
||||
t:eq(code("<plist><integer>x</integer></plist>"), Err.CORRUPT, "bad integer")
|
||||
t:eq(code("<plist><data>!!</data></plist>"), Err.CORRUPT, "bad base64")
|
||||
t:eq(code("<plist><foo/></plist>"), Err.CORRUPT, "unknown element")
|
||||
t:eq(code("bplist00"), Err.TRUNCATED, "short binary")
|
||||
local _, ne = Plist.encode({ a = F.null })
|
||||
t:eq(ne and ne.code, Err.ARG, "null cannot be written")
|
||||
local _, ke = Plist.encode({ [1] = 1, x = 2 })
|
||||
t:eq(ke and ke.code, Err.ARG, "non-string key")
|
||||
-- a binary plist with a cycle: array 0 -> [array 0]
|
||||
local cyc = "bplist00" .. "\xa1\x00" .. "\x08" .. string.rep("\0", 6) .. "\1\1" .. "\0\0\0\0\0\0\0\1" .. "\0\0\0\0\0\0\0\0" .. "\0\0\0\0\0\0\0\10"
|
||||
t:eq(code(cyc), Err.CORRUPT, "reference cycle")
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for i = 1, 25 do
|
||||
table.insert(samples, Fx.cases[i].xml)
|
||||
table.insert(samples, Fx.cases[i].binary)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Plist.decode(Bytes.reader(b))
|
||||
end, samples, { keepHeader = 0 })
|
||||
t:fuzz("decode binary (header kept)", function(b: buffer)
|
||||
return Plist.decode(Bytes.reader(b))
|
||||
end, { Fx.cases[3].binary, Fx.cases[4].binary, Fx.wide[1].binary }, { keepHeader = 8, mutations = 200, garbage = 0 })
|
||||
t:done()
|
||||
@@ -0,0 +1,121 @@
|
||||
-- data/toml tests: the toml-test suite's TOML 1.0 files (every valid/ case decodes to its expected value, every
|
||||
-- invalid/ case fails), a tomli-w corpus against Python's tomllib, encoder round trips (decode(encode(v)) is the same
|
||||
-- value) and exact encoder output, options, error codes, the contract and the fuzz pass. Fixtures: tools/fixtures/toml.py.
|
||||
local T = require("@tests/T")
|
||||
local Toml = require("@formats/data/toml")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Canon = require("@tests/data/Canon")
|
||||
local Suite = require("@tests/gen/toml_suite")
|
||||
local Corpus = require("@tests/gen/toml_corpus")
|
||||
|
||||
local t = T.suite("data/toml")
|
||||
|
||||
t:eq(Toml.name, "toml", "name")
|
||||
t:eq(Toml.category, "data", "category")
|
||||
t:check(Toml.caps.decode and Toml.caps.encode, "caps")
|
||||
|
||||
local function dec(s: string, opts: any?): (any, any)
|
||||
return Toml.decode(Bytes.reader(buffer.fromstring(s)), opts)
|
||||
end
|
||||
local function enc(v: any, opts: any?): (string?, any)
|
||||
local b, e = Toml.encode(v, opts)
|
||||
return if b then buffer.tostring(b) else nil, e
|
||||
end
|
||||
|
||||
-- 1. toml-test
|
||||
local nv, ni, rt = 0, 0, 0
|
||||
for _, c in Suite do
|
||||
local v, err = dec(c.data)
|
||||
if c.valid then
|
||||
t:check(v ~= nil, c.name .. ": parses (" .. tostring(err) .. ")")
|
||||
t:eq(Canon.of(v), c.canon, c.name .. ": value")
|
||||
-- the encoder's output reads back as the same value (floats that are integral become integers, so compare
|
||||
-- the decoded values, not the toml-test canon)
|
||||
local s, eerr = enc(v)
|
||||
t:check(s ~= nil, c.name .. ": encodes (" .. tostring(eerr) .. ")")
|
||||
local back, berr = dec(s :: string)
|
||||
t:check(back ~= nil, c.name .. ": re-decodes (" .. tostring(berr) .. ")\n" .. tostring(s))
|
||||
t:eq(Canon.of(back), Canon.of(v), c.name .. ": round trip")
|
||||
nv += 1
|
||||
rt += 1
|
||||
else
|
||||
t:check(v == nil and Err.is(err), c.name .. ": rejected")
|
||||
ni += 1
|
||||
end
|
||||
end
|
||||
t:note("toml-test 1.0: %d valid decoded and round-tripped, %d invalid rejected", nv, ni)
|
||||
|
||||
-- 2. tomli-w corpus vs tomllib
|
||||
for i, c in Corpus do
|
||||
local v, err = dec(c.data)
|
||||
t:check(v ~= nil, "corpus " .. i .. ": " .. tostring(err))
|
||||
t:eq(Canon.of(v), c.canon, "corpus " .. i .. ": value")
|
||||
local s = enc(v) :: string
|
||||
t:eq(Canon.of(dec(s)), c.canon, "corpus " .. i .. ": round trip")
|
||||
t:eq(Canon.of(dec(enc(v, { inline = true }) :: string)), c.canon, "corpus " .. i .. ": inline round trip")
|
||||
end
|
||||
|
||||
-- 3. API details
|
||||
do
|
||||
local v = dec('z = 1\na = 2\n[t]\ny = "x"\nb = 1979-05-27T07:32:00.5-07:00\n[[arr]]\nk = 1\n[[arr]]\nk = 2\n')
|
||||
t:eq(table.concat(Types.keys(v), ","), "z,a,t,arr", "key order")
|
||||
t:check(Types.Date.is(v.t.b) and v.t.b.kind == "datetime" and v.t.b.offset == -420, "datetime value")
|
||||
t:eq(tostring(v.t.b), "1979-05-27T07:32:00.5-07:00", "datetime text")
|
||||
t:eq(v.arr[2].k, 2, "array of tables")
|
||||
t:eq(enc(v), 'z = 1\na = 2\n\n[t]\ny = "x"\nb = 1979-05-27T07:32:00.5-07:00\n\n[[arr]]\nk = 1\n\n[[arr]]\nk = 2\n', "encode text")
|
||||
t:eq(enc({ b = { 1, 2.5, "s" }, a = { x = true } }), 'b = [1, 2.5, "s"]\n\n[a]\nx = true\n', "plain tables: scalars first, sorted")
|
||||
t:eq(enc({ ["a b"] = "q\"\n\1" }), '"a b" = "q\\"\\n\\u0001"\n', "key / string escapes")
|
||||
t:eq(enc({ a = { x = 1 } }, { inline = true }), "a = { x = 1 }\n", "inline option")
|
||||
t:eq(enc({ f = 0 / 0, g = math.huge, h = 1e300, i = -0.5 }), "f = nan\ng = inf\nh = 1e+300\ni = -0.5\n", "floats")
|
||||
t:eq(enc({ a = { b = { c = 1 } } }, { indent = 2 }), "[a]\n\n [a.b]\n c = 1\n", "indent")
|
||||
local big = dec("a = 9223372036854775807\nb = 0x7fffffffffffffff\nc = 12", { bigInts = "string" })
|
||||
t:eq(big.a, "9223372036854775807", "bigInts string")
|
||||
t:eq(big.b, "0x7fffffffffffffff", "bigInts string hex")
|
||||
t:eq(big.c, 12, "small ints stay numbers")
|
||||
t:eq(dec("a = 9223372036854775807").a, 9223372036854775807, "bigInts number")
|
||||
local _, e1 = enc({ a = Types.null })
|
||||
t:eq(e1 and e1.code, Err.ARG, "null is an error")
|
||||
local cyc = {}
|
||||
cyc.self = cyc
|
||||
local _, e2 = enc(cyc)
|
||||
t:eq(e2 and e2.code, Err.ARG, "cycle is an error")
|
||||
local _, e3 = enc({ 1, 2 })
|
||||
t:eq(e3 and e3.code, Err.ARG, "top level must be a table")
|
||||
local _, e4 = enc({ [1] = 1, x = 2 })
|
||||
t:eq(e4 and e4.code, Err.ARG, "non-string key")
|
||||
end
|
||||
|
||||
-- 4. errors
|
||||
local function code(s: string): (string?, number?)
|
||||
local _, e = dec(s)
|
||||
return e and e.code, e and e.offset
|
||||
end
|
||||
t:eq(code('a = "abc'), Err.TRUNCATED, "unterminated string")
|
||||
t:eq(code("a = 1\na = 2"), Err.CORRUPT, "duplicate key")
|
||||
t:eq(code("[a]\n[a]"), Err.CORRUPT, "duplicate table")
|
||||
t:eq(code("a = 01"), Err.CORRUPT, "leading zero")
|
||||
t:eq(code("a = 9223372036854775808"), Err.CORRUPT, "int64 overflow")
|
||||
t:eq(select(2, code("x = 1\na = tru")), 10, "error offset")
|
||||
t:eq(Toml.sniff(Bytes.reader(buffer.fromstring("# c\n[server]\nport = 80\n"))), 0.2, "sniff")
|
||||
t:eq(Toml.sniff(Bytes.reader(buffer.fromstring("{\"a\": 1}"))), 0, "sniff json")
|
||||
|
||||
-- 5. fuzz
|
||||
local samples = {}
|
||||
for _, c in Suite do
|
||||
if c.valid and #samples < 80 and #c.data < 400 then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
end
|
||||
for i = 1, 20 do
|
||||
table.insert(samples, Corpus[i].data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Toml.decode(Bytes.reader(b))
|
||||
end, samples)
|
||||
t:fuzz("encode(decode)", function(b: buffer)
|
||||
local v = Toml.decode(Bytes.reader(b))
|
||||
return v and Toml.encode(v)
|
||||
end, samples, { garbage = 20 })
|
||||
t:done()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,198 @@
|
||||
-- data/yaml tests: the yaml-test-suite (every case with an in.json must decode to it, every error case must be
|
||||
-- rejected, the valid cases without JSON must decode), a random corpus dumped by PyYAML in five styles (block, flow,
|
||||
-- indent 4 with explicit markers, sorted / narrow, multi-document) compared with Python's values, encoder round trips,
|
||||
-- options, errors and limits, the API, and the fuzz pass. Fixtures: tools/fixtures/yaml.py.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Yaml = require("@formats/data/yaml")
|
||||
local Json = require("@formats/codecs/Json")
|
||||
local Types = require("@formats/Types")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Canon = require("@tests/data/Canon")
|
||||
local Suite = require("@tests/gen/yaml_suite")
|
||||
local Corpus = require("@tests/gen/yaml_corpus")
|
||||
|
||||
local t = T.suite("data/yaml")
|
||||
|
||||
t:eq(Yaml.name, "yaml", "name")
|
||||
t:eq(Yaml.category, "data", "category")
|
||||
t:check(Yaml.caps.decode and Yaml.caps.encode, "caps")
|
||||
|
||||
local function dec(s: string, opts: any?): (any, any)
|
||||
return Yaml.decode(Bytes.reader(buffer.fromstring(s)), opts)
|
||||
end
|
||||
local function enc(v: any, opts: any?): string?
|
||||
local b = Yaml.encode(v, opts)
|
||||
return if b then buffer.tostring(b) else nil
|
||||
end
|
||||
|
||||
-- 1. yaml-test-suite
|
||||
local SKIP = { -- !!binary decodes to a buffer; the suite's JSON keeps the base64 text
|
||||
["565N"] = true,
|
||||
["name/construct-binary"] = true,
|
||||
}
|
||||
local pass, valid, rejected, errors, other, otherOk = 0, 0, 0, 0, 0, 0
|
||||
for _, c in Suite do
|
||||
local v, e = dec(c.yaml, { all = true, tags = "ignore" })
|
||||
t:check(e == nil or not string.find(e.message, "internal error", 1, true), c.name .. ": " .. tostring(e))
|
||||
if c.error then
|
||||
errors += 1
|
||||
t:check(v == nil, c.name .. ": an error case is rejected")
|
||||
rejected += if v == nil then 1 else 0
|
||||
elseif c.json and not SKIP[c.name] then
|
||||
valid += 1
|
||||
t:check(v ~= nil, c.name .. ": decodes (" .. tostring(e) .. ")")
|
||||
local want = {}
|
||||
for _, x in Json.lines(c.json) do
|
||||
table.insert(want, Canon.of(x))
|
||||
end
|
||||
local got = {}
|
||||
for _, d in v do
|
||||
local s = Json.encode(d, { nan = "null" })
|
||||
table.insert(got, if s then Canon.of(Json.decode(s)) else "?")
|
||||
end
|
||||
t:eq(table.concat(got, "|"), table.concat(want, "|"), c.name .. ": value")
|
||||
pass += 1
|
||||
elseif not c.json then
|
||||
other += 1
|
||||
otherOk += if v ~= nil or (e and e.code == Err.UNSUPPORTED) then 1 else 0
|
||||
end
|
||||
end
|
||||
t:note("yaml-test-suite: %d of %d JSON cases match, %d of %d error cases rejected, %d of %d other valid cases decode or say UNSUPPORTED", pass, valid, rejected, errors, otherOk, other)
|
||||
t:check(otherOk == other, "valid cases without JSON never fail as CORRUPT")
|
||||
|
||||
-- 2. PyYAML's output in five styles
|
||||
for i, c in Corpus do
|
||||
for style, text in c.texts do
|
||||
if style == "multi" then
|
||||
local v, e = dec(text, { all = true })
|
||||
t:check(v ~= nil, "corpus " .. i .. " " .. style .. ": " .. tostring(e))
|
||||
t:eq(Canon.of(v), c.multi, "corpus " .. i .. " " .. style)
|
||||
else
|
||||
local v, e = dec(text)
|
||||
t:check(v ~= nil or e == nil, "corpus " .. i .. " " .. style .. ": " .. tostring(e))
|
||||
t:eq(Canon.of(v), c.canon, "corpus " .. i .. " " .. style)
|
||||
end
|
||||
end
|
||||
-- our own output reads back the same (indent 2 and 4, explicit start)
|
||||
local v = dec(c.texts.block)
|
||||
for _, o in { {}, { indent = 4 }, { explicitStart = true } } do
|
||||
local s = enc(v, o)
|
||||
t:check(s ~= nil, "corpus " .. i .. ": encodes")
|
||||
t:eq(Canon.of(dec(s :: string)), c.canon, "corpus " .. i .. ": round trip " .. tostring(s))
|
||||
end
|
||||
local m = dec(c.texts.multi, { all = true })
|
||||
t:eq(Canon.of(dec(enc(m, { all = true }) :: string, { all = true })), c.multi, "corpus " .. i .. ": multi round trip")
|
||||
end
|
||||
|
||||
-- 3. details
|
||||
do
|
||||
local v = dec("b: 1\na: 2\nc: {}\nd: []\ne:\nf: ~\n")
|
||||
t:eq(table.concat(Types.keys(v), ","), "b,a,c,d,e,f", "key order")
|
||||
t:check(Types.isObject(v.c), "empty flow map is an object")
|
||||
t:eq(v.e, Types.null, "empty value is null")
|
||||
t:eq(enc(v), "b: 1\na: 2\nc: {}\nd: []\ne: null\nf: null\n", "encode keeps the order")
|
||||
local s = dec("a: &x [1, 2]\nb: *x\n")
|
||||
t:check(s.a == s.b, "aliases are shared references")
|
||||
t:eq(enc(s), "a: &id001\n - 1\n - 2\nb: *id001\n", "shared tables get anchors")
|
||||
local n = dec("[0o17, 0x1F, +12, -0.5e1, .5, .inf, -.Inf, .nan, 1_000, 0b11, yes, ~, Null, TRUE]")
|
||||
t:eq(n[1], 15, "0o")
|
||||
t:eq(n[2], 31, "0x")
|
||||
t:eq(n[3], 12, "+int")
|
||||
t:eq(n[4], -5, "float exp")
|
||||
t:eq(n[5], 0.5, ".5")
|
||||
t:eq(n[6], math.huge, ".inf")
|
||||
t:eq(n[7], -math.huge, "-.Inf")
|
||||
t:check(n[8] ~= n[8], ".nan")
|
||||
t:eq(n[9], "1_000", "1.1 ints are strings")
|
||||
t:eq(n[10], "0b11", "0b is a string")
|
||||
t:eq(n[11], "yes", "yes is a string")
|
||||
t:eq(n[12], Types.null, "~")
|
||||
t:eq(n[13], Types.null, "Null")
|
||||
t:eq(n[14], true, "TRUE")
|
||||
local tg = dec("a: !!str 12\nb: !!float 3\nc: !!binary aGVsbG8=\nd: !!timestamp 2001-12-14T21:59:43Z\ne: !!int '7'\n")
|
||||
t:eq(tg.a, "12", "!!str")
|
||||
t:eq(tg.b, 3, "!!float")
|
||||
t:eq(buffer.tostring(tg.c), "hello", "!!binary")
|
||||
t:check(Types.Date.is(tg.d), "!!timestamp")
|
||||
t:eq(tg.e, 7, "!!int on a quoted scalar")
|
||||
local _, te = dec("a: !custom x")
|
||||
t:eq(te and te.code, Err.UNSUPPORTED, "unknown tags are UNSUPPORTED")
|
||||
t:eq(dec("a: !custom x", { tags = "ignore" }).a, "x", "tags = ignore")
|
||||
t:eq(dec("--- 1\n--- 2\n"), 1, "the first document")
|
||||
t:eq(#dec("--- 1\n--- 2\n", { all = true }), 2, "all documents")
|
||||
t:eq(dec(""), Types.null, "empty stream")
|
||||
t:eq(dec("k: |\n a\n b\n\nz: >+\n f\n g\n\n").k, "a\nb\n", "literal")
|
||||
t:eq(dec("k: |\n a\n b\n\nz: >+\n f\n g\n\n").z, "f g\n\n", "folded keep")
|
||||
t:eq(dec("? a\n: b\n").a, "b", "explicit key")
|
||||
t:eq(dec("[a: 1, {b: 2}]")[1].a, 1, "single-pair flow mapping")
|
||||
-- strings that need quoting survive
|
||||
for _, str in { "", "true", "null", "12", "1.5", "- x", "a: b", "# c", "x #y", " lead", "tail ", "multi\nline", "two\n\n", "\ttab", "é", "\0\1", "'", '"', "yes", "on", "~", "[", "@", "&a", "*a", "!t", "%", "---", "...", "a\u{2028}b", ".inf", "0x10", "0o7", "-", "?", ":" } do
|
||||
local v2 = dec(enc({ k = str }) :: string)
|
||||
t:eq(v2 and v2.k, str, "string round trip " .. string.format("%q", str))
|
||||
end
|
||||
for _, x in { 0.1, -2.5e-8, 1e300, 2 ^ 53, -0.0, 123456789, math.huge, -math.huge } do
|
||||
t:eq(dec(enc({ x }) :: string)[1], x, "number round trip " .. tostring(x))
|
||||
end
|
||||
local cyc = {}
|
||||
cyc.self = cyc
|
||||
local _, ce = Yaml.encode(cyc)
|
||||
t:eq(ce and ce.code, Err.ARG, "cycles are an error")
|
||||
local _, fe = Yaml.encode({ f = print })
|
||||
t:eq(fe and fe.code, Err.ARG, "functions are an error")
|
||||
t:eq(enc(buffer.fromstring("hi")), "!!binary aGk=\n", "buffers as !!binary")
|
||||
end
|
||||
|
||||
-- 4. errors and limits
|
||||
local function code(s: string, opts: any?): string?
|
||||
local _, e = dec(s, opts)
|
||||
return e and e.code
|
||||
end
|
||||
t:eq(code("a: [1, 2"), Err.TRUNCATED, "unterminated flow")
|
||||
t:eq(code('a: "x'), Err.TRUNCATED, "unterminated quote")
|
||||
t:eq(code("a: b: c"), Err.CORRUPT, "mapping on its key's line")
|
||||
t:eq(code("a: *nope"), Err.CORRUPT, "undefined alias")
|
||||
t:eq(code("a:\n b: 1\n c: 2"), Err.CORRUPT, "bad indentation")
|
||||
t:eq(code("[[1]]: x"), Err.UNSUPPORTED, "collection keys")
|
||||
t:eq(code(string.rep("[", 600) .. string.rep("]", 600)), Err.LIMIT, "depth limit")
|
||||
do
|
||||
local bomb = { "a: &a [x, x, x, x, x, x, x, x, x, x]" }
|
||||
for i = 2, 8 do
|
||||
local prev = string.char(96 + i - 1)
|
||||
table.insert(bomb, string.format("%s: &%s [*%s, *%s, *%s, *%s, *%s, *%s, *%s, *%s, *%s, *%s]", string.char(96 + i), string.char(96 + i), prev, prev, prev, prev, prev, prev, prev, prev, prev, prev))
|
||||
end
|
||||
t:eq(code(table.concat(bomb, "\n")), Err.LIMIT, "alias bomb")
|
||||
t:check(dec(table.concat(bomb, "\n", 1, 3)) ~= nil, "small alias trees are fine")
|
||||
end
|
||||
do
|
||||
local _, e = dec("a: 1\nb: [1, }\n")
|
||||
t:eq(e and e.offset, 12, "error offset")
|
||||
end
|
||||
|
||||
-- 5. API
|
||||
do
|
||||
local v, err = F.load(buffer.fromstring("---\nname: x\nlist:\n - 1\n"))
|
||||
t:check(v ~= nil, "F.load sniffs yaml: " .. tostring(err))
|
||||
t:eq(v.list[1], 1, "F.load value")
|
||||
t:eq(F.saveString(v, { format = "yaml" }), "name: x\nlist:\n - 1\n", "F.saveString yaml")
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for i = 1, 30 do
|
||||
table.insert(samples, Corpus[i].texts.block)
|
||||
table.insert(samples, Corpus[i].texts.flow)
|
||||
end
|
||||
for i = 1, 400, 7 do
|
||||
if Suite[i] then
|
||||
table.insert(samples, Suite[i].yaml)
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Yaml.decode(Bytes.reader(b), { all = true })
|
||||
end, samples)
|
||||
t:fuzz("encode(decode)", function(b: buffer)
|
||||
local v = Yaml.decode(Bytes.reader(b))
|
||||
return v and Yaml.encode(v)
|
||||
end, samples, { garbage = 20 })
|
||||
t:done()
|
||||
Reference in new issue
Block a user