github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/cdc/api/v2/health_test.go (about) 1 // Copyright 2023 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 v2 15 16 import ( 17 "context" 18 "encoding/json" 19 "net/http" 20 "net/http/httptest" 21 "testing" 22 23 "github.com/golang/mock/gomock" 24 mock_capture "github.com/pingcap/tiflow/cdc/capture/mock" 25 "github.com/pingcap/tiflow/cdc/model" 26 mock_owner "github.com/pingcap/tiflow/cdc/owner/mock" 27 cerror "github.com/pingcap/tiflow/pkg/errors" 28 "github.com/stretchr/testify/require" 29 ) 30 31 func TestHealth(t *testing.T) { 32 t.Parallel() 33 health := testCase{url: "/api/v2/health", method: "GET"} 34 helpers := NewMockAPIV2Helpers(gomock.NewController(t)) 35 cp := mock_capture.NewMockCapture(gomock.NewController(t)) 36 apiV2 := NewOpenAPIV2ForTest(cp, helpers) 37 router := newRouter(apiV2) 38 39 statusProvider := mock_owner.NewMockStatusProvider(gomock.NewController(t)) 40 cp.EXPECT().StatusProvider().Return(statusProvider).AnyTimes() 41 cp.EXPECT().IsReady().Return(true).AnyTimes() 42 cp.EXPECT().IsController().Return(true).AnyTimes() 43 44 statusProvider.EXPECT().IsHealthy(gomock.Any()).Return(false, 45 cerror.ErrUnknown.FastGenByArgs()) 46 w := httptest.NewRecorder() 47 req, _ := http.NewRequestWithContext(context.Background(), health.method, 48 health.url, nil) 49 router.ServeHTTP(w, req) 50 require.Equal(t, http.StatusInternalServerError, w.Code) 51 respErr := model.HTTPError{} 52 err := json.NewDecoder(w.Body).Decode(&respErr) 53 require.Nil(t, err) 54 require.Contains(t, respErr.Code, "ErrUnknown") 55 56 statusProvider.EXPECT().IsHealthy(gomock.Any()).Return(false, nil) 57 w = httptest.NewRecorder() 58 req, _ = http.NewRequestWithContext(context.Background(), health.method, 59 health.url, nil) 60 router.ServeHTTP(w, req) 61 require.Equal(t, http.StatusInternalServerError, w.Code) 62 respErr = model.HTTPError{} 63 err = json.NewDecoder(w.Body).Decode(&respErr) 64 require.Nil(t, err) 65 require.Contains(t, respErr.Code, "ErrClusterIsUnhealthy") 66 67 statusProvider.EXPECT().IsHealthy(gomock.Any()).Return(true, nil) 68 w = httptest.NewRecorder() 69 req, _ = http.NewRequestWithContext(context.Background(), health.method, 70 health.url, nil) 71 router.ServeHTTP(w, req) 72 require.Equal(t, http.StatusOK, w.Code) 73 require.Equal(t, "{}", w.Body.String()) 74 }