@@ -217,3 +217,99 @@ func TestOpenAPIWithConfig_Request_Validation(t *testing.T) {
217217 })
218218 }
219219}
220+
221+ func TestOpenAPIFromBytes (t * testing.T ) {
222+ sampleOpenAPISpec := []byte (`
223+ openapi: 3.0.0
224+ info:
225+ title: Sample API
226+ version: "1.0"
227+ paths:
228+ /:
229+ get:
230+ responses:
231+ '200':
232+ description: OK
233+ /validation:
234+ post:
235+ requestBody:
236+ required: true
237+ content:
238+ application/json:
239+ schema:
240+ type: object
241+ properties:
242+ username:
243+ type: string
244+ minLength: 2
245+ responses:
246+ '200':
247+ description: OK
248+ ` )
249+
250+ testCases := []struct {
251+ name string
252+ method string
253+ path string
254+ body * bytes.Buffer
255+ statusCode int
256+ contentType string
257+ }{
258+ {
259+ name : "valid GET request to /" ,
260+ method : http .MethodGet ,
261+ path : "/" ,
262+ body : nil , // No body for GET requests
263+ statusCode : http .StatusOK ,
264+ },
265+ {
266+ name : "invalid POST request to /validation with empty body" ,
267+ method : http .MethodPost ,
268+ path : "/validation" ,
269+ body : bytes .NewBuffer ([]byte (`` )),
270+ statusCode : http .StatusBadRequest ,
271+ contentType : echo .MIMEApplicationJSON ,
272+ },
273+ {
274+ name : "valid POST request to /validation" ,
275+ method : http .MethodPost ,
276+ path : "/validation" ,
277+ body : bytes .NewBuffer ([]byte (`{"username": "test"}` )),
278+ statusCode : http .StatusOK ,
279+ contentType : echo .MIMEApplicationJSON ,
280+ },
281+ }
282+
283+ e := echo .New ()
284+
285+ e .Any ("/" , func (c echo.Context ) error {
286+ return c .JSON (http .StatusOK , "ok" )
287+ })
288+
289+ e .Any ("/validation" , func (c echo.Context ) error {
290+ return c .JSON (http .StatusOK , "ok" )
291+ })
292+
293+ e .Use (OpenAPIFromBytes (sampleOpenAPISpec ))
294+
295+ for _ , tc := range testCases {
296+ t .Run (tc .name , func (t * testing.T ) {
297+ var req * http.Request
298+
299+ if tc .body == nil {
300+ req = httptest .NewRequest (tc .method , tc .path , http .NoBody )
301+ } else {
302+ req = httptest .NewRequest (tc .method , tc .path , tc .body )
303+ }
304+
305+ if tc .contentType != "" {
306+ req .Header .Set ("Content-Type" , tc .contentType )
307+ }
308+
309+ resp := httptest .NewRecorder ()
310+ e .ServeHTTP (resp , req )
311+
312+ assert .Equal (t , tc .statusCode , resp .Code )
313+ })
314+ }
315+ }
0 commit comments