@@ -2,15 +2,16 @@ package middleware
2
2
3
3
import (
4
4
"errors"
5
- "github.com/labstack/echo/v4"
6
- "github.com/stretchr/testify/assert"
7
5
"net/http"
8
6
"net/http/httptest"
9
7
"net/url"
10
8
"reflect"
11
9
"strings"
12
10
"testing"
13
11
"time"
12
+
13
+ "github.com/labstack/echo/v4"
14
+ "github.com/stretchr/testify/assert"
14
15
)
15
16
16
17
func TestTimeoutSkipper (t * testing.T ) {
@@ -273,3 +274,42 @@ func TestTimeoutWithDefaultErrorMessage(t *testing.T) {
273
274
assert .Equal (t , http .StatusServiceUnavailable , rec .Code )
274
275
assert .Equal (t , `<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>` , rec .Body .String ())
275
276
}
277
+
278
+ func TestTimeoutCanHandleContextDeadlineOnNextHandler (t * testing.T ) {
279
+ t .Parallel ()
280
+
281
+ timeout := 1 * time .Millisecond
282
+ m := TimeoutWithConfig (TimeoutConfig {
283
+ Timeout : timeout ,
284
+ ErrorMessage : "Timeout! change me" ,
285
+ })
286
+
287
+ handlerFinishedExecution := make (chan bool )
288
+
289
+ req := httptest .NewRequest (http .MethodGet , "/" , nil )
290
+ rec := httptest .NewRecorder ()
291
+
292
+ e := echo .New ()
293
+ c := e .NewContext (req , rec )
294
+
295
+ stopChan := make (chan struct {})
296
+ err := m (func (c echo.Context ) error {
297
+ // NOTE: when difference between timeout duration and handler execution time is almost the same (in range of 100microseconds)
298
+ // the result of timeout does not seem to be reliable - could respond timeout, could respond handler output
299
+ // difference over 500microseconds (0.5millisecond) response seems to be reliable
300
+ <- stopChan
301
+
302
+ // The Request Context should have a Deadline set by http.TimeoutHandler
303
+ if _ , ok := c .Request ().Context ().Deadline (); ! ok {
304
+ assert .Fail (t , "No timeout set on Request Context" )
305
+ }
306
+ handlerFinishedExecution <- c .Request ().Context ().Err () == nil
307
+ return c .String (http .StatusOK , "Hello, World!" )
308
+ })(c )
309
+ stopChan <- struct {}{}
310
+
311
+ assert .NoError (t , err )
312
+ assert .Equal (t , http .StatusServiceUnavailable , rec .Code )
313
+ assert .Equal (t , "Timeout! change me" , rec .Body .String ())
314
+ assert .False (t , <- handlerFinishedExecution )
315
+ }
0 commit comments