-
Notifications
You must be signed in to change notification settings - Fork 2
/
validate_test.go
64 lines (48 loc) · 1.5 KB
/
validate_test.go
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
package cosy
import (
"encoding/json"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/uozi-tech/cosy/logger"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
type Deep struct {
DiveStrings []string `json:"dive_strings" binding:"required,dive,hostname_port"`
}
type Json struct {
Name string `json:"name" binding:"required,url"`
DiveStrings []string `json:"dive_strings" binding:"required,dive,hostname_port"`
Deep Deep `json:"deep"`
}
func TestBindAndValid(t *testing.T) {
logger.Init("debug")
r := gin.New()
r.POST("/test", func(c *gin.Context) {
var data Json
if !BindAndValid(c, &data) {
return
}
c.JSON(http.StatusOK, data)
})
httptest.NewServer(r)
body := strings.NewReader(`{"name": "a", "dive_strings": ["a"], "deep": {"dive_strings": ["a"]}}`)
req := httptest.NewRequest(http.MethodPost, "/test", body)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
resp := w.Result()
defer resp.Body.Close()
assert.Equal(t, http.StatusNotAcceptable, resp.StatusCode)
bodyBytes, _ := io.ReadAll(resp.Body)
var b map[string]interface{}
_ = json.Unmarshal(bodyBytes, &b)
logger.Debug(b)
assert.Equal(t, "url", b["errors"].(map[string]interface{})["name"])
assert.Equal(t, "hostname_port",
b["errors"].(map[string]interface{})["dive_strings"].(map[string]interface{})["0"])
assert.Equal(t, "hostname_port",
b["errors"].(map[string]interface{})["deep"].(map[string]interface{})["dive_strings"].(map[string]interface{})["0"])
}