Repository navigation
Expand file tree
/
Copy pathdispatch_test.go
More file actions
90 lines (76 loc) · 2.28 KB
/
Copy pathdispatch_test.go
File metadata and controls
90 lines (76 loc) · 2.28 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
// Copyright 2025 Sylvain Müller. All rights reserved.
// Mount of this source code is governed by a Apache-2.0 license that can be found
// at https://github.com/stdapi/edge/blob/main/LICENSE.txt.
package edge
import (
"context"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type closeRecorder struct {
r io.Reader
onRead func()
closed bool
}
func (c *closeRecorder) Read(p []byte) (int, error) {
if c.onRead != nil {
c.onRead()
}
return c.r.Read(p)
}
func (c *closeRecorder) Close() error {
c.closed = true
return nil
}
type deadlineRecorder struct {
http.ResponseWriter
calls int
}
func (d *deadlineRecorder) SetReadDeadline(time.Time) error {
d.calls++
return nil
}
func TestH3Body_CloseAfterTheHandlerReturnedLeavesTheStream(t *testing.T) {
w := &deadlineRecorder{ResponseWriter: httptest.NewRecorder()}
rc := &closeRecorder{r: strings.NewReader("abc")}
b := &h3Body{ReadCloser: rc, w: w}
b.handlerReturned()
require.NoError(t, b.Close())
assert.Zero(t, w.calls)
assert.False(t, rc.closed)
_, err := b.Read(make([]byte, 1))
assert.ErrorIs(t, err, http.ErrBodyReadAfterClose)
}
func TestH3Body_CloseWhileTheHandlerRunsSetsAReadDeadline(t *testing.T) {
w := &deadlineRecorder{ResponseWriter: httptest.NewRecorder()}
rc := &closeRecorder{r: strings.NewReader("abc")}
b := &h3Body{ReadCloser: rc, w: w}
require.NoError(t, b.Close())
assert.Equal(t, 1, w.calls)
assert.False(t, rc.closed)
}
func TestH3Body_EndReachedAsTheBodyClosesIsTheEnd(t *testing.T) {
rc := &closeRecorder{r: strings.NewReader("")}
b := &h3Body{ReadCloser: rc, w: httptest.NewRecorder()}
rc.onRead = func() { _ = b.Close() }
_, err := b.Read(make([]byte, 1))
assert.ErrorIs(t, err, io.EOF)
}
func TestRunKindHandler_LogsAPanicWithTheSessionContext(t *testing.T) {
type key struct{}
logs := &ctxHandler{}
p := testProxy(t, WithLogger(slog.New(logs)))
sess := newSession(p, context.WithValue(t.Context(), key{}, "session"), nil, Target{Host: "a.test", Port: "443"}, KindTCP, 0)
err := runKindHandler(p, sess, func() error { panic("boom") })
require.ErrorAs(t, err, new(*PanicError))
ctxs := logs.contexts()
require.Len(t, ctxs, 1)
assert.Equal(t, "session", ctxs[0].Value(key{}))
}