From 3882fac81a08c24c948faafe980dd181a906fa00 Mon Sep 17 00:00:00 2001 From: leaf corcoran Date: Sat, 21 Sep 2019 19:09:00 -0700 Subject: add one_of testing to avoid hash table ordering causing test to fail --- lua/cjson/util.lua | 29 +++++++++++++++++++++++++++-- tests/test.lua | 7 ++++++- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/lua/cjson/util.lua b/lua/cjson/util.lua index 2405257..7cf66be 100644 --- a/lua/cjson/util.lua +++ b/lua/cjson/util.lua @@ -12,6 +12,17 @@ local maxn = table.maxn or function(t) return max end +local _one_of_mt = {} + +local function one_of(t) + setmetatable(t, _one_of_mt) + return t +end + +local function is_one_of(t) + return type(t) == "table" and getmetatable(t) == _one_of_mt +end + -- Various common routines used by the Lua CJSON package -- -- Mark Pulford @@ -59,7 +70,11 @@ local function serialise_table(value, indent, depth) local max = is_array(value) local comma = false - local fragment = { "{" .. spacing2 } + local prefix = "{" + if is_one_of(value) then + prefix = "ONE_OF{" + end + local fragment = { prefix .. spacing2 } if max > 0 then -- Serialise array for i = 1, max do @@ -146,6 +161,15 @@ local function file_save(filename, data) end local function compare_values(val1, val2) + if is_one_of(val2) then + for _, option in ipairs(val2) do + if compare_values(val1, option) then + return true + end + end + return false + end + local type1 = type(val1) local type2 = type(val2) if type1 ~= type2 then @@ -281,7 +305,8 @@ return { run_test_summary = run_test_summary, run_test = run_test, run_test_group = run_test_group, - run_script = run_script + run_script = run_script, + one_of = one_of } -- vi:ai et sw=4 ts=4: diff --git a/tests/test.lua b/tests/test.lua index d1bf7e4..b2162b9 100755 --- a/tests/test.lua +++ b/tests/test.lua @@ -293,7 +293,12 @@ local cjson_tests = { true, { '["one",null,null,"sparse test"]' } }, { "Encode sparse array as object", json.encode, { { [1] = "one", [5] = "sparse test" } }, - true, { '{"5":"sparse test","1":"one"}' } }, + true, { + util.one_of{ + '{"5":"sparse test","1":"one"}', + '{"1":"one","5":"sparse test"}' + } + } }, { "Encode table with numeric string key as object", json.encode, { { ["2"] = "numeric string key test" } }, true, { '{"2":"numeric string key test"}' } }, -- cgit v1.2.3-55-g6feb