-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathrequest_test.go
61 lines (53 loc) · 1.85 KB
/
request_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
package rpc_test
import (
"net/http/httptest"
"strings"
"testing"
"github.com/tj/assert"
"github.com/apex/rpc"
)
// Test requests.
func TestReadRequest(t *testing.T) {
t.Run("with a no content-type", func(t *testing.T) {
r := httptest.NewRequest("GET", "/", strings.NewReader(`{ "name": "Tobi" }`))
var in struct{ Name string }
err := rpc.ReadRequest(r, &in)
assert.EqualError(t, err, `Unsupported request Content-Type, must be application/json`)
})
t.Run("with malformed JSON", func(t *testing.T) {
r := httptest.NewRequest("GET", "/", strings.NewReader(`{ "name": "Tobi`))
r.Header.Set("Content-Type", "application/json")
var in struct{ Name string }
err := rpc.ReadRequest(r, &in)
assert.EqualError(t, err, `Failed to parse malformed request body, must be a valid JSON object`)
})
t.Run("with JSON array", func(t *testing.T) {
r := httptest.NewRequest("GET", "/", strings.NewReader(`[{}]`))
r.Header.Set("Content-Type", "application/json")
var in struct{ Name string }
err := rpc.ReadRequest(r, &in)
assert.EqualError(t, err, `Failed to parse malformed request body, must be a valid JSON object`)
})
t.Run("with a json body", func(t *testing.T) {
r := httptest.NewRequest("GET", "/", strings.NewReader(`{ "name": "Tobi" }`))
r.Header.Set("Content-Type", "application/json")
var in struct{ Name string }
err := rpc.ReadRequest(r, &in)
assert.NoError(t, err, "parsing")
assert.Equal(t, "Tobi", in.Name)
})
}
// Benchmark requests.
func BenchmarkReadRequest(b *testing.B) {
b.ReportAllocs()
b.SetBytes(1)
for i := 0; i < b.N; i++ {
r := httptest.NewRequest("GET", "/", strings.NewReader(`{ "name": "Tobi", "species": "ferret", "email": "[email protected]" }`))
r.Header.Set("Content-Type", "application/json")
var in struct{ Name, Species, Email string }
err := rpc.ReadRequest(r, &in)
if err != nil {
b.Fatal(err)
}
}
}