github.com/zooyer/miskit@v1.0.71/micro/controller_test.go (about) 1 package micro 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "errors" 7 "github.com/stretchr/testify/assert" 8 "github.com/zooyer/jsons" 9 "io/ioutil" 10 "net/http" 11 "net/http/httptest" 12 "testing" 13 14 "github.com/gin-gonic/gin" 15 ) 16 17 func get(engine *gin.Engine, uri string, header ...http.Header) *httptest.ResponseRecorder { 18 req := httptest.NewRequest("GET", uri, nil) 19 for _, header := range header { 20 for key, header := range header { 21 req.Header[key] = header 22 } 23 } 24 res := httptest.NewRecorder() 25 engine.ServeHTTP(res, req) 26 return res 27 } 28 29 func postJson(engine *gin.Engine, uri string, data interface{}) *httptest.ResponseRecorder { 30 body, _ := json.Marshal(data) 31 req := httptest.NewRequest("POST", uri, bytes.NewReader(body)) 32 req.Header.Set("Content-Type", "application/json") 33 res := httptest.NewRecorder() 34 engine.ServeHTTP(res, req) 35 return res 36 } 37 38 type Student struct { 39 Name string `json:"name" binding:"required"` 40 Age int `json:"age"` 41 Phone string `json:"phone"` 42 } 43 44 func (s *Student) Valid(ctx *gin.Context) (err error) { 45 if s.Age == 0 { 46 s.Age = 25 47 } 48 49 if s.Phone == "" { 50 return errors.New("invalid phone") 51 } 52 53 return 54 } 55 56 type studentController struct { 57 Controller 58 } 59 60 func (s studentController) Valid(ctx *gin.Context) { 61 var ( 62 err error 63 req Student 64 ) 65 66 defer func() { s.Response(ctx, req, err) }() 67 68 if err = s.Bind(ctx, &req); err != nil { 69 return 70 } 71 } 72 73 func TestController_Bind(t *testing.T) { 74 engine := gin.Default() 75 76 stu := new(studentController) 77 78 engine.POST("/valid", stu.Valid) 79 80 var tests = []struct { 81 Input Student 82 Equal bool 83 Code int 84 }{ 85 { 86 Input: Student{ 87 Name: "张三", 88 Age: 0, 89 Phone: "", 90 }, 91 Equal: false, 92 Code: http.StatusInternalServerError, 93 }, 94 { 95 Input: Student{ 96 Name: "李四", 97 Age: 16, 98 Phone: "", 99 }, 100 Equal: false, 101 Code: http.StatusInternalServerError, 102 }, 103 { 104 Input: Student{ 105 Name: "王五", 106 Age: 0, 107 Phone: "999", 108 }, 109 Equal: true, 110 Code: http.StatusOK, 111 }, 112 { 113 Input: Student{ 114 Name: "赵六", 115 Age: 15, 116 Phone: "111", 117 }, 118 Equal: true, 119 Code: http.StatusOK, 120 }, 121 } 122 123 var resp *httptest.ResponseRecorder 124 var data []byte 125 126 for _, test := range tests { 127 resp = postJson(engine, "/valid", test.Input) 128 data, _ = ioutil.ReadAll(resp.Body) 129 assert.Equal(t, test.Code, resp.Code) 130 if test.Equal { 131 assert.Equal(t, "0", jsons.Raw(data).Number("errno").JSONString()) 132 } else { 133 assert.NotEqual(t, "0", jsons.Raw(data).Number("errno").JSONString()) 134 } 135 t.Log(string(data)) 136 } 137 }