-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontainers_4errors_test.go
90 lines (71 loc) · 1.91 KB
/
containers_4errors_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
package containers_test
import (
"errors"
"net/http"
"net/http/httptest"
"testing"
"fmt"
ct "github.com/theplant/containers"
"github.com/theplant/testingutils"
)
type errhandler struct {
}
func (eh *errhandler) HandleErr(w http.ResponseWriter, r *http.Request, err error) {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "err `%s` is properly handled", err.Error())
}
func Cat(r *http.Request) (html string, err error) {
err = ct.NewRedirectError("/fff", http.StatusPermanentRedirect)
return
}
func BadBoy(r *http.Request) (html string, err error) {
err = errors.New("ohh No.")
return
}
func MyCatHome(r *http.Request) (cs []ct.Container, err error) {
cs = []ct.Container{
ct.ContainerFunc(Cat),
}
return
}
func ExampleContainer_4errors() {
http.Handle("/page4", ct.UseErrHandler(ct.PageHandler(ct.PageFunc(MyCatHome), nil), &errhandler{}))
//Output:
}
func TestErrorRedirect(t *testing.T) {
ts := httptest.NewServer(ct.UseErrHandler(ct.PageHandler(ct.PageFunc(MyCatHome), nil), &errhandler{}))
defer ts.Close()
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
res, err := client.Get(ts.URL)
if err != nil {
t.Error(err)
}
if res.StatusCode != http.StatusPermanentRedirect {
t.Error("wrong http status", res.Status)
}
}
func TestErrorInternal(t *testing.T) {
ts := httptest.NewServer(ct.UseErrHandler(ct.PageHandler(ct.PageFunc(func(r *http.Request) (cs []ct.Container, err error) {
cs = []ct.Container{
ct.ContainerFunc(BadBoy),
}
return
}), nil), &errhandler{}))
defer ts.Close()
res, err := http.Get(ts.URL)
if err != nil {
t.Error(err)
}
if res.StatusCode != http.StatusInternalServerError {
t.Error("didn't handle err")
}
expectedBody := "err `ohh No.` is properly handled"
diff := testingutils.PrettyJsonDiff(expectedBody, res.Body)
if len(diff) > 0 {
t.Error(diff)
}
}