-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter_test.go
105 lines (91 loc) · 2.15 KB
/
router_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
package acrouter
import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/urfave/cli/v2"
"github.com/zfs123/go-ac-router/handle"
)
type header struct {
Key string
Value string
}
func performRequest(r *Router, method, path string, headers ...header) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, nil)
for _, h := range headers {
req.Header.Add(h.Key, h.Value)
}
w := httptest.NewRecorder()
r.api.Engine.ServeHTTP(w, req)
return w
}
func TestRouteOK(t *testing.T) {
passed := false
r, err := New()
if err != nil {
t.Fatal(err)
}
r.AddApiRoute("/test", "GET", "test api", nil, nil, func(action handle.Action, response handle.Response) {
passed = true
})
w := performRequest(r, "GET", "/test")
assert.True(t, passed)
assert.Equal(t, http.StatusOK, w.Code)
}
func TestApiRouter(t *testing.T) {
r, err := New()
if err != nil {
t.Fatal(err)
}
r.AddApiRoute("/hello", "GET", "hello api", nil, nil, func(action handle.Action, response handle.Response) {
response.Response(http.StatusOK, "hello")
})
w := performRequest(r, "GET", "/hello")
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "\"hello\"", w.Body.String())
}
func TestNotFound(t *testing.T) {
r, err := New()
if err != nil {
t.Fatal(err)
}
w := performRequest(r, "GET", "/xxxx")
assert.Equal(t, http.StatusNotFound, w.Code)
}
func ExampleRun() {
os.Args = []string{"test"}
r, _ := New()
r.Run()
//Output:
//NAME:
//test - A new cli application
//
//USAGE:
// test [global options] command [command options] [arguments...]
//
//COMMANDS:
// server, s start a api server
// tls_server, tls start a api tls server
// help, h Shows a list of commands or help for one command
//
//GLOBAL OPTIONS:
// --help, -h show help (default: false)
}
func ExampleRunCli() {
os.Args = []string{"-", "hello"} // the first string is program name
r, _ := New()
r.AddCliCommand(&cli.Command{
Name: "hello",
Usage: "hello cli command",
Action: func(c *cli.Context) error {
fmt.Println("hello world")
return nil
},
})
r.Run()
//Output:
//hello world
}