From f5512c73982073e13f77e162f743db879142381c Mon Sep 17 00:00:00 2001 From: Colin Adler Date: Fri, 17 Feb 2023 11:35:26 -0600 Subject: [PATCH 1/2] fix: actually test `httpapi.WebsocketCloseSprintf` Tests didn't run because it wasn't prefixed with `Test`. --- coderd/httpapi/httpapi.go | 2 +- coderd/httpapi/httpapi_test.go | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/coderd/httpapi/httpapi.go b/coderd/httpapi/httpapi.go index 942419182dfc1..e0f510b372276 100644 --- a/coderd/httpapi/httpapi.go +++ b/coderd/httpapi/httpapi.go @@ -182,7 +182,7 @@ func WebsocketCloseSprintf(format string, vars ...any) string { if len(msg) > websocketCloseMaxLen { // Trim the string to 123 bytes. If we accidentally cut in the middle of // a UTF-8 character, remove it from the string. - return strings.ToValidUTF8(string(msg[123]), "") + return strings.ToValidUTF8(msg[:websocketCloseMaxLen], "") } return msg diff --git a/coderd/httpapi/httpapi_test.go b/coderd/httpapi/httpapi_test.go index 77ff9cdca6fd6..780d35d4fa61e 100644 --- a/coderd/httpapi/httpapi_test.go +++ b/coderd/httpapi/httpapi_test.go @@ -122,7 +122,7 @@ func TestRead(t *testing.T) { }) } -func WebsocketCloseMsg(t *testing.T) { +func TestWebsocketCloseMsg(t *testing.T) { t.Parallel() t.Run("TruncateSingleByteCharacters", func(t *testing.T) { @@ -130,7 +130,7 @@ func WebsocketCloseMsg(t *testing.T) { msg := strings.Repeat("d", 255) trunc := httpapi.WebsocketCloseSprintf(msg) - assert.LessOrEqual(t, len(trunc), 123) + assert.Equal(t, len(trunc), 123) }) t.Run("TruncateMultiByteCharacters", func(t *testing.T) { @@ -138,6 +138,6 @@ func WebsocketCloseMsg(t *testing.T) { msg := strings.Repeat("こんにちは", 10) trunc := httpapi.WebsocketCloseSprintf(msg) - assert.LessOrEqual(t, len(trunc), 123) + assert.Equal(t, len(trunc), 123) }) } From e62c7fac6f412340146f72284c3ae040078abcca Mon Sep 17 00:00:00 2001 From: Colin Adler Date: Fri, 17 Feb 2023 11:39:50 -0600 Subject: [PATCH 2/2] fixup! fix: actually test `httpapi.WebsocketCloseSprintf` --- coderd/httpapi/httpapi_test.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/coderd/httpapi/httpapi_test.go b/coderd/httpapi/httpapi_test.go index 780d35d4fa61e..ea6d5a92ea5be 100644 --- a/coderd/httpapi/httpapi_test.go +++ b/coderd/httpapi/httpapi_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "fmt" "net/http" "net/http/httptest" "strings" @@ -125,6 +126,19 @@ func TestRead(t *testing.T) { func TestWebsocketCloseMsg(t *testing.T) { t.Parallel() + t.Run("Sprintf", func(t *testing.T) { + t.Parallel() + + var ( + msg = "this is my message %q %q" + opts = []any{"colin", "kyle"} + ) + + expected := fmt.Sprintf(msg, opts...) + got := httpapi.WebsocketCloseSprintf(msg, opts...) + assert.Equal(t, expected, got) + }) + t.Run("TruncateSingleByteCharacters", func(t *testing.T) { t.Parallel()