forked from lyraproj/dgoyaml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parameter_test.go
112 lines (100 loc) · 2.36 KB
/
parameter_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
100
101
102
103
104
105
106
107
108
109
110
111
112
package examples
import (
"testing"
"github.com/tada/dgo/dgo"
"github.com/tada/dgo/tf"
"github.com/tada/dgoyaml/yaml"
)
// Sample parameter map
const sampleParameters = `
host:
type: string[1]
name: sample/service_host
required: true
port:
type: 1..999
name: sample/service_port
`
func TestValidateParameterValues(t *testing.T) {
const sampleValues = `
host: example.com
port: 22
`
params, err := yaml.Unmarshal([]byte(sampleValues))
if err != nil {
t.Fatal(err)
}
expectNoErrors(t, validate(t, params))
}
func TestValidateParameterValues_failRequired(t *testing.T) {
const sampleValues = `
port: 22
`
params, err := yaml.Unmarshal([]byte(sampleValues))
if err != nil {
t.Fatal(err)
}
expectError(t, `missing required parameter 'host'`, validate(t, params))
}
func TestValidateParameterValues_failNotRecognized(t *testing.T) {
const sampleValues = `
host: example.com
port: 22
login: foo:bar
`
params, err := yaml.Unmarshal([]byte(sampleValues))
if err != nil {
t.Fatal(err)
}
expectError(t, `unknown parameter 'login'`, validate(t, params))
}
func TestValidateParameterValues_failInvalidHostType(t *testing.T) {
const sampleValues = `
host: 85493
port: 22
`
params, err := yaml.Unmarshal([]byte(sampleValues))
if err != nil {
t.Fatal(err)
}
expectError(t, `parameter 'host' is not an instance of type string[1]`, validate(t, params))
}
func TestValidateParameterValues_failInvalidPortType(t *testing.T) {
const sampleValues = `
host: example.com
port: 1022
`
params, err := yaml.Unmarshal([]byte(sampleValues))
if err != nil {
t.Fatal(err)
}
expectError(t, `parameter 'port' is not an instance of type 1..999`, validate(t, params))
}
func validate(t *testing.T, params dgo.Value) []error {
t.Helper()
pt, err := loadDesc([]byte(sampleParameters))
if err != nil {
t.Fatal(err)
}
return pt.(dgo.MapValidation).Validate(nil, params)
}
func loadDesc(yamlData []byte) (dgo.StructMapType, error) {
data, err := yaml.Unmarshal(yamlData)
if err != nil {
return nil, err
}
return tf.StructMapFromMap(false, data.(dgo.Map)), nil
}
func expectError(t *testing.T, error string, errors []error) {
t.Helper()
if len(errors) != 1 || error != errors[0].Error() {
t.Errorf(`expected "%s" error`, error)
expectNoErrors(t, errors)
}
}
func expectNoErrors(t *testing.T, errors []error) {
t.Helper()
for _, err := range errors {
t.Error(err)
}
}