Debian Codegraph @

pkg/validation/validate/doc_test.go

raw
1 // Copyright 2015 go-swagger maintainers
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package validate_test
16
17 import (
18 "encoding/json"
19 "fmt"
20 "testing"
21
22 // Spec loading
23 "github.com/stretchr/testify/require"
24 "k8s.io/kube-openapi/pkg/validation/spec"
25 "k8s.io/kube-openapi/pkg/validation/strfmt" // OpenAPI format extensions
26 "k8s.io/kube-openapi/pkg/validation/validate" // This package
27 )
28
29 func ExampleAgainstSchema() {
30 // Example using encoding/json as unmarshaller
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 // JSON data to validate
58 inputJSON := `{"name": "Ivan","address-1": "sesame street"}`
59 _ = json.Unmarshal([]byte(inputJSON), &input)
60
61 // strfmt.Default is the registry of recognized formats
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 // Output:
69 // OK
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 }