...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package validate_test
16
17 import (
18 "encoding/json"
19 "fmt"
20 "testing"
21
22
23 "github.com/stretchr/testify/require"
24 "k8s.io/kube-openapi/pkg/validation/spec"
25 "k8s.io/kube-openapi/pkg/validation/strfmt"
26 "k8s.io/kube-openapi/pkg/validation/validate"
27 )
28
29 func ExampleAgainstSchema() {
30
31 var schemaJSON = `
32 {
33 "properties": {
34 "name": {
35 "type": "string",
36 "pattern": "^[A-Za-z]+$",
37 "minLength": 1
38 }
39 },
40 "patternProperties": {
41 "address-[0-9]+": {
42 "type": "string",
43 "pattern": "^[\\s|a-z]+$"
44 }
45 },
46 "required": [
47 "name"
48 ],
49 "additionalProperties": false
50 }`
51
52 schema := new(spec.Schema)
53 _ = json.Unmarshal([]byte(schemaJSON), schema)
54
55 input := map[string]interface{}{}
56
57
58 inputJSON := `{"name": "Ivan","address-1": "sesame street"}`
59 _ = json.Unmarshal([]byte(inputJSON), &input)
60
61
62 err := validate.AgainstSchema(schema, input, strfmt.Default)
63 if err != nil {
64 fmt.Printf("JSON does not validate against schema: %v", err)
65 } else {
66 fmt.Printf("OK")
67 }
68
69
70 }
71
72 func TestValidate_Issue112(t *testing.T) {
73 t.Run("returns no error on body includes `items` key", func(t *testing.T) {
74 body := map[string]interface{}{"items1": nil}
75 err := validate.AgainstSchema(getSimpleSchema(), body, strfmt.Default)
76 require.NoError(t, err)
77 })
78
79 t.Run("returns no error when body includes `items` key", func(t *testing.T) {
80 body := map[string]interface{}{"items": nil}
81 err := validate.AgainstSchema(getSimpleSchema(), body, strfmt.Default)
82 require.NoError(t, err)
83 })
84 }
85
86 func getSimpleSchema() *spec.Schema {
87 return &spec.Schema{
88 SchemaProps: spec.SchemaProps{
89 Type: spec.StringOrArray{"object"},
90 },
91 }
92 }
93
View as plain text