This repository has been archived by the owner on May 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testing.go
108 lines (91 loc) · 2.12 KB
/
testing.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package testing
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"time"
"github.com/ez-connect/go-rest/rest"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
)
type RequestConfig struct {
// Default GET
Method string
// Default "/"
Target string
Path string
PathParamName string
PathParamValue string
HeaderAuthorization string
Body interface{}
}
func TestFields(t *testing.T, doc interface{}) {
v := reflect.ValueOf(doc)
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
if f.Kind() == reflect.String {
assert.NotEqual(t, "", f.String())
}
if f.Type().String() == "time.Time" {
date := f.Interface()
var now time.Time
assert.Equal(t, fmt.Sprintf("%v", now), fmt.Sprintf("%v", date))
}
}
}
func MakeRequest(e *echo.Echo, config *RequestConfig) (echo.Context, *httptest.ResponseRecorder) {
var method string
if config != nil && config.Method != "" {
method = config.Method
} else {
method = http.MethodGet
}
var target string
if config != nil && config.Target != "" {
target = config.Target
} else {
target = "/"
}
var body io.Reader
if config != nil && config.Body != nil {
data, _ := json.Marshal(config.Body)
body = bytes.NewReader(data)
}
req := httptest.NewRequest(
method,
target,
body,
)
if config != nil && config.HeaderAuthorization != "" {
req.Header.Set(echo.HeaderAuthorization, config.HeaderAuthorization)
}
res := httptest.NewRecorder()
c := e.NewContext(req, res)
if config != nil && config.Path != "" {
c.SetPath(config.Path)
if config.PathParamName != "" {
c.SetParamNames(config.PathParamName)
}
if config.PathParamValue != "" {
c.SetParamValues(config.PathParamValue)
}
}
if config != nil && config.HeaderAuthorization != "" {
middlewareFunc := rest.JWTWithDefault(nil)
handlerFunc := middlewareFunc(func(c echo.Context) error {
return nil
})
handlerFunc(c)
}
return c, res
}
func PrintResponse(t *testing.T, res *httptest.ResponseRecorder) {
data := &bytes.Buffer{}
json.Indent(data, res.Body.Bytes(), "", " ")
t.Error(data)
}