From 416526e0cd368d850e5c4cf7210562e409e15166 Mon Sep 17 00:00:00 2001 From: Roland Lammel Date: Sun, 7 Feb 2021 21:27:46 +0100 Subject: [PATCH] Add test to reproduce race for timeout middleware (#1761) Run with `go test -race -count 1 -timeout 10s -run ^TestTimeoutDataRace$ github.com/labstack/echo/v4/middleware` --- middleware/timeout_test.go | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/middleware/timeout_test.go b/middleware/timeout_test.go index c0e945933..07a725482 100644 --- a/middleware/timeout_test.go +++ b/middleware/timeout_test.go @@ -5,8 +5,6 @@ package middleware import ( "context" "errors" - "github.com/labstack/echo/v4" - "github.com/stretchr/testify/assert" "net/http" "net/http/httptest" "net/url" @@ -14,6 +12,9 @@ import ( "strings" "testing" "time" + + "github.com/labstack/echo/v4" + "github.com/stretchr/testify/assert" ) func TestTimeoutSkipper(t *testing.T) { @@ -175,3 +176,28 @@ func TestTimeoutTestRequestClone(t *testing.T) { assert.NoError(t, err) } + +// TestTimeoutDataRace shows a data race occurs if the handle func executes for same duration as specified timeout. +func TestTimeoutDataRace(t *testing.T) { + t.Parallel() + const timeout = 10 * time.Millisecond + mw := TimeoutWithConfig(TimeoutConfig{ + Timeout: timeout, + }) + + req := httptest.NewRequest(http.MethodGet, "/", nil) + rec := httptest.NewRecorder() + + e := echo.New() + c := e.NewContext(req, rec) + + const helloWorld = "Hello, World!" + err := mw(func(c echo.Context) error { + time.Sleep(timeout) + return c.String(http.StatusOK, helloWorld) + })(c) + + assert.NoError(t, err) + assert.Equal(t, http.StatusOK, rec.Code) + assert.Equal(t, helloWorld, rec.Body.String()) +}