tests: updates more strongly to Lua 5.2/5.3 requirements by dropping _M usage
[luajson.git] / tests / lunit-tests.lua
blobd7adfe459a018db5f3cc9646ada7e322940785b5
1 local json = require("json")
2 local lunit = require("lunit")
3 local testutil = require("testutil")
4 -- DECODE NOT 'local' due to requirement for testutil to access it
5 decode = json.decode.getDecoder(false)
7 local TEST_ENV
8 if not module then
9 _ENV = lunit.module("lunit-tests", 'seeall')
10 TEST_ENV = _ENV
11 else
12 module("lunit-tests", lunit.testcase, package.seeall)
13 TEST_ENV = _M
14 end
16 function setup()
17 _G["decode"] = json.decode.getDecoder(false)
18 end
20 function test_array_empty()
21 local ret = assert_table(decode("[]"))
22 assert_equal(0, #ret)
23 assert_nil(next(ret))
24 end
26 function test_array_trailComma_nostrict()
27 local ret = assert_table(decode("[true,]"))
28 assert_equal(true, ret[1])
29 assert_nil(next(ret, 1))
30 assert_equal(1, #ret)
31 end
33 function test_array_innerComma()
34 assert_error(function()
35 decode("[true,,true]")
36 end)
37 end
39 function test_preprocess()
40 assert_equal('"Hello"', json.encode(1, {preProcess = function() return "Hello" end}))
41 assert_equal('-1', json.encode(1, {preProcess = function(x) return -x end}))
42 assert_equal('-Infinity', json.encode(1/0, {preProcess = function(x) return -x end}))
43 end
45 local strictDecoder = json.decode.getDecoder(true)
47 local function buildStrictDecoder(f)
48 return testutil.buildPatchedDecoder(f, strictDecoder)
49 end
50 local function buildFailedStrictDecoder(f)
51 return testutil.buildFailedPatchedDecoder(f, strictDecoder)
52 end
53 -- SETUP CHECKS FOR SEQUENCE OF DECODERS
54 for k, v in pairs(TEST_ENV) do
55 if k:match("^test_") and not k:match("_gen$") then
56 if k:match("_nostrict") then
57 TEST_ENV[k .. "_strict_gen"] = buildFailedStrictDecoder(v)
58 else
59 TEST_ENV[k .. "_strict_gen"] = buildStrictDecoder(v)
60 end
61 end
62 end