-
Notifications
You must be signed in to change notification settings - Fork 5
/
testing_testapp.go
114 lines (96 loc) · 2.39 KB
/
testing_testapp.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
109
110
111
112
113
114
package azugo
import (
"net"
"testing"
"azugo.io/azugo/config"
"azugo.io/core"
"github.com/stretchr/testify/require"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttputil"
"go.uber.org/zap"
"go.uber.org/zap/zaptest/observer"
)
// TestApp represents testing app instance
type TestApp struct {
*App
ln *fasthttputil.InmemoryListener
logs *observer.ObservedLogs
}
// NewTestApp creates new testing application instance
func NewTestApp(app ...*App) *TestApp {
var a *App
if len(app) == 0 {
a = New()
a.AppName = "Azugo TestApp"
} else {
a = app[0]
}
// Trust all proxy headers for test app
a.RouterOptions.Proxy.TrustAll = true
conf := config.New()
a.SetConfig(nil, conf)
a.App.SetConfig(nil, conf.Core())
_ = conf.Load(nil, conf, string(core.EnvironmentDevelopment))
return &TestApp{
App: a,
}
}
func (a *TestApp) initLogs() {
observedZapCore, observedLogs := observer.New(zap.InfoLevel)
a.ReplaceLogger(zap.New(observedZapCore))
a.logs = observedLogs
}
// Start starts testing web server instance
func (a *TestApp) Start(t *testing.T) {
a.initLogs()
a.App.App.Start()
server := &fasthttp.Server{
NoDefaultServerHeader: true,
Handler: a.App.Handler,
Logger: zap.NewStdLog(a.App.Log().Named("http")),
StreamRequestBody: true,
DisablePreParseMultipartForm: true,
}
ln := fasthttputil.NewInmemoryListener()
go func() {
require.NoError(t, server.Serve(ln))
}()
a.ln = ln
}
// StartBenchmark starts benchmarking web server instance
func (a *TestApp) StartBenchmark() {
a.initLogs()
a.App.App.Start()
server := &fasthttp.Server{
NoDefaultServerHeader: true,
Handler: a.App.Handler,
Logger: zap.NewStdLog(a.App.Log().Named("http")),
StreamRequestBody: true,
DisablePreParseMultipartForm: true,
}
ln := fasthttputil.NewInmemoryListener()
go func() {
if err := server.Serve(ln); err != nil {
panic(err)
}
}()
a.ln = ln
}
// Stop web server instance
func (a *TestApp) Stop() {
if a.ln != nil {
a.ln.Close()
}
a.App.Stop()
}
// TestClient returns testing client that will do HTTP requests to test web server
func (a *TestApp) TestClient() *TestClient {
client := &fasthttp.Client{}
client.Dial = func(addr string) (net.Conn, error) {
return a.ln.Dial()
}
return &TestClient{
app: a,
client: client,
}
}