-
Notifications
You must be signed in to change notification settings - Fork 5
/
middleware_timeout_test.go
73 lines (58 loc) · 2.21 KB
/
middleware_timeout_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package fiber
import (
"fmt"
"io"
"net/http"
"testing"
"time"
contractshttp "github.com/goravel/framework/contracts/http"
mocksconfig "github.com/goravel/framework/mocks/config"
mockslog "github.com/goravel/framework/mocks/log"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
func TestTimeoutMiddleware(t *testing.T) {
mockConfig := mocksconfig.NewConfig(t)
mockConfig.On("GetBool", "http.drivers.fiber.prefork", false).Return(false).Once()
mockConfig.On("GetInt", "http.drivers.fiber.body_limit", 4096).Return(4096).Once()
mockConfig.On("GetInt", "http.drivers.fiber.header_limit", 4096).Return(4096).Once()
route, err := NewRoute(mockConfig, nil)
require.NoError(t, err)
route.Middleware(Timeout(1*time.Second)).Get("/timeout", func(ctx contractshttp.Context) contractshttp.Response {
time.Sleep(2 * time.Second)
return ctx.Response().Success().String("timeout")
})
route.Middleware(Timeout(1*time.Second)).Get("/normal", func(ctx contractshttp.Context) contractshttp.Response {
return ctx.Response().Success().String("normal")
})
route.Middleware(Timeout(1*time.Second)).Get("/panic", func(ctx contractshttp.Context) contractshttp.Response {
panic(1)
})
req, err := http.NewRequest("GET", "/timeout", nil)
require.NoError(t, err)
resp, err := route.instance.Test(req, -1)
assert.NoError(t, err)
assert.Equal(t, http.StatusGatewayTimeout, resp.StatusCode)
req, err = http.NewRequest("GET", "/normal", nil)
require.NoError(t, err)
resp, err = route.Test(req)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Equal(t, "normal", string(body))
req, err = http.NewRequest("GET", "/panic", nil)
require.NoError(t, err)
mockLog := mockslog.NewLog(t)
mockLog.EXPECT().Request(mock.Anything).Return(mockLog).Once()
mockLog.EXPECT().Error(mock.Anything).Once()
LogFacade = mockLog
resp, err = route.instance.Test(req)
fmt.Printf("resp: %+v\n", resp)
assert.NoError(t, err)
assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
body, err = io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Equal(t, "Internal Server Error", string(body))
}