This repository has been archived by the owner on Jul 6, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
RequestBody_test.go
92 lines (72 loc) · 2.21 KB
/
RequestBody_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
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
package aero_test
import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/aerogo/aero"
"github.com/akyoto/assert"
)
func TestRequestBody(t *testing.T) {
app := aero.New()
app.Get("/", func(ctx aero.Context) error {
body := ctx.Request().Body()
assert.NotNil(t, ctx.Request().Body().Reader())
bodyText, _ := body.String()
return ctx.Text(bodyText)
})
requestBody := []byte(helloWorld)
request := httptest.NewRequest("GET", "/", bytes.NewReader(requestBody))
response := httptest.NewRecorder()
app.ServeHTTP(response, request)
assert.Equal(t, response.Code, http.StatusOK)
assert.Equal(t, response.Body.String(), helloWorld)
}
func TestRequestBodyJSON(t *testing.T) {
app := aero.New()
app.Get("/", func(ctx aero.Context) error {
body := ctx.Request().Body()
obj, _ := body.JSONObject()
return ctx.Text(fmt.Sprint(obj["key"]))
})
requestBody := []byte(`{"key":"value"}`)
request := httptest.NewRequest("GET", "/", bytes.NewReader(requestBody))
response := httptest.NewRecorder()
app.ServeHTTP(response, request)
assert.Equal(t, response.Code, http.StatusOK)
assert.Equal(t, response.Body.String(), "value")
}
func TestRequestBodyErrors(t *testing.T) {
app := aero.New()
app.Get("/", func(ctx aero.Context) error {
body := ctx.Request().Body()
bodyJSON, err := body.JSON()
assert.NotNil(t, err)
assert.Nil(t, bodyJSON)
return ctx.Text(helloWorld)
})
app.Get("/json-object", func(ctx aero.Context) error {
body := ctx.Request().Body()
bodyJSONObject, err := body.JSONObject()
assert.NotNil(t, err)
assert.Nil(t, bodyJSONObject)
return ctx.Text(helloWorld)
})
// No body
request := httptest.NewRequest("GET", "/", nil)
response := httptest.NewRecorder()
app.ServeHTTP(response, request)
assert.Equal(t, response.Code, http.StatusOK)
// Invalid JSON
request = httptest.NewRequest("GET", "/", strings.NewReader("{"))
response = httptest.NewRecorder()
app.ServeHTTP(response, request)
assert.Equal(t, response.Code, http.StatusOK)
// Not a JSON object
request = httptest.NewRequest("GET", "/json-object", strings.NewReader("{"))
response = httptest.NewRecorder()
app.ServeHTTP(response, request)
assert.Equal(t, response.Code, http.StatusOK)
}