github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/cdc/api/middleware/middleware_test.go (about) 1 // Copyright 2022 PingCAP, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package middleware 15 16 import ( 17 "context" 18 "net/http" 19 "net/http/httptest" 20 "testing" 21 22 "github.com/gin-gonic/gin" 23 "github.com/pingcap/tiflow/cdc/capture" 24 "github.com/stretchr/testify/require" 25 ) 26 27 type testCaptureInfoProvider struct { 28 capture.Capture 29 ready bool 30 } 31 32 func (c *testCaptureInfoProvider) IsReady() bool { 33 return c.ready 34 } 35 36 func TestCheckServerReadyMiddleware(t *testing.T) { 37 capture := &testCaptureInfoProvider{ready: false} 38 router := gin.New() 39 router.Use(CheckServerReadyMiddleware(capture)) 40 router.Use(LogMiddleware()) 41 router.Use(ErrorHandleMiddleware()) 42 router.GET("/test", func(c *gin.Context) { 43 c.Status(http.StatusOK) 44 }) 45 46 w := httptest.NewRecorder() 47 req, err := http.NewRequestWithContext(context.Background(), 48 "GET", "/test", nil) 49 require.Nil(t, err) 50 router.ServeHTTP(w, req) 51 require.Equal(t, http.StatusServiceUnavailable, w.Code) 52 capture.ready = true 53 w = httptest.NewRecorder() 54 req, err = http.NewRequestWithContext(context.Background(), 55 "GET", "/test", nil) 56 require.Nil(t, err) 57 router.ServeHTTP(w, req) 58 require.Equal(t, http.StatusOK, w.Code) 59 }