-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathschema.go
90 lines (84 loc) · 2.13 KB
/
schema.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
// Package schema makes it easier to check if map/array structures match a certain schema. Great for testing JSON API's.
//
// Example:
//
// func TestJSON(t *testing.T) {
// reader := getJSONResponse()
//
// err := schema.MatchJSON(
// schema.Map{
// "id": schema.IsInteger,
// "name": "Max Mustermann",
// "age": 42,
// "height": schema.IsFloat,
// "footsize": schema.IsPresent,
// "address": schema.Map{
// "street": schema.IsString,
// "zip": schema.IsString,
// },
// "tags": schema.ArrayIncluding("red"),
// },
// reader,
// )
//
// if err != nil {
// t.Fatal(err)
// }
// }
//
// JSON Input
//
// {
// "id": 12,
// "name": "Hans Meier",
// "age": 42,
// "height": 1.91,
// "address": {
// "street": 12
// },
// "tags": ["blue", "green"]
// }
//
// err.Error() Output
//
// "address": Missing keys: "zip"
// "address.street": is no string but float64
// "name": "Hans Meier" != "Max Mustermann"
// "tags": red:string(0) not included
// Missing keys: "footsize"
//
// See https://github.com/jgroeneveld/schema for more examples.
//
// Also see https://github.com/jgroeneveld/trial for lightweight assertions.
package schema
import (
"encoding/json"
"fmt"
"io"
)
// Matcher is the interface for all matchers
type Matcher interface {
Match(data interface{}) *Error
}
// MatcherFunc turns a func into a Matcher
func MatcherFunc(name string, fun func(data interface{}) *Error) *MatcherFuncImpl {
return &MatcherFuncImpl{
Name: name,
Fun: fun,
}
}
// Match wraps matcher.Match for nil error handling.
func Match(m Matcher, data interface{}) error {
if err := m.Match(data); err != nil {
return err
}
return nil
}
// MatchJSON wraps Match with a reader for JSON raw data.
func MatchJSON(m Matcher, r io.Reader) error {
var data interface{}
if err := json.NewDecoder(r).Decode(&data); err != nil {
return fmt.Errorf("cant parse JSON: %s", err.Error())
}
return Match(m, data)
}