From 5f9efa4829a72935ddcd40c7da6b1a9e10939b65 Mon Sep 17 00:00:00 2001 From: Thibault Charbonnier Date: Sat, 8 Jul 2017 21:54:18 -0700 Subject: feature: added new cjson.array_mt metatable to allow enforcing JSON array encoding. Signed-off-by: Yichun Zhang (agentzh) --- tests/agentzh.t | 79 ++++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 75 insertions(+), 4 deletions(-) (limited to 'tests') diff --git a/tests/agentzh.t b/tests/agentzh.t index 0b281a1..dd70fb8 100644 --- a/tests/agentzh.t +++ b/tests/agentzh.t @@ -116,7 +116,78 @@ print(cjson.encode(data)) -=== TEST 9: multiple calls to lua_cjson_new (1/2) +=== TEST 9: array_mt on empty tables +--- lua +local cjson = require "cjson" +local data = {} +setmetatable(data, cjson.array_mt) +print(cjson.encode(data)) +--- out +[] + + + +=== TEST 10: array_mt on non-empty tables +--- lua +local cjson = require "cjson" +local data = { "foo", "bar" } +setmetatable(data, cjson.array_mt) +print(cjson.encode(data)) +--- out +["foo","bar"] + + + +=== TEST 11: array_mt on non-empty tables with holes +--- lua +local cjson = require "cjson" +local data = {} +data[1] = "foo" +data[2] = "bar" +data[4] = "last" +data[9] = "none" +setmetatable(data, cjson.array_mt) +print(cjson.encode(data)) +--- out +["foo","bar",null,"last"] + + + +=== TEST 12: array_mt on tables with hash part +--- lua +local cjson = require "cjson" +local data + +if jit and string.find(jit.version, "LuaJIT 2.1.0", nil, true) then + local new_tab = require "table.new" + data = new_tab(0, 2) -- allocating hash part only + +else + data = {} +end + +data.foo = "bar" +data[1] = "hello" +setmetatable(data, cjson.array_mt) +print(cjson.encode(data)) +--- out +["hello"] + + + +=== TEST 13: multiple calls to lua_cjson_new (1/3) +--- lua +local cjson = require "cjson" +package.loaded["cjson"] = nil +require "cjson" +local arr = setmetatable({}, cjson.array_mt) +print(cjson.encode(arr)) +--- out +[] + + + +=== TEST 14: multiple calls to lua_cjson_new (2/3) --- lua local cjson = require "cjson" package.loaded["cjson"] = nil @@ -128,7 +199,7 @@ print(cjson.encode(arr)) -=== TEST 10: multiple calls to lua_cjson_new (2/2) +=== TEST 15: multiple calls to lua_cjson_new (3/3) --- lua local cjson = require "cjson.safe" -- load another cjson instance (not in package.loaded) @@ -140,7 +211,7 @@ print(cjson.encode(arr)) -=== TEST 11: & in JSON +=== TEST 16: & in JSON --- lua local cjson = require "cjson" local a="[\"a=1&b=2\"]" @@ -151,7 +222,7 @@ print(cjson.encode(b)) -=== TEST 12: default and max precision +=== TEST 17: default and max precision --- lua local math = require "math" local cjson = require "cjson" -- cgit v1.2.3-55-g6feb