-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathyap_test.go
95 lines (79 loc) · 2.16 KB
/
yap_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
/*
* Copyright (c) 2023 The GoPlus Authors (goplus.org). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package yap_test
import (
"net/http"
"os"
"testing"
"github.com/goplus/yap"
"github.com/qiniu/x/mockhttp"
)
// mock runs a YAP server by mockhttp.
func mock(host string, app yap.AppType) *mockhttp.Transport {
tr := mockhttp.NewTransport()
app.InitYap()
app.SetLAS(func(addr string, h http.Handler) error {
return tr.ListenAndServe(host, h)
})
app.(interface{ Main() }).Main()
return tr
}
func TestBasic(t *testing.T) {
y := yap.New(os.DirFS("."))
y.GET("/", func(ctx *yap.Context) {
ctx.TEXT(200, "text/html", `<html><body>Hello, <a href="/p/123">YAP</a>!</body></html>`)
})
y.GET("/p/:id", func(ctx *yap.Context) {
ctx.YAP(200, "article", yap.H{
"id": ctx.Param("id"),
})
})
y.SetLAS(func(addr string, h http.Handler) error {
return nil
})
y.Run(":8888")
}
type handler struct{}
func (p *handler) Main(ctx *yap.Context) {
ctx.TEXT(200, "text/html", `<html><body>Hello, <a href="/p/123">YAP</a>!</body></html>`)
}
func (p *handler) Classclone() yap.HandlerProto {
ret := *p
return &ret
}
type app struct {
*yap.Engine
}
func (app) Main() {
}
func TestProto(t *testing.T) {
y := yap.New(os.DirFS("."))
y.ProtoHandle("/", new(handler))
y.ProtoRoute("GET", "/p/:id", new(handler))
tr := mock("example.com", app{y})
y.Run(":8888")
c := http.Client{Transport: tr}
resp, err := c.Get("http://example.com/p/123")
if err != nil {
t.Fatal("GET /p/123 failed:", err)
}
defer resp.Body.Close()
resp, err = c.Get("http://example.com/")
if err != nil {
t.Fatal("GET / failed:", err)
}
defer resp.Body.Close()
}