-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtestsupport.go
More file actions
94 lines (85 loc) · 2.01 KB
/
testsupport.go
File metadata and controls
94 lines (85 loc) · 2.01 KB
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
package jaws
import (
"bytes"
"html/template"
"net/http"
"net/http/httptest"
"strings"
"github.com/linkdata/jaws/lib/wire"
)
// TestRequest is a request harness intended for tests.
type TestRequest struct {
*Request
*requestHarness
}
type requestHarness struct {
Req *Request
*httptest.ResponseRecorder
ReadyCh chan struct{}
DoneCh chan struct{}
InCh chan wire.WsMsg
OutCh chan wire.WsMsg
BcastCh chan wire.Message
ExpectPanic bool
Panicked bool
PanicVal any
}
func newRequestHarness(jw *Jaws, hr *http.Request) (rh *requestHarness) {
if hr == nil {
hr = httptest.NewRequest(http.MethodGet, "/", nil)
}
rr := httptest.NewRecorder()
rr.Body = &bytes.Buffer{}
rq := jw.NewRequest(hr)
if rq == nil || jw.UseRequest(rq.JawsKey, hr) != rq {
return nil
}
bcastCh := jw.subscribe(rq, 64)
for i := 0; i <= cap(jw.subCh); i++ {
jw.subCh <- subscription{}
}
rh = &requestHarness{
Req: rq,
ResponseRecorder: rr,
ReadyCh: make(chan struct{}),
DoneCh: make(chan struct{}),
InCh: make(chan wire.WsMsg),
OutCh: make(chan wire.WsMsg, cap(bcastCh)),
BcastCh: bcastCh,
}
go func() {
defer func() {
if rh.ExpectPanic {
if rh.PanicVal = recover(); rh.PanicVal != nil {
rh.Panicked = true
}
}
close(rh.DoneCh)
}()
close(rh.ReadyCh)
rq.process(rh.BcastCh, rh.InCh, rh.OutCh)
jw.recycle(rq)
}()
return
}
func (rh *requestHarness) Close() {
close(rh.InCh)
}
func (rh *requestHarness) BodyString() string {
return strings.TrimSpace(rh.Body.String())
}
func (rh *requestHarness) BodyHTML() template.HTML {
return template.HTML(rh.BodyString()) /* #nosec G203 */
}
// NewTestRequest creates a TestRequest for use when testing.
// Passing nil for hr creates a GET / request with no body.
func NewTestRequest(jw *Jaws, hr *http.Request) (tr *TestRequest) {
rh := newRequestHarness(jw, hr)
if rh != nil {
tr = &TestRequest{
Request: rh.Req,
requestHarness: rh,
}
}
return
}