docs: updates README to reflect new test LPEG platform and Lua 5.3.4 release
[luajson.git] / tests / lunit-tests.lua
blobd2f183fa3064e63f087f07894e480b3edd0eb404
1 local json = require("json")
2 local lunit = require("lunit")
3 local testutil = require("testutil")
4 local lpeg = require("lpeg")
5 -- DECODE NOT 'local' due to requirement for testutil to access it
6 decode = json.decode.getDecoder(false)
8 local TEST_ENV
9 if not module then
10 _ENV = lunit.module("lunit-tests", 'seeall')
11 TEST_ENV = _ENV
12 else
13 module("lunit-tests", lunit.testcase, package.seeall)
14 TEST_ENV = _M
15 end
17 function setup()
18 _G["decode"] = json.decode.getDecoder(false)
19 end
21 function test_array_empty()
22 local ret = assert_table(decode("[]"))
23 assert_equal(0, #ret)
24 assert_nil(next(ret))
25 end
27 function test_array_trailComma_nostrict()
28 local ret = assert_table(decode("[true,]"))
29 assert_equal(true, ret[1])
30 assert_nil(next(ret, 1))
31 assert_equal(1, #ret)
32 end
34 function test_array_innerComma()
35 assert_error(function()
36 decode("[true,,true]")
37 end)
38 end
40 function test_preprocess()
41 assert_equal('"Hello"', json.encode(1, {preProcess = function() return "Hello" end}))
42 assert_equal('-1', json.encode(1, {preProcess = function(x) return -x end}))
43 assert_equal('-Infinity', json.encode(1/0, {preProcess = function(x) return -x end}))
44 end
46 function test_additionalEscapes_only()
47 -- Test that additionalEscapes is processed on its own - side-stepping normal processing
48 assert_equal("Hello\\?", json.decode([["\S"]], { strings = { additionalEscapes = lpeg.C(lpeg.P("S")) / "Hello\\?" } }))
49 -- Test that additionalEscapes overrides any builtin handling
50 assert_equal("Hello\\?", json.decode([["\n"]], { strings = { additionalEscapes = lpeg.C(lpeg.P("n")) / "Hello\\?" } }))
51 end
53 local strictDecoder = json.decode.getDecoder(true)
55 local function buildStrictDecoder(f)
56 return testutil.buildPatchedDecoder(f, strictDecoder)
57 end
58 local function buildFailedStrictDecoder(f)
59 return testutil.buildFailedPatchedDecoder(f, strictDecoder)
60 end
61 -- SETUP CHECKS FOR SEQUENCE OF DECODERS
62 for k, v in pairs(TEST_ENV) do
63 if k:match("^test_") and not k:match("_gen$") and not k:match("_only$") then
64 if k:match("_nostrict") then
65 TEST_ENV[k .. "_strict_gen"] = buildFailedStrictDecoder(v)
66 else
67 TEST_ENV[k .. "_strict_gen"] = buildStrictDecoder(v)
68 end
69 end
70 end