1 -- Additional path that may be required
8 local function getFileData(fileName
)
9 local f
= io
.open(fileName
, 'rb')
10 if not f
then return end
11 local data
= f
:read('*a')
16 local function putTempData(data
)
17 local name
= os
.tmpname()
18 local f
= assert(io
.open(name
, 'wb'))
24 -- Ensure that the encoder/decoder can round-trip valid JSON
25 local function RoundTripTest(parseFunc
, jsonData
, luaData
, fullRoundTrip
)
26 local dataString
= json
.encode(luaData
)
27 assert(dataString
, "Couldn't encode the lua data")
28 local success
, result
= pcall(parseFunc
, dataString
)
30 print("Could not parse the generated JSON of (", luaData
)
31 print("GENERATED: [[" .. dataString
.. "]]")
32 print("DATA STORED IN: ", putTempData(dataString
))
36 -- Ensure that whitespace is trimmed off ends
37 dataString
= dataString
:match("^[%s]*(.-)[%s]*$")
38 jsonData
= jsonData
:match("^[%s]*(.-)[%s]*$")
39 if dataString
~= jsonData
then
40 print("Encoded values do not match")
41 print("ORIGINAL: << " .. jsonData
.. " >>")
42 print("RE-ENCOD: << " .. dataString
.. " >>")
49 local function testFile(fileName
, parseFunc
, expectSuccess
, fullRoundTrip
)
50 local data
= getFileData(fileName
)
51 if not data
then return end
53 local succeed
, result
= pcall(parseFunc
, data
)
54 if expectSuccess
~= succeed
then
55 print("Wrongly " .. (expectSuccess
and "Failed" or "Succeeded") .. " on : " .. fileName
.. "(" .. tostring(result
) .. ")")
58 if not RoundTripTest(parseFunc
, data
, result
, fullRoundTrip
) then
59 print("FAILED TO ROUND TRIP: " .. fileName
)
65 local function testDirectories(parseFunc
, directories
, ...)
66 if not directories
then return end
67 for _
,directory
in ipairs(directories
) do
68 if lfs
.attributes(directory
, 'mode') == 'directory' then
69 for f
in lfs
.dir(directory
) do
70 testFile(directory
.. "/" .. f
, parseFunc
, ...)
77 local function TestParser(parseFunc
, successNames
, failNames
, roundTripNames
)
78 testDirectories(parseFunc
, successNames
, true, false)
79 testDirectories(parseFunc
, failNames
, false, false)
80 testDirectories(parseFunc
, roundTripNames
, true, true)
82 print("Testing lax/fast mode:")
83 TestParser(function(data
) return json
.decode(data
) end, {"test/pass","test/fail_strict"}, {"test/fail_all"},{"test/roundtrip","test/roundtrip_lax"})
85 print("Testing (mostly) strict mode:")
86 local strict
= json
.decode
.util
.merge({}, json
.decode
.strict
, {
93 TestParser(function(data
) return json
.decode(data
, strict
) end, {"test/pass"}, {"test/fail_strict","test/fail_all"}, {"test/roundtrip"})