-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathengine_test.go
111 lines (84 loc) · 2.38 KB
/
engine_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
package gongular
import (
"errors"
"net/http"
"testing"
"bytes"
"io/ioutil"
"github.com/stretchr/testify/assert"
)
type errorTester struct{}
func (e *errorTester) Handle(c *Context) error {
return errors.New("Shit")
}
func TestEngine_SetRouteCallback(t *testing.T) {
var isErr error
fn := func(err error, c *Context) {
isErr = http.ErrUseLastResponse
}
e := newEngineTest()
e.SetErrorHandler(fn)
e.GetRouter().GET("/", &errorTester{})
_, _ = get(t, e, "/")
assert.Error(t, isErr)
assert.Equal(t, http.ErrUseLastResponse, isErr)
}
type middlewareFailIfUserId5 struct {
Param struct {
UserID int
}
}
func (m *middlewareFailIfUserId5) Handle(c *Context) error {
if m.Param.UserID == 5 {
c.Status(http.StatusTeapot)
c.SetBody("Sorry")
c.StopChain()
}
return nil
}
func TestGroup(t *testing.T) {
e := newEngineTest()
r := e.GetRouter()
g := r.Group("/api/user/:UserID", &middlewareFailIfUserId5{})
g.GET("/name", &simpleHandler{})
g.GET("/wow", &simpleHandler{})
resp1, _ := get(t, e, "/api/user/30/name")
assert.Equal(t, http.StatusOK, resp1.Code)
resp2, _ := get(t, e, "/api/user/5/name")
assert.Equal(t, http.StatusTeapot, resp2.Code)
resp3, _ := get(t, e, "/api/user/30/wow")
assert.Equal(t, http.StatusOK, resp3.Code)
resp4, _ := get(t, e, "/api/user/5/wow")
assert.Equal(t, http.StatusTeapot, resp4.Code)
}
func TestEngineWithDefaultRouteCallback(t *testing.T) {
e := NewEngine()
e.GetRouter().GET("/", &simpleHandler{})
resp, content := get(t, e, "/")
assert.Equal(t, http.StatusOK, resp.Code)
assert.Equal(t, `"selam"`, content)
}
func TestEngineFileServe(t *testing.T) {
e := NewEngine()
e.ServeFile("/", "README.md")
e.ServeFiles("/static", http.Dir("."))
bytesReadme, err := ioutil.ReadFile("README.md")
if err != nil {
assert.NoError(t, err, "cannot read file")
}
// Test binary files as well
bytesLogo, err := ioutil.ReadFile("logo.png")
if err != nil {
assert.NoError(t, err, "cannot read file")
}
resp, content := get(t, e, "/")
assert.Equal(t, http.StatusOK, resp.Code)
assert.Equal(t, string(bytesReadme), content)
resp2, content2 := get(t, e, "/static/logo.png")
assert.Equal(t, http.StatusOK, resp2.Code)
// Sorry for the inefficiency
assert.Equal(t, 0, bytes.Compare([]byte(content2), bytesLogo))
// Not found test
resp3, _ := get(t, e, "/static/no-file-should-be-here")
assert.Equal(t, http.StatusNotFound, resp3.Code)
}