From 0de6a2f3949aed476aeab5fcbdf42c8bb6303e6a Mon Sep 17 00:00:00 2001 From: Jason McNeil Date: Mon, 22 Jul 2024 03:50:44 -0300 Subject: [PATCH] test(ctx_test): Fix race condition (#3081) * test(ctx_test): Fix race condition * chore: Release ctx resource after sending file * refactor: sendFileBodyReader function Refactor the `sendFileBodyReader` function to remove the unnecessary `app` parameter. This simplifies the function signature and improves code readability. --- ctx_test.go | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/ctx_test.go b/ctx_test.go index e27aa421..88e57620 100644 --- a/ctx_test.go +++ b/ctx_test.go @@ -3099,23 +3099,25 @@ func Test_Ctx_SendFile_Compress_CheckCompressed(t *testing.T) { expectedFileContent, err := io.ReadAll(f) require.NoError(t, err) - sendFileBodyReader := func(compression string) []byte { - reqCtx := &fasthttp.RequestCtx{} - reqCtx.Request.Header.Add(HeaderAcceptEncoding, compression) + sendFileBodyReader := func(compression string) ([]byte, error) { + t.Helper() + c := app.AcquireCtx(&fasthttp.RequestCtx{}) + defer app.ReleaseCtx(c) + c.Request().Header.Add(HeaderAcceptEncoding, compression) - c := app.AcquireCtx(reqCtx) - err = c.SendFile("./ctx.go", SendFile{ + err := c.SendFile("./ctx.go", SendFile{ Compress: true, }) - require.NoError(t, err) - return c.Response().Body() + return c.Response().Body(), err } t.Run("gzip", func(t *testing.T) { t.Parallel() - body, err := fasthttp.AppendGunzipBytes(nil, sendFileBodyReader("gzip")) + b, err := sendFileBodyReader("gzip") + require.NoError(t, err) + body, err := fasthttp.AppendGunzipBytes(nil, b) require.NoError(t, err) require.Equal(t, expectedFileContent, body) @@ -3124,7 +3126,9 @@ func Test_Ctx_SendFile_Compress_CheckCompressed(t *testing.T) { t.Run("zstd", func(t *testing.T) { t.Parallel() - body, err := fasthttp.AppendUnzstdBytes(nil, sendFileBodyReader("zstd")) + b, err := sendFileBodyReader("zstd") + require.NoError(t, err) + body, err := fasthttp.AppendUnzstdBytes(nil, b) require.NoError(t, err) require.Equal(t, expectedFileContent, body) @@ -3133,7 +3137,9 @@ func Test_Ctx_SendFile_Compress_CheckCompressed(t *testing.T) { t.Run("br", func(t *testing.T) { t.Parallel() - body, err := fasthttp.AppendUnbrotliBytes(nil, sendFileBodyReader("br")) + b, err := sendFileBodyReader("br") + require.NoError(t, err) + body, err := fasthttp.AppendUnbrotliBytes(nil, b) require.NoError(t, err) require.Equal(t, expectedFileContent, body) @@ -3242,6 +3248,8 @@ func Test_Ctx_SendFile_Multiple(t *testing.T) { require.Contains(t, string(body), tc.body) } + app.sendfilesMutex.RLock() + defer app.sendfilesMutex.RUnlock() require.Len(t, app.sendfiles, 3) }