forked from mingderwang/gas
/
gas_test.go
130 lines (100 loc) · 2.53 KB
/
gas_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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package gas
import (
"crypto/tls"
"github.com/gavv/httpexpect"
"github.com/go-gas/gas/model/MySQL"
"github.com/stretchr/testify/assert"
"github.com/valyala/fasthttp"
"io/ioutil"
"net/http"
"testing"
"time"
)
var (
indexString = "indexpage"
)
func newHttpExpect(t *testing.T, h fasthttp.RequestHandler) *httpexpect.Expect {
// create fasthttp.RequestHandler
//handler := g.Router.Handler
// create httpexpect instance that will call fasthtpp.RequestHandler directly
e := httpexpect.WithConfig(httpexpect.Config{
Reporter: httpexpect.NewAssertReporter(t),
Client: &http.Client{
Transport: httpexpect.NewFastBinder(h),
Jar: httpexpect.NewJar(),
},
})
return e
}
func testRequest(t *testing.T, url string) {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
resp, err := client.Get(url)
defer resp.Body.Close()
assert.NoError(t, err)
b, ioerr := ioutil.ReadAll(resp.Body)
assert.NoError(t, ioerr)
assert.Equal(t, "200 OK", resp.Status, "should get a 200")
assert.Equal(t, indexString, string(b))
}
func indexPage(ctx *Context) error {
return ctx.STRING(http.StatusOK, indexString)
}
func TestGas(t *testing.T) {
// new gas
g := New("testfiles/config_test.yaml")
// set route
g.Router.Get("/", indexPage)
e := newHttpExpect(t, g.Router.Handler)
e.GET("/").
Expect().
Status(http.StatusOK).
Body().Equal(indexString)
}
func TestRun(t *testing.T) {
g := New()
// set route
g.Router.Get("/", indexPage)
go func() {
assert.NoError(t, g.Run())
}()
// have to wait for the goroutine to start and run the server
// otherwise the main thread will complete
time.Sleep(5 * time.Millisecond)
testRequest(t, "http://localhost:8080")
}
func TestRunTLS(t *testing.T) {
g := New()
// set route
g.Router.Get("/", indexPage)
go func() {
assert.NoError(t, g.RunTLS("localhost:8081", "certificate/localhost.cert", "certificate/localhost.key"))
}()
time.Sleep(5 * time.Millisecond)
testRequest(t, "https://localhost:8081")
}
func TestGas_NewModel(t *testing.T) {
as := assert.New(t)
// new gas
g := New("testfiles/config_test.yaml")
m := g.NewModel()
as.IsType(&MySQLModel.MySQLModel{}, m)
}
func BenchmarkGas(b *testing.B) {
b.ReportAllocs()
// new gas
g := New("testfiles/config_test.yaml")
// set route
g.Router.Get("/", indexPage)
req := fasthttp.Request{}
req.SetRequestURI("/")
req.Header.SetMethod("GET")
for i := 0; i < b.N; i++ {
ctx := fasthttp.RequestCtx{
Request: req,
}
g.Router.Handler(&ctx)
}
}