-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathvalidate_request_test.go
More file actions
236 lines (211 loc) · 6.76 KB
/
validate_request_test.go
File metadata and controls
236 lines (211 loc) · 6.76 KB
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package requests
import (
"fmt"
"io"
"net/http"
"net/url"
"strings"
"testing"
"github.com/pb33f/libopenapi"
"github.com/pb33f/libopenapi/datamodel/high/base"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/pb33f/libopenapi-validator/config"
)
func TestValidateRequestSchema(t *testing.T) {
for name, tc := range map[string]struct {
request *http.Request
schemaYAML string
version float32
assertValidRequestSchema assert.BoolAssertionFunc
expectedErrorsCount int
}{
"FailOnBooleanExclusiveMinimum": {
request: postRequestWithBody(`{"exclusiveNumber": 10}`),
schemaYAML: `type: object
properties:
exclusiveNumber:
type: number
description: This number starts its journey where most numbers are too scared to begin!
exclusiveMinimum: true
minimum: !!float 10`,
version: 3.0,
assertValidRequestSchema: assert.False,
expectedErrorsCount: 1,
},
"PassWithCorrectExclusiveMinimum": {
request: postRequestWithBody(`{"exclusiveNumber": 15}`),
schemaYAML: `type: object
properties:
exclusiveNumber:
type: number
description: This number is properly constrained by a numeric exclusive minimum.
exclusiveMinimum: 12
minimum: 12`,
version: 3.1,
assertValidRequestSchema: assert.True,
expectedErrorsCount: 0,
},
"PassWithValidStringType": {
request: postRequestWithBody(`{"greeting": "Hello, world!"}`),
schemaYAML: `type: object
properties:
greeting:
type: string
description: A simple greeting
example: "Hello, world!"`,
version: 3.1,
assertValidRequestSchema: assert.True,
expectedErrorsCount: 0,
},
"PassWithNullablePropertyInOpenAPI30": {
request: postRequestWithBody(`{"name": "John", "middleName": null}`),
schemaYAML: `type: object
properties:
name:
type: string
description: User's first name
middleName:
type: string
nullable: true
description: User's middle name (optional)`,
version: 3.0,
assertValidRequestSchema: assert.True,
expectedErrorsCount: 0,
},
"PassWithNullablePropertyInOpenAPI31": {
request: postRequestWithBody(`{"name": "John", "middleName": null}`),
schemaYAML: `type: object
properties:
name:
type: string
description: User's first name
middleName:
type: string
nullable: true
description: User's middle name (optional)`,
version: 3.1,
assertValidRequestSchema: assert.False,
expectedErrorsCount: 1,
},
} {
t.Run(name, func(t *testing.T) {
t.Parallel()
schema := parseSchemaFromSpec(t, tc.schemaYAML, tc.version)
valid, errors := ValidateRequestSchema(&ValidateRequestSchemaInput{
Request: tc.request,
Schema: schema,
Version: tc.version,
})
tc.assertValidRequestSchema(t, valid)
assert.Len(t, errors, tc.expectedErrorsCount)
})
}
}
func TestInvalidMin(t *testing.T) {
openAPIVersion := float32(3.0)
schema := parseSchemaFromSpec(t, `type: object
properties:
exclusiveNumber:
type: number
description: This number starts its journey where most numbers are too scared to begin!
exclusiveMinimum: true
minimum: 10`, openAPIVersion)
valid, errors := ValidateRequestSchema(&ValidateRequestSchemaInput{
Request: postRequestWithBody(`{"exclusiveNumber": 13}`),
Schema: schema,
Version: openAPIVersion,
})
assert.False(t, valid)
assert.Len(t, errors, 1)
}
func TestValidateRequestSchema_CachePopulation(t *testing.T) {
openAPIVersion := float32(3.1)
schema := parseSchemaFromSpec(t, `type: object
properties:
name:
type: string`, openAPIVersion)
// Create options with a cache
opts := config.NewValidationOptions()
require.NotNil(t, opts.SchemaCache)
// First call should populate the cache
valid, errors := ValidateRequestSchema(&ValidateRequestSchemaInput{
Request: postRequestWithBody(`{"name": "test"}`),
Schema: schema,
Version: openAPIVersion,
Options: []config.Option{config.WithExistingOpts(opts)},
})
assert.True(t, valid)
assert.Len(t, errors, 0)
// Verify cache was populated
hash := schema.GoLow().Hash()
cached, ok := opts.SchemaCache.Load(hash)
assert.True(t, ok, "Schema should be in cache")
assert.NotNil(t, cached, "Cached entry should not be nil")
assert.NotNil(t, cached.CompiledSchema, "Compiled schema should be cached")
assert.NotNil(t, cached.RenderedInline, "Rendered schema should be cached")
assert.NotNil(t, cached.RenderedJSON, "JSON schema should be cached")
}
func TestValidateRequestSchema_NilSchema(t *testing.T) {
// Test when schema is nil
valid, errors := ValidateRequestSchema(&ValidateRequestSchemaInput{
Request: postRequestWithBody(`{"name": "test"}`),
Schema: nil,
Version: 3.1,
})
assert.False(t, valid)
require.Len(t, errors, 1)
assert.Equal(t, "schema is nil", errors[0].Message)
assert.Equal(t, "The schema to validate against is nil", errors[0].Reason)
}
func TestValidateRequestSchema_NilSchemaGoLow(t *testing.T) {
// Test when schema.GoLow() is nil by creating a schema without low-level data
schema := &base.Schema{} // Empty schema without GoLow() data
valid, errors := ValidateRequestSchema(&ValidateRequestSchemaInput{
Request: postRequestWithBody(`{"name": "test"}`),
Schema: schema,
Version: 3.1,
})
assert.False(t, valid)
require.Len(t, errors, 1)
assert.Equal(t, "schema cannot be rendered", errors[0].Message)
assert.Contains(t, errors[0].Reason, "does not have low-level information")
}
func postRequestWithBody(payload string) *http.Request {
return &http.Request{
Method: http.MethodPost,
URL: &url.URL{Path: "/test"},
Body: io.NopCloser(strings.NewReader(payload)),
}
}
// parseSchemaFromSpec creates a base.Schema from an OpenAPI spec YAML string.
// This ensures that we're using the native libopenapi logic for generating the schema.
func parseSchemaFromSpec(t *testing.T, schemaYAML string, version float32) *base.Schema {
// Convert version to API version string (3.0 -> "3.0.0", 3.1 -> "3.1.0")
apiVersion := fmt.Sprintf("%.1f.0", version)
spec := fmt.Sprintf(`openapi: %s
info:
title: Test
version: 1.0.0
components:
schemas:
TestSchema:
%s`, apiVersion, indentLines(schemaYAML, " "))
doc, err := libopenapi.NewDocument([]byte(spec))
require.NoError(t, err)
model, errs := doc.BuildV3Model()
require.Empty(t, errs)
schema := model.Model.Components.Schemas.GetOrZero("TestSchema")
require.NotNil(t, schema)
return schema.Schema()
}
// indentLines adds the specified indentation to each line of the input string
func indentLines(s string, indent string) string {
lines := strings.Split(strings.TrimSpace(s), "\n")
for i, line := range lines {
if line != "" {
lines[i] = indent + line
}
}
return strings.Join(lines, "\n")
}