github.com/gramework/gramework@v1.8.1-0.20231027140105-82555c9057f5/app_serve_test.go (about) 1 // Copyright 2017-present Kirill Danshin and Gramework contributors 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 10 package gramework 11 12 import ( 13 "net" 14 "testing" 15 16 "github.com/valyala/fasthttp" 17 "github.com/valyala/fasthttp/fasthttputil" 18 ) 19 20 func testBuildReqRes(method, uri string) (*fasthttp.Request, *fasthttp.Response) { 21 req, res := fasthttp.AcquireRequest(), fasthttp.AcquireResponse() 22 req.Header.SetMethod(method) 23 req.SetRequestURI(uri) 24 return req, res 25 } 26 27 func TestAppServe(t *testing.T) { 28 const uri = "http://test.request" 29 30 testCases := []func(*App) (func(string, interface{}) *App, string){ 31 // check GET request 32 func(app *App) (func(string, interface{}) *App, string) { 33 return app.GET, GET 34 }, 35 // check POST request 36 func(app *App) (func(string, interface{}) *App, string) { 37 return app.POST, POST 38 }, 39 // check PUT request 40 func(app *App) (func(string, interface{}) *App, string) { 41 return app.PUT, PUT 42 }, 43 // check PATCH request 44 func(app *App) (func(string, interface{}) *App, string) { 45 return app.PATCH, PATCH 46 }, 47 // check DELETE request 48 func(app *App) (func(string, interface{}) *App, string) { 49 return app.DELETE, DELETE 50 }, 51 // check HEAD request 52 func(app *App) (func(string, interface{}) *App, string) { 53 return app.HEAD, HEAD 54 }, 55 // check OPTIONS request 56 func(app *App) (func(string, interface{}) *App, string) { 57 return app.OPTIONS, OPTIONS 58 }, 59 } 60 61 for _, test := range testCases { 62 var handleOK bool 63 64 app := New() 65 ln := fasthttputil.NewInmemoryListener() 66 c := &fasthttp.Client{ 67 Dial: func(addr string) (net.Conn, error) { 68 return ln.Dial() 69 }, 70 } 71 72 reg, method := test(app) 73 74 go func() { 75 _ = app.Serve(ln) 76 }() 77 78 reg("/", func() { 79 handleOK = true 80 }) 81 err := c.Do(testBuildReqRes(method, uri)) 82 if err != nil { 83 t.Fatal(err) 84 } 85 86 ln.Close() 87 88 if !handleOK { 89 t.Errorf("%s request was not served correctly", method) 90 } 91 } 92 }