-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathjson_test.go
99 lines (81 loc) · 2.11 KB
/
json_test.go
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
92
93
94
95
96
97
98
99
package json
import (
"encoding/json"
"testing"
"github.com/yuin/gopher-lua"
)
func TestSimple(t *testing.T) {
const str = `
local json = require("json")
assert(type(json) == "table")
assert(type(json.decode) == "function")
assert(type(json.encode) == "function")
assert(json.encode(true) == "true")
assert(json.encode(1) == "1")
assert(json.encode(-10) == "-10")
assert(json.encode(nil) == "null")
assert(json.encode({}) == "[]")
assert(json.encode({1, 2, 3}) == "[1,2,3]")
local _, err = json.encode({1, 2, [10] = 3})
assert(string.find(err, "sparse array"))
local _, err = json.encode({1, 2, 3, name = "Tim"})
assert(string.find(err, "mixed or invalid key types"))
local _, err = json.encode({name = "Tim", [false] = 123})
assert(string.find(err, "mixed or invalid key types"))
local obj = {"a",1,"b",2,"c",3}
local jsonStr = json.encode(obj)
local jsonObj = json.decode(jsonStr)
for i = 1, #obj do
assert(obj[i] == jsonObj[i])
end
local obj = {name="Tim",number=12345}
local jsonStr = json.encode(obj)
local jsonObj = json.decode(jsonStr)
assert(obj.name == jsonObj.name)
assert(obj.number == jsonObj.number)
assert(json.decode("null") == nil)
assert(json.decode(json.encode({person={name = "tim",}})).person.name == "tim")
local obj = {
abc = 123,
def = nil,
}
local obj2 = {
obj = obj,
}
obj.obj2 = obj2
assert(json.encode(obj) == nil)
local a = {}
for i=1, 5 do
a[i] = i
end
assert(json.encode(a) == "[1,2,3,4,5]")
`
s := lua.NewState()
defer s.Close()
Preload(s)
if err := s.DoString(str); err != nil {
t.Error(err)
}
}
func TestCustomRequire(t *testing.T) {
const str = `
local j = require("JSON")
assert(type(j) == "table")
assert(type(j.decode) == "function")
assert(type(j.encode) == "function")
`
s := lua.NewState()
defer s.Close()
s.PreloadModule("JSON", Loader)
if err := s.DoString(str); err != nil {
t.Error(err)
}
}
func TestDecodeValue_jsonNumber(t *testing.T) {
s := lua.NewState()
defer s.Close()
v := DecodeValue(s, json.Number("124.11"))
if v.Type() != lua.LTString || v.String() != "124.11" {
t.Fatalf("expecting LString, got %T", v)
}
}