/
test_request.go
108 lines (89 loc) · 2.35 KB
/
test_request.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 restserver
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
"strings"
"github.com/gofiber/fiber/v2"
)
const (
DefaultTestUserId = "5e859dae-c879-11eb-b8bc-0242ac130003"
DefaultTestTenantId = "5e859dae-c879-11eb-b8bc-0242ac130004"
)
// RequestTest is a contract to test http requests
type RequestTest struct {
// Method http method
Method string
// Url to call in test
Url string
// Path to register endpoint
Path string
// Request headers
Headers map[string]string
// Body request
Body string
// UploadFile file to upload in multipart form file
UploadFile *os.File
// FormFileField field name
FormFileField string
// FormFileName file name
FormFileName string
}
// NewRequestTest returns a TestResponse with result of test execution
func NewRequestTest(request *RequestTest, handlerFn func(ctx WebContext)) *TestResponse {
app := fiber.New()
app.Use(authenticationContextFiberMiddleware())
path := convertUriToFiberUri(request.Path)
app.Add(request.Method, path, func(ctx *fiber.Ctx) error {
webContext := newFiberWebContext(ctx)
handlerFn(webContext)
return nil
})
var req *http.Request
if request.UploadFile != nil {
b := new(bytes.Buffer)
writer := multipart.NewWriter(b)
formFile, err := writer.CreateFormFile(request.FormFileField, request.FormFileName)
if err != nil {
panic(err)
}
_, _ = io.Copy(formFile, request.UploadFile)
if err = writer.Close(); err != nil {
panic(err)
}
req = httptest.NewRequest(request.Method, request.Url, b)
req.Header.Set(fiber.HeaderContentType, writer.FormDataContentType())
} else {
req = httptest.NewRequest(request.Method, request.Url, bytes.NewBuffer([]byte(request.Body)))
}
req.Header.Add(tenantIDHeader, DefaultTestTenantId)
req.Header.Add(userIDHeader, DefaultTestUserId)
for key, value := range request.Headers {
req.Header.Add(key, value)
}
resp, err := app.Test(req, -1)
if err != nil {
panic(err)
}
return &TestResponse{resp: resp}
}
func convertUriToFiberUri(uri string) string {
replacer := strings.NewReplacer(
"{", "",
"}", "",
)
paths := strings.Split(uri, "/")
for idx, path := range paths {
if pathIsPathParam(path) {
paths[idx] = fmt.Sprintf(":%s", replacer.Replace(path))
}
}
return strings.Join(paths, "/")
}
func pathIsPathParam(path string) bool {
return strings.Contains(path, "{")
}