github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/ginx/gintest/gintest.go (about)

     1  package gintest
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"io"
     7  	"io/ioutil"
     8  	"net/http"
     9  	"net/http/httptest"
    10  	"strings"
    11  )
    12  
    13  func Get(target string, router http.Handler, fns ...VarsFn) *Response {
    14  	return Request(http.MethodGet, target, router, fns...)
    15  }
    16  
    17  func Post(target string, router http.Handler, fns ...VarsFn) *Response {
    18  	return Request(http.MethodPost, target, router, fns...)
    19  }
    20  
    21  // from https://github.com/gin-gonic/gin/issues/1120
    22  func Request(method, target string, router http.Handler, fns ...VarsFn) *Response {
    23  	vars := &Vars{
    24  		Query: make(map[string]string),
    25  	}
    26  
    27  	for _, fn := range fns {
    28  		fn(vars)
    29  	}
    30  
    31  	r := httptest.NewRequest(method, target, vars.Body)
    32  
    33  	if len(vars.Query) > 0 {
    34  		q := r.URL.Query()
    35  		for k, v := range vars.Query {
    36  			q.Add(k, v)
    37  		}
    38  
    39  		r.URL.RawQuery = q.Encode()
    40  	}
    41  
    42  	if vars.ContentType != "" {
    43  		r.Header.Set("Content-Type", vars.ContentType)
    44  	}
    45  
    46  	w := httptest.NewRecorder()
    47  	router.ServeHTTP(w, r)
    48  
    49  	return &Response{
    50  		ResponseRecorder: w,
    51  	}
    52  }
    53  
    54  type Response struct {
    55  	*httptest.ResponseRecorder
    56  	body []byte
    57  }
    58  
    59  func (r *Response) Body() string {
    60  	if r.body == nil {
    61  		r.body, _ = ioutil.ReadAll(r.ResponseRecorder.Body)
    62  	}
    63  
    64  	return string(r.body)
    65  }
    66  
    67  func (r *Response) StatusCode() int {
    68  	return r.ResponseRecorder.Code
    69  }
    70  
    71  type Vars struct {
    72  	Body        io.Reader
    73  	ContentType string
    74  	Query       map[string]string
    75  }
    76  
    77  type VarsFn func(r *Vars)
    78  
    79  func Query(k, v string) VarsFn {
    80  	return func(r *Vars) {
    81  		r.Query[k] = v
    82  	}
    83  }
    84  
    85  func JSONVar(s interface{}) VarsFn {
    86  	switch v := s.(type) {
    87  	case string:
    88  		return func(r *Vars) {
    89  			r.Body = strings.NewReader(v)
    90  			r.ContentType = "application/json; charset=utf-8"
    91  		}
    92  	default:
    93  		return func(r *Vars) {
    94  			b, _ := json.Marshal(v)
    95  			r.Body = bytes.NewReader(b)
    96  			r.ContentType = "application/json; charset=utf-8"
    97  		}
    98  	}
    99  }