-
Notifications
You must be signed in to change notification settings - Fork 180
/
mock.go
72 lines (62 loc) · 1.97 KB
/
mock.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
package dotweb
const (
requestHeaderUseMockKey = "dotweb_req_mock"
requestHeaderUseMockFlag = "true"
)
// MockHandle the handle define on mock module
type MockHandle func(ctx Context)
// Mock the define Mock module
type Mock interface {
// Register register MockHandle on route
Register(route string, handler MockHandle)
// RegisterString register return mock string on route
RegisterString(route string, resData interface{})
// RegisterJSON register return mock json on route
RegisterJSON(route string, resData interface{})
// CheckNeedMock check is need do mock logic
CheckNeedMock(Context) bool
// Do do mock logic
Do(Context)
}
// StandardMock standard mock implement for Mock interface
type StandardMock struct {
routeMap map[string]MockHandle
}
// NewStandardMock create new StandardMock
func NewStandardMock() *StandardMock {
return &StandardMock{routeMap: make(map[string]MockHandle)}
}
// CheckNeedMock check is need do mock logic
func (m *StandardMock) CheckNeedMock(ctx Context) bool {
if ctx.Request().QueryHeader(requestHeaderUseMockKey) == requestHeaderUseMockFlag {
return true
}
return false
}
// Do do mock logic
func (m *StandardMock) Do(ctx Context) {
handler, exists := m.routeMap[ctx.RouterNode().Node().fullPath]
if exists {
handler(ctx)
}
}
// Register register MockHandle on route
func (m *StandardMock) Register(route string, handler MockHandle) {
m.routeMap[route] = handler
}
// RegisterString register return mock string on route
func (m *StandardMock) RegisterString(route string, resData interface{}) {
m.routeMap[route] = func(ctx Context) {
ctx.Response().SetHeader(requestHeaderUseMockKey, requestHeaderUseMockFlag)
ctx.WriteString(resData)
ctx.End()
}
}
// RegisterJSON register return mock json on route
func (m *StandardMock) RegisterJSON(route string, resData interface{}) {
m.routeMap[route] = func(ctx Context) {
ctx.Response().SetHeader(requestHeaderUseMockKey, requestHeaderUseMockFlag)
ctx.WriteJson(resData)
ctx.End()
}
}