forked from fritzpay/paymentd
/
testutil.go
92 lines (77 loc) · 2.11 KB
/
testutil.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 testutil
import (
"bytes"
"net/http"
"testing"
"github.com/fritzpay/paymentd/pkg/config"
"github.com/fritzpay/paymentd/pkg/service"
. "github.com/smartystreets/goconvey/convey"
"golang.org/x/net/context"
"gopkg.in/inconshreveable/log15.v2"
)
const (
logChanBufferSize = 32
)
// WithContext is a decorator for GoConvey based tests
//
// It will inject a service context and a log channel, where log messages can be read from
func WithContext(f func(*service.Context, <-chan *log15.Record)) func() {
return func() {
logChan := make(chan *log15.Record, logChanBufferSize)
log := log15.New()
log.SetHandler(log15.ChannelHandler(logChan))
var cancel context.CancelFunc
baseCtx := context.Background()
baseCtx, cancel = context.WithCancel(baseCtx)
ctx, err := service.NewContext(context.Background(), config.DefaultConfig(), log)
So(err, ShouldBeNil)
ctx.APIKeychain().AddBinKey([]byte("test"))
So(ctx.APIKeychain().KeyCount(), ShouldEqual, 1)
f(ctx, logChan)
Reset(func() {
cancel()
})
}
}
// ResponseWriter is a mock http.ResponseWriter which can be used to inspect
// HTTP handler responses
type ResponseWriter struct {
Buf bytes.Buffer
H http.Header
HeaderWritten bool
StatusCode int
}
// NewResponseWriter creates a response writer to capture http handler responses
func NewResponseWriter() *ResponseWriter {
return &ResponseWriter{
H: http.Header(make(map[string][]string)),
StatusCode: http.StatusOK,
}
}
// Header implementing the http.ResponseWriter
func (r *ResponseWriter) Header() http.Header {
return r.H
}
// Write implementing the http.ResponseWriter, io.Writer
func (r *ResponseWriter) Write(p []byte) (int, error) {
if !r.HeaderWritten {
r.HeaderWritten = true
}
return (&(r.Buf)).Write(p)
}
// WriteHeader implementing the http.ResponseWriter
func (r *ResponseWriter) WriteHeader(statusCode int) {
r.HeaderWritten = true
r.StatusCode = statusCode
}
func ReportLog(t *testing.T, logChan <-chan *log15.Record) {
drain:
for {
select {
case r := <-logChan:
t.Logf("Log: %s, %+v", r.Msg, r.Ctx)
default:
break drain
}
}
}