tests: updates to Lua 5.2/5.3 requirements
[luajson.git] / tests / lunit-encoding.lua
blobfc8c33b6b1adb6e4fd08ff22994951c6a5a0c154
1 local json = require("json")
2 local lunit = require("lunit")
4 if not module then
5 _ENV = lunit.module("lunit-encoding", 'seeall')
6 else
7 module("lunit-encoding", lunit.testcase, package.seeall)
8 end
10 function test_cloned_array_sibling()
11 local obj = {}
12 assert_pass(function()
13 json.encode({obj, obj})
14 end)
15 end
17 function test_cloned_object_sibling()
18 local obj = {}
19 assert_pass(function()
20 json.encode({x = obj, y = obj})
21 end)
22 end
24 function test_cloned_array_deep_sibling()
25 local obj = {}
26 assert_pass(function()
27 json.encode({
28 {obj}, {obj}
30 end)
31 end
33 function test_cloned_array_multilevel_sibling()
34 local obj = {}
35 assert_pass(function()
36 json.encode({
37 {obj, {obj}}
39 end)
40 end
42 function test_recursive_object()
43 local obj = {}
44 obj.x = obj
45 assert_error(function()
46 json.encode(obj)
47 end)
48 end
50 function test_recursive_array()
51 local obj = {}
52 obj[1] = obj
53 assert_error(function()
54 json.encode(obj)
55 end)
56 end
58 function test_custom_encode()
59 local obj = { x = "y" }
60 local sawX
61 local function preProcessor(value, isObjectKey)
62 if value == "x" then
63 sawX = true
64 assert_true(isObjectKey)
65 else
66 assert_false(isObjectKey)
67 end
68 return value
69 end
70 local encoder = json.encode.getEncoder({
71 preProcess = preProcessor
73 assert_nil(sawX)
74 encoder(obj)
75 assert_true(sawX)
76 end
78 function test_custom_array()
79 assert_equal("[]", json.encode(setmetatable({}, {__is_luajson_array = true})))
80 assert_equal("[]", json.encode(json.util.InitArray({})))
81 end