Merge branch '1.2.x'
[luajson.git] / tests / lunit-encoding.lua
blob2f9b06a503865fc00d9393d1dcc52aede75d9945
1 local json = require("json")
2 local lunit = require("lunit")
4 module("lunit-encoding", lunit.testcase, package.seeall)
6 function test_cloned_array_sibling()
7 local obj = {}
8 assert_pass(function()
9 json.encode({obj, obj})
10 end)
11 end
13 function test_cloned_object_sibling()
14 local obj = {}
15 assert_pass(function()
16 json.encode({x = obj, y = obj})
17 end)
18 end
20 function test_cloned_array_deep_sibling()
21 local obj = {}
22 assert_pass(function()
23 json.encode({
24 {obj}, {obj}
26 end)
27 end
29 function test_cloned_array_multilevel_sibling()
30 local obj = {}
31 assert_pass(function()
32 json.encode({
33 {obj, {obj}}
35 end)
36 end
38 function test_recursive_object()
39 local obj = {}
40 obj.x = obj
41 assert_error(function()
42 json.encode(obj)
43 end)
44 end
46 function test_recursive_array()
47 local obj = {}
48 obj[1] = obj
49 assert_error(function()
50 json.encode(obj)
51 end)
52 end
54 function test_custom_encode()
55 local obj = { x = "y" }
56 local sawX
57 local function preProcessor(value, isObjectKey)
58 if value == "x" then
59 sawX = true
60 assert_true(isObjectKey)
61 else
62 assert_false(isObjectKey)
63 end
64 return value
65 end
66 local encoder = json.encode.getEncoder({
67 preProcess = preProcessor
69 assert_nil(sawX)
70 encoder(obj)
71 assert_true(sawX)
72 end
74 function test_custom_array()
75 assert_equal("[]", json.encode(setmetatable({}, {__is_luajson_array = true})))
76 assert_equal("[]", json.encode(json.util.InitArray({})))
77 end