Skip to content

Commit 19ae411

Browse files
authored
fix: actually test httpapi.WebsocketCloseSprintf (#6261)
1 parent a79f4a0 commit 19ae411

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

coderd/httpapi/httpapi.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ func WebsocketCloseSprintf(format string, vars ...any) string {
182182
if len(msg) > websocketCloseMaxLen {
183183
// Trim the string to 123 bytes. If we accidentally cut in the middle of
184184
// a UTF-8 character, remove it from the string.
185-
return strings.ToValidUTF8(string(msg[123]), "")
185+
return strings.ToValidUTF8(msg[:websocketCloseMaxLen], "")
186186
}
187187

188188
return msg

coderd/httpapi/httpapi_test.go

+17-3
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"bytes"
55
"context"
66
"encoding/json"
7+
"fmt"
78
"net/http"
89
"net/http/httptest"
910
"strings"
@@ -122,22 +123,35 @@ func TestRead(t *testing.T) {
122123
})
123124
}
124125

125-
func WebsocketCloseMsg(t *testing.T) {
126+
func TestWebsocketCloseMsg(t *testing.T) {
126127
t.Parallel()
127128

129+
t.Run("Sprintf", func(t *testing.T) {
130+
t.Parallel()
131+
132+
var (
133+
msg = "this is my message %q %q"
134+
opts = []any{"colin", "kyle"}
135+
)
136+
137+
expected := fmt.Sprintf(msg, opts...)
138+
got := httpapi.WebsocketCloseSprintf(msg, opts...)
139+
assert.Equal(t, expected, got)
140+
})
141+
128142
t.Run("TruncateSingleByteCharacters", func(t *testing.T) {
129143
t.Parallel()
130144

131145
msg := strings.Repeat("d", 255)
132146
trunc := httpapi.WebsocketCloseSprintf(msg)
133-
assert.LessOrEqual(t, len(trunc), 123)
147+
assert.Equal(t, len(trunc), 123)
134148
})
135149

136150
t.Run("TruncateMultiByteCharacters", func(t *testing.T) {
137151
t.Parallel()
138152

139153
msg := strings.Repeat("こんにちは", 10)
140154
trunc := httpapi.WebsocketCloseSprintf(msg)
141-
assert.LessOrEqual(t, len(trunc), 123)
155+
assert.Equal(t, len(trunc), 123)
142156
})
143157
}

0 commit comments

Comments
 (0)