Files
rosetta/tests/codecs/godotvariant.luau
2026-11-01 19:25:15 -06:00

48 lines
2.8 KiB
Luau

-- codecs/text/GodotVariant tests: the Variant text syntax (strings and escapes, StringName / NodePath, arrays,
-- dictionaries with non-string keys, constructors, packed arrays incl. base64 bytes, typed arrays, Object), format
-- round trips, int / float keeping, section documents, limits, fuzz. Godot's own files: tests/model/godot.luau.
local T = require("@tests/T")
local GodotVariant = require("@rosetta/codecs/text/GodotVariant")
local t = T.suite("godotvariant")
local v = assert(GodotVariant.value("{\"a\": [1, 2.5, \"x\\ny\", &\"sn\", ^\"np\"], 3: Vector3(1, -2, 3e-05), \"b\": PackedByteArray(\"AAEC\")}"))
t:check(v.a[2] == 2.5 and v.a[3] == "x\ny" and v.a[4].type == "StringName" and v.a[5].type == "NodePath", "array values")
t:check(v[3].type == "Vector3" and v[3].args[3] == 3e-05, "number keys, constructors")
local b = GodotVariant.bytes(v.b)
t:check(b and buffer.len(b) == 3 and buffer.readu8(b, 2) == 2, "base64 PackedByteArray")
local again = assert(GodotVariant.value(GodotVariant.format(v)))
t:eq(GodotVariant.format(again), GodotVariant.format(v), "format round trip")
local typed = assert(GodotVariant.value("Array[int]([1, 2])"))
t:check(typed.type == "Array[int]" and #typed.args[1] == 2, "typed array")
t:eq(GodotVariant.format(typed), "Array[int]([1, 2])", "typed array format")
local _, e1 = GodotVariant.value("Vector3(1, 2")
t:check(e1 ~= nil, "unterminated constructor")
local deep = string.rep("[", 300) .. string.rep("]", 300)
local _, e2 = GodotVariant.value(deep)
t:check(e2 and string.find(e2, "limit", 1, true), "depth limit")
do
local doc = assert(GodotVariant.parse("[gd_scene format=3]\n\n; comment\n[node name=\"A\" type=\"Node3D\"]\nmetadata/x = 1.0\n\"quoted key\" = [1, 2.0]\n"))
t:eq(#doc.sections, 2, "sections")
local n = doc.sections[2]
t:check(n.attrs.name == "A" and n.props["metadata/x"] == 1 and n.props["quoted key"][2] == 2, "attributes and properties")
local text = GodotVariant.encode(doc)
t:check(string.find(text, "metadata/x = 1.0", 1, true) ~= nil and string.find(text, "[1, 2.0]", 1, true) ~= nil, "floats keep their .0")
local o = assert(GodotVariant.value("Object(Resource,\"a\":1,\"b\":\"x\")"))
t:check(o.type == "Object" and o.class == "Resource" and o.args[1].b == "x", "Object")
t:eq(GodotVariant.number(0.1), "0.1", "shortest float")
t:eq(GodotVariant.format("a\"b\\c"), "\"a\\\"b\\\\c\"", "string escapes")
local u = assert(GodotVariant.value("\"\\u00e9\\ud83d\\ude00\""))
t:eq(u, "\u{e9}\u{1f600}", "unicode escapes and surrogate pairs")
end
local samples = {
"[gd_scene format=3]\n[node name=\"A\" type=\"Node3D\"]\ntransform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)\n",
"[gd_resource type=\"X\" format=3]\n[resource]\nd = {\n\"k\": [1, &\"s\", NodePath(\"a\"), PackedFloat32Array(1, 2)]\n}\n",
}
t:fuzz("parse", function(b: buffer)
return GodotVariant.parse(buffer.tostring(b))
end, samples)
t:done()