File: lunit-encoding.lua

package info (click to toggle)
lua-json 1.3.4-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster, sid, trixie
  • size: 652 kB
  • sloc: makefile: 67; php: 3
file content (91 lines) | stat: -rw-r--r-- 1,749 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
local json = require("json")
local lunit = require("lunit")

if not module then
    _ENV = lunit.module("lunit-encoding", 'seeall')
else
    module("lunit-encoding", lunit.testcase, package.seeall)
end

function test_cloned_array_sibling()
	local obj = {}
	assert_pass(function()
		json.encode({obj, obj})
	end)
end

function test_cloned_object_sibling()
	local obj = {}
	assert_pass(function()
		json.encode({x = obj, y = obj})
	end)
end

function test_cloned_array_deep_sibling()
	local obj = {}
	assert_pass(function()
		json.encode({
			{obj}, {obj}
		})
	end)
end

function test_cloned_array_multilevel_sibling()
	local obj = {}
	assert_pass(function()
		json.encode({
			{obj, {obj}}
		})
	end)
end

function test_recursive_object()
	local obj = {}
	obj.x = obj
	assert_error(function()
		json.encode(obj)
	end)
end

function test_recursive_array()
	local obj = {}
	obj[1] = obj
	assert_error(function()
		json.encode(obj)
	end)
end

function test_custom_encode()
	local obj = { x = "y" }
	local sawX
	local function preProcessor(value, isObjectKey)
		if value == "x" then
			sawX = true
			assert_true(isObjectKey)
		else
			assert_false(isObjectKey)
		end
		return value
	end
	local encoder = json.encode.getEncoder({
		preProcess = preProcessor
	})
	assert_nil(sawX)
	encoder(obj)
	assert_true(sawX)
end

function test_custom_array()
    assert_equal("[]", json.encode(setmetatable({}, {__is_luajson_array = true})))
    assert_equal("[]", json.encode(json.util.InitArray({})))
end

function test_undefined()
	assert_equal("[undefined]", json.encode({ json.util.undefined }))
end

function test_unknown()
	assert_error("Expected attempting to encode an unregistered function to fail", function()
		json.encode({ function() end })
	end)
end