-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathobject_test.go
91 lines (75 loc) · 2.02 KB
/
object_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
package vjson
import (
"encoding/json"
"github.com/stretchr/testify/assert"
"testing"
)
func TestObjectField_GetName(t *testing.T) {
field := Object("foo", Schema{})
assert.Equal(t, "foo", field.GetName())
}
func TestObjectField_Validate(t *testing.T) {
objSchema := Schema{
Fields: []Field{
Integer("age").Min(0).Max(90).Required(),
},
}
t.Run("invalid_input", func(t *testing.T) {
field := Object("foo", objSchema)
err := field.Validate(1)
assert.NotNil(t, err)
})
t.Run("not_required_field", func(t *testing.T) {
t.Run("nil_value", func(t *testing.T) {
field := Object("foo", objSchema)
err := field.Validate(nil)
assert.Nil(t, err)
})
t.Run("valid_value", func(t *testing.T) {
field := Object("foo", objSchema)
err := field.Validate(`{"age":10}`)
assert.Nil(t, err)
})
})
t.Run("required_field", func(t *testing.T) {
t.Run("nil_value", func(t *testing.T) {
field := Object("foo", objSchema).Required()
err := field.Validate(nil)
assert.NotNil(t, err)
})
t.Run("valid_value", func(t *testing.T) {
field := Object("foo", objSchema)
err := field.Validate(`{"age":10}`)
assert.Nil(t, err)
})
t.Run("valid_struct_value", func(t *testing.T) {
field := Object("foo", objSchema)
obj := struct {
Age int `json:"age"`
}{10}
err := field.Validate(obj)
assert.Nil(t, err)
})
})
}
func TestObjectField_MarshalJSON(t *testing.T) {
field := Object("foo", NewSchema(String("bar")))
b, err := json.Marshal(field)
assert.Nil(t, err)
data := map[string]interface{}{}
err = json.Unmarshal(b, &data)
assert.Nil(t, err)
assert.Equal(t, "foo", data["name"])
assert.Equal(t, string(objectType), data["type"])
assert.Equal(t, "bar", data["schema"].(map[string]interface{})["fields"].([]interface{})[0].(map[string]interface{})["name"])
}
func TestNewObject(t *testing.T) {
s := Schema{}
field := NewObject(ObjectFieldSpec{
Name: "bar",
Required: true,
}, s)
assert.NotNil(t, field)
assert.Equal(t, "bar", field.name)
assert.Equal(t, s, field.schema)
}