-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontext_test.go
105 lines (81 loc) · 2.38 KB
/
context_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
93
94
95
96
97
98
99
100
101
102
103
104
105
package httpwrap
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
)
func nopConstructor(http.ResponseWriter, *http.Request, interface{}) error { return nil }
func jsonBodyConstructor(_ http.ResponseWriter, req *http.Request, obj interface{}) error {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
return err
}
err = json.Unmarshal(body, obj)
req.Body = ioutil.NopCloser(bytes.NewBuffer(body))
return err
}
func failedConstructor(http.ResponseWriter, *http.Request, interface{}) error {
return fmt.Errorf("error")
}
type myerr struct{}
func (e myerr) Error() string { return "error" }
var _ error = myerr{}
func TestContext(t *testing.T) {
t.Run("default http types", func(t *testing.T) {
req := httptest.NewRequest("GET", "/test", nil)
rw := httptest.NewRecorder()
ctx := newRunCtx(rw, req, nopConstructor)
types, _ := typesOf(func(http.ResponseWriter, *http.Request) {})
_, found := ctx.get(types[0])
require.True(t, found)
_, found = ctx.get(types[1])
require.True(t, found)
vals, err := ctx.generate(types)
require.NoError(t, err)
require.Len(t, vals, 2)
})
t.Run("provide error", func(t *testing.T) {
req := httptest.NewRequest("GET", "/test", nil)
rw := httptest.NewRecorder()
ctx := newRunCtx(rw, req, nopConstructor)
err := fmt.Errorf("error")
ctx.provide(err)
fn := func(err error) {}
types, _ := typesOf(fn)
vals, err := ctx.generate(types)
require.NoError(t, err)
require.Len(t, vals, 1)
require.False(t, vals[0].IsNil())
})
t.Run("provide special error", func(t *testing.T) {
req := httptest.NewRequest("GET", "/test", nil)
rw := httptest.NewRecorder()
ctx := newRunCtx(rw, req, nopConstructor)
err := myerr{}
ctx.provide(err)
fn := func(err error) {}
types, _ := typesOf(fn)
vals, err1 := ctx.generate(types)
require.NoError(t, err1)
require.Len(t, vals, 1)
require.NotNil(t, vals[0].Interface())
})
t.Run("provide nil value that satisfies interface", func(t *testing.T) {
req := httptest.NewRequest("GET", "/test", nil)
rw := httptest.NewRecorder()
ctx := newRunCtx(rw, req, nopConstructor)
var err *myerr
ctx.provide(err)
fn := func(err error) {}
types, _ := typesOf(fn)
vals, err1 := ctx.generate(types)
require.NoError(t, err1)
require.Len(t, vals, 1)
require.Nil(t, vals[0].Interface())
})
}