diff --git a/client/option_test.go b/client/option_test.go index 2a7f7824e12..1b5604f4d19 100644 --- a/client/option_test.go +++ b/client/option_test.go @@ -45,7 +45,7 @@ func TestDynamicOptionChange(t *testing.T) { expectBool := true o.setEnableTSOFollowerProxy(expectBool) // Check the value changing notification. - testutil.WaitUntil(t, func() bool { + testutil.Eventually(re, func() bool { <-o.enableTSOFollowerProxyCh return true }) diff --git a/client/testutil/testutil.go b/client/testutil/testutil.go index 095a31ae74a..79a3c9eb913 100644 --- a/client/testutil/testutil.go +++ b/client/testutil/testutil.go @@ -15,49 +15,47 @@ package testutil import ( - "testing" "time" + + "github.com/stretchr/testify/require" ) const ( - waitMaxRetry = 200 - waitRetrySleep = time.Millisecond * 100 + defaultWaitFor = time.Second * 20 + defaultSleepInterval = time.Millisecond * 100 ) -// WaitOp represents available options when execute WaitUntil +// WaitOp represents available options when execute Eventually. type WaitOp struct { - retryTimes int + waitFor time.Duration sleepInterval time.Duration } // WaitOption configures WaitOp type WaitOption func(op *WaitOp) -// WithRetryTimes specify the retry times -func WithRetryTimes(retryTimes int) WaitOption { - return func(op *WaitOp) { op.retryTimes = retryTimes } -} - // WithSleepInterval specify the sleep duration func WithSleepInterval(sleep time.Duration) WaitOption { return func(op *WaitOp) { op.sleepInterval = sleep } } -// WaitUntil repeatedly evaluates f() for a period of time, util it returns true. -func WaitUntil(t *testing.T, f func() bool, opts ...WaitOption) { - t.Log("wait start") +// WithWaitFor specify the max wait for duration +func WithWaitFor(waitFor time.Duration) WaitOption { + return func(op *WaitOp) { op.waitFor = waitFor } +} + +// Eventually asserts that given condition will be met in a period of time. +func Eventually(re *require.Assertions, condition func() bool, opts ...WaitOption) { option := &WaitOp{ - retryTimes: waitMaxRetry, - sleepInterval: waitRetrySleep, + waitFor: defaultWaitFor, + sleepInterval: defaultSleepInterval, } for _, opt := range opts { opt(option) } - for i := 0; i < option.retryTimes; i++ { - if f() { - return - } - time.Sleep(option.sleepInterval) - } - t.Fatal("wait timeout") + re.Eventually( + condition, + option.waitFor, + option.sleepInterval, + ) } diff --git a/pkg/testutil/api_check.go b/pkg/testutil/api_check.go index cbe0e01d166..015b7168a8c 100644 --- a/pkg/testutil/api_check.go +++ b/pkg/testutil/api_check.go @@ -18,69 +18,67 @@ import ( "encoding/json" "io" "net/http" - "strings" - "github.com/pingcap/check" + "github.com/stretchr/testify/require" "github.com/tikv/pd/pkg/apiutil" ) // Status is used to check whether http response code is equal given code -func Status(c *check.C, code int) func([]byte, int) { +func Status(re *require.Assertions, code int) func([]byte, int) { return func(_ []byte, i int) { - c.Assert(i, check.Equals, code) + re.Equal(code, i) } } // StatusOK is used to check whether http response code is equal http.StatusOK -func StatusOK(c *check.C) func([]byte, int) { - return Status(c, http.StatusOK) +func StatusOK(re *require.Assertions) func([]byte, int) { + return Status(re, http.StatusOK) } // StatusNotOK is used to check whether http response code is not equal http.StatusOK -func StatusNotOK(c *check.C) func([]byte, int) { +func StatusNotOK(re *require.Assertions) func([]byte, int) { return func(_ []byte, i int) { - c.Assert(i == http.StatusOK, check.IsFalse) + re.NotEqual(http.StatusOK, i) } } // ExtractJSON is used to check whether given data can be extracted successfully -func ExtractJSON(c *check.C, data interface{}) func([]byte, int) { +func ExtractJSON(re *require.Assertions, data interface{}) func([]byte, int) { return func(res []byte, _ int) { - err := json.Unmarshal(res, data) - c.Assert(err, check.IsNil) + re.NoError(json.Unmarshal(res, data)) } } // StringContain is used to check whether response context contains given string -func StringContain(c *check.C, sub string) func([]byte, int) { +func StringContain(re *require.Assertions, sub string) func([]byte, int) { return func(res []byte, _ int) { - c.Assert(strings.Contains(string(res), sub), check.IsTrue) + re.Contains(string(res), sub) } } // StringEqual is used to check whether response context equal given string -func StringEqual(c *check.C, str string) func([]byte, int) { +func StringEqual(re *require.Assertions, str string) func([]byte, int) { return func(res []byte, _ int) { - c.Assert(strings.Contains(string(res), str), check.IsTrue) + re.Contains(string(res), str) } } // ReadGetJSON is used to do get request and check whether given data can be extracted successfully -func ReadGetJSON(c *check.C, client *http.Client, url string, data interface{}) error { +func ReadGetJSON(re *require.Assertions, client *http.Client, url string, data interface{}) error { resp, err := apiutil.GetJSON(client, url, nil) if err != nil { return err } - return checkResp(resp, StatusOK(c), ExtractJSON(c, data)) + return checkResp(resp, StatusOK(re), ExtractJSON(re, data)) } // ReadGetJSONWithBody is used to do get request with input and check whether given data can be extracted successfully -func ReadGetJSONWithBody(c *check.C, client *http.Client, url string, input []byte, data interface{}) error { +func ReadGetJSONWithBody(re *require.Assertions, client *http.Client, url string, input []byte, data interface{}) error { resp, err := apiutil.GetJSON(client, url, input) if err != nil { return err } - return checkResp(resp, StatusOK(c), ExtractJSON(c, data)) + return checkResp(resp, StatusOK(re), ExtractJSON(re, data)) } // CheckPostJSON is used to do post request and do check options diff --git a/pkg/testutil/testutil.go b/pkg/testutil/testutil.go index 59063aa5385..236438ecfd1 100644 --- a/pkg/testutil/testutil.go +++ b/pkg/testutil/testutil.go @@ -104,16 +104,7 @@ func NewRequestHeader(clusterID uint64) *pdpb.RequestHeader { } // MustNewGrpcClient must create a new grpc client. -func MustNewGrpcClient(c *check.C, addr string) pdpb.PDClient { - conn, err := grpc.Dial(strings.TrimPrefix(addr, "http://"), grpc.WithInsecure()) - - c.Assert(err, check.IsNil) - return pdpb.NewPDClient(conn) -} - -// MustNewGrpcClientWithTestify must create a new grpc client. -// NOTICE: this is a temporary function that we will be used to replace `MustNewGrpcClient` later. -func MustNewGrpcClientWithTestify(re *require.Assertions, addr string) pdpb.PDClient { +func MustNewGrpcClient(re *require.Assertions, addr string) pdpb.PDClient { conn, err := grpc.Dial(strings.TrimPrefix(addr, "http://"), grpc.WithInsecure()) re.NoError(err) diff --git a/pkg/typeutil/duration_test.go b/pkg/typeutil/duration_test.go index f815b29ab6b..9a0beda7979 100644 --- a/pkg/typeutil/duration_test.go +++ b/pkg/typeutil/duration_test.go @@ -32,7 +32,7 @@ func TestDurationJSON(t *testing.T) { example := &example{} text := []byte(`{"interval":"1h1m1s"}`) - re.Nil(json.Unmarshal(text, example)) + re.NoError(json.Unmarshal(text, example)) re.Equal(float64(60*60+60+1), example.Interval.Seconds()) b, err := json.Marshal(example) diff --git a/server/api/admin_test.go b/server/api/admin_test.go index 1ece28a5239..ba9aaa875a4 100644 --- a/server/api/admin_test.go +++ b/server/api/admin_test.go @@ -18,39 +18,44 @@ import ( "encoding/json" "fmt" "net/http" + "testing" "time" - . "github.com/pingcap/check" "github.com/pingcap/kvproto/pkg/metapb" + "github.com/stretchr/testify/suite" tu "github.com/tikv/pd/pkg/testutil" "github.com/tikv/pd/server" "github.com/tikv/pd/server/core" ) -var _ = Suite(&testAdminSuite{}) - -type testAdminSuite struct { +type adminTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testAdminSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c) - mustWaitLeader(c, []*server.Server{s.svr}) +func TestAdminTestSuite(t *testing.T) { + suite.Run(t, new(adminTestSuite)) +} + +func (suite *adminTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) - mustBootstrapCluster(c, s.svr) + mustBootstrapCluster(re, suite.svr) } -func (s *testAdminSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *adminTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *testAdminSuite) TestDropRegion(c *C) { - cluster := s.svr.GetRaftCluster() +func (suite *adminTestSuite) TestDropRegion() { + cluster := suite.svr.GetRaftCluster() // Update region's epoch to (100, 100). region := cluster.GetRegionByKey([]byte("foo")).Clone( @@ -63,7 +68,7 @@ func (s *testAdminSuite) TestDropRegion(c *C) { }, })) err := cluster.HandleRegionHeartbeat(region) - c.Assert(err, IsNil) + suite.NoError(err) // Region epoch cannot decrease. region = region.Clone( @@ -71,39 +76,32 @@ func (s *testAdminSuite) TestDropRegion(c *C) { core.SetRegionVersion(50), ) err = cluster.HandleRegionHeartbeat(region) - c.Assert(err, NotNil) + suite.Error(err) // After drop region from cache, lower version is accepted. - url := fmt.Sprintf("%s/admin/cache/region/%d", s.urlPrefix, region.GetID()) + url := fmt.Sprintf("%s/admin/cache/region/%d", suite.urlPrefix, region.GetID()) req, err := http.NewRequest(http.MethodDelete, url, nil) - c.Assert(err, IsNil) + suite.NoError(err) res, err := testDialClient.Do(req) - c.Assert(err, IsNil) - c.Assert(res.StatusCode, Equals, http.StatusOK) + suite.NoError(err) + suite.Equal(http.StatusOK, res.StatusCode) res.Body.Close() err = cluster.HandleRegionHeartbeat(region) - c.Assert(err, IsNil) + suite.NoError(err) region = cluster.GetRegionByKey([]byte("foo")) - c.Assert(region.GetRegionEpoch().ConfVer, Equals, uint64(50)) - c.Assert(region.GetRegionEpoch().Version, Equals, uint64(50)) + suite.Equal(uint64(50), region.GetRegionEpoch().ConfVer) + suite.Equal(uint64(50), region.GetRegionEpoch().Version) } -func (s *testAdminSuite) TestPersistFile(c *C) { +func (suite *adminTestSuite) TestPersistFile() { data := []byte("#!/bin/sh\nrm -rf /") - err := tu.CheckPostJSON(testDialClient, s.urlPrefix+"/admin/persist-file/fun.sh", data, tu.StatusNotOK(c)) - c.Assert(err, IsNil) + re := suite.Require() + err := tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/admin/persist-file/fun.sh", data, tu.StatusNotOK(re)) + suite.NoError(err) data = []byte(`{"foo":"bar"}`) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/admin/persist-file/good.json", data, tu.StatusOK(c)) - c.Assert(err, IsNil) -} - -var _ = Suite(&testTSOSuite{}) - -type testTSOSuite struct { - svr *server.Server - cleanup cleanUpFunc - urlPrefix string + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/admin/persist-file/good.json", data, tu.StatusOK(re)) + suite.NoError(err) } func makeTS(offset time.Duration) uint64 { @@ -111,62 +109,49 @@ func makeTS(offset time.Duration) uint64 { return uint64(physical << 18) } -func (s *testTSOSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c) - mustWaitLeader(c, []*server.Server{s.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1/admin/reset-ts", addr, apiPrefix) - - mustBootstrapCluster(c, s.svr) - mustPutStore(c, s.svr, 1, metapb.StoreState_Up, metapb.NodeState_Serving, nil) -} - -func (s *testTSOSuite) TearDownSuite(c *C) { - s.cleanup() -} - -func (s *testTSOSuite) TestResetTS(c *C) { +func (suite *adminTestSuite) TestResetTS() { args := make(map[string]interface{}) t1 := makeTS(time.Hour) - url := s.urlPrefix + url := fmt.Sprintf("%s/admin/reset-ts", suite.urlPrefix) args["tso"] = fmt.Sprintf("%d", t1) values, err := json.Marshal(args) - c.Assert(err, IsNil) + suite.NoError(err) + re := suite.Require() err = tu.CheckPostJSON(testDialClient, url, values, - tu.StatusOK(c), - tu.StringEqual(c, "\"Reset ts successfully.\"\n")) - c.Assert(err, IsNil) + tu.StatusOK(re), + tu.StringEqual(re, "\"Reset ts successfully.\"\n")) + suite.NoError(err) t2 := makeTS(32 * time.Hour) args["tso"] = fmt.Sprintf("%d", t2) values, err = json.Marshal(args) - c.Assert(err, IsNil) + suite.NoError(err) err = tu.CheckPostJSON(testDialClient, url, values, - tu.Status(c, http.StatusForbidden), - tu.StringContain(c, "too large")) - c.Assert(err, IsNil) + tu.Status(re, http.StatusForbidden), + tu.StringContain(re, "too large")) + suite.NoError(err) t3 := makeTS(-2 * time.Hour) args["tso"] = fmt.Sprintf("%d", t3) values, err = json.Marshal(args) - c.Assert(err, IsNil) + suite.NoError(err) err = tu.CheckPostJSON(testDialClient, url, values, - tu.Status(c, http.StatusForbidden), - tu.StringContain(c, "small")) - c.Assert(err, IsNil) + tu.Status(re, http.StatusForbidden), + tu.StringContain(re, "small")) + suite.NoError(err) args["tso"] = "" values, err = json.Marshal(args) - c.Assert(err, IsNil) + suite.NoError(err) err = tu.CheckPostJSON(testDialClient, url, values, - tu.Status(c, http.StatusBadRequest), - tu.StringEqual(c, "\"invalid tso value\"\n")) - c.Assert(err, IsNil) + tu.Status(re, http.StatusBadRequest), + tu.StringEqual(re, "\"invalid tso value\"\n")) + suite.NoError(err) args["tso"] = "test" values, err = json.Marshal(args) - c.Assert(err, IsNil) + suite.NoError(err) err = tu.CheckPostJSON(testDialClient, url, values, - tu.Status(c, http.StatusBadRequest), - tu.StringEqual(c, "\"invalid tso value\"\n")) - c.Assert(err, IsNil) + tu.Status(re, http.StatusBadRequest), + tu.StringEqual(re, "\"invalid tso value\"\n")) + suite.NoError(err) } diff --git a/server/api/checker_test.go b/server/api/checker_test.go index 99fbb9ee68a..a3ab815ffb7 100644 --- a/server/api/checker_test.go +++ b/server/api/checker_test.go @@ -17,40 +17,45 @@ package api import ( "encoding/json" "fmt" + "testing" "time" - . "github.com/pingcap/check" "github.com/pingcap/kvproto/pkg/metapb" + "github.com/stretchr/testify/suite" tu "github.com/tikv/pd/pkg/testutil" "github.com/tikv/pd/server" ) -var _ = Suite(&testCheckerSuite{}) - -type testCheckerSuite struct { +type checkerTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testCheckerSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c) - mustWaitLeader(c, []*server.Server{s.svr}) +func TestCheckerTestSuite(t *testing.T) { + suite.Run(t, new(checkerTestSuite)) +} + +func (suite *checkerTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1/checker", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1/checker", addr, apiPrefix) - mustBootstrapCluster(c, s.svr) - mustPutStore(c, s.svr, 1, metapb.StoreState_Up, metapb.NodeState_Serving, nil) - mustPutStore(c, s.svr, 2, metapb.StoreState_Up, metapb.NodeState_Serving, nil) + mustBootstrapCluster(re, suite.svr) + mustPutStore(re, suite.svr, 1, metapb.StoreState_Up, metapb.NodeState_Serving, nil) + mustPutStore(re, suite.svr, 2, metapb.StoreState_Up, metapb.NodeState_Serving, nil) } -func (s *testCheckerSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *checkerTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *testCheckerSuite) TestAPI(c *C) { - s.testErrCases(c) +func (suite *checkerTestSuite) TestAPI() { + suite.testErrCases() cases := []struct { name string @@ -63,101 +68,104 @@ func (s *testCheckerSuite) TestAPI(c *C) { {name: "joint-state"}, } for _, ca := range cases { - s.testGetStatus(ca.name, c) - s.testPauseOrResume(ca.name, c) + suite.testGetStatus(ca.name) + suite.testPauseOrResume(ca.name) } } -func (s *testCheckerSuite) testErrCases(c *C) { +func (suite *checkerTestSuite) testErrCases() { // missing args input := make(map[string]interface{}) pauseArgs, err := json.Marshal(input) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/merge", pauseArgs, tu.StatusNotOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + re := suite.Require() + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/merge", pauseArgs, tu.StatusNotOK(re)) + suite.NoError(err) // negative delay input["delay"] = -10 pauseArgs, err = json.Marshal(input) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/merge", pauseArgs, tu.StatusNotOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/merge", pauseArgs, tu.StatusNotOK(re)) + suite.NoError(err) // wrong name name := "dummy" input["delay"] = 30 pauseArgs, err = json.Marshal(input) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/"+name, pauseArgs, tu.StatusNotOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/"+name, pauseArgs, tu.StatusNotOK(re)) + suite.NoError(err) input["delay"] = 0 pauseArgs, err = json.Marshal(input) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/"+name, pauseArgs, tu.StatusNotOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/"+name, pauseArgs, tu.StatusNotOK(re)) + suite.NoError(err) } -func (s *testCheckerSuite) testGetStatus(name string, c *C) { - handler := s.svr.GetHandler() +func (suite *checkerTestSuite) testGetStatus(name string) { + handler := suite.svr.GetHandler() // normal run resp := make(map[string]interface{}) - err := tu.ReadGetJSON(c, testDialClient, fmt.Sprintf("%s/%s", s.urlPrefix, name), &resp) - c.Assert(err, IsNil) - c.Assert(resp["paused"], IsFalse) + re := suite.Require() + err := tu.ReadGetJSON(re, testDialClient, fmt.Sprintf("%s/%s", suite.urlPrefix, name), &resp) + suite.NoError(err) + suite.False(resp["paused"].(bool)) // paused err = handler.PauseOrResumeChecker(name, 30) - c.Assert(err, IsNil) + suite.NoError(err) resp = make(map[string]interface{}) - err = tu.ReadGetJSON(c, testDialClient, fmt.Sprintf("%s/%s", s.urlPrefix, name), &resp) - c.Assert(err, IsNil) - c.Assert(resp["paused"], IsTrue) + err = tu.ReadGetJSON(re, testDialClient, fmt.Sprintf("%s/%s", suite.urlPrefix, name), &resp) + suite.NoError(err) + suite.True(resp["paused"].(bool)) // resumed err = handler.PauseOrResumeChecker(name, 1) - c.Assert(err, IsNil) + suite.NoError(err) time.Sleep(time.Second) resp = make(map[string]interface{}) - err = tu.ReadGetJSON(c, testDialClient, fmt.Sprintf("%s/%s", s.urlPrefix, name), &resp) - c.Assert(err, IsNil) - c.Assert(resp["paused"], IsFalse) + err = tu.ReadGetJSON(re, testDialClient, fmt.Sprintf("%s/%s", suite.urlPrefix, name), &resp) + suite.NoError(err) + suite.False(resp["paused"].(bool)) } -func (s *testCheckerSuite) testPauseOrResume(name string, c *C) { - handler := s.svr.GetHandler() +func (suite *checkerTestSuite) testPauseOrResume(name string) { + handler := suite.svr.GetHandler() input := make(map[string]interface{}) // test pause. input["delay"] = 30 pauseArgs, err := json.Marshal(input) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/"+name, pauseArgs, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + re := suite.Require() + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/"+name, pauseArgs, tu.StatusOK(re)) + suite.NoError(err) isPaused, err := handler.IsCheckerPaused(name) - c.Assert(err, IsNil) - c.Assert(isPaused, IsTrue) + suite.NoError(err) + suite.True(isPaused) input["delay"] = 1 pauseArgs, err = json.Marshal(input) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/"+name, pauseArgs, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/"+name, pauseArgs, tu.StatusOK(re)) + suite.NoError(err) time.Sleep(time.Second) isPaused, err = handler.IsCheckerPaused(name) - c.Assert(err, IsNil) - c.Assert(isPaused, IsFalse) + suite.NoError(err) + suite.False(isPaused) // test resume. input = make(map[string]interface{}) input["delay"] = 30 pauseArgs, err = json.Marshal(input) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/"+name, pauseArgs, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/"+name, pauseArgs, tu.StatusOK(re)) + suite.NoError(err) input["delay"] = 0 pauseArgs, err = json.Marshal(input) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/"+name, pauseArgs, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/"+name, pauseArgs, tu.StatusOK(re)) + suite.NoError(err) isPaused, err = handler.IsCheckerPaused(name) - c.Assert(err, IsNil) - c.Assert(isPaused, IsFalse) + suite.NoError(err) + suite.False(isPaused) } diff --git a/server/api/cluster_test.go b/server/api/cluster_test.go index d1ece1041a1..496d75e6f38 100644 --- a/server/api/cluster_test.go +++ b/server/api/cluster_test.go @@ -16,83 +16,91 @@ package api import ( "fmt" + "testing" "time" - . "github.com/pingcap/check" "github.com/pingcap/kvproto/pkg/metapb" + "github.com/stretchr/testify/suite" tu "github.com/tikv/pd/pkg/testutil" "github.com/tikv/pd/server" "github.com/tikv/pd/server/cluster" "github.com/tikv/pd/server/config" ) -var _ = Suite(&testClusterSuite{}) - -type testClusterSuite struct { +type clusterTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testClusterSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c) - mustWaitLeader(c, []*server.Server{s.svr}) +func TestClusterTestSuite(t *testing.T) { + suite.Run(t, new(clusterTestSuite)) +} + +func (suite *clusterTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) } -func (s *testClusterSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *clusterTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *testClusterSuite) TestCluster(c *C) { +func (suite *clusterTestSuite) TestCluster() { // Test get cluster status, and bootstrap cluster - s.testGetClusterStatus(c) - s.svr.GetPersistOptions().SetPlacementRuleEnabled(true) - s.svr.GetPersistOptions().GetReplicationConfig().LocationLabels = []string{"host"} - rm := s.svr.GetRaftCluster().GetRuleManager() + suite.testGetClusterStatus() + suite.svr.GetPersistOptions().SetPlacementRuleEnabled(true) + suite.svr.GetPersistOptions().GetReplicationConfig().LocationLabels = []string{"host"} + rm := suite.svr.GetRaftCluster().GetRuleManager() rule := rm.GetRule("pd", "default") rule.LocationLabels = []string{"host"} rule.Count = 1 rm.SetRule(rule) // Test set the config - url := fmt.Sprintf("%s/cluster", s.urlPrefix) + url := fmt.Sprintf("%s/cluster", suite.urlPrefix) c1 := &metapb.Cluster{} - err := tu.ReadGetJSON(c, testDialClient, url, c1) - c.Assert(err, IsNil) + re := suite.Require() + err := tu.ReadGetJSON(re, testDialClient, url, c1) + suite.NoError(err) c2 := &metapb.Cluster{} r := config.ReplicationConfig{ MaxReplicas: 6, EnablePlacementRules: true, } - c.Assert(s.svr.SetReplicationConfig(r), IsNil) - err = tu.ReadGetJSON(c, testDialClient, url, c2) - c.Assert(err, IsNil) + suite.NoError(suite.svr.SetReplicationConfig(r)) + + err = tu.ReadGetJSON(re, testDialClient, url, c2) + suite.NoError(err) c1.MaxPeerCount = 6 - c.Assert(c1, DeepEquals, c2) - c.Assert(int(r.MaxReplicas), Equals, s.svr.GetRaftCluster().GetRuleManager().GetRule("pd", "default").Count) + suite.Equal(c2, c1) + suite.Equal(int(r.MaxReplicas), suite.svr.GetRaftCluster().GetRuleManager().GetRule("pd", "default").Count) } -func (s *testClusterSuite) testGetClusterStatus(c *C) { - url := fmt.Sprintf("%s/cluster/status", s.urlPrefix) +func (suite *clusterTestSuite) testGetClusterStatus() { + url := fmt.Sprintf("%s/cluster/status", suite.urlPrefix) status := cluster.Status{} - err := tu.ReadGetJSON(c, testDialClient, url, &status) - c.Assert(err, IsNil) - c.Assert(status.RaftBootstrapTime.IsZero(), IsTrue) - c.Assert(status.IsInitialized, IsFalse) + re := suite.Require() + err := tu.ReadGetJSON(re, testDialClient, url, &status) + suite.NoError(err) + suite.True(status.RaftBootstrapTime.IsZero()) + suite.False(status.IsInitialized) now := time.Now() - mustBootstrapCluster(c, s.svr) - err = tu.ReadGetJSON(c, testDialClient, url, &status) - c.Assert(err, IsNil) - c.Assert(status.RaftBootstrapTime.After(now), IsTrue) - c.Assert(status.IsInitialized, IsFalse) - s.svr.SetReplicationConfig(config.ReplicationConfig{MaxReplicas: 1}) - err = tu.ReadGetJSON(c, testDialClient, url, &status) - c.Assert(err, IsNil) - c.Assert(status.RaftBootstrapTime.After(now), IsTrue) - c.Assert(status.IsInitialized, IsTrue) + mustBootstrapCluster(re, suite.svr) + err = tu.ReadGetJSON(re, testDialClient, url, &status) + suite.NoError(err) + suite.True(status.RaftBootstrapTime.After(now)) + suite.False(status.IsInitialized) + suite.svr.SetReplicationConfig(config.ReplicationConfig{MaxReplicas: 1}) + err = tu.ReadGetJSON(re, testDialClient, url, &status) + suite.NoError(err) + suite.True(status.RaftBootstrapTime.After(now)) + suite.True(status.IsInitialized) } diff --git a/server/api/config_test.go b/server/api/config_test.go index 7abfafd04a6..144e511979a 100644 --- a/server/api/config_test.go +++ b/server/api/config_test.go @@ -17,9 +17,10 @@ package api import ( "encoding/json" "fmt" + "testing" "time" - . "github.com/pingcap/check" + "github.com/stretchr/testify/suite" tu "github.com/tikv/pd/pkg/testutil" "github.com/tikv/pd/pkg/typeutil" "github.com/tikv/pd/server" @@ -27,65 +28,70 @@ import ( "github.com/tikv/pd/server/versioninfo" ) -var _ = Suite(&testConfigSuite{}) - -type testConfigSuite struct { +type configTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testConfigSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c, func(cfg *config.Config) { +func TestConfigTestSuite(t *testing.T) { + suite.Run(t, new(configTestSuite)) +} + +func (suite *configTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re, func(cfg *config.Config) { cfg.Replication.EnablePlacementRules = false }) - mustWaitLeader(c, []*server.Server{s.svr}) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) } -func (s *testConfigSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *configTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *testConfigSuite) TestConfigAll(c *C) { - addr := fmt.Sprintf("%s/config", s.urlPrefix) +func (suite *configTestSuite) TestConfigAll() { + re := suite.Require() + addr := fmt.Sprintf("%s/config", suite.urlPrefix) cfg := &config.Config{} - err := tu.ReadGetJSON(c, testDialClient, addr, cfg) - c.Assert(err, IsNil) + err := tu.ReadGetJSON(re, testDialClient, addr, cfg) + suite.NoError(err) // the original way r := map[string]int{"max-replicas": 5} postData, err := json.Marshal(r) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re)) + suite.NoError(err) l := map[string]interface{}{ "location-labels": "zone,rack", "region-schedule-limit": 10, } postData, err = json.Marshal(l) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re)) + suite.NoError(err) l = map[string]interface{}{ "metric-storage": "http://127.0.0.1:9090", } postData, err = json.Marshal(l) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re)) + suite.NoError(err) newCfg := &config.Config{} - err = tu.ReadGetJSON(c, testDialClient, addr, newCfg) - c.Assert(err, IsNil) + err = tu.ReadGetJSON(re, testDialClient, addr, newCfg) + suite.NoError(err) cfg.Replication.MaxReplicas = 5 cfg.Replication.LocationLabels = []string{"zone", "rack"} cfg.Schedule.RegionScheduleLimit = 10 cfg.PDServerCfg.MetricStorage = "http://127.0.0.1:9090" - c.Assert(cfg, DeepEquals, newCfg) + suite.Equal(newCfg, cfg) // the new way l = map[string]interface{}{ @@ -98,12 +104,12 @@ func (s *testConfigSuite) TestConfigAll(c *C) { "replication-mode.dr-auto-sync.label-key": "foobar", } postData, err = json.Marshal(l) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re)) + suite.NoError(err) newCfg1 := &config.Config{} - err = tu.ReadGetJSON(c, testDialClient, addr, newCfg1) - c.Assert(err, IsNil) + err = tu.ReadGetJSON(re, testDialClient, addr, newCfg1) + suite.NoError(err) cfg.Schedule.TolerantSizeRatio = 2.5 cfg.Replication.LocationLabels = []string{"idc", "host"} cfg.PDServerCfg.MetricStorage = "http://127.0.0.1:1234" @@ -111,109 +117,110 @@ func (s *testConfigSuite) TestConfigAll(c *C) { cfg.ReplicationMode.DRAutoSync.LabelKey = "foobar" cfg.ReplicationMode.ReplicationMode = "dr-auto-sync" v, err := versioninfo.ParseVersion("v4.0.0-beta") - c.Assert(err, IsNil) + suite.NoError(err) cfg.ClusterVersion = *v - c.Assert(newCfg1, DeepEquals, cfg) + suite.Equal(cfg, newCfg1) postData, err = json.Marshal(l) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re)) + suite.NoError(err) // illegal prefix l = map[string]interface{}{ "replicate.max-replicas": 1, } postData, err = json.Marshal(l) - c.Assert(err, IsNil) + suite.NoError(err) err = tu.CheckPostJSON(testDialClient, addr, postData, - tu.StatusNotOK(c), - tu.StringContain(c, "not found")) - c.Assert(err, IsNil) + tu.StatusNotOK(re), + tu.StringContain(re, "not found")) + suite.NoError(err) // update prefix directly l = map[string]interface{}{ "replication-mode": nil, } postData, err = json.Marshal(l) - c.Assert(err, IsNil) + suite.NoError(err) err = tu.CheckPostJSON(testDialClient, addr, postData, - tu.StatusNotOK(c), - tu.StringContain(c, "cannot update config prefix")) - c.Assert(err, IsNil) + tu.StatusNotOK(re), + tu.StringContain(re, "cannot update config prefix")) + suite.NoError(err) // config item not found l = map[string]interface{}{ "schedule.region-limit": 10, } postData, err = json.Marshal(l) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusNotOK(c), tu.StringContain(c, "not found")) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusNotOK(re), tu.StringContain(re, "not found")) + suite.NoError(err) } -func (s *testConfigSuite) TestConfigSchedule(c *C) { - addr := fmt.Sprintf("%s/config/schedule", s.urlPrefix) +func (suite *configTestSuite) TestConfigSchedule() { + re := suite.Require() + addr := fmt.Sprintf("%s/config/schedule", suite.urlPrefix) sc := &config.ScheduleConfig{} - c.Assert(tu.ReadGetJSON(c, testDialClient, addr, sc), IsNil) - + suite.NoError(tu.ReadGetJSON(re, testDialClient, addr, sc)) sc.MaxStoreDownTime.Duration = time.Second postData, err := json.Marshal(sc) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re)) + suite.NoError(err) sc1 := &config.ScheduleConfig{} - c.Assert(tu.ReadGetJSON(c, testDialClient, addr, sc1), IsNil) - c.Assert(*sc, DeepEquals, *sc1) + suite.NoError(tu.ReadGetJSON(re, testDialClient, addr, sc1)) + suite.Equal(*sc1, *sc) } -func (s *testConfigSuite) TestConfigReplication(c *C) { - addr := fmt.Sprintf("%s/config/replicate", s.urlPrefix) +func (suite *configTestSuite) TestConfigReplication() { + re := suite.Require() + addr := fmt.Sprintf("%s/config/replicate", suite.urlPrefix) rc := &config.ReplicationConfig{} - err := tu.ReadGetJSON(c, testDialClient, addr, rc) - c.Assert(err, IsNil) + err := tu.ReadGetJSON(re, testDialClient, addr, rc) + suite.NoError(err) rc.MaxReplicas = 5 rc1 := map[string]int{"max-replicas": 5} postData, err := json.Marshal(rc1) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re)) + suite.NoError(err) rc.LocationLabels = []string{"zone", "rack"} rc2 := map[string]string{"location-labels": "zone,rack"} postData, err = json.Marshal(rc2) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re)) + suite.NoError(err) rc.IsolationLevel = "zone" rc3 := map[string]string{"isolation-level": "zone"} postData, err = json.Marshal(rc3) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re)) + suite.NoError(err) rc4 := &config.ReplicationConfig{} - err = tu.ReadGetJSON(c, testDialClient, addr, rc4) - c.Assert(err, IsNil) + err = tu.ReadGetJSON(re, testDialClient, addr, rc4) + suite.NoError(err) - c.Assert(*rc, DeepEquals, *rc4) + suite.Equal(*rc4, *rc) } -func (s *testConfigSuite) TestConfigLabelProperty(c *C) { - addr := s.svr.GetAddr() + apiPrefix + "/api/v1/config/label-property" - +func (suite *configTestSuite) TestConfigLabelProperty() { + re := suite.Require() + addr := suite.svr.GetAddr() + apiPrefix + "/api/v1/config/label-property" loadProperties := func() config.LabelPropertyConfig { var cfg config.LabelPropertyConfig - err := tu.ReadGetJSON(c, testDialClient, addr, &cfg) - c.Assert(err, IsNil) + err := tu.ReadGetJSON(re, testDialClient, addr, &cfg) + suite.NoError(err) return cfg } cfg := loadProperties() - c.Assert(cfg, HasLen, 0) + suite.Len(cfg, 0) cmds := []string{ `{"type": "foo", "action": "set", "label-key": "zone", "label-value": "cn1"}`, @@ -221,90 +228,89 @@ func (s *testConfigSuite) TestConfigLabelProperty(c *C) { `{"type": "bar", "action": "set", "label-key": "host", "label-value": "h1"}`, } for _, cmd := range cmds { - err := tu.CheckPostJSON(testDialClient, addr, []byte(cmd), tu.StatusOK(c)) - c.Assert(err, IsNil) + err := tu.CheckPostJSON(testDialClient, addr, []byte(cmd), tu.StatusOK(re)) + suite.NoError(err) } cfg = loadProperties() - c.Assert(cfg, HasLen, 2) - c.Assert(cfg["foo"], DeepEquals, []config.StoreLabel{ + suite.Len(cfg, 2) + suite.Equal([]config.StoreLabel{ {Key: "zone", Value: "cn1"}, {Key: "zone", Value: "cn2"}, - }) - c.Assert(cfg["bar"], DeepEquals, []config.StoreLabel{{Key: "host", Value: "h1"}}) + }, cfg["foo"]) + suite.Equal([]config.StoreLabel{{Key: "host", Value: "h1"}}, cfg["bar"]) cmds = []string{ `{"type": "foo", "action": "delete", "label-key": "zone", "label-value": "cn1"}`, `{"type": "bar", "action": "delete", "label-key": "host", "label-value": "h1"}`, } for _, cmd := range cmds { - err := tu.CheckPostJSON(testDialClient, addr, []byte(cmd), tu.StatusOK(c)) - c.Assert(err, IsNil) + err := tu.CheckPostJSON(testDialClient, addr, []byte(cmd), tu.StatusOK(re)) + suite.NoError(err) } cfg = loadProperties() - c.Assert(cfg, HasLen, 1) - c.Assert(cfg["foo"], DeepEquals, []config.StoreLabel{{Key: "zone", Value: "cn2"}}) + suite.Len(cfg, 1) + suite.Equal([]config.StoreLabel{{Key: "zone", Value: "cn2"}}, cfg["foo"]) } -func (s *testConfigSuite) TestConfigDefault(c *C) { - addr := fmt.Sprintf("%s/config", s.urlPrefix) +func (suite *configTestSuite) TestConfigDefault() { + addr := fmt.Sprintf("%s/config", suite.urlPrefix) r := map[string]int{"max-replicas": 5} postData, err := json.Marshal(r) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + re := suite.Require() + err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re)) + suite.NoError(err) l := map[string]interface{}{ "location-labels": "zone,rack", "region-schedule-limit": 10, } postData, err = json.Marshal(l) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re)) + suite.NoError(err) l = map[string]interface{}{ "metric-storage": "http://127.0.0.1:9090", } postData, err = json.Marshal(l) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re)) + suite.NoError(err) - addr = fmt.Sprintf("%s/config/default", s.urlPrefix) + addr = fmt.Sprintf("%s/config/default", suite.urlPrefix) defaultCfg := &config.Config{} - err = tu.ReadGetJSON(c, testDialClient, addr, defaultCfg) - c.Assert(err, IsNil) + err = tu.ReadGetJSON(re, testDialClient, addr, defaultCfg) + suite.NoError(err) - c.Assert(defaultCfg.Replication.MaxReplicas, Equals, uint64(3)) - c.Assert(defaultCfg.Replication.LocationLabels, DeepEquals, typeutil.StringSlice([]string{})) - c.Assert(defaultCfg.Schedule.RegionScheduleLimit, Equals, uint64(2048)) - c.Assert(defaultCfg.PDServerCfg.MetricStorage, Equals, "") + suite.Equal(uint64(3), defaultCfg.Replication.MaxReplicas) + suite.Equal(typeutil.StringSlice([]string{}), defaultCfg.Replication.LocationLabels) + suite.Equal(uint64(2048), defaultCfg.Schedule.RegionScheduleLimit) + suite.Equal("", defaultCfg.PDServerCfg.MetricStorage) } -func (s *testConfigSuite) TestConfigPDServer(c *C) { - addrPost := fmt.Sprintf("%s/config", s.urlPrefix) - +func (suite *configTestSuite) TestConfigPDServer() { + re := suite.Require() + addrPost := fmt.Sprintf("%s/config", suite.urlPrefix) ms := map[string]interface{}{ "metric-storage": "", } postData, err := json.Marshal(ms) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, addrPost, postData, tu.StatusOK(c)), IsNil) - - addrGet := fmt.Sprintf("%s/config/pd-server", s.urlPrefix) + suite.NoError(err) + suite.NoError(tu.CheckPostJSON(testDialClient, addrPost, postData, tu.StatusOK(re))) + addrGet := fmt.Sprintf("%s/config/pd-server", suite.urlPrefix) sc := &config.PDServerConfig{} - c.Assert(tu.ReadGetJSON(c, testDialClient, addrGet, sc), IsNil) - - c.Assert(sc.UseRegionStorage, Equals, bool(true)) - c.Assert(sc.KeyType, Equals, "table") - c.Assert(sc.RuntimeServices, DeepEquals, typeutil.StringSlice([]string{})) - c.Assert(sc.MetricStorage, Equals, "") - c.Assert(sc.DashboardAddress, Equals, "auto") - c.Assert(sc.FlowRoundByDigit, Equals, int(3)) - c.Assert(sc.MinResolvedTSPersistenceInterval, Equals, typeutil.NewDuration(0)) - c.Assert(sc.MaxResetTSGap.Duration, Equals, 24*time.Hour) + suite.NoError(tu.ReadGetJSON(re, testDialClient, addrGet, sc)) + suite.Equal(bool(true), sc.UseRegionStorage) + suite.Equal("table", sc.KeyType) + suite.Equal(typeutil.StringSlice([]string{}), sc.RuntimeServices) + suite.Equal("", sc.MetricStorage) + suite.Equal("auto", sc.DashboardAddress) + suite.Equal(int(3), sc.FlowRoundByDigit) + suite.Equal(typeutil.NewDuration(0), sc.MinResolvedTSPersistenceInterval) + suite.Equal(24*time.Hour, sc.MaxResetTSGap.Duration) } var ttlConfig = map[string]interface{}{ @@ -324,89 +330,94 @@ var invalidTTLConfig = map[string]interface{}{ "schedule.invalid-ttl-config": 0, } -func assertTTLConfig(c *C, options *config.PersistOptions, checker Checker) { - c.Assert(options.GetMaxSnapshotCount(), checker, uint64(999)) - c.Assert(options.IsLocationReplacementEnabled(), checker, false) - c.Assert(options.GetMaxMergeRegionSize(), checker, uint64(999)) - c.Assert(options.GetMaxMergeRegionKeys(), checker, uint64(999)) - c.Assert(options.GetSchedulerMaxWaitingOperator(), checker, uint64(999)) - c.Assert(options.GetLeaderScheduleLimit(), checker, uint64(999)) - c.Assert(options.GetRegionScheduleLimit(), checker, uint64(999)) - c.Assert(options.GetHotRegionScheduleLimit(), checker, uint64(999)) - c.Assert(options.GetReplicaScheduleLimit(), checker, uint64(999)) - c.Assert(options.GetMergeScheduleLimit(), checker, uint64(999)) +func assertTTLConfig( + options *config.PersistOptions, + equality func(interface{}, interface{}, ...interface{}) bool, +) { + equality(uint64(999), options.GetMaxSnapshotCount()) + equality(false, options.IsLocationReplacementEnabled()) + equality(uint64(999), options.GetMaxMergeRegionSize()) + equality(uint64(999), options.GetMaxMergeRegionKeys()) + equality(uint64(999), options.GetSchedulerMaxWaitingOperator()) + equality(uint64(999), options.GetLeaderScheduleLimit()) + equality(uint64(999), options.GetRegionScheduleLimit()) + equality(uint64(999), options.GetHotRegionScheduleLimit()) + equality(uint64(999), options.GetReplicaScheduleLimit()) + equality(uint64(999), options.GetMergeScheduleLimit()) } func createTTLUrl(url string, ttl int) string { return fmt.Sprintf("%s/config?ttlSecond=%d", url, ttl) } -func (s *testConfigSuite) TestConfigTTL(c *C) { +func (suite *configTestSuite) TestConfigTTL() { postData, err := json.Marshal(ttlConfig) - c.Assert(err, IsNil) + suite.NoError(err) // test no config and cleaning up - err = tu.CheckPostJSON(testDialClient, createTTLUrl(s.urlPrefix, 0), postData, tu.StatusOK(c)) - c.Assert(err, IsNil) - assertTTLConfig(c, s.svr.GetPersistOptions(), Not(Equals)) + re := suite.Require() + err = tu.CheckPostJSON(testDialClient, createTTLUrl(suite.urlPrefix, 0), postData, tu.StatusOK(re)) + suite.NoError(err) + assertTTLConfig(suite.svr.GetPersistOptions(), suite.NotEqual) // test time goes by - err = tu.CheckPostJSON(testDialClient, createTTLUrl(s.urlPrefix, 1), postData, tu.StatusOK(c)) - c.Assert(err, IsNil) - assertTTLConfig(c, s.svr.GetPersistOptions(), Equals) + err = tu.CheckPostJSON(testDialClient, createTTLUrl(suite.urlPrefix, 1), postData, tu.StatusOK(re)) + suite.NoError(err) + assertTTLConfig(suite.svr.GetPersistOptions(), suite.Equal) time.Sleep(2 * time.Second) - assertTTLConfig(c, s.svr.GetPersistOptions(), Not(Equals)) + assertTTLConfig(suite.svr.GetPersistOptions(), suite.NotEqual) // test cleaning up - err = tu.CheckPostJSON(testDialClient, createTTLUrl(s.urlPrefix, 1), postData, tu.StatusOK(c)) - c.Assert(err, IsNil) - assertTTLConfig(c, s.svr.GetPersistOptions(), Equals) - err = tu.CheckPostJSON(testDialClient, createTTLUrl(s.urlPrefix, 0), postData, tu.StatusOK(c)) - c.Assert(err, IsNil) - assertTTLConfig(c, s.svr.GetPersistOptions(), Not(Equals)) + err = tu.CheckPostJSON(testDialClient, createTTLUrl(suite.urlPrefix, 1), postData, tu.StatusOK(re)) + suite.NoError(err) + assertTTLConfig(suite.svr.GetPersistOptions(), suite.Equal) + err = tu.CheckPostJSON(testDialClient, createTTLUrl(suite.urlPrefix, 0), postData, tu.StatusOK(re)) + suite.NoError(err) + assertTTLConfig(suite.svr.GetPersistOptions(), suite.NotEqual) postData, err = json.Marshal(invalidTTLConfig) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, createTTLUrl(s.urlPrefix, 1), postData, - tu.StatusNotOK(c), tu.StringEqual(c, "\"unsupported ttl config schedule.invalid-ttl-config\"\n")) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, createTTLUrl(suite.urlPrefix, 1), postData, + tu.StatusNotOK(re), tu.StringEqual(re, "\"unsupported ttl config schedule.invalid-ttl-config\"\n")) + suite.NoError(err) // only set max-merge-region-size mergeConfig := map[string]interface{}{ "schedule.max-merge-region-size": 999, } postData, err = json.Marshal(mergeConfig) - c.Assert(err, IsNil) + suite.NoError(err) - err = tu.CheckPostJSON(testDialClient, createTTLUrl(s.urlPrefix, 1), postData, tu.StatusOK(c)) - c.Assert(err, IsNil) - c.Assert(s.svr.GetPersistOptions().GetMaxMergeRegionSize(), Equals, uint64(999)) + err = tu.CheckPostJSON(testDialClient, createTTLUrl(suite.urlPrefix, 1), postData, tu.StatusOK(re)) + suite.NoError(err) + suite.Equal(uint64(999), suite.svr.GetPersistOptions().GetMaxMergeRegionSize()) // max-merge-region-keys should keep consistence with max-merge-region-size. - c.Assert(s.svr.GetPersistOptions().GetMaxMergeRegionKeys(), Equals, uint64(999*10000)) + suite.Equal(uint64(999*10000), suite.svr.GetPersistOptions().GetMaxMergeRegionKeys()) } -func (s *testConfigSuite) TestTTLConflict(c *C) { - addr := createTTLUrl(s.urlPrefix, 1) +func (suite *configTestSuite) TestTTLConflict() { + addr := createTTLUrl(suite.urlPrefix, 1) postData, err := json.Marshal(ttlConfig) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c)) - c.Assert(err, IsNil) - assertTTLConfig(c, s.svr.GetPersistOptions(), Equals) + suite.NoError(err) + re := suite.Require() + err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re)) + suite.NoError(err) + assertTTLConfig(suite.svr.GetPersistOptions(), suite.Equal) cfg := map[string]interface{}{"max-snapshot-count": 30} postData, err = json.Marshal(cfg) - c.Assert(err, IsNil) - addr = fmt.Sprintf("%s/config", s.urlPrefix) - err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusNotOK(c), tu.StringEqual(c, "\"need to clean up TTL first for schedule.max-snapshot-count\"\n")) - c.Assert(err, IsNil) - addr = fmt.Sprintf("%s/config/schedule", s.urlPrefix) - err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusNotOK(c), tu.StringEqual(c, "\"need to clean up TTL first for schedule.max-snapshot-count\"\n")) - c.Assert(err, IsNil) + suite.NoError(err) + addr = fmt.Sprintf("%s/config", suite.urlPrefix) + err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusNotOK(re), tu.StringEqual(re, "\"need to clean up TTL first for schedule.max-snapshot-count\"\n")) + suite.NoError(err) + addr = fmt.Sprintf("%s/config/schedule", suite.urlPrefix) + err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusNotOK(re), tu.StringEqual(re, "\"need to clean up TTL first for schedule.max-snapshot-count\"\n")) + suite.NoError(err) cfg = map[string]interface{}{"schedule.max-snapshot-count": 30} postData, err = json.Marshal(cfg) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, createTTLUrl(s.urlPrefix, 0), postData, tu.StatusOK(c)) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, createTTLUrl(suite.urlPrefix, 0), postData, tu.StatusOK(re)) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re)) + suite.NoError(err) } diff --git a/server/api/etcd_api_test.go b/server/api/etcd_api_test.go index 76e0dcb3af5..23406bb64cd 100644 --- a/server/api/etcd_api_test.go +++ b/server/api/etcd_api_test.go @@ -16,27 +16,25 @@ package api import ( "encoding/json" + "testing" - . "github.com/pingcap/check" + "github.com/stretchr/testify/require" tu "github.com/tikv/pd/pkg/testutil" ) -var _ = Suite(&testEtcdAPISuite{}) - -type testEtcdAPISuite struct{} - -func (s *testEtcdAPISuite) TestGRPCGateway(c *C) { - svr, clean := mustNewServer(c) +func TestGRPCGateway(t *testing.T) { + re := require.New(t) + svr, clean := mustNewServer(re) defer clean() addr := svr.GetConfig().ClientUrls + "/v3/kv/put" putKey := map[string]string{"key": "Zm9v", "value": "YmFy"} v, _ := json.Marshal(putKey) - err := tu.CheckPostJSON(testDialClient, addr, v, tu.StatusOK(c)) - c.Assert(err, IsNil) + err := tu.CheckPostJSON(testDialClient, addr, v, tu.StatusOK(re)) + re.NoError(err) addr = svr.GetConfig().ClientUrls + "/v3/kv/range" getKey := map[string]string{"key": "Zm9v"} v, _ = json.Marshal(getKey) - err = tu.CheckPostJSON(testDialClient, addr, v, tu.StatusOK(c), tu.StringContain(c, "Zm9v")) - c.Assert(err, IsNil) + err = tu.CheckPostJSON(testDialClient, addr, v, tu.StatusOK(re), tu.StringContain(re, "Zm9v")) + re.NoError(err) } diff --git a/server/api/health_test.go b/server/api/health_test.go index ec3ac54be00..6d2caec12cd 100644 --- a/server/api/health_test.go +++ b/server/api/health_test.go @@ -18,38 +18,36 @@ import ( "encoding/json" "io" "strings" + "testing" - . "github.com/pingcap/check" + "github.com/stretchr/testify/require" "github.com/tikv/pd/server" "github.com/tikv/pd/server/config" ) -var _ = Suite(&testHealthAPISuite{}) - -type testHealthAPISuite struct{} - -func checkSliceResponse(c *C, body []byte, cfgs []*config.Config, unhealthy string) { +func checkSliceResponse(re *require.Assertions, body []byte, cfgs []*config.Config, unhealthy string) { got := []Health{} - c.Assert(json.Unmarshal(body, &got), IsNil) - c.Assert(len(got), Equals, len(cfgs)) + re.NoError(json.Unmarshal(body, &got)) + re.Len(cfgs, len(got)) for _, h := range got { for _, cfg := range cfgs { if h.Name != cfg.Name { continue } - relaxEqualStings(c, h.ClientUrls, strings.Split(cfg.ClientUrls, ",")) + relaxEqualStings(re, h.ClientUrls, strings.Split(cfg.ClientUrls, ",")) } if h.Name == unhealthy { - c.Assert(h.Health, IsFalse) + re.False(h.Health) continue } - c.Assert(h.Health, IsTrue) + re.True(h.Health) } } -func (s *testHealthAPISuite) TestHealthSlice(c *C) { - cfgs, svrs, clean := mustNewCluster(c, 3) +func TestHealthSlice(t *testing.T) { + re := require.New(t) + cfgs, svrs, clean := mustNewCluster(re, 3) defer clean() var leader, follow *server.Server @@ -60,13 +58,13 @@ func (s *testHealthAPISuite) TestHealthSlice(c *C) { follow = svr } } - mustBootstrapCluster(c, leader) + mustBootstrapCluster(re, leader) addr := leader.GetConfig().ClientUrls + apiPrefix + "/api/v1/health" follow.Close() resp, err := testDialClient.Get(addr) - c.Assert(err, IsNil) + re.NoError(err) defer resp.Body.Close() buf, err := io.ReadAll(resp.Body) - c.Assert(err, IsNil) - checkSliceResponse(c, buf, cfgs, follow.GetConfig().Name) + re.NoError(err) + checkSliceResponse(re, buf, cfgs, follow.GetConfig().Name) } diff --git a/server/api/hot_status_test.go b/server/api/hot_status_test.go index 18af694fce6..66a4e29afb7 100644 --- a/server/api/hot_status_test.go +++ b/server/api/hot_status_test.go @@ -17,10 +17,10 @@ package api import ( "encoding/json" "fmt" - "reflect" + "testing" "time" - . "github.com/pingcap/check" + "github.com/stretchr/testify/suite" "github.com/syndtr/goleveldb/leveldb" tu "github.com/tikv/pd/pkg/testutil" "github.com/tikv/pd/server" @@ -29,50 +29,55 @@ import ( "github.com/tikv/pd/server/storage/kv" ) -var _ = Suite(&testHotStatusSuite{}) - -type testHotStatusSuite struct { +type hotStatusTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testHotStatusSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c) - mustWaitLeader(c, []*server.Server{s.svr}) +func TestHotStatusTestSuite(t *testing.T) { + suite.Run(t, new(hotStatusTestSuite)) +} + +func (suite *hotStatusTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1/hotspot", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1/hotspot", addr, apiPrefix) - mustBootstrapCluster(c, s.svr) + mustBootstrapCluster(re, suite.svr) } -func (s *testHotStatusSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *hotStatusTestSuite) TearDownSuite() { + suite.cleanup() } -func (s testHotStatusSuite) TestGetHotStore(c *C) { +func (suite *hotStatusTestSuite) TestGetHotStore() { stat := HotStoreStats{} - err := tu.ReadGetJSON(c, testDialClient, s.urlPrefix+"/stores", &stat) - c.Assert(err, IsNil) + err := tu.ReadGetJSON(suite.Require(), testDialClient, suite.urlPrefix+"/stores", &stat) + suite.NoError(err) } -func (s testHotStatusSuite) TestGetHistoryHotRegionsBasic(c *C) { +func (suite *hotStatusTestSuite) TestGetHistoryHotRegionsBasic() { request := HistoryHotRegionsRequest{ StartTime: 0, EndTime: time.Now().AddDate(0, 2, 0).UnixNano() / int64(time.Millisecond), } data, err := json.Marshal(request) - c.Assert(err, IsNil) - err = tu.CheckGetJSON(testDialClient, s.urlPrefix+"/regions/history", data, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + re := suite.Require() + err = tu.CheckGetJSON(testDialClient, suite.urlPrefix+"/regions/history", data, tu.StatusOK(re)) + suite.NoError(err) errRequest := "{\"start_time\":\"err\"}" - err = tu.CheckGetJSON(testDialClient, s.urlPrefix+"/regions/history", []byte(errRequest), tu.StatusNotOK(c)) - c.Assert(err, IsNil) + err = tu.CheckGetJSON(testDialClient, suite.urlPrefix+"/regions/history", []byte(errRequest), tu.StatusNotOK(re)) + suite.NoError(err) } -func (s testHotStatusSuite) TestGetHistoryHotRegionsTimeRange(c *C) { - hotRegionStorage := s.svr.GetHistoryHotRegionStorage() +func (suite *hotStatusTestSuite) TestGetHistoryHotRegionsTimeRange() { + hotRegionStorage := suite.svr.GetHistoryHotRegionStorage() now := time.Now() hotRegions := []*storage.HistoryHotRegion{ { @@ -89,24 +94,24 @@ func (s testHotStatusSuite) TestGetHistoryHotRegionsTimeRange(c *C) { EndTime: now.Add(10*time.Second).UnixNano() / int64(time.Millisecond), } check := func(res []byte, statusCode int) { - c.Assert(statusCode, Equals, 200) + suite.Equal(200, statusCode) historyHotRegions := &storage.HistoryHotRegions{} json.Unmarshal(res, historyHotRegions) for _, region := range historyHotRegions.HistoryHotRegion { - c.Assert(region.UpdateTime, GreaterEqual, request.StartTime) - c.Assert(region.UpdateTime, LessEqual, request.EndTime) + suite.GreaterOrEqual(region.UpdateTime, request.StartTime) + suite.LessOrEqual(region.UpdateTime, request.EndTime) } } err := writeToDB(hotRegionStorage.LevelDBKV, hotRegions) - c.Assert(err, IsNil) + suite.NoError(err) data, err := json.Marshal(request) - c.Assert(err, IsNil) - err = tu.CheckGetJSON(testDialClient, s.urlPrefix+"/regions/history", data, check) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckGetJSON(testDialClient, suite.urlPrefix+"/regions/history", data, check) + suite.NoError(err) } -func (s testHotStatusSuite) TestGetHistoryHotRegionsIDAndTypes(c *C) { - hotRegionStorage := s.svr.GetHistoryHotRegionStorage() +func (suite *hotStatusTestSuite) TestGetHistoryHotRegionsIDAndTypes() { + hotRegionStorage := suite.svr.GetHistoryHotRegionStorage() now := time.Now() hotRegions := []*storage.HistoryHotRegion{ { @@ -174,18 +179,18 @@ func (s testHotStatusSuite) TestGetHistoryHotRegionsIDAndTypes(c *C) { EndTime: now.Add(10*time.Minute).UnixNano() / int64(time.Millisecond), } check := func(res []byte, statusCode int) { - c.Assert(statusCode, Equals, 200) + suite.Equal(200, statusCode) historyHotRegions := &storage.HistoryHotRegions{} json.Unmarshal(res, historyHotRegions) - c.Assert(historyHotRegions.HistoryHotRegion, HasLen, 1) - c.Assert(reflect.DeepEqual(historyHotRegions.HistoryHotRegion[0], hotRegions[0]), IsTrue) + suite.Len(historyHotRegions.HistoryHotRegion, 1) + suite.Equal(hotRegions[0], historyHotRegions.HistoryHotRegion[0]) } err := writeToDB(hotRegionStorage.LevelDBKV, hotRegions) - c.Assert(err, IsNil) + suite.NoError(err) data, err := json.Marshal(request) - c.Assert(err, IsNil) - err = tu.CheckGetJSON(testDialClient, s.urlPrefix+"/regions/history", data, check) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckGetJSON(testDialClient, suite.urlPrefix+"/regions/history", data, check) + suite.NoError(err) } func writeToDB(kv *kv.LevelDBKV, hotRegions []*storage.HistoryHotRegion) error { diff --git a/server/api/label_test.go b/server/api/label_test.go index 12933d17e64..b9503871a5a 100644 --- a/server/api/label_test.go +++ b/server/api/label_test.go @@ -17,28 +17,30 @@ package api import ( "context" "fmt" - "strings" + "testing" - . "github.com/pingcap/check" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" + "github.com/stretchr/testify/suite" tu "github.com/tikv/pd/pkg/testutil" "github.com/tikv/pd/server" "github.com/tikv/pd/server/config" ) -var _ = Suite(&testLabelsStoreSuite{}) -var _ = Suite(&testStrictlyLabelsStoreSuite{}) - -type testLabelsStoreSuite struct { +type labelsStoreTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string stores []*metapb.Store } -func (s *testLabelsStoreSuite) SetUpSuite(c *C) { - s.stores = []*metapb.Store{ +func TestLabelsStoreTestSuite(t *testing.T) { + suite.Run(t, new(labelsStoreTestSuite)) +} + +func (suite *labelsStoreTestSuite) SetupSuite() { + suite.stores = []*metapb.Store{ { Id: 1, Address: "tikv1", @@ -113,58 +115,58 @@ func (s *testLabelsStoreSuite) SetUpSuite(c *C) { }, } - s.svr, s.cleanup = mustNewServer(c, func(cfg *config.Config) { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re, func(cfg *config.Config) { cfg.Replication.StrictlyMatchLabel = false }) - mustWaitLeader(c, []*server.Server{s.svr}) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) - mustBootstrapCluster(c, s.svr) - for _, store := range s.stores { - mustPutStore(c, s.svr, store.Id, store.State, store.NodeState, store.Labels) + mustBootstrapCluster(re, suite.svr) + for _, store := range suite.stores { + mustPutStore(re, suite.svr, store.Id, store.State, store.NodeState, store.Labels) } } -func (s *testLabelsStoreSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *labelsStoreTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *testLabelsStoreSuite) TestLabelsGet(c *C) { - url := fmt.Sprintf("%s/labels", s.urlPrefix) - labels := make([]*metapb.StoreLabel, 0, len(s.stores)) - err := tu.ReadGetJSON(c, testDialClient, url, &labels) - c.Assert(err, IsNil) +func (suite *labelsStoreTestSuite) TestLabelsGet() { + url := fmt.Sprintf("%s/labels", suite.urlPrefix) + labels := make([]*metapb.StoreLabel, 0, len(suite.stores)) + suite.NoError(tu.ReadGetJSON(suite.Require(), testDialClient, url, &labels)) } -func (s *testLabelsStoreSuite) TestStoresLabelFilter(c *C) { +func (suite *labelsStoreTestSuite) TestStoresLabelFilter() { var table = []struct { name, value string want []*metapb.Store }{ { name: "Zone", - want: s.stores, + want: suite.stores, }, { name: "other", - want: s.stores[3:], + want: suite.stores[3:], }, { name: "zone", value: "Us-west-1", - want: s.stores[:1], + want: suite.stores[:1], }, { name: "Zone", value: "west", - want: s.stores[:2], + want: suite.stores[:2], }, { name: "Zo", value: "Beijing", - want: s.stores[2:3], + want: suite.stores[2:3], }, { name: "ZONE", @@ -172,40 +174,47 @@ func (s *testLabelsStoreSuite) TestStoresLabelFilter(c *C) { want: []*metapb.Store{}, }, } + re := suite.Require() for _, t := range table { - url := fmt.Sprintf("%s/labels/stores?name=%s&value=%s", s.urlPrefix, t.name, t.value) + url := fmt.Sprintf("%s/labels/stores?name=%s&value=%s", suite.urlPrefix, t.name, t.value) info := new(StoresInfo) - err := tu.ReadGetJSON(c, testDialClient, url, info) - c.Assert(err, IsNil) - checkStoresInfo(c, info.Stores, t.want) + err := tu.ReadGetJSON(re, testDialClient, url, info) + suite.NoError(err) + checkStoresInfo(re, info.Stores, t.want) } _, err := newStoresLabelFilter("test", ".[test") - c.Assert(err, NotNil) + suite.Error(err) } -type testStrictlyLabelsStoreSuite struct { +type strictlyLabelsStoreTestSuite struct { + suite.Suite svr *server.Server grpcSvr *server.GrpcServer cleanup cleanUpFunc urlPrefix string } -func (s *testStrictlyLabelsStoreSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c, func(cfg *config.Config) { +func TestStrictlyLabelsStoreTestSuite(t *testing.T) { + suite.Run(t, new(strictlyLabelsStoreTestSuite)) +} + +func (suite *strictlyLabelsStoreTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re, func(cfg *config.Config) { cfg.Replication.LocationLabels = []string{"zone", "disk"} cfg.Replication.StrictlyMatchLabel = true cfg.Replication.EnablePlacementRules = false }) - mustWaitLeader(c, []*server.Server{s.svr}) + mustWaitLeader(re, []*server.Server{suite.svr}) - s.grpcSvr = &server.GrpcServer{Server: s.svr} - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) + suite.grpcSvr = &server.GrpcServer{Server: suite.svr} + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) - mustBootstrapCluster(c, s.svr) + mustBootstrapCluster(re, suite.svr) } -func (s *testStrictlyLabelsStoreSuite) TestStoreMatch(c *C) { +func (suite *strictlyLabelsStoreTestSuite) TestStoreMatch() { cases := []struct { store *metapb.Store valid bool @@ -268,8 +277,8 @@ func (s *testStrictlyLabelsStoreSuite) TestStoreMatch(c *C) { } for _, t := range cases { - _, err := s.grpcSvr.PutStore(context.Background(), &pdpb.PutStoreRequest{ - Header: &pdpb.RequestHeader{ClusterId: s.svr.ClusterID()}, + _, err := suite.grpcSvr.PutStore(context.Background(), &pdpb.PutStoreRequest{ + Header: &pdpb.RequestHeader{ClusterId: suite.svr.ClusterID()}, Store: &metapb.Store{ Id: t.store.Id, Address: fmt.Sprintf("tikv%d", t.store.Id), @@ -279,17 +288,21 @@ func (s *testStrictlyLabelsStoreSuite) TestStoreMatch(c *C) { }, }) if t.valid { - c.Assert(err, IsNil) + suite.NoError(err) } else { - c.Assert(strings.Contains(err.Error(), t.expectError), IsTrue) + suite.Contains(err.Error(), t.expectError) } } // enable placement rules. Report no error any more. - c.Assert(tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/config", s.urlPrefix), []byte(`{"enable-placement-rules":"true"}`), tu.StatusOK(c)), IsNil) + suite.NoError(tu.CheckPostJSON( + testDialClient, + fmt.Sprintf("%s/config", suite.urlPrefix), + []byte(`{"enable-placement-rules":"true"}`), + tu.StatusOK(suite.Require()))) for _, t := range cases { - _, err := s.grpcSvr.PutStore(context.Background(), &pdpb.PutStoreRequest{ - Header: &pdpb.RequestHeader{ClusterId: s.svr.ClusterID()}, + _, err := suite.grpcSvr.PutStore(context.Background(), &pdpb.PutStoreRequest{ + Header: &pdpb.RequestHeader{ClusterId: suite.svr.ClusterID()}, Store: &metapb.Store{ Id: t.store.Id, Address: fmt.Sprintf("tikv%d", t.store.Id), @@ -299,13 +312,13 @@ func (s *testStrictlyLabelsStoreSuite) TestStoreMatch(c *C) { }, }) if t.valid { - c.Assert(err, IsNil) + suite.NoError(err) } else { - c.Assert(strings.Contains(err.Error(), t.expectError), IsTrue) + suite.Contains(err.Error(), t.expectError) } } } -func (s *testStrictlyLabelsStoreSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *strictlyLabelsStoreTestSuite) TearDownSuite() { + suite.cleanup() } diff --git a/server/api/log_test.go b/server/api/log_test.go index afd65bb35b3..f03472b8146 100644 --- a/server/api/log_test.go +++ b/server/api/log_test.go @@ -17,40 +17,45 @@ package api import ( "encoding/json" "fmt" + "testing" - . "github.com/pingcap/check" "github.com/pingcap/log" + "github.com/stretchr/testify/suite" tu "github.com/tikv/pd/pkg/testutil" "github.com/tikv/pd/server" ) -var _ = Suite(&testLogSuite{}) - -type testLogSuite struct { +type logTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testLogSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c) - mustWaitLeader(c, []*server.Server{s.svr}) +func TestLogTestSuite(t *testing.T) { + suite.Run(t, new(logTestSuite)) +} + +func (suite *logTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1/admin", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1/admin", addr, apiPrefix) - mustBootstrapCluster(c, s.svr) + mustBootstrapCluster(re, suite.svr) } -func (s *testLogSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *logTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *testLogSuite) TestSetLogLevel(c *C) { +func (suite *logTestSuite) TestSetLogLevel() { level := "error" data, err := json.Marshal(level) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/log", data, tu.StatusOK(c)) - c.Assert(err, IsNil) - c.Assert(log.GetLevel().String(), Equals, level) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/log", data, tu.StatusOK(suite.Require())) + suite.NoError(err) + suite.Equal(level, log.GetLevel().String()) } diff --git a/server/api/member_test.go b/server/api/member_test.go index bffad22380b..1132010319d 100644 --- a/server/api/member_test.go +++ b/server/api/member_test.go @@ -23,24 +23,28 @@ import ( "net/http" "sort" "strings" + "testing" - . "github.com/pingcap/check" "github.com/pingcap/kvproto/pkg/pdpb" + "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" "github.com/tikv/pd/server" "github.com/tikv/pd/server/config" ) -var _ = Suite(&testMemberAPISuite{}) -var _ = Suite(&testResignAPISuite{}) - -type testMemberAPISuite struct { +type memberTestSuite struct { + suite.Suite cfgs []*config.Config servers []*server.Server clean func() } -func (s *testMemberAPISuite) SetUpSuite(c *C) { - s.cfgs, s.servers, s.clean = mustNewCluster(c, 3, func(cfg *config.Config) { +func TestMemberTestSuite(t *testing.T) { + suite.Run(t, new(memberTestSuite)) +} + +func (suite *memberTestSuite) SetupSuite() { + suite.cfgs, suite.servers, suite.clean = mustNewCluster(suite.Require(), 3, func(cfg *config.Config) { cfg.EnableLocalTSO = true cfg.Labels = map[string]string{ config.ZoneLabel: "dc-1", @@ -48,128 +52,132 @@ func (s *testMemberAPISuite) SetUpSuite(c *C) { }) } -func (s *testMemberAPISuite) TearDownSuite(c *C) { - s.clean() +func (suite *memberTestSuite) TearDownSuite() { + suite.clean() } -func relaxEqualStings(c *C, a, b []string) { +func relaxEqualStings(re *require.Assertions, a, b []string) { sort.Strings(a) sortedStringA := strings.Join(a, "") sort.Strings(b) sortedStringB := strings.Join(b, "") - c.Assert(sortedStringA, Equals, sortedStringB) + re.Equal(sortedStringB, sortedStringA) } -func checkListResponse(c *C, body []byte, cfgs []*config.Config) { +func (suite *memberTestSuite) checkListResponse(body []byte, cfgs []*config.Config) { got := make(map[string][]*pdpb.Member) json.Unmarshal(body, &got) - - c.Assert(len(got["members"]), Equals, len(cfgs)) - + suite.Len(cfgs, len(got["members"])) + re := suite.Require() for _, member := range got["members"] { for _, cfg := range cfgs { if member.GetName() != cfg.Name { continue } - c.Assert(member.DcLocation, Equals, "dc-1") - relaxEqualStings(c, member.ClientUrls, strings.Split(cfg.ClientUrls, ",")) - relaxEqualStings(c, member.PeerUrls, strings.Split(cfg.PeerUrls, ",")) + suite.Equal("dc-1", member.DcLocation) + relaxEqualStings(re, member.ClientUrls, strings.Split(cfg.ClientUrls, ",")) + relaxEqualStings(re, member.PeerUrls, strings.Split(cfg.PeerUrls, ",")) } } } -func (s *testMemberAPISuite) TestMemberList(c *C) { - for _, cfg := range s.cfgs { +func (suite *memberTestSuite) TestMemberList() { + for _, cfg := range suite.cfgs { addr := cfg.ClientUrls + apiPrefix + "/api/v1/members" resp, err := testDialClient.Get(addr) - c.Assert(err, IsNil) + suite.NoError(err) buf, err := io.ReadAll(resp.Body) - c.Assert(err, IsNil) + suite.NoError(err) resp.Body.Close() - checkListResponse(c, buf, s.cfgs) + suite.checkListResponse(buf, suite.cfgs) } } -func (s *testMemberAPISuite) TestMemberLeader(c *C) { - leader := s.servers[0].GetLeader() - addr := s.cfgs[rand.Intn(len(s.cfgs))].ClientUrls + apiPrefix + "/api/v1/leader" +func (suite *memberTestSuite) TestMemberLeader() { + leader := suite.servers[0].GetLeader() + addr := suite.cfgs[rand.Intn(len(suite.cfgs))].ClientUrls + apiPrefix + "/api/v1/leader" resp, err := testDialClient.Get(addr) - c.Assert(err, IsNil) + suite.NoError(err) defer resp.Body.Close() buf, err := io.ReadAll(resp.Body) - c.Assert(err, IsNil) + suite.NoError(err) var got pdpb.Member - c.Assert(json.Unmarshal(buf, &got), IsNil) - c.Assert(got.GetClientUrls(), DeepEquals, leader.GetClientUrls()) - c.Assert(got.GetMemberId(), Equals, leader.GetMemberId()) + suite.NoError(json.Unmarshal(buf, &got)) + suite.Equal(leader.GetClientUrls(), got.GetClientUrls()) + suite.Equal(leader.GetMemberId(), got.GetMemberId()) } -func (s *testMemberAPISuite) TestChangeLeaderPeerUrls(c *C) { - leader := s.servers[0].GetLeader() - addr := s.cfgs[rand.Intn(len(s.cfgs))].ClientUrls + apiPrefix + "/api/v1/leader" +func (suite *memberTestSuite) TestChangeLeaderPeerUrls() { + leader := suite.servers[0].GetLeader() + addr := suite.cfgs[rand.Intn(len(suite.cfgs))].ClientUrls + apiPrefix + "/api/v1/leader" resp, err := testDialClient.Get(addr) - c.Assert(err, IsNil) + suite.NoError(err) defer resp.Body.Close() buf, err := io.ReadAll(resp.Body) - c.Assert(err, IsNil) + suite.NoError(err) var got pdpb.Member - c.Assert(json.Unmarshal(buf, &got), IsNil) + suite.NoError(json.Unmarshal(buf, &got)) id := got.GetMemberId() peerUrls := got.GetPeerUrls() newPeerUrls := []string{"http://127.0.0.1:1111"} - changeLeaderPeerUrls(c, leader, id, newPeerUrls) - addr = s.cfgs[rand.Intn(len(s.cfgs))].ClientUrls + apiPrefix + "/api/v1/members" + suite.changeLeaderPeerUrls(leader, id, newPeerUrls) + addr = suite.cfgs[rand.Intn(len(suite.cfgs))].ClientUrls + apiPrefix + "/api/v1/members" resp, err = testDialClient.Get(addr) - c.Assert(err, IsNil) + suite.NoError(err) buf, err = io.ReadAll(resp.Body) - c.Assert(err, IsNil) + suite.NoError(err) resp.Body.Close() got1 := make(map[string]*pdpb.Member) json.Unmarshal(buf, &got1) - c.Assert(got1["leader"].GetPeerUrls(), DeepEquals, newPeerUrls) - c.Assert(got1["etcd_leader"].GetPeerUrls(), DeepEquals, newPeerUrls) + suite.Equal(newPeerUrls, got1["leader"].GetPeerUrls()) + suite.Equal(newPeerUrls, got1["etcd_leader"].GetPeerUrls()) // reset - changeLeaderPeerUrls(c, leader, id, peerUrls) + suite.changeLeaderPeerUrls(leader, id, peerUrls) } -func changeLeaderPeerUrls(c *C, leader *pdpb.Member, id uint64, urls []string) { +func (suite *memberTestSuite) changeLeaderPeerUrls(leader *pdpb.Member, id uint64, urls []string) { data := map[string][]string{"peerURLs": urls} postData, err := json.Marshal(data) - c.Assert(err, IsNil) + suite.NoError(err) req, err := http.NewRequest(http.MethodPut, fmt.Sprintf("%s/v2/members/%s", leader.GetClientUrls()[0], fmt.Sprintf("%x", id)), bytes.NewBuffer(postData)) - c.Assert(err, IsNil) + suite.NoError(err) req.Header.Set("Content-Type", "application/json") resp, err := testDialClient.Do(req) - c.Assert(err, IsNil) - c.Assert(resp.StatusCode, Equals, 204) + suite.NoError(err) + suite.Equal(204, resp.StatusCode) resp.Body.Close() } -type testResignAPISuite struct { +type resignTestSuite struct { + suite.Suite cfgs []*config.Config servers []*server.Server clean func() } -func (s *testResignAPISuite) SetUpSuite(c *C) { - s.cfgs, s.servers, s.clean = mustNewCluster(c, 1) +func TestResignTestSuite(t *testing.T) { + suite.Run(t, new(resignTestSuite)) +} + +func (suite *resignTestSuite) SetupSuite() { + suite.cfgs, suite.servers, suite.clean = mustNewCluster(suite.Require(), 1) } -func (s *testResignAPISuite) TearDownSuite(c *C) { - s.clean() +func (suite *resignTestSuite) TearDownSuite() { + suite.clean() } -func (s *testResignAPISuite) TestResignMyself(c *C) { - addr := s.cfgs[0].ClientUrls + apiPrefix + "/api/v1/leader/resign" +func (suite *resignTestSuite) TestResignMyself() { + addr := suite.cfgs[0].ClientUrls + apiPrefix + "/api/v1/leader/resign" resp, err := testDialClient.Post(addr, "", nil) - c.Assert(err, IsNil) - c.Assert(resp.StatusCode, Equals, http.StatusOK) + suite.NoError(err) + suite.Equal(http.StatusOK, resp.StatusCode) _, _ = io.Copy(io.Discard, resp.Body) resp.Body.Close() } diff --git a/server/api/min_resolved_ts_test.go b/server/api/min_resolved_ts_test.go index 69f4935f184..47c47713bff 100644 --- a/server/api/min_resolved_ts_test.go +++ b/server/api/min_resolved_ts_test.go @@ -16,47 +16,52 @@ package api import ( "fmt" + "testing" "time" - . "github.com/pingcap/check" "github.com/pingcap/kvproto/pkg/metapb" + "github.com/stretchr/testify/suite" "github.com/tikv/pd/pkg/apiutil" "github.com/tikv/pd/pkg/typeutil" "github.com/tikv/pd/server" "github.com/tikv/pd/server/cluster" ) -var _ = Suite(&testMinResolvedTSSuite{}) - -type testMinResolvedTSSuite struct { +type minResolvedTSTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testMinResolvedTSSuite) SetUpSuite(c *C) { +func TestMinResolvedTSTestSuite(t *testing.T) { + suite.Run(t, new(minResolvedTSTestSuite)) +} + +func (suite *minResolvedTSTestSuite) SetupSuite() { + re := suite.Require() cluster.DefaultMinResolvedTSPersistenceInterval = time.Microsecond - s.svr, s.cleanup = mustNewServer(c) - mustWaitLeader(c, []*server.Server{s.svr}) + suite.svr, suite.cleanup = mustNewServer(re) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) - mustBootstrapCluster(c, s.svr) - mustPutStore(c, s.svr, 1, metapb.StoreState_Up, metapb.NodeState_Serving, nil) + mustBootstrapCluster(re, suite.svr) + mustPutStore(re, suite.svr, 1, metapb.StoreState_Up, metapb.NodeState_Serving, nil) r1 := newTestRegionInfo(7, 1, []byte("a"), []byte("b")) - mustRegionHeartbeat(c, s.svr, r1) + mustRegionHeartbeat(re, suite.svr, r1) r2 := newTestRegionInfo(8, 1, []byte("b"), []byte("c")) - mustRegionHeartbeat(c, s.svr, r2) + mustRegionHeartbeat(re, suite.svr, r2) } -func (s *testMinResolvedTSSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *minResolvedTSTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *testMinResolvedTSSuite) TestMinResolvedTS(c *C) { - url := s.urlPrefix + "/min-resolved-ts" - rc := s.svr.GetRaftCluster() +func (suite *minResolvedTSTestSuite) TestMinResolvedTS() { + url := suite.urlPrefix + "/min-resolved-ts" + rc := suite.svr.GetRaftCluster() ts := uint64(233) rc.SetMinResolvedTS(1, ts) @@ -67,18 +72,18 @@ func (s *testMinResolvedTSSuite) TestMinResolvedTS(c *C) { PersistInterval: typeutil.Duration{Duration: 0}, } res, err := testDialClient.Get(url) - c.Assert(err, IsNil) + suite.NoError(err) defer res.Body.Close() listResp := &minResolvedTS{} err = apiutil.ReadJSON(res.Body, listResp) - c.Assert(err, IsNil) - c.Assert(listResp, DeepEquals, result) + suite.NoError(err) + suite.Equal(result, listResp) // run job interval := typeutil.NewDuration(time.Microsecond) - cfg := s.svr.GetRaftCluster().GetOpts().GetPDServerConfig().Clone() + cfg := suite.svr.GetRaftCluster().GetOpts().GetPDServerConfig().Clone() cfg.MinResolvedTSPersistenceInterval = interval - s.svr.GetRaftCluster().GetOpts().SetPDServerConfig(cfg) + suite.svr.GetRaftCluster().GetOpts().SetPDServerConfig(cfg) time.Sleep(time.Millisecond) result = &minResolvedTS{ MinResolvedTS: ts, @@ -86,10 +91,10 @@ func (s *testMinResolvedTSSuite) TestMinResolvedTS(c *C) { PersistInterval: interval, } res, err = testDialClient.Get(url) - c.Assert(err, IsNil) + suite.NoError(err) defer res.Body.Close() listResp = &minResolvedTS{} err = apiutil.ReadJSON(res.Body, listResp) - c.Assert(err, IsNil) - c.Assert(listResp, DeepEquals, result) + suite.NoError(err) + suite.Equal(result, listResp) } diff --git a/server/api/operator_test.go b/server/api/operator_test.go index 86d99c5e726..ba08b890b9b 100644 --- a/server/api/operator_test.go +++ b/server/api/operator_test.go @@ -21,12 +21,14 @@ import ( "io" "strconv" "strings" + "testing" "time" - . "github.com/pingcap/check" "github.com/pingcap/failpoint" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" + "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" "github.com/tikv/pd/pkg/apiutil" "github.com/tikv/pd/pkg/mock/mockhbstream" tu "github.com/tikv/pd/pkg/testutil" @@ -38,34 +40,37 @@ import ( "github.com/tikv/pd/server/versioninfo" ) -var _ = Suite(&testOperatorSuite{}) - -var _ = Suite(&testTransferRegionOperatorSuite{}) - -type testOperatorSuite struct { +type operatorTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testOperatorSuite) SetUpSuite(c *C) { - c.Assert(failpoint.Enable("github.com/tikv/pd/server/schedule/unexpectedOperator", "return(true)"), IsNil) - s.svr, s.cleanup = mustNewServer(c, func(cfg *config.Config) { cfg.Replication.MaxReplicas = 1 }) - mustWaitLeader(c, []*server.Server{s.svr}) +func TestOperatorTestSuite(t *testing.T) { + suite.Run(t, new(operatorTestSuite)) +} + +func (suite *operatorTestSuite) SetupSuite() { + re := suite.Require() + suite.NoError(failpoint.Enable("github.com/tikv/pd/server/schedule/unexpectedOperator", "return(true)")) + suite.svr, suite.cleanup = mustNewServer(re, func(cfg *config.Config) { cfg.Replication.MaxReplicas = 1 }) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) - mustBootstrapCluster(c, s.svr) + mustBootstrapCluster(re, suite.svr) } -func (s *testOperatorSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *operatorTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *testOperatorSuite) TestAddRemovePeer(c *C) { - mustPutStore(c, s.svr, 1, metapb.StoreState_Up, metapb.NodeState_Serving, nil) - mustPutStore(c, s.svr, 2, metapb.StoreState_Up, metapb.NodeState_Serving, nil) +func (suite *operatorTestSuite) TestAddRemovePeer() { + re := suite.Require() + mustPutStore(re, suite.svr, 1, metapb.StoreState_Up, metapb.NodeState_Serving, nil) + mustPutStore(re, suite.svr, 2, metapb.StoreState_Up, metapb.NodeState_Serving, nil) peer1 := &metapb.Peer{Id: 1, StoreId: 1} peer2 := &metapb.Peer{Id: 2, StoreId: 2} @@ -78,115 +83,123 @@ func (s *testOperatorSuite) TestAddRemovePeer(c *C) { }, } regionInfo := core.NewRegionInfo(region, peer1) - mustRegionHeartbeat(c, s.svr, regionInfo) - - regionURL := fmt.Sprintf("%s/operators/%d", s.urlPrefix, region.GetId()) - operator := mustReadURL(c, regionURL) - c.Assert(strings.Contains(operator, "operator not found"), IsTrue) - recordURL := fmt.Sprintf("%s/operators/records?from=%s", s.urlPrefix, strconv.FormatInt(time.Now().Unix(), 10)) - records := mustReadURL(c, recordURL) - c.Assert(strings.Contains(records, "operator not found"), IsTrue) - - mustPutStore(c, s.svr, 3, metapb.StoreState_Up, metapb.NodeState_Serving, nil) - err := tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", s.urlPrefix), []byte(`{"name":"add-peer", "region_id": 1, "store_id": 3}`), tu.StatusOK(c)) - c.Assert(err, IsNil) - operator = mustReadURL(c, regionURL) - c.Assert(strings.Contains(operator, "add learner peer 1 on store 3"), IsTrue) - c.Assert(strings.Contains(operator, "RUNNING"), IsTrue) + mustRegionHeartbeat(re, suite.svr, regionInfo) + + regionURL := fmt.Sprintf("%s/operators/%d", suite.urlPrefix, region.GetId()) + operator := mustReadURL(re, regionURL) + suite.Contains(operator, "operator not found") + recordURL := fmt.Sprintf("%s/operators/records?from=%s", suite.urlPrefix, strconv.FormatInt(time.Now().Unix(), 10)) + records := mustReadURL(re, recordURL) + suite.Contains(records, "operator not found") + + mustPutStore(re, suite.svr, 3, metapb.StoreState_Up, metapb.NodeState_Serving, nil) + err := tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", suite.urlPrefix), []byte(`{"name":"add-peer", "region_id": 1, "store_id": 3}`), tu.StatusOK(re)) + suite.NoError(err) + operator = mustReadURL(re, regionURL) + suite.Contains(operator, "add learner peer 1 on store 3") + suite.Contains(operator, "RUNNING") _, err = apiutil.DoDelete(testDialClient, regionURL) - c.Assert(err, IsNil) - records = mustReadURL(c, recordURL) - c.Assert(strings.Contains(records, "admin-add-peer {add peer: store [3]}"), IsTrue) + suite.NoError(err) + records = mustReadURL(re, recordURL) + suite.Contains(records, "admin-add-peer {add peer: store [3]}") - err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", s.urlPrefix), []byte(`{"name":"remove-peer", "region_id": 1, "store_id": 2}`), tu.StatusOK(c)) - c.Assert(err, IsNil) - operator = mustReadURL(c, regionURL) - c.Assert(strings.Contains(operator, "RUNNING"), IsTrue) - c.Assert(strings.Contains(operator, "remove peer on store 2"), IsTrue) + err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", suite.urlPrefix), []byte(`{"name":"remove-peer", "region_id": 1, "store_id": 2}`), tu.StatusOK(re)) + suite.NoError(err) + operator = mustReadURL(re, regionURL) + suite.Contains(operator, "RUNNING") + suite.Contains(operator, "remove peer on store 2") _, err = apiutil.DoDelete(testDialClient, regionURL) - c.Assert(err, IsNil) - records = mustReadURL(c, recordURL) - c.Assert(strings.Contains(records, "admin-remove-peer {rm peer: store [2]}"), IsTrue) + suite.NoError(err) + records = mustReadURL(re, recordURL) + suite.Contains(records, "admin-remove-peer {rm peer: store [2]}") - mustPutStore(c, s.svr, 4, metapb.StoreState_Up, metapb.NodeState_Serving, nil) - err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", s.urlPrefix), []byte(`{"name":"add-learner", "region_id": 1, "store_id": 4}`), tu.StatusOK(c)) - c.Assert(err, IsNil) - operator = mustReadURL(c, regionURL) - c.Assert(strings.Contains(operator, "add learner peer 2 on store 4"), IsTrue) + mustPutStore(re, suite.svr, 4, metapb.StoreState_Up, metapb.NodeState_Serving, nil) + err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", suite.urlPrefix), []byte(`{"name":"add-learner", "region_id": 1, "store_id": 4}`), tu.StatusOK(re)) + suite.NoError(err) + operator = mustReadURL(re, regionURL) + suite.Contains(operator, "add learner peer 2 on store 4") // Fail to add peer to tombstone store. - err = s.svr.GetRaftCluster().RemoveStore(3, true) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", s.urlPrefix), []byte(`{"name":"add-peer", "region_id": 1, "store_id": 3}`), tu.StatusNotOK(c)) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", s.urlPrefix), []byte(`{"name":"transfer-peer", "region_id": 1, "from_store_id": 1, "to_store_id": 3}`), tu.StatusNotOK(c)) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", s.urlPrefix), []byte(`{"name":"transfer-region", "region_id": 1, "to_store_ids": [1, 2, 3]}`), tu.StatusNotOK(c)) - c.Assert(err, IsNil) + err = suite.svr.GetRaftCluster().RemoveStore(3, true) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", suite.urlPrefix), []byte(`{"name":"add-peer", "region_id": 1, "store_id": 3}`), tu.StatusNotOK(re)) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", suite.urlPrefix), []byte(`{"name":"transfer-peer", "region_id": 1, "from_store_id": 1, "to_store_id": 3}`), tu.StatusNotOK(re)) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", suite.urlPrefix), []byte(`{"name":"transfer-region", "region_id": 1, "to_store_ids": [1, 2, 3]}`), tu.StatusNotOK(re)) + suite.NoError(err) // Fail to get operator if from is latest. time.Sleep(time.Second) - records = mustReadURL(c, fmt.Sprintf("%s/operators/records?from=%s", s.urlPrefix, strconv.FormatInt(time.Now().Unix(), 10))) - c.Assert(strings.Contains(records, "operator not found"), IsTrue) + records = mustReadURL(re, fmt.Sprintf("%s/operators/records?from=%s", suite.urlPrefix, strconv.FormatInt(time.Now().Unix(), 10))) + suite.Contains(records, "operator not found") } -func (s *testOperatorSuite) TestMergeRegionOperator(c *C) { +func (suite *operatorTestSuite) TestMergeRegionOperator() { + re := suite.Require() r1 := newTestRegionInfo(10, 1, []byte(""), []byte("b"), core.SetWrittenBytes(1000), core.SetReadBytes(1000), core.SetRegionConfVer(1), core.SetRegionVersion(1)) - mustRegionHeartbeat(c, s.svr, r1) + mustRegionHeartbeat(re, suite.svr, r1) r2 := newTestRegionInfo(20, 1, []byte("b"), []byte("c"), core.SetWrittenBytes(2000), core.SetReadBytes(0), core.SetRegionConfVer(2), core.SetRegionVersion(3)) - mustRegionHeartbeat(c, s.svr, r2) + mustRegionHeartbeat(re, suite.svr, r2) r3 := newTestRegionInfo(30, 1, []byte("c"), []byte(""), core.SetWrittenBytes(500), core.SetReadBytes(800), core.SetRegionConfVer(3), core.SetRegionVersion(2)) - mustRegionHeartbeat(c, s.svr, r3) - - err := tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", s.urlPrefix), []byte(`{"name":"merge-region", "source_region_id": 10, "target_region_id": 20}`), tu.StatusOK(c)) - c.Assert(err, IsNil) - - s.svr.GetHandler().RemoveOperator(10) - s.svr.GetHandler().RemoveOperator(20) - err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", s.urlPrefix), []byte(`{"name":"merge-region", "source_region_id": 20, "target_region_id": 10}`), tu.StatusOK(c)) - c.Assert(err, IsNil) - s.svr.GetHandler().RemoveOperator(10) - s.svr.GetHandler().RemoveOperator(20) - err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", s.urlPrefix), []byte(`{"name":"merge-region", "source_region_id": 10, "target_region_id": 30}`), - tu.StatusNotOK(c), tu.StringContain(c, "not adjacent")) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", s.urlPrefix), []byte(`{"name":"merge-region", "source_region_id": 30, "target_region_id": 10}`), - tu.StatusNotOK(c), tu.StringContain(c, "not adjacent")) - c.Assert(err, IsNil) + mustRegionHeartbeat(re, suite.svr, r3) + + err := tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", suite.urlPrefix), []byte(`{"name":"merge-region", "source_region_id": 10, "target_region_id": 20}`), tu.StatusOK(re)) + suite.NoError(err) + + suite.svr.GetHandler().RemoveOperator(10) + suite.svr.GetHandler().RemoveOperator(20) + err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", suite.urlPrefix), []byte(`{"name":"merge-region", "source_region_id": 20, "target_region_id": 10}`), tu.StatusOK(re)) + suite.NoError(err) + suite.svr.GetHandler().RemoveOperator(10) + suite.svr.GetHandler().RemoveOperator(20) + err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", suite.urlPrefix), []byte(`{"name":"merge-region", "source_region_id": 10, "target_region_id": 30}`), + tu.StatusNotOK(re), tu.StringContain(re, "not adjacent")) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", suite.urlPrefix), []byte(`{"name":"merge-region", "source_region_id": 30, "target_region_id": 10}`), + tu.StatusNotOK(re), tu.StringContain(re, "not adjacent")) + suite.NoError(err) } -type testTransferRegionOperatorSuite struct { +type transferRegionOperatorTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testTransferRegionOperatorSuite) SetUpSuite(c *C) { - c.Assert(failpoint.Enable("github.com/tikv/pd/server/schedule/unexpectedOperator", "return(true)"), IsNil) - s.svr, s.cleanup = mustNewServer(c, func(cfg *config.Config) { cfg.Replication.MaxReplicas = 3 }) - mustWaitLeader(c, []*server.Server{s.svr}) +func TestTransferRegionOperatorTestSuite(t *testing.T) { + suite.Run(t, new(transferRegionOperatorTestSuite)) +} + +func (suite *transferRegionOperatorTestSuite) SetupSuite() { + re := suite.Require() + suite.NoError(failpoint.Enable("github.com/tikv/pd/server/schedule/unexpectedOperator", "return(true)")) + suite.svr, suite.cleanup = mustNewServer(re, func(cfg *config.Config) { cfg.Replication.MaxReplicas = 3 }) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) - mustBootstrapCluster(c, s.svr) + mustBootstrapCluster(re, suite.svr) } -func (s *testTransferRegionOperatorSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *transferRegionOperatorTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *testTransferRegionOperatorSuite) TestTransferRegionWithPlacementRule(c *C) { - mustPutStore(c, s.svr, 1, metapb.StoreState_Up, metapb.NodeState_Serving, []*metapb.StoreLabel{{Key: "key", Value: "1"}}) - mustPutStore(c, s.svr, 2, metapb.StoreState_Up, metapb.NodeState_Serving, []*metapb.StoreLabel{{Key: "key", Value: "2"}}) - mustPutStore(c, s.svr, 3, metapb.StoreState_Up, metapb.NodeState_Serving, []*metapb.StoreLabel{{Key: "key", Value: "3"}}) +func (suite *transferRegionOperatorTestSuite) TestTransferRegionWithPlacementRule() { + re := suite.Require() + mustPutStore(re, suite.svr, 1, metapb.StoreState_Up, metapb.NodeState_Serving, []*metapb.StoreLabel{{Key: "key", Value: "1"}}) + mustPutStore(re, suite.svr, 2, metapb.StoreState_Up, metapb.NodeState_Serving, []*metapb.StoreLabel{{Key: "key", Value: "2"}}) + mustPutStore(re, suite.svr, 3, metapb.StoreState_Up, metapb.NodeState_Serving, []*metapb.StoreLabel{{Key: "key", Value: "3"}}) hbStream := mockhbstream.NewHeartbeatStream() - s.svr.GetHBStreams().BindStream(1, hbStream) - s.svr.GetHBStreams().BindStream(2, hbStream) - s.svr.GetHBStreams().BindStream(3, hbStream) + suite.svr.GetHBStreams().BindStream(1, hbStream) + suite.svr.GetHBStreams().BindStream(2, hbStream) + suite.svr.GetHBStreams().BindStream(3, hbStream) peer1 := &metapb.Peer{Id: 1, StoreId: 1} peer2 := &metapb.Peer{Id: 2, StoreId: 2} @@ -199,11 +212,11 @@ func (s *testTransferRegionOperatorSuite) TestTransferRegionWithPlacementRule(c Version: 1, }, } - mustRegionHeartbeat(c, s.svr, core.NewRegionInfo(region, peer1)) + mustRegionHeartbeat(re, suite.svr, core.NewRegionInfo(region, peer1)) - regionURL := fmt.Sprintf("%s/operators/%d", s.urlPrefix, region.GetId()) - operator := mustReadURL(c, regionURL) - c.Assert(strings.Contains(operator, "operator not found"), IsTrue) + regionURL := fmt.Sprintf("%s/operators/%d", suite.urlPrefix, region.GetId()) + operator := mustReadURL(re, regionURL) + suite.Contains(operator, "operator not found") tt := []struct { name string @@ -359,39 +372,39 @@ func (s *testTransferRegionOperatorSuite) TestTransferRegionWithPlacementRule(c }, } for _, tc := range tt { - c.Log(tc.name) - s.svr.GetRaftCluster().GetOpts().SetPlacementRuleEnabled(tc.placementRuleEnable) + suite.T().Log(tc.name) + suite.svr.GetRaftCluster().GetOpts().SetPlacementRuleEnabled(tc.placementRuleEnable) if tc.placementRuleEnable { - err := s.svr.GetRaftCluster().GetRuleManager().Initialize( - s.svr.GetRaftCluster().GetOpts().GetMaxReplicas(), - s.svr.GetRaftCluster().GetOpts().GetLocationLabels()) - c.Assert(err, IsNil) + err := suite.svr.GetRaftCluster().GetRuleManager().Initialize( + suite.svr.GetRaftCluster().GetOpts().GetMaxReplicas(), + suite.svr.GetRaftCluster().GetOpts().GetLocationLabels()) + suite.NoError(err) } if len(tc.rules) > 0 { // add customized rule first and then remove default rule - err := s.svr.GetRaftCluster().GetRuleManager().SetRules(tc.rules) - c.Assert(err, IsNil) - err = s.svr.GetRaftCluster().GetRuleManager().DeleteRule("pd", "default") - c.Assert(err, IsNil) + err := suite.svr.GetRaftCluster().GetRuleManager().SetRules(tc.rules) + suite.NoError(err) + err = suite.svr.GetRaftCluster().GetRuleManager().DeleteRule("pd", "default") + suite.NoError(err) } var err error if tc.expectedError == nil { - err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", s.urlPrefix), tc.input, tu.StatusOK(c)) + err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", suite.urlPrefix), tc.input, tu.StatusOK(re)) } else { - err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", s.urlPrefix), tc.input, - tu.StatusNotOK(c), tu.StringContain(c, tc.expectedError.Error())) + err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/operators", suite.urlPrefix), tc.input, + tu.StatusNotOK(re), tu.StringContain(re, tc.expectedError.Error())) } - c.Assert(err, IsNil) + suite.NoError(err) if len(tc.expectSteps) > 0 { - operator = mustReadURL(c, regionURL) - c.Assert(strings.Contains(operator, tc.expectSteps), IsTrue) + operator = mustReadURL(re, regionURL) + suite.Contains(operator, tc.expectSteps) } _, err = apiutil.DoDelete(testDialClient, regionURL) - c.Assert(err, IsNil) + suite.NoError(err) } } -func mustPutStore(c *C, svr *server.Server, id uint64, state metapb.StoreState, nodeState metapb.NodeState, labels []*metapb.StoreLabel) { +func mustPutStore(re *require.Assertions, svr *server.Server, id uint64, state metapb.StoreState, nodeState metapb.NodeState, labels []*metapb.StoreLabel) { s := &server.GrpcServer{Server: svr} _, err := s.PutStore(context.Background(), &pdpb.PutStoreRequest{ Header: &pdpb.RequestHeader{ClusterId: svr.ClusterID()}, @@ -404,27 +417,27 @@ func mustPutStore(c *C, svr *server.Server, id uint64, state metapb.StoreState, Version: versioninfo.MinSupportedVersion(versioninfo.Version2_0).String(), }, }) - c.Assert(err, IsNil) + re.NoError(err) if state == metapb.StoreState_Up { _, err = s.StoreHeartbeat(context.Background(), &pdpb.StoreHeartbeatRequest{ Header: &pdpb.RequestHeader{ClusterId: svr.ClusterID()}, Stats: &pdpb.StoreStats{StoreId: id}, }) - c.Assert(err, IsNil) + re.NoError(err) } } -func mustRegionHeartbeat(c *C, svr *server.Server, region *core.RegionInfo) { +func mustRegionHeartbeat(re *require.Assertions, svr *server.Server, region *core.RegionInfo) { cluster := svr.GetRaftCluster() err := cluster.HandleRegionHeartbeat(region) - c.Assert(err, IsNil) + re.NoError(err) } -func mustReadURL(c *C, url string) string { +func mustReadURL(re *require.Assertions, url string) string { res, err := testDialClient.Get(url) - c.Assert(err, IsNil) + re.NoError(err) defer res.Body.Close() data, err := io.ReadAll(res.Body) - c.Assert(err, IsNil) + re.NoError(err) return string(data) } diff --git a/server/api/pprof_test.go b/server/api/pprof_test.go index 326b4d09005..3d80a325758 100644 --- a/server/api/pprof_test.go +++ b/server/api/pprof_test.go @@ -18,41 +18,46 @@ import ( "bytes" "fmt" "io/ioutil" + "testing" - . "github.com/pingcap/check" + "github.com/stretchr/testify/suite" "github.com/tikv/pd/server" ) -var _ = Suite(&ProfSuite{}) - -type ProfSuite struct { +type profTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *ProfSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c) - mustWaitLeader(c, []*server.Server{s.svr}) +func TestProfTestSuite(t *testing.T) { + suite.Run(t, new(profTestSuite)) +} + +func (suite *profTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1/debug", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1/debug", addr, apiPrefix) - mustBootstrapCluster(c, s.svr) + mustBootstrapCluster(re, suite.svr) } -func (s *ProfSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *profTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *ProfSuite) TestGetZip(c *C) { - rsp, err := testDialClient.Get(s.urlPrefix + "/pprof/zip?" + "seconds=5s") - c.Assert(err, IsNil) +func (suite *profTestSuite) TestGetZip() { + rsp, err := testDialClient.Get(suite.urlPrefix + "/pprof/zip?" + "seconds=5s") + suite.NoError(err) defer rsp.Body.Close() body, err := ioutil.ReadAll(rsp.Body) - c.Assert(err, IsNil) - c.Assert(body, NotNil) + suite.NoError(err) + suite.NotNil(body) zipReader, err := zip.NewReader(bytes.NewReader(body), int64(len(body))) - c.Assert(err, IsNil) - c.Assert(zipReader.File, HasLen, 7) + suite.NoError(err) + suite.Len(zipReader.File, 7) } diff --git a/server/api/region.go b/server/api/region.go index a4ae3fe0df9..9756f12e3c2 100644 --- a/server/api/region.go +++ b/server/api/region.go @@ -137,12 +137,12 @@ func fromPBReplicationStatus(s *replication_modepb.RegionReplicationStatus) *Rep } } -// NewRegionInfo create a new api RegionInfo. -func NewRegionInfo(r *core.RegionInfo) *RegionInfo { +// NewAPIRegionInfo create a new API RegionInfo. +func NewAPIRegionInfo(r *core.RegionInfo) *RegionInfo { return InitRegion(r, &RegionInfo{}) } -// InitRegion init a new api RegionInfo from the core.RegionInfo. +// InitRegion init a new API RegionInfo from the core.RegionInfo. func InitRegion(r *core.RegionInfo, s *RegionInfo) *RegionInfo { if r == nil { return nil @@ -228,7 +228,7 @@ func (h *regionHandler) GetRegionByID(w http.ResponseWriter, r *http.Request) { } regionInfo := rc.GetRegion(regionID) - h.rd.JSON(w, http.StatusOK, NewRegionInfo(regionInfo)) + h.rd.JSON(w, http.StatusOK, NewAPIRegionInfo(regionInfo)) } // @Tags region @@ -247,7 +247,7 @@ func (h *regionHandler) GetRegion(w http.ResponseWriter, r *http.Request) { return } regionInfo := rc.GetRegionByKey([]byte(key)) - h.rd.JSON(w, http.StatusOK, NewRegionInfo(regionInfo)) + h.rd.JSON(w, http.StatusOK, NewAPIRegionInfo(regionInfo)) } // @Tags region diff --git a/server/api/region_label_test.go b/server/api/region_label_test.go index 0e6aa7ccf62..0165ec7d37e 100644 --- a/server/api/region_label_test.go +++ b/server/api/region_label_test.go @@ -19,41 +19,47 @@ import ( "fmt" "net/url" "sort" + "testing" - . "github.com/pingcap/check" + "github.com/stretchr/testify/suite" "github.com/tikv/pd/pkg/apiutil" tu "github.com/tikv/pd/pkg/testutil" "github.com/tikv/pd/server" "github.com/tikv/pd/server/schedule/labeler" ) -var _ = Suite(&testRegionLabelSuite{}) - -type testRegionLabelSuite struct { +type regionLabelTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testRegionLabelSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c) - mustWaitLeader(c, []*server.Server{s.svr}) +func TestRegionLabelTestSuite(t *testing.T) { + suite.Run(t, new(regionLabelTestSuite)) +} + +func (suite *regionLabelTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1/config/region-label/", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1/config/region-label/", addr, apiPrefix) - mustBootstrapCluster(c, s.svr) + mustBootstrapCluster(re, suite.svr) } -func (s *testRegionLabelSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *regionLabelTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *testRegionLabelSuite) TestGetSet(c *C) { +func (suite *regionLabelTestSuite) TestGetSet() { + re := suite.Require() var resp []*labeler.LabelRule - err := tu.ReadGetJSON(c, testDialClient, s.urlPrefix+"rules", &resp) - c.Assert(err, IsNil) - c.Assert(resp, HasLen, 0) + err := tu.ReadGetJSON(re, testDialClient, suite.urlPrefix+"rules", &resp) + suite.NoError(err) + suite.Len(resp, 0) rules := []*labeler.LabelRule{ {ID: "rule1", Labels: []labeler.RegionLabel{{Key: "k1", Value: "v1"}}, RuleType: "key-range", Data: makeKeyRanges("1234", "5678")}, @@ -63,27 +69,27 @@ func (s *testRegionLabelSuite) TestGetSet(c *C) { ruleIDs := []string{"rule1", "rule2/a/b", "rule3"} for _, rule := range rules { data, _ := json.Marshal(rule) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"rule", data, tu.StatusOK(c)) - c.Assert(err, IsNil) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"rule", data, tu.StatusOK(re)) + suite.NoError(err) } for i, id := range ruleIDs { var rule labeler.LabelRule - err = tu.ReadGetJSON(c, testDialClient, s.urlPrefix+"rule/"+url.QueryEscape(id), &rule) - c.Assert(err, IsNil) - c.Assert(&rule, DeepEquals, rules[i]) + err = tu.ReadGetJSON(re, testDialClient, suite.urlPrefix+"rule/"+url.QueryEscape(id), &rule) + suite.NoError(err) + suite.Equal(rules[i], &rule) } - err = tu.ReadGetJSONWithBody(c, testDialClient, s.urlPrefix+"rules/ids", []byte(`["rule1", "rule3"]`), &resp) - c.Assert(err, IsNil) + err = tu.ReadGetJSONWithBody(re, testDialClient, suite.urlPrefix+"rules/ids", []byte(`["rule1", "rule3"]`), &resp) + suite.NoError(err) expects := []*labeler.LabelRule{rules[0], rules[2]} - c.Assert(resp, DeepEquals, expects) + suite.Equal(expects, resp) - _, err = apiutil.DoDelete(testDialClient, s.urlPrefix+"rule/"+url.QueryEscape("rule2/a/b")) - c.Assert(err, IsNil) - err = tu.ReadGetJSON(c, testDialClient, s.urlPrefix+"rules", &resp) - c.Assert(err, IsNil) + _, err = apiutil.DoDelete(testDialClient, suite.urlPrefix+"rule/"+url.QueryEscape("rule2/a/b")) + suite.NoError(err) + err = tu.ReadGetJSON(re, testDialClient, suite.urlPrefix+"rules", &resp) + suite.NoError(err) sort.Slice(resp, func(i, j int) bool { return resp[i].ID < resp[j].ID }) - c.Assert(resp, DeepEquals, []*labeler.LabelRule{rules[0], rules[2]}) + suite.Equal([]*labeler.LabelRule{rules[0], rules[2]}, resp) patch := labeler.LabelRulePatch{ SetRules: []*labeler.LabelRule{ @@ -92,12 +98,12 @@ func (s *testRegionLabelSuite) TestGetSet(c *C) { DeleteRules: []string{"rule1"}, } data, _ := json.Marshal(patch) - err = tu.CheckPatchJSON(testDialClient, s.urlPrefix+"rules", data, tu.StatusOK(c)) - c.Assert(err, IsNil) - err = tu.ReadGetJSON(c, testDialClient, s.urlPrefix+"rules", &resp) - c.Assert(err, IsNil) + err = tu.CheckPatchJSON(testDialClient, suite.urlPrefix+"rules", data, tu.StatusOK(re)) + suite.NoError(err) + err = tu.ReadGetJSON(re, testDialClient, suite.urlPrefix+"rules", &resp) + suite.NoError(err) sort.Slice(resp, func(i, j int) bool { return resp[i].ID < resp[j].ID }) - c.Assert(resp, DeepEquals, []*labeler.LabelRule{rules[1], rules[2]}) + suite.Equal([]*labeler.LabelRule{rules[1], rules[2]}, resp) } func makeKeyRanges(keys ...string) []interface{} { diff --git a/server/api/region_test.go b/server/api/region_test.go index 816fefcc092..168edd0e419 100644 --- a/server/api/region_test.go +++ b/server/api/region_test.go @@ -25,21 +25,19 @@ import ( "sort" "testing" - . "github.com/pingcap/check" "github.com/pingcap/failpoint" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" + "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" tu "github.com/tikv/pd/pkg/testutil" "github.com/tikv/pd/server" "github.com/tikv/pd/server/core" "github.com/tikv/pd/server/schedule/placement" ) -var _ = Suite(&testRegionStructSuite{}) - -type testRegionStructSuite struct{} - -func (s *testRegionStructSuite) TestPeer(c *C) { +func TestPeer(t *testing.T) { + re := require.New(t) peers := []*metapb.Peer{ {Id: 1, StoreId: 10, Role: metapb.PeerRole_Voter}, {Id: 2, StoreId: 20, Role: metapb.PeerRole_Learner}, @@ -55,13 +53,14 @@ func (s *testRegionStructSuite) TestPeer(c *C) { } data, err := json.Marshal(fromPeerSlice(peers)) - c.Assert(err, IsNil) + re.NoError(err) var ret []map[string]interface{} - c.Assert(json.Unmarshal(data, &ret), IsNil) - c.Assert(ret, DeepEquals, expected) + re.NoError(json.Unmarshal(data, &ret)) + re.Equal(expected, ret) } -func (s *testRegionStructSuite) TestPeerStats(c *C) { +func TestPeerStats(t *testing.T) { + re := require.New(t) peers := []*pdpb.PeerStats{ {Peer: &metapb.Peer{Id: 1, StoreId: 10, Role: metapb.PeerRole_Voter}, DownSeconds: 0}, {Peer: &metapb.Peer{Id: 2, StoreId: 20, Role: metapb.PeerRole_Learner}, DownSeconds: 1}, @@ -77,32 +76,36 @@ func (s *testRegionStructSuite) TestPeerStats(c *C) { } data, err := json.Marshal(fromPeerStatsSlice(peers)) - c.Assert(err, IsNil) + re.NoError(err) var ret []map[string]interface{} - c.Assert(json.Unmarshal(data, &ret), IsNil) - c.Assert(ret, DeepEquals, expected) + re.NoError(json.Unmarshal(data, &ret)) + re.Equal(expected, ret) } -var _ = Suite(&testRegionSuite{}) - -type testRegionSuite struct { +type regionTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testRegionSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c) - mustWaitLeader(c, []*server.Server{s.svr}) +func TestRegionTestSuite(t *testing.T) { + suite.Run(t, new(regionTestSuite)) +} + +func (suite *regionTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) - mustBootstrapCluster(c, s.svr) + mustBootstrapCluster(re, suite.svr) } -func (s *testRegionSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *regionTestSuite) TearDownSuite() { + suite.cleanup() } func newTestRegionInfo(regionID, storeID uint64, start, end []byte, opts ...core.RegionCreateOption) *core.RegionInfo { @@ -130,7 +133,7 @@ func newTestRegionInfo(regionID, storeID uint64, start, end []byte, opts ...core return region } -func (s *testRegionSuite) TestRegion(c *C) { +func (suite *regionTestSuite) TestRegion() { r := newTestRegionInfo(2, 1, []byte("a"), []byte("b")) buckets := &metapb.Buckets{ RegionId: 2, @@ -138,227 +141,236 @@ func (s *testRegionSuite) TestRegion(c *C) { Version: 1, } r.UpdateBuckets(buckets, r.GetBuckets()) - mustRegionHeartbeat(c, s.svr, r) - url := fmt.Sprintf("%s/region/id/%d", s.urlPrefix, r.GetID()) + re := suite.Require() + mustRegionHeartbeat(re, suite.svr, r) + url := fmt.Sprintf("%s/region/id/%d", suite.urlPrefix, r.GetID()) r1 := &RegionInfo{} r1m := make(map[string]interface{}) - c.Assert(tu.ReadGetJSON(c, testDialClient, url, r1), IsNil) + suite.NoError(tu.ReadGetJSON(re, testDialClient, url, r1)) r1.Adjust() - c.Assert(r1, DeepEquals, NewRegionInfo(r)) - c.Assert(tu.ReadGetJSON(c, testDialClient, url, &r1m), IsNil) - c.Assert(r1m["written_bytes"].(float64), Equals, float64(r.GetBytesWritten())) - c.Assert(r1m["written_keys"].(float64), Equals, float64(r.GetKeysWritten())) - c.Assert(r1m["read_bytes"].(float64), Equals, float64(r.GetBytesRead())) - c.Assert(r1m["read_keys"].(float64), Equals, float64(r.GetKeysRead())) + suite.Equal(NewAPIRegionInfo(r), r1) + suite.NoError(tu.ReadGetJSON(re, testDialClient, url, &r1m)) + suite.Equal(float64(r.GetBytesWritten()), r1m["written_bytes"].(float64)) + suite.Equal(float64(r.GetKeysWritten()), r1m["written_keys"].(float64)) + suite.Equal(float64(r.GetBytesRead()), r1m["read_bytes"].(float64)) + suite.Equal(float64(r.GetKeysRead()), r1m["read_keys"].(float64)) keys := r1m["buckets"].([]interface{}) - c.Assert(keys, HasLen, 2) - c.Assert(keys[0].(string), Equals, core.HexRegionKeyStr([]byte("a"))) - c.Assert(keys[1].(string), Equals, core.HexRegionKeyStr([]byte("b"))) + suite.Len(keys, 2) + suite.Equal(core.HexRegionKeyStr([]byte("a")), keys[0].(string)) + suite.Equal(core.HexRegionKeyStr([]byte("b")), keys[1].(string)) - url = fmt.Sprintf("%s/region/key/%s", s.urlPrefix, "a") + url = fmt.Sprintf("%s/region/key/%s", suite.urlPrefix, "a") r2 := &RegionInfo{} - c.Assert(tu.ReadGetJSON(c, testDialClient, url, r2), IsNil) + suite.NoError(tu.ReadGetJSON(re, testDialClient, url, r2)) r2.Adjust() - c.Assert(r2, DeepEquals, NewRegionInfo(r)) + suite.Equal(NewAPIRegionInfo(r), r2) } -func (s *testRegionSuite) TestRegionCheck(c *C) { +func (suite *regionTestSuite) TestRegionCheck() { r := newTestRegionInfo(2, 1, []byte("a"), []byte("b")) downPeer := &metapb.Peer{Id: 13, StoreId: 2} r = r.Clone(core.WithAddPeer(downPeer), core.WithDownPeers([]*pdpb.PeerStats{{Peer: downPeer, DownSeconds: 3600}}), core.WithPendingPeers([]*metapb.Peer{downPeer})) - mustRegionHeartbeat(c, s.svr, r) - url := fmt.Sprintf("%s/region/id/%d", s.urlPrefix, r.GetID()) + re := suite.Require() + mustRegionHeartbeat(re, suite.svr, r) + url := fmt.Sprintf("%s/region/id/%d", suite.urlPrefix, r.GetID()) r1 := &RegionInfo{} - c.Assert(tu.ReadGetJSON(c, testDialClient, url, r1), IsNil) + suite.NoError(tu.ReadGetJSON(re, testDialClient, url, r1)) r1.Adjust() - c.Assert(r1, DeepEquals, NewRegionInfo(r)) + suite.Equal(NewAPIRegionInfo(r), r1) - url = fmt.Sprintf("%s/regions/check/%s", s.urlPrefix, "down-peer") + url = fmt.Sprintf("%s/regions/check/%s", suite.urlPrefix, "down-peer") r2 := &RegionsInfo{} - c.Assert(tu.ReadGetJSON(c, testDialClient, url, r2), IsNil) + suite.NoError(tu.ReadGetJSON(re, testDialClient, url, r2)) r2.Adjust() - c.Assert(r2, DeepEquals, &RegionsInfo{Count: 1, Regions: []RegionInfo{*NewRegionInfo(r)}}) + suite.Equal(&RegionsInfo{Count: 1, Regions: []RegionInfo{*NewAPIRegionInfo(r)}}, r2) - url = fmt.Sprintf("%s/regions/check/%s", s.urlPrefix, "pending-peer") + url = fmt.Sprintf("%s/regions/check/%s", suite.urlPrefix, "pending-peer") r3 := &RegionsInfo{} - c.Assert(tu.ReadGetJSON(c, testDialClient, url, r3), IsNil) + suite.NoError(tu.ReadGetJSON(re, testDialClient, url, r3)) r3.Adjust() - c.Assert(r3, DeepEquals, &RegionsInfo{Count: 1, Regions: []RegionInfo{*NewRegionInfo(r)}}) + suite.Equal(&RegionsInfo{Count: 1, Regions: []RegionInfo{*NewAPIRegionInfo(r)}}, r3) - url = fmt.Sprintf("%s/regions/check/%s", s.urlPrefix, "offline-peer") + url = fmt.Sprintf("%s/regions/check/%s", suite.urlPrefix, "offline-peer") r4 := &RegionsInfo{} - c.Assert(tu.ReadGetJSON(c, testDialClient, url, r4), IsNil) + suite.NoError(tu.ReadGetJSON(re, testDialClient, url, r4)) r4.Adjust() - c.Assert(r4, DeepEquals, &RegionsInfo{Count: 0, Regions: []RegionInfo{}}) + suite.Equal(&RegionsInfo{Count: 0, Regions: []RegionInfo{}}, r4) r = r.Clone(core.SetApproximateSize(1)) - mustRegionHeartbeat(c, s.svr, r) - url = fmt.Sprintf("%s/regions/check/%s", s.urlPrefix, "empty-region") + mustRegionHeartbeat(re, suite.svr, r) + url = fmt.Sprintf("%s/regions/check/%s", suite.urlPrefix, "empty-region") r5 := &RegionsInfo{} - c.Assert(tu.ReadGetJSON(c, testDialClient, url, r5), IsNil) + suite.NoError(tu.ReadGetJSON(re, testDialClient, url, r5)) r5.Adjust() - c.Assert(r5, DeepEquals, &RegionsInfo{Count: 1, Regions: []RegionInfo{*NewRegionInfo(r)}}) + suite.Equal(&RegionsInfo{Count: 1, Regions: []RegionInfo{*NewAPIRegionInfo(r)}}, r5) r = r.Clone(core.SetApproximateSize(1)) - mustRegionHeartbeat(c, s.svr, r) - url = fmt.Sprintf("%s/regions/check/%s", s.urlPrefix, "hist-size") + mustRegionHeartbeat(re, suite.svr, r) + url = fmt.Sprintf("%s/regions/check/%s", suite.urlPrefix, "hist-size") r6 := make([]*histItem, 1) - c.Assert(tu.ReadGetJSON(c, testDialClient, url, &r6), IsNil) + suite.NoError(tu.ReadGetJSON(re, testDialClient, url, &r6)) histSizes := []*histItem{{Start: 1, End: 1, Count: 1}} - c.Assert(r6, DeepEquals, histSizes) + suite.Equal(histSizes, r6) r = r.Clone(core.SetApproximateKeys(1000)) - mustRegionHeartbeat(c, s.svr, r) - url = fmt.Sprintf("%s/regions/check/%s", s.urlPrefix, "hist-keys") + mustRegionHeartbeat(re, suite.svr, r) + url = fmt.Sprintf("%s/regions/check/%s", suite.urlPrefix, "hist-keys") r7 := make([]*histItem, 1) - c.Assert(tu.ReadGetJSON(c, testDialClient, url, &r7), IsNil) + suite.NoError(tu.ReadGetJSON(re, testDialClient, url, &r7)) histKeys := []*histItem{{Start: 1000, End: 1999, Count: 1}} - c.Assert(r7, DeepEquals, histKeys) + suite.Equal(histKeys, r7) } -func (s *testRegionSuite) TestRegions(c *C) { +func (suite *regionTestSuite) TestRegions() { rs := []*core.RegionInfo{ newTestRegionInfo(2, 1, []byte("a"), []byte("b")), newTestRegionInfo(3, 1, []byte("b"), []byte("c")), newTestRegionInfo(4, 2, []byte("c"), []byte("d")), } regions := make([]RegionInfo, 0, len(rs)) + re := suite.Require() for _, r := range rs { - regions = append(regions, *NewRegionInfo(r)) - mustRegionHeartbeat(c, s.svr, r) + regions = append(regions, *NewAPIRegionInfo(r)) + mustRegionHeartbeat(re, suite.svr, r) } - url := fmt.Sprintf("%s/regions", s.urlPrefix) + url := fmt.Sprintf("%s/regions", suite.urlPrefix) RegionsInfo := &RegionsInfo{} - err := tu.ReadGetJSON(c, testDialClient, url, RegionsInfo) - c.Assert(err, IsNil) - c.Assert(RegionsInfo.Count, Equals, len(regions)) + err := tu.ReadGetJSON(re, testDialClient, url, RegionsInfo) + suite.NoError(err) + suite.Len(regions, RegionsInfo.Count) sort.Slice(RegionsInfo.Regions, func(i, j int) bool { return RegionsInfo.Regions[i].ID < RegionsInfo.Regions[j].ID }) for i, r := range RegionsInfo.Regions { - c.Assert(r.ID, Equals, regions[i].ID) - c.Assert(r.ApproximateSize, Equals, regions[i].ApproximateSize) - c.Assert(r.ApproximateKeys, Equals, regions[i].ApproximateKeys) + suite.Equal(regions[i].ID, r.ID) + suite.Equal(regions[i].ApproximateSize, r.ApproximateSize) + suite.Equal(regions[i].ApproximateKeys, r.ApproximateKeys) } } -func (s *testRegionSuite) TestStoreRegions(c *C) { +func (suite *regionTestSuite) TestStoreRegions() { + re := suite.Require() r1 := newTestRegionInfo(2, 1, []byte("a"), []byte("b")) r2 := newTestRegionInfo(3, 1, []byte("b"), []byte("c")) r3 := newTestRegionInfo(4, 2, []byte("c"), []byte("d")) - mustRegionHeartbeat(c, s.svr, r1) - mustRegionHeartbeat(c, s.svr, r2) - mustRegionHeartbeat(c, s.svr, r3) + mustRegionHeartbeat(re, suite.svr, r1) + mustRegionHeartbeat(re, suite.svr, r2) + mustRegionHeartbeat(re, suite.svr, r3) regionIDs := []uint64{2, 3} - url := fmt.Sprintf("%s/regions/store/%d", s.urlPrefix, 1) + url := fmt.Sprintf("%s/regions/store/%d", suite.urlPrefix, 1) r4 := &RegionsInfo{} - err := tu.ReadGetJSON(c, testDialClient, url, r4) - c.Assert(err, IsNil) - c.Assert(r4.Count, Equals, len(regionIDs)) + err := tu.ReadGetJSON(re, testDialClient, url, r4) + suite.NoError(err) + suite.Len(regionIDs, r4.Count) sort.Slice(r4.Regions, func(i, j int) bool { return r4.Regions[i].ID < r4.Regions[j].ID }) for i, r := range r4.Regions { - c.Assert(r.ID, Equals, regionIDs[i]) + suite.Equal(regionIDs[i], r.ID) } regionIDs = []uint64{4} - url = fmt.Sprintf("%s/regions/store/%d", s.urlPrefix, 2) + url = fmt.Sprintf("%s/regions/store/%d", suite.urlPrefix, 2) r5 := &RegionsInfo{} - err = tu.ReadGetJSON(c, testDialClient, url, r5) - c.Assert(err, IsNil) - c.Assert(r5.Count, Equals, len(regionIDs)) + err = tu.ReadGetJSON(re, testDialClient, url, r5) + suite.NoError(err) + suite.Len(regionIDs, r5.Count) for i, r := range r5.Regions { - c.Assert(r.ID, Equals, regionIDs[i]) + suite.Equal(regionIDs[i], r.ID) } regionIDs = []uint64{} - url = fmt.Sprintf("%s/regions/store/%d", s.urlPrefix, 3) + url = fmt.Sprintf("%s/regions/store/%d", suite.urlPrefix, 3) r6 := &RegionsInfo{} - err = tu.ReadGetJSON(c, testDialClient, url, r6) - c.Assert(err, IsNil) - c.Assert(r6.Count, Equals, len(regionIDs)) + err = tu.ReadGetJSON(re, testDialClient, url, r6) + suite.NoError(err) + suite.Len(regionIDs, r6.Count) } -func (s *testRegionSuite) TestTopFlow(c *C) { +func (suite *regionTestSuite) TestTopFlow() { + re := suite.Require() r1 := newTestRegionInfo(1, 1, []byte("a"), []byte("b"), core.SetWrittenBytes(1000), core.SetReadBytes(1000), core.SetRegionConfVer(1), core.SetRegionVersion(1)) - mustRegionHeartbeat(c, s.svr, r1) + mustRegionHeartbeat(re, suite.svr, r1) r2 := newTestRegionInfo(2, 1, []byte("b"), []byte("c"), core.SetWrittenBytes(2000), core.SetReadBytes(0), core.SetRegionConfVer(2), core.SetRegionVersion(3)) - mustRegionHeartbeat(c, s.svr, r2) + mustRegionHeartbeat(re, suite.svr, r2) r3 := newTestRegionInfo(3, 1, []byte("c"), []byte("d"), core.SetWrittenBytes(500), core.SetReadBytes(800), core.SetRegionConfVer(3), core.SetRegionVersion(2)) - mustRegionHeartbeat(c, s.svr, r3) - s.checkTopRegions(c, fmt.Sprintf("%s/regions/writeflow", s.urlPrefix), []uint64{2, 1, 3}) - s.checkTopRegions(c, fmt.Sprintf("%s/regions/readflow", s.urlPrefix), []uint64{1, 3, 2}) - s.checkTopRegions(c, fmt.Sprintf("%s/regions/writeflow?limit=2", s.urlPrefix), []uint64{2, 1}) - s.checkTopRegions(c, fmt.Sprintf("%s/regions/confver", s.urlPrefix), []uint64{3, 2, 1}) - s.checkTopRegions(c, fmt.Sprintf("%s/regions/confver?limit=2", s.urlPrefix), []uint64{3, 2}) - s.checkTopRegions(c, fmt.Sprintf("%s/regions/version", s.urlPrefix), []uint64{2, 3, 1}) - s.checkTopRegions(c, fmt.Sprintf("%s/regions/version?limit=2", s.urlPrefix), []uint64{2, 3}) -} - -func (s *testRegionSuite) TestTopSize(c *C) { + mustRegionHeartbeat(re, suite.svr, r3) + suite.checkTopRegions(fmt.Sprintf("%s/regions/writeflow", suite.urlPrefix), []uint64{2, 1, 3}) + suite.checkTopRegions(fmt.Sprintf("%s/regions/readflow", suite.urlPrefix), []uint64{1, 3, 2}) + suite.checkTopRegions(fmt.Sprintf("%s/regions/writeflow?limit=2", suite.urlPrefix), []uint64{2, 1}) + suite.checkTopRegions(fmt.Sprintf("%s/regions/confver", suite.urlPrefix), []uint64{3, 2, 1}) + suite.checkTopRegions(fmt.Sprintf("%s/regions/confver?limit=2", suite.urlPrefix), []uint64{3, 2}) + suite.checkTopRegions(fmt.Sprintf("%s/regions/version", suite.urlPrefix), []uint64{2, 3, 1}) + suite.checkTopRegions(fmt.Sprintf("%s/regions/version?limit=2", suite.urlPrefix), []uint64{2, 3}) +} + +func (suite *regionTestSuite) TestTopSize() { + re := suite.Require() baseOpt := []core.RegionCreateOption{core.SetRegionConfVer(3), core.SetRegionVersion(3)} opt := core.SetApproximateSize(1000) r1 := newTestRegionInfo(7, 1, []byte("a"), []byte("b"), append(baseOpt, opt)...) - mustRegionHeartbeat(c, s.svr, r1) + mustRegionHeartbeat(re, suite.svr, r1) opt = core.SetApproximateSize(900) r2 := newTestRegionInfo(8, 1, []byte("b"), []byte("c"), append(baseOpt, opt)...) - mustRegionHeartbeat(c, s.svr, r2) + mustRegionHeartbeat(re, suite.svr, r2) opt = core.SetApproximateSize(800) r3 := newTestRegionInfo(9, 1, []byte("c"), []byte("d"), append(baseOpt, opt)...) - mustRegionHeartbeat(c, s.svr, r3) + mustRegionHeartbeat(re, suite.svr, r3) // query with limit - s.checkTopRegions(c, fmt.Sprintf("%s/regions/size?limit=%d", s.urlPrefix, 2), []uint64{7, 8}) + suite.checkTopRegions(fmt.Sprintf("%s/regions/size?limit=%d", suite.urlPrefix, 2), []uint64{7, 8}) } -func (s *testRegionSuite) TestAccelerateRegionsScheduleInRange(c *C) { +func (suite *regionTestSuite) TestAccelerateRegionsScheduleInRange() { + re := suite.Require() r1 := newTestRegionInfo(557, 13, []byte("a1"), []byte("a2")) r2 := newTestRegionInfo(558, 14, []byte("a2"), []byte("a3")) r3 := newTestRegionInfo(559, 15, []byte("a3"), []byte("a4")) - mustRegionHeartbeat(c, s.svr, r1) - mustRegionHeartbeat(c, s.svr, r2) - mustRegionHeartbeat(c, s.svr, r3) + mustRegionHeartbeat(re, suite.svr, r1) + mustRegionHeartbeat(re, suite.svr, r2) + mustRegionHeartbeat(re, suite.svr, r3) body := fmt.Sprintf(`{"start_key":"%s", "end_key": "%s"}`, hex.EncodeToString([]byte("a1")), hex.EncodeToString([]byte("a3"))) - err := tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/regions/accelerate-schedule", s.urlPrefix), []byte(body), tu.StatusOK(c)) - c.Assert(err, IsNil) - idList := s.svr.GetRaftCluster().GetSuspectRegions() - c.Assert(idList, HasLen, 2) + err := tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/regions/accelerate-schedule", suite.urlPrefix), []byte(body), tu.StatusOK(re)) + suite.NoError(err) + idList := suite.svr.GetRaftCluster().GetSuspectRegions() + suite.Len(idList, 2) } -func (s *testRegionSuite) TestScatterRegions(c *C) { +func (suite *regionTestSuite) TestScatterRegions() { + re := suite.Require() r1 := newTestRegionInfo(601, 13, []byte("b1"), []byte("b2")) r1.GetMeta().Peers = append(r1.GetMeta().Peers, &metapb.Peer{Id: 5, StoreId: 14}, &metapb.Peer{Id: 6, StoreId: 15}) r2 := newTestRegionInfo(602, 13, []byte("b2"), []byte("b3")) r2.GetMeta().Peers = append(r2.GetMeta().Peers, &metapb.Peer{Id: 7, StoreId: 14}, &metapb.Peer{Id: 8, StoreId: 15}) r3 := newTestRegionInfo(603, 13, []byte("b4"), []byte("b4")) r3.GetMeta().Peers = append(r3.GetMeta().Peers, &metapb.Peer{Id: 9, StoreId: 14}, &metapb.Peer{Id: 10, StoreId: 15}) - mustRegionHeartbeat(c, s.svr, r1) - mustRegionHeartbeat(c, s.svr, r2) - mustRegionHeartbeat(c, s.svr, r3) - mustPutStore(c, s.svr, 13, metapb.StoreState_Up, metapb.NodeState_Serving, []*metapb.StoreLabel{}) - mustPutStore(c, s.svr, 14, metapb.StoreState_Up, metapb.NodeState_Serving, []*metapb.StoreLabel{}) - mustPutStore(c, s.svr, 15, metapb.StoreState_Up, metapb.NodeState_Serving, []*metapb.StoreLabel{}) - mustPutStore(c, s.svr, 16, metapb.StoreState_Up, metapb.NodeState_Serving, []*metapb.StoreLabel{}) + mustRegionHeartbeat(re, suite.svr, r1) + mustRegionHeartbeat(re, suite.svr, r2) + mustRegionHeartbeat(re, suite.svr, r3) + mustPutStore(re, suite.svr, 13, metapb.StoreState_Up, metapb.NodeState_Serving, []*metapb.StoreLabel{}) + mustPutStore(re, suite.svr, 14, metapb.StoreState_Up, metapb.NodeState_Serving, []*metapb.StoreLabel{}) + mustPutStore(re, suite.svr, 15, metapb.StoreState_Up, metapb.NodeState_Serving, []*metapb.StoreLabel{}) + mustPutStore(re, suite.svr, 16, metapb.StoreState_Up, metapb.NodeState_Serving, []*metapb.StoreLabel{}) body := fmt.Sprintf(`{"start_key":"%s", "end_key": "%s"}`, hex.EncodeToString([]byte("b1")), hex.EncodeToString([]byte("b3"))) - err := tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/regions/scatter", s.urlPrefix), []byte(body), tu.StatusOK(c)) - c.Assert(err, IsNil) - op1 := s.svr.GetRaftCluster().GetOperatorController().GetOperator(601) - op2 := s.svr.GetRaftCluster().GetOperatorController().GetOperator(602) - op3 := s.svr.GetRaftCluster().GetOperatorController().GetOperator(603) + err := tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/regions/scatter", suite.urlPrefix), []byte(body), tu.StatusOK(re)) + suite.NoError(err) + op1 := suite.svr.GetRaftCluster().GetOperatorController().GetOperator(601) + op2 := suite.svr.GetRaftCluster().GetOperatorController().GetOperator(602) + op3 := suite.svr.GetRaftCluster().GetOperatorController().GetOperator(603) // At least one operator used to scatter region - c.Assert(op1 != nil || op2 != nil || op3 != nil, IsTrue) + suite.True(op1 != nil || op2 != nil || op3 != nil) body = `{"regions_id": [601, 602, 603]}` - err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/regions/scatter", s.urlPrefix), []byte(body), tu.StatusOK(c)) - c.Assert(err, IsNil) + err = tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/regions/scatter", suite.urlPrefix), []byte(body), tu.StatusOK(re)) + suite.NoError(err) } -func (s *testRegionSuite) TestSplitRegions(c *C) { +func (suite *regionTestSuite) TestSplitRegions() { + re := suite.Require() r1 := newTestRegionInfo(601, 13, []byte("aaa"), []byte("ggg")) r1.GetMeta().Peers = append(r1.GetMeta().Peers, &metapb.Peer{Id: 5, StoreId: 13}, &metapb.Peer{Id: 6, StoreId: 13}) - mustRegionHeartbeat(c, s.svr, r1) - mustPutStore(c, s.svr, 13, metapb.StoreState_Up, metapb.NodeState_Serving, []*metapb.StoreLabel{}) + mustRegionHeartbeat(re, suite.svr, r1) + mustPutStore(re, suite.svr, 13, metapb.StoreState_Up, metapb.NodeState_Serving, []*metapb.StoreLabel{}) newRegionID := uint64(11) body := fmt.Sprintf(`{"retry_limit":%v, "split_keys": ["%s","%s","%s"]}`, 3, hex.EncodeToString([]byte("bbb")), @@ -370,27 +382,27 @@ func (s *testRegionSuite) TestSplitRegions(c *C) { NewRegionsID []uint64 `json:"regions-id"` }{} err := json.Unmarshal(res, s) - c.Assert(err, IsNil) - c.Assert(s.ProcessedPercentage, Equals, 100) - c.Assert(s.NewRegionsID, DeepEquals, []uint64{newRegionID}) + suite.NoError(err) + suite.Equal(100, s.ProcessedPercentage) + suite.Equal([]uint64{newRegionID}, s.NewRegionsID) } - c.Assert(failpoint.Enable("github.com/tikv/pd/server/api/splitResponses", fmt.Sprintf("return(%v)", newRegionID)), IsNil) - err := tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/regions/split", s.urlPrefix), []byte(body), checkOpt) - c.Assert(failpoint.Disable("github.com/tikv/pd/server/api/splitResponses"), IsNil) - c.Assert(err, IsNil) + suite.NoError(failpoint.Enable("github.com/tikv/pd/server/api/splitResponses", fmt.Sprintf("return(%v)", newRegionID))) + err := tu.CheckPostJSON(testDialClient, fmt.Sprintf("%s/regions/split", suite.urlPrefix), []byte(body), checkOpt) + suite.NoError(failpoint.Disable("github.com/tikv/pd/server/api/splitResponses")) + suite.NoError(err) } -func (s *testRegionSuite) checkTopRegions(c *C, url string, regionIDs []uint64) { +func (suite *regionTestSuite) checkTopRegions(url string, regionIDs []uint64) { regions := &RegionsInfo{} - err := tu.ReadGetJSON(c, testDialClient, url, regions) - c.Assert(err, IsNil) - c.Assert(regions.Count, Equals, len(regionIDs)) + err := tu.ReadGetJSON(suite.Require(), testDialClient, url, regions) + suite.NoError(err) + suite.Len(regionIDs, regions.Count) for i, r := range regions.Regions { - c.Assert(r.ID, Equals, regionIDs[i]) + suite.Equal(regionIDs[i], r.ID) } } -func (s *testRegionSuite) TestTopN(c *C) { +func (suite *regionTestSuite) TestTopN() { writtenBytes := []uint64{10, 10, 9, 5, 3, 2, 2, 1, 0, 0} for n := 0; n <= len(writtenBytes)+1; n++ { regions := make([]*core.RegionInfo, 0, len(writtenBytes)) @@ -401,138 +413,150 @@ func (s *testRegionSuite) TestTopN(c *C) { } topN := TopNRegions(regions, func(a, b *core.RegionInfo) bool { return a.GetBytesWritten() < b.GetBytesWritten() }, n) if n > len(writtenBytes) { - c.Assert(len(topN), Equals, len(writtenBytes)) + suite.Len(writtenBytes, len(topN)) } else { - c.Assert(topN, HasLen, n) + suite.Len(topN, n) } for i := range topN { - c.Assert(topN[i].GetBytesWritten(), Equals, writtenBytes[i]) + suite.Equal(writtenBytes[i], topN[i].GetBytesWritten()) } } } -var _ = Suite(&testGetRegionSuite{}) - -type testGetRegionSuite struct { +type getRegionTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testGetRegionSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c) - mustWaitLeader(c, []*server.Server{s.svr}) +func TestGetRegionTestSuite(t *testing.T) { + suite.Run(t, new(getRegionTestSuite)) +} + +func (suite *getRegionTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) - mustBootstrapCluster(c, s.svr) + mustBootstrapCluster(re, suite.svr) } -func (s *testGetRegionSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *getRegionTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *testGetRegionSuite) TestRegionKey(c *C) { +func (suite *getRegionTestSuite) TestRegionKey() { + re := suite.Require() r := newTestRegionInfo(99, 1, []byte{0xFF, 0xFF, 0xAA}, []byte{0xFF, 0xFF, 0xCC}, core.SetWrittenBytes(500), core.SetReadBytes(800), core.SetRegionConfVer(3), core.SetRegionVersion(2)) - mustRegionHeartbeat(c, s.svr, r) - url := fmt.Sprintf("%s/region/key/%s", s.urlPrefix, url.QueryEscape(string([]byte{0xFF, 0xFF, 0xBB}))) + mustRegionHeartbeat(re, suite.svr, r) + url := fmt.Sprintf("%s/region/key/%s", suite.urlPrefix, url.QueryEscape(string([]byte{0xFF, 0xFF, 0xBB}))) RegionInfo := &RegionInfo{} - err := tu.ReadGetJSON(c, testDialClient, url, RegionInfo) - c.Assert(err, IsNil) - c.Assert(r.GetID(), Equals, RegionInfo.ID) + err := tu.ReadGetJSON(re, testDialClient, url, RegionInfo) + suite.NoError(err) + suite.Equal(RegionInfo.ID, r.GetID()) } -func (s *testGetRegionSuite) TestScanRegionByKeys(c *C) { +func (suite *getRegionTestSuite) TestScanRegionByKeys() { + re := suite.Require() r1 := newTestRegionInfo(2, 1, []byte("a"), []byte("b")) r2 := newTestRegionInfo(3, 1, []byte("b"), []byte("c")) r3 := newTestRegionInfo(4, 2, []byte("c"), []byte("e")) r4 := newTestRegionInfo(5, 2, []byte("x"), []byte("z")) r := newTestRegionInfo(99, 1, []byte{0xFF, 0xFF, 0xAA}, []byte{0xFF, 0xFF, 0xCC}, core.SetWrittenBytes(500), core.SetReadBytes(800), core.SetRegionConfVer(3), core.SetRegionVersion(2)) - mustRegionHeartbeat(c, s.svr, r1) - mustRegionHeartbeat(c, s.svr, r2) - mustRegionHeartbeat(c, s.svr, r3) - mustRegionHeartbeat(c, s.svr, r4) - mustRegionHeartbeat(c, s.svr, r) + mustRegionHeartbeat(re, suite.svr, r1) + mustRegionHeartbeat(re, suite.svr, r2) + mustRegionHeartbeat(re, suite.svr, r3) + mustRegionHeartbeat(re, suite.svr, r4) + mustRegionHeartbeat(re, suite.svr, r) - url := fmt.Sprintf("%s/regions/key?key=%s", s.urlPrefix, "b") + url := fmt.Sprintf("%s/regions/key?key=%s", suite.urlPrefix, "b") regionIDs := []uint64{3, 4, 5, 99} regions := &RegionsInfo{} - err := tu.ReadGetJSON(c, testDialClient, url, regions) - c.Assert(err, IsNil) - c.Assert(regionIDs, HasLen, regions.Count) + err := tu.ReadGetJSON(re, testDialClient, url, regions) + suite.NoError(err) + suite.Len(regionIDs, regions.Count) for i, v := range regionIDs { - c.Assert(v, Equals, regions.Regions[i].ID) + suite.Equal(regions.Regions[i].ID, v) } - url = fmt.Sprintf("%s/regions/key?key=%s", s.urlPrefix, "d") + url = fmt.Sprintf("%s/regions/key?key=%s", suite.urlPrefix, "d") regionIDs = []uint64{4, 5, 99} regions = &RegionsInfo{} - err = tu.ReadGetJSON(c, testDialClient, url, regions) - c.Assert(err, IsNil) - c.Assert(regionIDs, HasLen, regions.Count) + err = tu.ReadGetJSON(re, testDialClient, url, regions) + suite.NoError(err) + suite.Len(regionIDs, regions.Count) for i, v := range regionIDs { - c.Assert(v, Equals, regions.Regions[i].ID) + suite.Equal(regions.Regions[i].ID, v) } - url = fmt.Sprintf("%s/regions/key?key=%s", s.urlPrefix, "g") + url = fmt.Sprintf("%s/regions/key?key=%s", suite.urlPrefix, "g") regionIDs = []uint64{5, 99} regions = &RegionsInfo{} - err = tu.ReadGetJSON(c, testDialClient, url, regions) - c.Assert(err, IsNil) - c.Assert(regionIDs, HasLen, regions.Count) + err = tu.ReadGetJSON(re, testDialClient, url, regions) + suite.NoError(err) + suite.Len(regionIDs, regions.Count) for i, v := range regionIDs { - c.Assert(v, Equals, regions.Regions[i].ID) + suite.Equal(regions.Regions[i].ID, v) } - url = fmt.Sprintf("%s/regions/key?end_key=%s", s.urlPrefix, "e") + url = fmt.Sprintf("%s/regions/key?end_key=%s", suite.urlPrefix, "e") regionIDs = []uint64{2, 3, 4} regions = &RegionsInfo{} - err = tu.ReadGetJSON(c, testDialClient, url, regions) - c.Assert(err, IsNil) - c.Assert(len(regionIDs), Equals, regions.Count) + err = tu.ReadGetJSON(re, testDialClient, url, regions) + suite.NoError(err) + suite.Equal(regions.Count, len(regionIDs)) for i, v := range regionIDs { - c.Assert(v, Equals, regions.Regions[i].ID) + suite.Equal(regions.Regions[i].ID, v) } - url = fmt.Sprintf("%s/regions/key?key=%s&end_key=%s", s.urlPrefix, "b", "g") + url = fmt.Sprintf("%s/regions/key?key=%s&end_key=%s", suite.urlPrefix, "b", "g") regionIDs = []uint64{3, 4} regions = &RegionsInfo{} - err = tu.ReadGetJSON(c, testDialClient, url, regions) - c.Assert(err, IsNil) - c.Assert(len(regionIDs), Equals, regions.Count) + err = tu.ReadGetJSON(re, testDialClient, url, regions) + suite.NoError(err) + suite.Equal(regions.Count, len(regionIDs)) for i, v := range regionIDs { - c.Assert(v, Equals, regions.Regions[i].ID) + suite.Equal(regions.Regions[i].ID, v) } - url = fmt.Sprintf("%s/regions/key?key=%s&end_key=%s", s.urlPrefix, "b", []byte{0xFF, 0xFF, 0xCC}) + url = fmt.Sprintf("%s/regions/key?key=%s&end_key=%s", suite.urlPrefix, "b", []byte{0xFF, 0xFF, 0xCC}) regionIDs = []uint64{3, 4, 5, 99} regions = &RegionsInfo{} - err = tu.ReadGetJSON(c, testDialClient, url, regions) - c.Assert(err, IsNil) - c.Assert(len(regionIDs), Equals, regions.Count) + err = tu.ReadGetJSON(re, testDialClient, url, regions) + suite.NoError(err) + suite.Equal(regions.Count, len(regionIDs)) for i, v := range regionIDs { - c.Assert(v, Equals, regions.Regions[i].ID) + suite.Equal(regions.Regions[i].ID, v) } } // Start a new test suite to prevent from being interfered by other tests. -var _ = Suite(&testGetRegionRangeHolesSuite{}) -type testGetRegionRangeHolesSuite struct { +type getRegionRangeHolesTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testGetRegionRangeHolesSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c) - mustWaitLeader(c, []*server.Server{s.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) - mustBootstrapCluster(c, s.svr) +func TestGetRegionRangeHolesTestSuite(t *testing.T) { + suite.Run(t, new(getRegionRangeHolesTestSuite)) } -func (s *testGetRegionRangeHolesSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *getRegionRangeHolesTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re) + mustWaitLeader(re, []*server.Server{suite.svr}) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) + mustBootstrapCluster(re, suite.svr) } -func (s *testGetRegionRangeHolesSuite) TestRegionRangeHoles(c *C) { +func (suite *getRegionRangeHolesTestSuite) TearDownSuite() { + suite.cleanup() +} + +func (suite *getRegionRangeHolesTestSuite) TestRegionRangeHoles() { + re := suite.Require() // Missing r0 with range [0, 0xEA] r1 := newTestRegionInfo(2, 1, []byte{0xEA}, []byte{0xEB}) // Missing r2 with range [0xEB, 0xEC] @@ -540,54 +564,59 @@ func (s *testGetRegionRangeHolesSuite) TestRegionRangeHoles(c *C) { r4 := newTestRegionInfo(4, 2, []byte{0xED}, []byte{0xEE}) // Missing r5 with range [0xEE, 0xFE] r6 := newTestRegionInfo(5, 2, []byte{0xFE}, []byte{0xFF}) - mustRegionHeartbeat(c, s.svr, r1) - mustRegionHeartbeat(c, s.svr, r3) - mustRegionHeartbeat(c, s.svr, r4) - mustRegionHeartbeat(c, s.svr, r6) + mustRegionHeartbeat(re, suite.svr, r1) + mustRegionHeartbeat(re, suite.svr, r3) + mustRegionHeartbeat(re, suite.svr, r4) + mustRegionHeartbeat(re, suite.svr, r6) - url := fmt.Sprintf("%s/regions/range-holes", s.urlPrefix) + url := fmt.Sprintf("%s/regions/range-holes", suite.urlPrefix) rangeHoles := new([][]string) - c.Assert(tu.ReadGetJSON(c, testDialClient, url, rangeHoles), IsNil) - c.Assert(*rangeHoles, DeepEquals, [][]string{ + suite.NoError(tu.ReadGetJSON(re, testDialClient, url, rangeHoles)) + suite.Equal([][]string{ {"", core.HexRegionKeyStr(r1.GetStartKey())}, {core.HexRegionKeyStr(r1.GetEndKey()), core.HexRegionKeyStr(r3.GetStartKey())}, {core.HexRegionKeyStr(r4.GetEndKey()), core.HexRegionKeyStr(r6.GetStartKey())}, {core.HexRegionKeyStr(r6.GetEndKey()), ""}, - }) + }, *rangeHoles) } -var _ = Suite(&testRegionsReplicatedSuite{}) - -type testRegionsReplicatedSuite struct { +type regionsReplicatedTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testRegionsReplicatedSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c) - mustWaitLeader(c, []*server.Server{s.svr}) +func TestRegionsReplicatedTestSuite(t *testing.T) { + suite.Run(t, new(regionsReplicatedTestSuite)) +} - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) +func (suite *regionsReplicatedTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re) + mustWaitLeader(re, []*server.Server{suite.svr}) - mustBootstrapCluster(c, s.svr) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) + + mustBootstrapCluster(re, suite.svr) } -func (s *testRegionsReplicatedSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *regionsReplicatedTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *testRegionsReplicatedSuite) TestCheckRegionsReplicated(c *C) { +func (suite *regionsReplicatedTestSuite) TestCheckRegionsReplicated() { + re := suite.Require() // enable placement rule - c.Assert(tu.CheckPostJSON(testDialClient, s.urlPrefix+"/config", []byte(`{"enable-placement-rules":"true"}`), tu.StatusOK(c)), IsNil) + suite.NoError(tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/config", []byte(`{"enable-placement-rules":"true"}`), tu.StatusOK(re))) defer func() { - c.Assert(tu.CheckPostJSON(testDialClient, s.urlPrefix+"/config", []byte(`{"enable-placement-rules":"false"}`), tu.StatusOK(c)), IsNil) + suite.NoError(tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/config", []byte(`{"enable-placement-rules":"false"}`), tu.StatusOK(re))) }() // add test region r1 := newTestRegionInfo(2, 1, []byte("a"), []byte("b")) - mustRegionHeartbeat(c, s.svr, r1) + mustRegionHeartbeat(re, suite.svr, r1) // set the bundle bundle := []placement.GroupBundle{ @@ -605,49 +634,48 @@ func (s *testRegionsReplicatedSuite) TestCheckRegionsReplicated(c *C) { status := "" // invalid url - url := fmt.Sprintf(`%s/regions/replicated?startKey=%s&endKey=%s`, s.urlPrefix, "_", "t") - err := tu.CheckGetJSON(testDialClient, url, nil, tu.Status(c, http.StatusBadRequest)) - c.Assert(err, IsNil) + url := fmt.Sprintf(`%s/regions/replicated?startKey=%s&endKey=%s`, suite.urlPrefix, "_", "t") + err := tu.CheckGetJSON(testDialClient, url, nil, tu.Status(re, http.StatusBadRequest)) + suite.NoError(err) - url = fmt.Sprintf(`%s/regions/replicated?startKey=%s&endKey=%s`, s.urlPrefix, hex.EncodeToString(r1.GetStartKey()), "_") - err = tu.CheckGetJSON(testDialClient, url, nil, tu.Status(c, http.StatusBadRequest)) - c.Assert(err, IsNil) + url = fmt.Sprintf(`%s/regions/replicated?startKey=%s&endKey=%s`, suite.urlPrefix, hex.EncodeToString(r1.GetStartKey()), "_") + err = tu.CheckGetJSON(testDialClient, url, nil, tu.Status(re, http.StatusBadRequest)) + suite.NoError(err) // correct test - url = fmt.Sprintf(`%s/regions/replicated?startKey=%s&endKey=%s`, s.urlPrefix, hex.EncodeToString(r1.GetStartKey()), hex.EncodeToString(r1.GetEndKey())) + url = fmt.Sprintf(`%s/regions/replicated?startKey=%s&endKey=%s`, suite.urlPrefix, hex.EncodeToString(r1.GetStartKey()), hex.EncodeToString(r1.GetEndKey())) // test one rule data, err := json.Marshal(bundle) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/config/placement-rule", data, tu.StatusOK(c)) - c.Assert(err, IsNil) - - err = tu.ReadGetJSON(c, testDialClient, url, &status) - c.Assert(err, IsNil) - c.Assert(status, Equals, "REPLICATED") - - c.Assert(failpoint.Enable("github.com/tikv/pd/server/api/mockPending", "return(true)"), IsNil) - err = tu.ReadGetJSON(c, testDialClient, url, &status) - c.Assert(err, IsNil) - c.Assert(status, Equals, "PENDING") - c.Assert(failpoint.Disable("github.com/tikv/pd/server/api/mockPending"), IsNil) - + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/config/placement-rule", data, tu.StatusOK(re)) + suite.NoError(err) + + err = tu.ReadGetJSON(re, testDialClient, url, &status) + suite.NoError(err) + suite.Equal("REPLICATED", status) + + suite.NoError(failpoint.Enable("github.com/tikv/pd/server/api/mockPending", "return(true)")) + err = tu.ReadGetJSON(re, testDialClient, url, &status) + suite.NoError(err) + suite.Equal("PENDING", status) + suite.NoError(failpoint.Disable("github.com/tikv/pd/server/api/mockPending")) // test multiple rules r1 = newTestRegionInfo(2, 1, []byte("a"), []byte("b")) r1.GetMeta().Peers = append(r1.GetMeta().Peers, &metapb.Peer{Id: 5, StoreId: 1}) - mustRegionHeartbeat(c, s.svr, r1) + mustRegionHeartbeat(re, suite.svr, r1) bundle[0].Rules = append(bundle[0].Rules, &placement.Rule{ ID: "bar", Index: 1, Role: "voter", Count: 1, }) data, err = json.Marshal(bundle) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/config/placement-rule", data, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/config/placement-rule", data, tu.StatusOK(re)) + suite.NoError(err) - err = tu.ReadGetJSON(c, testDialClient, url, &status) - c.Assert(err, IsNil) - c.Assert(status, Equals, "REPLICATED") + err = tu.ReadGetJSON(re, testDialClient, url, &status) + suite.NoError(err) + suite.Equal("REPLICATED", status) // test multiple bundles bundle = append(bundle, placement.GroupBundle{ @@ -660,21 +688,21 @@ func (s *testRegionsReplicatedSuite) TestCheckRegionsReplicated(c *C) { }, }) data, err = json.Marshal(bundle) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/config/placement-rule", data, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/config/placement-rule", data, tu.StatusOK(re)) + suite.NoError(err) - err = tu.ReadGetJSON(c, testDialClient, url, &status) - c.Assert(err, IsNil) - c.Assert(status, Equals, "INPROGRESS") + err = tu.ReadGetJSON(re, testDialClient, url, &status) + suite.NoError(err) + suite.Equal("INPROGRESS", status) r1 = newTestRegionInfo(2, 1, []byte("a"), []byte("b")) r1.GetMeta().Peers = append(r1.GetMeta().Peers, &metapb.Peer{Id: 5, StoreId: 1}, &metapb.Peer{Id: 6, StoreId: 1}, &metapb.Peer{Id: 7, StoreId: 1}) - mustRegionHeartbeat(c, s.svr, r1) + mustRegionHeartbeat(re, suite.svr, r1) - err = tu.ReadGetJSON(c, testDialClient, url, &status) - c.Assert(err, IsNil) - c.Assert(status, Equals, "REPLICATED") + err = tu.ReadGetJSON(re, testDialClient, url, &status) + suite.NoError(err) + suite.Equal("REPLICATED", status) } // Create n regions (0..n) of n stores (0..n). diff --git a/server/api/rule_test.go b/server/api/rule_test.go index 7e878168906..63af8b19c1c 100644 --- a/server/api/rule_test.go +++ b/server/api/rule_test.go @@ -20,42 +20,47 @@ import ( "fmt" "net/http" "net/url" + "testing" - . "github.com/pingcap/check" + "github.com/stretchr/testify/suite" "github.com/tikv/pd/pkg/apiutil" tu "github.com/tikv/pd/pkg/testutil" "github.com/tikv/pd/server" "github.com/tikv/pd/server/schedule/placement" ) -var _ = Suite(&testRuleSuite{}) - -type testRuleSuite struct { +type ruleTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testRuleSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c) - mustWaitLeader(c, []*server.Server{s.svr}) +func TestRuleTestSuite(t *testing.T) { + suite.Run(t, new(ruleTestSuite)) +} + +func (suite *ruleTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1/config", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1/config", addr, apiPrefix) - mustBootstrapCluster(c, s.svr) - PDServerCfg := s.svr.GetConfig().PDServerCfg + mustBootstrapCluster(re, suite.svr) + PDServerCfg := suite.svr.GetConfig().PDServerCfg PDServerCfg.KeyType = "raw" - err := s.svr.SetPDServerConfig(PDServerCfg) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, s.urlPrefix, []byte(`{"enable-placement-rules":"true"}`), tu.StatusOK(c)), IsNil) + err := suite.svr.SetPDServerConfig(PDServerCfg) + suite.NoError(err) + suite.NoError(tu.CheckPostJSON(testDialClient, suite.urlPrefix, []byte(`{"enable-placement-rules":"true"}`), tu.StatusOK(re))) } -func (s *testRuleSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *ruleTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *testRuleSuite) TearDownTest(c *C) { +func (suite *ruleTestSuite) TearDownTest() { def := placement.GroupBundle{ ID: "pd", Rules: []*placement.Rule{ @@ -63,35 +68,35 @@ func (s *testRuleSuite) TearDownTest(c *C) { }, } data, err := json.Marshal([]placement.GroupBundle{def}) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/placement-rule", data, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/placement-rule", data, tu.StatusOK(suite.Require())) + suite.NoError(err) } -func (s *testRuleSuite) TestSet(c *C) { +func (suite *ruleTestSuite) TestSet() { rule := placement.Rule{GroupID: "a", ID: "10", StartKeyHex: "1111", EndKeyHex: "3333", Role: "voter", Count: 1} successData, err := json.Marshal(rule) - c.Assert(err, IsNil) + suite.NoError(err) oldStartKey, err := hex.DecodeString(rule.StartKeyHex) - c.Assert(err, IsNil) + suite.NoError(err) oldEndKey, err := hex.DecodeString(rule.EndKeyHex) - c.Assert(err, IsNil) + suite.NoError(err) parseErrData := []byte("foo") rule1 := placement.Rule{GroupID: "a", ID: "10", StartKeyHex: "XXXX", EndKeyHex: "3333", Role: "voter", Count: 1} checkErrData, err := json.Marshal(rule1) - c.Assert(err, IsNil) + suite.NoError(err) rule2 := placement.Rule{GroupID: "a", ID: "10", StartKeyHex: "1111", EndKeyHex: "3333", Role: "voter", Count: -1} setErrData, err := json.Marshal(rule2) - c.Assert(err, IsNil) + suite.NoError(err) rule3 := placement.Rule{GroupID: "a", ID: "10", StartKeyHex: "1111", EndKeyHex: "3333", Role: "follower", Count: 3} updateData, err := json.Marshal(rule3) - c.Assert(err, IsNil) + suite.NoError(err) newStartKey, err := hex.DecodeString(rule.StartKeyHex) - c.Assert(err, IsNil) + suite.NoError(err) newEndKey, err := hex.DecodeString(rule.EndKeyHex) - c.Assert(err, IsNil) + suite.NoError(err) - testcases := []struct { + testCases := []struct { name string rawData []byte success bool @@ -148,42 +153,43 @@ func (s *testRuleSuite) TestSet(c *C) { `, }, } - - for _, testcase := range testcases { - c.Log(testcase.name) + re := suite.Require() + for _, testCase := range testCases { + suite.T().Log(testCase.name) // clear suspect keyRanges to prevent test case from others - s.svr.GetRaftCluster().ClearSuspectKeyRanges() - if testcase.success { - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/rule", testcase.rawData, tu.StatusOK(c)) + suite.svr.GetRaftCluster().ClearSuspectKeyRanges() + if testCase.success { + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/rule", testCase.rawData, tu.StatusOK(re)) popKeyRangeMap := map[string]struct{}{} - for i := 0; i < len(testcase.popKeyRange)/2; i++ { - v, got := s.svr.GetRaftCluster().PopOneSuspectKeyRange() - c.Assert(got, IsTrue) + for i := 0; i < len(testCase.popKeyRange)/2; i++ { + v, got := suite.svr.GetRaftCluster().PopOneSuspectKeyRange() + suite.True(got) popKeyRangeMap[hex.EncodeToString(v[0])] = struct{}{} popKeyRangeMap[hex.EncodeToString(v[1])] = struct{}{} } - c.Assert(len(popKeyRangeMap), Equals, len(testcase.popKeyRange)) + suite.Len(testCase.popKeyRange, len(popKeyRangeMap)) for k := range popKeyRangeMap { - _, ok := testcase.popKeyRange[k] - c.Assert(ok, IsTrue) + _, ok := testCase.popKeyRange[k] + suite.True(ok) } } else { - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/rule", testcase.rawData, - tu.StatusNotOK(c), - tu.StringEqual(c, testcase.response)) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/rule", testCase.rawData, + tu.StatusNotOK(re), + tu.StringEqual(re, testCase.response)) } - c.Assert(err, IsNil) + suite.NoError(err) } } -func (s *testRuleSuite) TestGet(c *C) { +func (suite *ruleTestSuite) TestGet() { rule := placement.Rule{GroupID: "a", ID: "20", StartKeyHex: "1111", EndKeyHex: "3333", Role: "voter", Count: 1} data, err := json.Marshal(rule) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/rule", data, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + re := suite.Require() + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/rule", data, tu.StatusOK(re)) + suite.NoError(err) - testcases := []struct { + testCases := []struct { name string rule placement.Rule found bool @@ -202,34 +208,35 @@ func (s *testRuleSuite) TestGet(c *C) { code: 404, }, } - for _, testcase := range testcases { - c.Log(testcase.name) + for _, testCase := range testCases { + suite.T().Log(testCase.name) var resp placement.Rule - url := fmt.Sprintf("%s/rule/%s/%s", s.urlPrefix, testcase.rule.GroupID, testcase.rule.ID) - if testcase.found { - err = tu.ReadGetJSON(c, testDialClient, url, &resp) - compareRule(c, &resp, &testcase.rule) + url := fmt.Sprintf("%s/rule/%s/%s", suite.urlPrefix, testCase.rule.GroupID, testCase.rule.ID) + if testCase.found { + err = tu.ReadGetJSON(re, testDialClient, url, &resp) + suite.compareRule(&resp, &testCase.rule) } else { - err = tu.CheckGetJSON(testDialClient, url, nil, tu.Status(c, testcase.code)) + err = tu.CheckGetJSON(testDialClient, url, nil, tu.Status(re, testCase.code)) } - c.Assert(err, IsNil) + suite.NoError(err) } } -func (s *testRuleSuite) TestGetAll(c *C) { +func (suite *ruleTestSuite) TestGetAll() { rule := placement.Rule{GroupID: "b", ID: "20", StartKeyHex: "1111", EndKeyHex: "3333", Role: "voter", Count: 1} data, err := json.Marshal(rule) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/rule", data, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + re := suite.Require() + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/rule", data, tu.StatusOK(re)) + suite.NoError(err) var resp2 []*placement.Rule - err = tu.ReadGetJSON(c, testDialClient, s.urlPrefix+"/rules", &resp2) - c.Assert(err, IsNil) - c.Assert(len(resp2), GreaterEqual, 1) + err = tu.ReadGetJSON(re, testDialClient, suite.urlPrefix+"/rules", &resp2) + suite.NoError(err) + suite.GreaterOrEqual(len(resp2), 1) } -func (s *testRuleSuite) TestSetAll(c *C) { +func (suite *ruleTestSuite) TestSetAll() { rule1 := placement.Rule{GroupID: "a", ID: "12", StartKeyHex: "1111", EndKeyHex: "3333", Role: "voter", Count: 1} rule2 := placement.Rule{GroupID: "b", ID: "12", StartKeyHex: "1111", EndKeyHex: "3333", Role: "voter", Count: 1} rule3 := placement.Rule{GroupID: "a", ID: "12", StartKeyHex: "XXXX", EndKeyHex: "3333", Role: "voter", Count: 1} @@ -238,27 +245,27 @@ func (s *testRuleSuite) TestSetAll(c *C) { LocationLabels: []string{"host"}} rule6 := placement.Rule{GroupID: "pd", ID: "default", StartKeyHex: "", EndKeyHex: "", Role: "voter", Count: 3} - s.svr.GetPersistOptions().GetReplicationConfig().LocationLabels = []string{"host"} - defaultRule := s.svr.GetRaftCluster().GetRuleManager().GetRule("pd", "default") + suite.svr.GetPersistOptions().GetReplicationConfig().LocationLabels = []string{"host"} + defaultRule := suite.svr.GetRaftCluster().GetRuleManager().GetRule("pd", "default") defaultRule.LocationLabels = []string{"host"} - s.svr.GetRaftCluster().GetRuleManager().SetRule(defaultRule) + suite.svr.GetRaftCluster().GetRuleManager().SetRule(defaultRule) successData, err := json.Marshal([]*placement.Rule{&rule1, &rule2}) - c.Assert(err, IsNil) + suite.NoError(err) checkErrData, err := json.Marshal([]*placement.Rule{&rule1, &rule3}) - c.Assert(err, IsNil) + suite.NoError(err) setErrData, err := json.Marshal([]*placement.Rule{&rule1, &rule4}) - c.Assert(err, IsNil) + suite.NoError(err) defaultData, err := json.Marshal([]*placement.Rule{&rule1, &rule5}) - c.Assert(err, IsNil) + suite.NoError(err) recoverData, err := json.Marshal([]*placement.Rule{&rule1, &rule6}) - c.Assert(err, IsNil) + suite.NoError(err) - testcases := []struct { + testCases := []struct { name string rawData []byte success bool @@ -320,38 +327,38 @@ func (s *testRuleSuite) TestSetAll(c *C) { count: 3, }, } - - for _, testcase := range testcases { - c.Log(testcase.name) - - if testcase.success { - err := tu.CheckPostJSON(testDialClient, s.urlPrefix+"/rules", testcase.rawData, tu.StatusOK(c)) - c.Assert(err, IsNil) - if testcase.isDefaultRule { - c.Assert(testcase.count, Equals, int(s.svr.GetPersistOptions().GetReplicationConfig().MaxReplicas)) + re := suite.Require() + for _, testCase := range testCases { + suite.T().Log(testCase.name) + if testCase.success { + err := tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/rules", testCase.rawData, tu.StatusOK(re)) + suite.NoError(err) + if testCase.isDefaultRule { + suite.Equal(int(suite.svr.GetPersistOptions().GetReplicationConfig().MaxReplicas), testCase.count) } } else { - err := tu.CheckPostJSON(testDialClient, s.urlPrefix+"/rules", testcase.rawData, - tu.StringEqual(c, testcase.response)) - c.Assert(err, IsNil) + err := tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/rules", testCase.rawData, + tu.StringEqual(re, testCase.response)) + suite.NoError(err) } } } -func (s *testRuleSuite) TestGetAllByGroup(c *C) { +func (suite *ruleTestSuite) TestGetAllByGroup() { + re := suite.Require() rule := placement.Rule{GroupID: "c", ID: "20", StartKeyHex: "1111", EndKeyHex: "3333", Role: "voter", Count: 1} data, err := json.Marshal(rule) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/rule", data, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/rule", data, tu.StatusOK(re)) + suite.NoError(err) rule1 := placement.Rule{GroupID: "c", ID: "30", StartKeyHex: "1111", EndKeyHex: "3333", Role: "voter", Count: 1} data, err = json.Marshal(rule1) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/rule", data, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/rule", data, tu.StatusOK(re)) + suite.NoError(err) - testcases := []struct { + testCases := []struct { name string groupID string count int @@ -368,31 +375,32 @@ func (s *testRuleSuite) TestGetAllByGroup(c *C) { }, } - for _, testcase := range testcases { - c.Log(testcase.name) + for _, testCase := range testCases { + suite.T().Log(testCase.name) var resp []*placement.Rule - url := fmt.Sprintf("%s/rules/group/%s", s.urlPrefix, testcase.groupID) - err = tu.ReadGetJSON(c, testDialClient, url, &resp) - c.Assert(err, IsNil) - c.Assert(resp, HasLen, testcase.count) - if testcase.count == 2 { - compareRule(c, resp[0], &rule) - compareRule(c, resp[1], &rule1) + url := fmt.Sprintf("%s/rules/group/%s", suite.urlPrefix, testCase.groupID) + err = tu.ReadGetJSON(re, testDialClient, url, &resp) + suite.NoError(err) + suite.Len(resp, testCase.count) + if testCase.count == 2 { + suite.compareRule(resp[0], &rule) + suite.compareRule(resp[1], &rule1) } } } -func (s *testRuleSuite) TestGetAllByRegion(c *C) { +func (suite *ruleTestSuite) TestGetAllByRegion() { rule := placement.Rule{GroupID: "e", ID: "20", StartKeyHex: "1111", EndKeyHex: "3333", Role: "voter", Count: 1} data, err := json.Marshal(rule) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/rule", data, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + re := suite.Require() + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/rule", data, tu.StatusOK(re)) + suite.NoError(err) r := newTestRegionInfo(4, 1, []byte{0x22, 0x22}, []byte{0x33, 0x33}) - mustRegionHeartbeat(c, s.svr, r) + mustRegionHeartbeat(re, suite.svr, r) - testcases := []struct { + testCases := []struct { name string regionID string success bool @@ -416,33 +424,34 @@ func (s *testRuleSuite) TestGetAllByRegion(c *C) { code: 404, }, } - for _, testcase := range testcases { - c.Log(testcase.name) + for _, testCase := range testCases { + suite.T().Log(testCase.name) var resp []*placement.Rule - url := fmt.Sprintf("%s/rules/region/%s", s.urlPrefix, testcase.regionID) + url := fmt.Sprintf("%s/rules/region/%s", suite.urlPrefix, testCase.regionID) - if testcase.success { - err = tu.ReadGetJSON(c, testDialClient, url, &resp) + if testCase.success { + err = tu.ReadGetJSON(re, testDialClient, url, &resp) for _, r := range resp { if r.GroupID == "e" { - compareRule(c, r, &rule) + suite.compareRule(r, &rule) } } } else { - err = tu.CheckGetJSON(testDialClient, url, nil, tu.Status(c, testcase.code)) + err = tu.CheckGetJSON(testDialClient, url, nil, tu.Status(re, testCase.code)) } - c.Assert(err, IsNil) + suite.NoError(err) } } -func (s *testRuleSuite) TestGetAllByKey(c *C) { +func (suite *ruleTestSuite) TestGetAllByKey() { rule := placement.Rule{GroupID: "f", ID: "40", StartKeyHex: "8888", EndKeyHex: "9111", Role: "voter", Count: 1} data, err := json.Marshal(rule) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/rule", data, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + re := suite.Require() + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/rule", data, tu.StatusOK(re)) + suite.NoError(err) - testcases := []struct { + testCases := []struct { name string key string success bool @@ -469,33 +478,32 @@ func (s *testRuleSuite) TestGetAllByKey(c *C) { respSize: 1, }, } - - for _, testcase := range testcases { - c.Log(testcase.name) + for _, testCase := range testCases { + suite.T().Log(testCase.name) var resp []*placement.Rule - url := fmt.Sprintf("%s/rules/key/%s", s.urlPrefix, testcase.key) - if testcase.success { - err = tu.ReadGetJSON(c, testDialClient, url, &resp) - c.Assert(resp, HasLen, testcase.respSize) + url := fmt.Sprintf("%s/rules/key/%s", suite.urlPrefix, testCase.key) + if testCase.success { + err = tu.ReadGetJSON(re, testDialClient, url, &resp) + suite.Len(resp, testCase.respSize) } else { - err = tu.CheckGetJSON(testDialClient, url, nil, tu.Status(c, testcase.code)) + err = tu.CheckGetJSON(testDialClient, url, nil, tu.Status(re, testCase.code)) } - c.Assert(err, IsNil) + suite.NoError(err) } } -func (s *testRuleSuite) TestDelete(c *C) { +func (suite *ruleTestSuite) TestDelete() { rule := placement.Rule{GroupID: "g", ID: "10", StartKeyHex: "8888", EndKeyHex: "9111", Role: "voter", Count: 1} data, err := json.Marshal(rule) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/rule", data, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/rule", data, tu.StatusOK(suite.Require())) + suite.NoError(err) oldStartKey, err := hex.DecodeString(rule.StartKeyHex) - c.Assert(err, IsNil) + suite.NoError(err) oldEndKey, err := hex.DecodeString(rule.EndKeyHex) - c.Assert(err, IsNil) + suite.NoError(err) - testcases := []struct { + testCases := []struct { name string groupID string id string @@ -517,41 +525,41 @@ func (s *testRuleSuite) TestDelete(c *C) { popKeyRange: map[string]struct{}{}, }, } - for _, testcase := range testcases { - c.Log(testcase.name) - url := fmt.Sprintf("%s/rule/%s/%s", s.urlPrefix, testcase.groupID, testcase.id) + for _, testCase := range testCases { + suite.T().Log(testCase.name) + url := fmt.Sprintf("%s/rule/%s/%s", suite.urlPrefix, testCase.groupID, testCase.id) // clear suspect keyRanges to prevent test case from others - s.svr.GetRaftCluster().ClearSuspectKeyRanges() + suite.svr.GetRaftCluster().ClearSuspectKeyRanges() statusCode, err := apiutil.DoDelete(testDialClient, url) - c.Assert(err, IsNil) - c.Assert(statusCode, Equals, http.StatusOK) - if len(testcase.popKeyRange) > 0 { + suite.NoError(err) + suite.Equal(http.StatusOK, statusCode) + if len(testCase.popKeyRange) > 0 { popKeyRangeMap := map[string]struct{}{} - for i := 0; i < len(testcase.popKeyRange)/2; i++ { - v, got := s.svr.GetRaftCluster().PopOneSuspectKeyRange() - c.Assert(got, IsTrue) + for i := 0; i < len(testCase.popKeyRange)/2; i++ { + v, got := suite.svr.GetRaftCluster().PopOneSuspectKeyRange() + suite.True(got) popKeyRangeMap[hex.EncodeToString(v[0])] = struct{}{} popKeyRangeMap[hex.EncodeToString(v[1])] = struct{}{} } - c.Assert(len(popKeyRangeMap), Equals, len(testcase.popKeyRange)) + suite.Len(testCase.popKeyRange, len(popKeyRangeMap)) for k := range popKeyRangeMap { - _, ok := testcase.popKeyRange[k] - c.Assert(ok, IsTrue) + _, ok := testCase.popKeyRange[k] + suite.True(ok) } } } } -func compareRule(c *C, r1 *placement.Rule, r2 *placement.Rule) { - c.Assert(r1.GroupID, Equals, r2.GroupID) - c.Assert(r1.ID, Equals, r2.ID) - c.Assert(r1.StartKeyHex, Equals, r2.StartKeyHex) - c.Assert(r1.EndKeyHex, Equals, r2.EndKeyHex) - c.Assert(r1.Role, Equals, r2.Role) - c.Assert(r1.Count, Equals, r2.Count) +func (suite *ruleTestSuite) compareRule(r1 *placement.Rule, r2 *placement.Rule) { + suite.Equal(r2.GroupID, r1.GroupID) + suite.Equal(r2.ID, r1.ID) + suite.Equal(r2.StartKeyHex, r1.StartKeyHex) + suite.Equal(r2.EndKeyHex, r1.EndKeyHex) + suite.Equal(r2.Role, r1.Role) + suite.Equal(r2.Count, r1.Count) } -func (s *testRuleSuite) TestBatch(c *C) { +func (suite *ruleTestSuite) TestBatch() { opt1 := placement.RuleOp{ Action: placement.RuleOpAdd, Rule: &placement.Rule{GroupID: "a", ID: "13", StartKeyHex: "1111", EndKeyHex: "3333", Role: "voter", Count: 1}, @@ -591,21 +599,21 @@ func (s *testRuleSuite) TestBatch(c *C) { } successData1, err := json.Marshal([]placement.RuleOp{opt1, opt2, opt3}) - c.Assert(err, IsNil) + suite.NoError(err) successData2, err := json.Marshal([]placement.RuleOp{opt5, opt7}) - c.Assert(err, IsNil) + suite.NoError(err) successData3, err := json.Marshal([]placement.RuleOp{opt4, opt6}) - c.Assert(err, IsNil) + suite.NoError(err) checkErrData, err := json.Marshal([]placement.RuleOp{opt8}) - c.Assert(err, IsNil) + suite.NoError(err) setErrData, err := json.Marshal([]placement.RuleOp{opt9}) - c.Assert(err, IsNil) + suite.NoError(err) - testcases := []struct { + testCases := []struct { name string rawData []byte success bool @@ -657,22 +665,23 @@ func (s *testRuleSuite) TestBatch(c *C) { `, }, } - - for _, testcase := range testcases { - c.Log(testcase.name) - if testcase.success { - err := tu.CheckPostJSON(testDialClient, s.urlPrefix+"/rules/batch", testcase.rawData, tu.StatusOK(c)) - c.Assert(err, IsNil) + re := suite.Require() + for _, testCase := range testCases { + suite.T().Log(testCase.name) + if testCase.success { + err := tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/rules/batch", testCase.rawData, tu.StatusOK(re)) + suite.NoError(err) } else { - err := tu.CheckPostJSON(testDialClient, s.urlPrefix+"/rules/batch", testcase.rawData, - tu.StatusNotOK(c), - tu.StringEqual(c, testcase.response)) - c.Assert(err, IsNil) + err := tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/rules/batch", testCase.rawData, + tu.StatusNotOK(re), + tu.StringEqual(re, testCase.response)) + suite.NoError(err) } } } -func (s *testRuleSuite) TestBundle(c *C) { +func (suite *ruleTestSuite) TestBundle() { + re := suite.Require() // GetAll b1 := placement.GroupBundle{ ID: "pd", @@ -681,10 +690,10 @@ func (s *testRuleSuite) TestBundle(c *C) { }, } var bundles []placement.GroupBundle - err := tu.ReadGetJSON(c, testDialClient, s.urlPrefix+"/placement-rule", &bundles) - c.Assert(err, IsNil) - c.Assert(bundles, HasLen, 1) - compareBundle(c, bundles[0], b1) + err := tu.ReadGetJSON(re, testDialClient, suite.urlPrefix+"/placement-rule", &bundles) + suite.NoError(err) + suite.Len(bundles, 1) + suite.compareBundle(bundles[0], b1) // Set b2 := placement.GroupBundle{ @@ -696,59 +705,59 @@ func (s *testRuleSuite) TestBundle(c *C) { }, } data, err := json.Marshal(b2) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/placement-rule/foo", data, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/placement-rule/foo", data, tu.StatusOK(re)) + suite.NoError(err) // Get var bundle placement.GroupBundle - err = tu.ReadGetJSON(c, testDialClient, s.urlPrefix+"/placement-rule/foo", &bundle) - c.Assert(err, IsNil) - compareBundle(c, bundle, b2) + err = tu.ReadGetJSON(re, testDialClient, suite.urlPrefix+"/placement-rule/foo", &bundle) + suite.NoError(err) + suite.compareBundle(bundle, b2) // GetAll again - err = tu.ReadGetJSON(c, testDialClient, s.urlPrefix+"/placement-rule", &bundles) - c.Assert(err, IsNil) - c.Assert(bundles, HasLen, 2) - compareBundle(c, bundles[0], b1) - compareBundle(c, bundles[1], b2) + err = tu.ReadGetJSON(re, testDialClient, suite.urlPrefix+"/placement-rule", &bundles) + suite.NoError(err) + suite.Len(bundles, 2) + suite.compareBundle(bundles[0], b1) + suite.compareBundle(bundles[1], b2) // Delete - _, err = apiutil.DoDelete(testDialClient, s.urlPrefix+"/placement-rule/pd") - c.Assert(err, IsNil) + _, err = apiutil.DoDelete(testDialClient, suite.urlPrefix+"/placement-rule/pd") + suite.NoError(err) // GetAll again - err = tu.ReadGetJSON(c, testDialClient, s.urlPrefix+"/placement-rule", &bundles) - c.Assert(err, IsNil) - c.Assert(bundles, HasLen, 1) - compareBundle(c, bundles[0], b2) + err = tu.ReadGetJSON(re, testDialClient, suite.urlPrefix+"/placement-rule", &bundles) + suite.NoError(err) + suite.Len(bundles, 1) + suite.compareBundle(bundles[0], b2) // SetAll b2.Rules = append(b2.Rules, &placement.Rule{GroupID: "foo", ID: "baz", Index: 2, Role: "follower", Count: 1}) b2.Index, b2.Override = 0, false b3 := placement.GroupBundle{ID: "foobar", Index: 100} data, err = json.Marshal([]placement.GroupBundle{b1, b2, b3}) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/placement-rule", data, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/placement-rule", data, tu.StatusOK(re)) + suite.NoError(err) // GetAll again - err = tu.ReadGetJSON(c, testDialClient, s.urlPrefix+"/placement-rule", &bundles) - c.Assert(err, IsNil) - c.Assert(bundles, HasLen, 3) - compareBundle(c, bundles[0], b2) - compareBundle(c, bundles[1], b1) - compareBundle(c, bundles[2], b3) + err = tu.ReadGetJSON(re, testDialClient, suite.urlPrefix+"/placement-rule", &bundles) + suite.NoError(err) + suite.Len(bundles, 3) + suite.compareBundle(bundles[0], b2) + suite.compareBundle(bundles[1], b1) + suite.compareBundle(bundles[2], b3) // Delete using regexp - _, err = apiutil.DoDelete(testDialClient, s.urlPrefix+"/placement-rule/"+url.PathEscape("foo.*")+"?regexp") - c.Assert(err, IsNil) + _, err = apiutil.DoDelete(testDialClient, suite.urlPrefix+"/placement-rule/"+url.PathEscape("foo.*")+"?regexp") + suite.NoError(err) // GetAll again - err = tu.ReadGetJSON(c, testDialClient, s.urlPrefix+"/placement-rule", &bundles) - c.Assert(err, IsNil) - c.Assert(bundles, HasLen, 1) - compareBundle(c, bundles[0], b1) + err = tu.ReadGetJSON(re, testDialClient, suite.urlPrefix+"/placement-rule", &bundles) + suite.NoError(err) + suite.Len(bundles, 1) + suite.compareBundle(bundles[0], b1) // Set id := "rule-without-group-id" @@ -759,24 +768,24 @@ func (s *testRuleSuite) TestBundle(c *C) { }, } data, err = json.Marshal(b4) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/placement-rule/"+id, data, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/placement-rule/"+id, data, tu.StatusOK(re)) + suite.NoError(err) b4.ID = id b4.Rules[0].GroupID = b4.ID // Get - err = tu.ReadGetJSON(c, testDialClient, s.urlPrefix+"/placement-rule/"+id, &bundle) - c.Assert(err, IsNil) - compareBundle(c, bundle, b4) + err = tu.ReadGetJSON(re, testDialClient, suite.urlPrefix+"/placement-rule/"+id, &bundle) + suite.NoError(err) + suite.compareBundle(bundle, b4) // GetAll again - err = tu.ReadGetJSON(c, testDialClient, s.urlPrefix+"/placement-rule", &bundles) - c.Assert(err, IsNil) - c.Assert(bundles, HasLen, 2) - compareBundle(c, bundles[0], b1) - compareBundle(c, bundles[1], b4) + err = tu.ReadGetJSON(re, testDialClient, suite.urlPrefix+"/placement-rule", &bundles) + suite.NoError(err) + suite.Len(bundles, 2) + suite.compareBundle(bundles[0], b1) + suite.compareBundle(bundles[1], b4) // SetAll b5 := placement.GroupBundle{ @@ -787,22 +796,22 @@ func (s *testRuleSuite) TestBundle(c *C) { }, } data, err = json.Marshal([]placement.GroupBundle{b1, b4, b5}) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/placement-rule", data, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/placement-rule", data, tu.StatusOK(re)) + suite.NoError(err) b5.Rules[0].GroupID = b5.ID // GetAll again - err = tu.ReadGetJSON(c, testDialClient, s.urlPrefix+"/placement-rule", &bundles) - c.Assert(err, IsNil) - c.Assert(bundles, HasLen, 3) - compareBundle(c, bundles[0], b1) - compareBundle(c, bundles[1], b4) - compareBundle(c, bundles[2], b5) + err = tu.ReadGetJSON(re, testDialClient, suite.urlPrefix+"/placement-rule", &bundles) + suite.NoError(err) + suite.Len(bundles, 3) + suite.compareBundle(bundles[0], b1) + suite.compareBundle(bundles[1], b4) + suite.compareBundle(bundles[2], b5) } -func (s *testRuleSuite) TestBundleBadRequest(c *C) { +func (suite *ruleTestSuite) TestBundleBadRequest() { testCases := []struct { uri string data string @@ -816,20 +825,20 @@ func (s *testRuleSuite) TestBundleBadRequest(c *C) { {"/placement-rule", `[{"group_id":"foo", "rules": [{"group_id":"bar", "id":"baz", "role":"voter", "count":1}]}]`, false}, } for _, tc := range testCases { - err := tu.CheckPostJSON(testDialClient, s.urlPrefix+tc.uri, []byte(tc.data), + err := tu.CheckPostJSON(testDialClient, suite.urlPrefix+tc.uri, []byte(tc.data), func(_ []byte, code int) { - c.Assert(code == http.StatusOK, Equals, tc.ok) + suite.Equal(tc.ok, code == http.StatusOK) }) - c.Assert(err, IsNil) + suite.NoError(err) } } -func compareBundle(c *C, b1, b2 placement.GroupBundle) { - c.Assert(b1.ID, Equals, b2.ID) - c.Assert(b1.Index, Equals, b2.Index) - c.Assert(b1.Override, Equals, b2.Override) - c.Assert(len(b1.Rules), Equals, len(b2.Rules)) +func (suite *ruleTestSuite) compareBundle(b1, b2 placement.GroupBundle) { + suite.Equal(b2.ID, b1.ID) + suite.Equal(b2.Index, b1.Index) + suite.Equal(b2.Override, b1.Override) + suite.Len(b2.Rules, len(b1.Rules)) for i := range b1.Rules { - compareRule(c, b1.Rules[i], b2.Rules[i]) + suite.compareRule(b1.Rules[i], b2.Rules[i]) } } diff --git a/server/api/scheduler_test.go b/server/api/scheduler_test.go index 8c20bdf6182..c4b30595967 100644 --- a/server/api/scheduler_test.go +++ b/server/api/scheduler_test.go @@ -18,11 +18,12 @@ import ( "encoding/json" "fmt" "net/http" + "testing" "time" - . "github.com/pingcap/check" "github.com/pingcap/failpoint" "github.com/pingcap/kvproto/pkg/metapb" + "github.com/stretchr/testify/suite" "github.com/tikv/pd/pkg/apiutil" tu "github.com/tikv/pd/pkg/testutil" "github.com/tikv/pd/server" @@ -30,86 +31,91 @@ import ( _ "github.com/tikv/pd/server/schedulers" ) -var _ = Suite(&testScheduleSuite{}) - -type testScheduleSuite struct { +type scheduleTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testScheduleSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c) - mustWaitLeader(c, []*server.Server{s.svr}) +func TestScheduleTestSuite(t *testing.T) { + suite.Run(t, new(scheduleTestSuite)) +} + +func (suite *scheduleTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1/schedulers", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1/schedulers", addr, apiPrefix) - mustBootstrapCluster(c, s.svr) - mustPutStore(c, s.svr, 1, metapb.StoreState_Up, metapb.NodeState_Serving, nil) - mustPutStore(c, s.svr, 2, metapb.StoreState_Up, metapb.NodeState_Serving, nil) + mustBootstrapCluster(re, suite.svr) + mustPutStore(re, suite.svr, 1, metapb.StoreState_Up, metapb.NodeState_Serving, nil) + mustPutStore(re, suite.svr, 2, metapb.StoreState_Up, metapb.NodeState_Serving, nil) } -func (s *testScheduleSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *scheduleTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *testScheduleSuite) TestOriginAPI(c *C) { - addURL := s.urlPrefix +func (suite *scheduleTestSuite) TestOriginAPI() { + addURL := suite.urlPrefix input := make(map[string]interface{}) input["name"] = "evict-leader-scheduler" input["store_id"] = 1 body, err := json.Marshal(input) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, addURL, body, tu.StatusOK(c)), IsNil) - rc := s.svr.GetRaftCluster() - c.Assert(rc.GetSchedulers(), HasLen, 1) + suite.NoError(err) + re := suite.Require() + suite.NoError(tu.CheckPostJSON(testDialClient, addURL, body, tu.StatusOK(re))) + rc := suite.svr.GetRaftCluster() + suite.Len(rc.GetSchedulers(), 1) resp := make(map[string]interface{}) - listURL := fmt.Sprintf("%s%s%s/%s/list", s.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, "evict-leader-scheduler") - c.Assert(tu.ReadGetJSON(c, testDialClient, listURL, &resp), IsNil) - c.Assert(resp["store-id-ranges"], HasLen, 1) + listURL := fmt.Sprintf("%s%s%s/%s/list", suite.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, "evict-leader-scheduler") + suite.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) + suite.Len(resp["store-id-ranges"], 1) input1 := make(map[string]interface{}) input1["name"] = "evict-leader-scheduler" input1["store_id"] = 2 body, err = json.Marshal(input1) - c.Assert(err, IsNil) - c.Assert(failpoint.Enable("github.com/tikv/pd/server/schedulers/persistFail", "return(true)"), IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, addURL, body, tu.StatusNotOK(c)), IsNil) - c.Assert(rc.GetSchedulers(), HasLen, 1) + suite.NoError(err) + suite.NoError(failpoint.Enable("github.com/tikv/pd/server/schedulers/persistFail", "return(true)")) + suite.NoError(tu.CheckPostJSON(testDialClient, addURL, body, tu.StatusNotOK(re))) + suite.Len(rc.GetSchedulers(), 1) resp = make(map[string]interface{}) - c.Assert(tu.ReadGetJSON(c, testDialClient, listURL, &resp), IsNil) - c.Assert(resp["store-id-ranges"], HasLen, 1) - c.Assert(failpoint.Disable("github.com/tikv/pd/server/schedulers/persistFail"), IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, addURL, body, tu.StatusOK(c)), IsNil) - c.Assert(rc.GetSchedulers(), HasLen, 1) + suite.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) + suite.Len(resp["store-id-ranges"], 1) + suite.NoError(failpoint.Disable("github.com/tikv/pd/server/schedulers/persistFail")) + suite.NoError(tu.CheckPostJSON(testDialClient, addURL, body, tu.StatusOK(re))) + suite.Len(rc.GetSchedulers(), 1) resp = make(map[string]interface{}) - c.Assert(tu.ReadGetJSON(c, testDialClient, listURL, &resp), IsNil) - c.Assert(resp["store-id-ranges"], HasLen, 2) - deleteURL := fmt.Sprintf("%s/%s", s.urlPrefix, "evict-leader-scheduler-1") + suite.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) + suite.Len(resp["store-id-ranges"], 2) + deleteURL := fmt.Sprintf("%s/%s", suite.urlPrefix, "evict-leader-scheduler-1") _, err = apiutil.DoDelete(testDialClient, deleteURL) - c.Assert(err, IsNil) - c.Assert(rc.GetSchedulers(), HasLen, 1) + suite.NoError(err) + suite.Len(rc.GetSchedulers(), 1) resp1 := make(map[string]interface{}) - c.Assert(tu.ReadGetJSON(c, testDialClient, listURL, &resp1), IsNil) - c.Assert(resp1["store-id-ranges"], HasLen, 1) - deleteURL = fmt.Sprintf("%s/%s", s.urlPrefix, "evict-leader-scheduler-2") - c.Assert(failpoint.Enable("github.com/tikv/pd/server/config/persistFail", "return(true)"), IsNil) + suite.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp1)) + suite.Len(resp1["store-id-ranges"], 1) + deleteURL = fmt.Sprintf("%s/%s", suite.urlPrefix, "evict-leader-scheduler-2") + suite.NoError(failpoint.Enable("github.com/tikv/pd/server/config/persistFail", "return(true)")) statusCode, err := apiutil.DoDelete(testDialClient, deleteURL) - c.Assert(err, IsNil) - c.Assert(statusCode, Equals, 500) - c.Assert(rc.GetSchedulers(), HasLen, 1) - c.Assert(failpoint.Disable("github.com/tikv/pd/server/config/persistFail"), IsNil) + suite.NoError(err) + suite.Equal(500, statusCode) + suite.Len(rc.GetSchedulers(), 1) + suite.NoError(failpoint.Disable("github.com/tikv/pd/server/config/persistFail")) statusCode, err = apiutil.DoDelete(testDialClient, deleteURL) - c.Assert(err, IsNil) - c.Assert(statusCode, Equals, 200) - c.Assert(rc.GetSchedulers(), HasLen, 0) - c.Assert(tu.CheckGetJSON(testDialClient, listURL, nil, tu.Status(c, 404)), IsNil) - + suite.NoError(err) + suite.Equal(200, statusCode) + suite.Len(rc.GetSchedulers(), 0) + suite.NoError(tu.CheckGetJSON(testDialClient, listURL, nil, tu.Status(re, 404))) statusCode, _ = apiutil.DoDelete(testDialClient, deleteURL) - c.Assert(statusCode, Equals, 404) + suite.Equal(404, statusCode) } -func (s *testScheduleSuite) TestAPI(c *C) { +func (suite *scheduleTestSuite) TestAPI() { + re := suite.Require() type arg struct { opt string value interface{} @@ -118,63 +124,63 @@ func (s *testScheduleSuite) TestAPI(c *C) { name string createdName string args []arg - extraTestFunc func(name string, c *C) + extraTestFunc func(name string) }{ { name: "balance-leader-scheduler", - extraTestFunc: func(name string, c *C) { + extraTestFunc: func(name string) { resp := make(map[string]interface{}) - listURL := fmt.Sprintf("%s%s%s/%s/list", s.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name) - c.Assert(tu.ReadGetJSON(c, testDialClient, listURL, &resp), IsNil) - c.Assert(resp["batch"], Equals, 4.0) + listURL := fmt.Sprintf("%s%s%s/%s/list", suite.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name) + suite.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) + suite.Equal(4.0, resp["batch"]) dataMap := make(map[string]interface{}) dataMap["batch"] = 3 - updateURL := fmt.Sprintf("%s%s%s/%s/config", s.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name) + updateURL := fmt.Sprintf("%s%s%s/%s/config", suite.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name) body, err := json.Marshal(dataMap) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, updateURL, body, tu.StatusOK(c)), IsNil) + suite.NoError(err) + suite.NoError(tu.CheckPostJSON(testDialClient, updateURL, body, tu.StatusOK(re))) resp = make(map[string]interface{}) - c.Assert(tu.ReadGetJSON(c, testDialClient, listURL, &resp), IsNil) - c.Assert(resp["batch"], Equals, 3.0) + suite.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) + suite.Equal(3.0, resp["batch"]) // update again err = tu.CheckPostJSON(testDialClient, updateURL, body, - tu.StatusOK(c), - tu.StringEqual(c, "\"no changed\"\n")) - c.Assert(err, IsNil) + tu.StatusOK(re), + tu.StringEqual(re, "\"no changed\"\n")) + suite.NoError(err) // update invalidate batch dataMap = map[string]interface{}{} dataMap["batch"] = 100 body, err = json.Marshal(dataMap) - c.Assert(err, IsNil) + suite.NoError(err) err = tu.CheckPostJSON(testDialClient, updateURL, body, - tu.Status(c, http.StatusBadRequest), - tu.StringEqual(c, "\"invalid batch size which should be an integer between 1 and 10\"\n")) - c.Assert(err, IsNil) + tu.Status(re, http.StatusBadRequest), + tu.StringEqual(re, "\"invalid batch size which should be an integer between 1 and 10\"\n")) + suite.NoError(err) resp = make(map[string]interface{}) - c.Assert(tu.ReadGetJSON(c, testDialClient, listURL, &resp), IsNil) - c.Assert(resp["batch"], Equals, 3.0) + suite.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) + suite.Equal(3.0, resp["batch"]) // empty body err = tu.CheckPostJSON(testDialClient, updateURL, nil, - tu.Status(c, http.StatusInternalServerError), - tu.StringEqual(c, "\"unexpected end of JSON input\"\n")) - c.Assert(err, IsNil) + tu.Status(re, http.StatusInternalServerError), + tu.StringEqual(re, "\"unexpected end of JSON input\"\n")) + suite.NoError(err) // config item not found dataMap = map[string]interface{}{} dataMap["error"] = 3 body, err = json.Marshal(dataMap) - c.Assert(err, IsNil) + suite.NoError(err) err = tu.CheckPostJSON(testDialClient, updateURL, body, - tu.Status(c, http.StatusBadRequest), - tu.StringEqual(c, "\"config item not found\"\n")) - c.Assert(err, IsNil) + tu.Status(re, http.StatusBadRequest), + tu.StringEqual(re, "\"config item not found\"\n")) + suite.NoError(err) }, }, { name: "balance-hot-region-scheduler", - extraTestFunc: func(name string, c *C) { + extraTestFunc: func(name string) { resp := make(map[string]interface{}) - listURL := fmt.Sprintf("%s%s%s/%s/list", s.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name) - c.Assert(tu.ReadGetJSON(c, testDialClient, listURL, &resp), IsNil) + listURL := fmt.Sprintf("%s%s%s/%s/list", suite.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name) + suite.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) expectMap := map[string]float64{ "min-hot-byte-rate": 100, "min-hot-key-rate": 10, @@ -188,25 +194,25 @@ func (s *testScheduleSuite) TestAPI(c *C) { "minor-dec-ratio": 0.99, } for key := range expectMap { - c.Assert(resp[key], DeepEquals, expectMap[key]) + suite.Equal(expectMap[key], resp[key]) } dataMap := make(map[string]interface{}) dataMap["max-zombie-rounds"] = 5.0 expectMap["max-zombie-rounds"] = 5.0 - updateURL := fmt.Sprintf("%s%s%s/%s/config", s.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name) + updateURL := fmt.Sprintf("%s%s%s/%s/config", suite.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name) body, err := json.Marshal(dataMap) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, updateURL, body, tu.StatusOK(c)), IsNil) + suite.NoError(err) + suite.NoError(tu.CheckPostJSON(testDialClient, updateURL, body, tu.StatusOK(re))) resp = make(map[string]interface{}) - c.Assert(tu.ReadGetJSON(c, testDialClient, listURL, &resp), IsNil) + suite.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) for key := range expectMap { - c.Assert(resp[key], DeepEquals, expectMap[key]) + suite.Equal(expectMap[key], resp[key]) } // update again err = tu.CheckPostJSON(testDialClient, updateURL, body, - tu.StatusOK(c), - tu.StringEqual(c, "no changed")) - c.Assert(err, IsNil) + tu.StatusOK(re), + tu.StringEqual(re, "no changed")) + suite.NoError(err) }, }, {name: "balance-region-scheduler"}, @@ -216,38 +222,38 @@ func (s *testScheduleSuite) TestAPI(c *C) { name: "grant-leader-scheduler", createdName: "grant-leader-scheduler", args: []arg{{"store_id", 1}}, - extraTestFunc: func(name string, c *C) { + extraTestFunc: func(name string) { resp := make(map[string]interface{}) - listURL := fmt.Sprintf("%s%s%s/%s/list", s.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name) - c.Assert(tu.ReadGetJSON(c, testDialClient, listURL, &resp), IsNil) + listURL := fmt.Sprintf("%s%s%s/%s/list", suite.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name) + suite.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) exceptMap := make(map[string]interface{}) exceptMap["1"] = []interface{}{map[string]interface{}{"end-key": "", "start-key": ""}} - c.Assert(resp["store-id-ranges"], DeepEquals, exceptMap) + suite.Equal(exceptMap, resp["store-id-ranges"]) // using /pd/v1/schedule-config/grant-leader-scheduler/config to add new store to grant-leader-scheduler input := make(map[string]interface{}) input["name"] = "grant-leader-scheduler" input["store_id"] = 2 - updateURL := fmt.Sprintf("%s%s%s/%s/config", s.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name) + updateURL := fmt.Sprintf("%s%s%s/%s/config", suite.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name) body, err := json.Marshal(input) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, updateURL, body, tu.StatusOK(c)), IsNil) + suite.NoError(err) + suite.NoError(tu.CheckPostJSON(testDialClient, updateURL, body, tu.StatusOK(re))) resp = make(map[string]interface{}) - c.Assert(tu.ReadGetJSON(c, testDialClient, listURL, &resp), IsNil) + suite.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) exceptMap["2"] = []interface{}{map[string]interface{}{"end-key": "", "start-key": ""}} - c.Assert(resp["store-id-ranges"], DeepEquals, exceptMap) + suite.Equal(exceptMap, resp["store-id-ranges"]) // using /pd/v1/schedule-config/grant-leader-scheduler/config to delete exists store from grant-leader-scheduler - deleteURL := fmt.Sprintf("%s%s%s/%s/delete/%s", s.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name, "2") + deleteURL := fmt.Sprintf("%s%s%s/%s/delete/%s", suite.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name, "2") _, err = apiutil.DoDelete(testDialClient, deleteURL) - c.Assert(err, IsNil) + suite.NoError(err) resp = make(map[string]interface{}) - c.Assert(tu.ReadGetJSON(c, testDialClient, listURL, &resp), IsNil) + suite.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) delete(exceptMap, "2") - c.Assert(resp["store-id-ranges"], DeepEquals, exceptMap) + suite.Equal(exceptMap, resp["store-id-ranges"]) statusCode, err := apiutil.DoDelete(testDialClient, deleteURL) - c.Assert(err, IsNil) - c.Assert(statusCode, Equals, 404) + suite.NoError(err) + suite.Equal(404, statusCode) }, }, { @@ -255,24 +261,24 @@ func (s *testScheduleSuite) TestAPI(c *C) { createdName: "scatter-range-test", args: []arg{{"start_key", ""}, {"end_key", ""}, {"range_name", "test"}}, // Test the scheduler config handler. - extraTestFunc: func(name string, c *C) { + extraTestFunc: func(name string) { resp := make(map[string]interface{}) - listURL := fmt.Sprintf("%s%s%s/%s/list", s.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name) - c.Assert(tu.ReadGetJSON(c, testDialClient, listURL, &resp), IsNil) - c.Assert(resp["start-key"], Equals, "") - c.Assert(resp["end-key"], Equals, "") - c.Assert(resp["range-name"], Equals, "test") + listURL := fmt.Sprintf("%s%s%s/%s/list", suite.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name) + suite.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) + suite.Equal("", resp["start-key"]) + suite.Equal("", resp["end-key"]) + suite.Equal("test", resp["range-name"]) resp["start-key"] = "a_00" resp["end-key"] = "a_99" - updateURL := fmt.Sprintf("%s%s%s/%s/config", s.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name) + updateURL := fmt.Sprintf("%s%s%s/%s/config", suite.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name) body, err := json.Marshal(resp) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, updateURL, body, tu.StatusOK(c)), IsNil) + suite.NoError(err) + suite.NoError(tu.CheckPostJSON(testDialClient, updateURL, body, tu.StatusOK(re))) resp = make(map[string]interface{}) - c.Assert(tu.ReadGetJSON(c, testDialClient, listURL, &resp), IsNil) - c.Assert(resp["start-key"], Equals, "a_00") - c.Assert(resp["end-key"], Equals, "a_99") - c.Assert(resp["range-name"], Equals, "test") + suite.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) + suite.Equal("a_00", resp["start-key"]) + suite.Equal("a_99", resp["end-key"]) + suite.Equal("test", resp["range-name"]) }, }, { @@ -280,38 +286,38 @@ func (s *testScheduleSuite) TestAPI(c *C) { createdName: "evict-leader-scheduler", args: []arg{{"store_id", 1}}, // Test the scheduler config handler. - extraTestFunc: func(name string, c *C) { + extraTestFunc: func(name string) { resp := make(map[string]interface{}) - listURL := fmt.Sprintf("%s%s%s/%s/list", s.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name) - c.Assert(tu.ReadGetJSON(c, testDialClient, listURL, &resp), IsNil) + listURL := fmt.Sprintf("%s%s%s/%s/list", suite.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name) + suite.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) exceptMap := make(map[string]interface{}) exceptMap["1"] = []interface{}{map[string]interface{}{"end-key": "", "start-key": ""}} - c.Assert(resp["store-id-ranges"], DeepEquals, exceptMap) + suite.Equal(exceptMap, resp["store-id-ranges"]) // using /pd/v1/schedule-config/evict-leader-scheduler/config to add new store to evict-leader-scheduler input := make(map[string]interface{}) input["name"] = "evict-leader-scheduler" input["store_id"] = 2 - updateURL := fmt.Sprintf("%s%s%s/%s/config", s.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name) + updateURL := fmt.Sprintf("%s%s%s/%s/config", suite.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name) body, err := json.Marshal(input) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, updateURL, body, tu.StatusOK(c)), IsNil) + suite.NoError(err) + suite.NoError(tu.CheckPostJSON(testDialClient, updateURL, body, tu.StatusOK(re))) resp = make(map[string]interface{}) - c.Assert(tu.ReadGetJSON(c, testDialClient, listURL, &resp), IsNil) + suite.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) exceptMap["2"] = []interface{}{map[string]interface{}{"end-key": "", "start-key": ""}} - c.Assert(resp["store-id-ranges"], DeepEquals, exceptMap) + suite.Equal(exceptMap, resp["store-id-ranges"]) // using /pd/v1/schedule-config/evict-leader-scheduler/config to delete exist store from evict-leader-scheduler - deleteURL := fmt.Sprintf("%s%s%s/%s/delete/%s", s.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name, "2") + deleteURL := fmt.Sprintf("%s%s%s/%s/delete/%s", suite.svr.GetAddr(), apiPrefix, server.SchedulerConfigHandlerPath, name, "2") _, err = apiutil.DoDelete(testDialClient, deleteURL) - c.Assert(err, IsNil) + suite.NoError(err) resp = make(map[string]interface{}) - c.Assert(tu.ReadGetJSON(c, testDialClient, listURL, &resp), IsNil) + suite.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) delete(exceptMap, "2") - c.Assert(resp["store-id-ranges"], DeepEquals, exceptMap) + suite.Equal(exceptMap, resp["store-id-ranges"]) statusCode, err := apiutil.DoDelete(testDialClient, deleteURL) - c.Assert(err, IsNil) - c.Assert(statusCode, Equals, 404) + suite.NoError(err) + suite.Equal(404, statusCode) }, }, } @@ -322,8 +328,8 @@ func (s *testScheduleSuite) TestAPI(c *C) { input[a.opt] = a.value } body, err := json.Marshal(input) - c.Assert(err, IsNil) - s.testPauseOrResume(ca.name, ca.createdName, body, ca.extraTestFunc, c) + suite.NoError(err) + suite.testPauseOrResume(ca.name, ca.createdName, body) } // test pause and resume all schedulers. @@ -337,32 +343,32 @@ func (s *testScheduleSuite) TestAPI(c *C) { input[a.opt] = a.value } body, err := json.Marshal(input) - c.Assert(err, IsNil) - s.addScheduler(ca.name, ca.createdName, body, ca.extraTestFunc, c) + suite.NoError(err) + suite.addScheduler(body) } // test pause all schedulers. input := make(map[string]interface{}) input["delay"] = 30 pauseArgs, err := json.Marshal(input) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/all", pauseArgs, tu.StatusOK(c)) - c.Assert(err, IsNil) - handler := s.svr.GetHandler() + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/all", pauseArgs, tu.StatusOK(re)) + suite.NoError(err) + handler := suite.svr.GetHandler() for _, ca := range cases { createdName := ca.createdName if createdName == "" { createdName = ca.name } isPaused, err := handler.IsSchedulerPaused(createdName) - c.Assert(err, IsNil) - c.Assert(isPaused, IsTrue) + suite.NoError(err) + suite.True(isPaused) } input["delay"] = 1 pauseArgs, err = json.Marshal(input) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/all", pauseArgs, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/all", pauseArgs, tu.StatusOK(re)) + suite.NoError(err) time.Sleep(time.Second) for _, ca := range cases { createdName := ca.createdName @@ -370,29 +376,29 @@ func (s *testScheduleSuite) TestAPI(c *C) { createdName = ca.name } isPaused, err := handler.IsSchedulerPaused(createdName) - c.Assert(err, IsNil) - c.Assert(isPaused, IsFalse) + suite.NoError(err) + suite.False(isPaused) } // test resume all schedulers. input["delay"] = 30 pauseArgs, err = json.Marshal(input) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/all", pauseArgs, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/all", pauseArgs, tu.StatusOK(re)) + suite.NoError(err) input["delay"] = 0 pauseArgs, err = json.Marshal(input) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/all", pauseArgs, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/all", pauseArgs, tu.StatusOK(re)) + suite.NoError(err) for _, ca := range cases { createdName := ca.createdName if createdName == "" { createdName = ca.name } isPaused, err := handler.IsSchedulerPaused(createdName) - c.Assert(err, IsNil) - c.Assert(isPaused, IsFalse) + suite.NoError(err) + suite.False(isPaused) } // delete schedulers. @@ -401,124 +407,114 @@ func (s *testScheduleSuite) TestAPI(c *C) { if createdName == "" { createdName = ca.name } - s.deleteScheduler(createdName, c) + suite.deleteScheduler(createdName) } } -func (s *testScheduleSuite) TestDisable(c *C) { +func (suite *scheduleTestSuite) TestDisable() { name := "shuffle-leader-scheduler" input := make(map[string]interface{}) input["name"] = name body, err := json.Marshal(input) - c.Assert(err, IsNil) - s.addScheduler(name, name, body, nil, c) + suite.NoError(err) + suite.addScheduler(body) - u := fmt.Sprintf("%s%s/api/v1/config/schedule", s.svr.GetAddr(), apiPrefix) + re := suite.Require() + u := fmt.Sprintf("%s%s/api/v1/config/schedule", suite.svr.GetAddr(), apiPrefix) var scheduleConfig config.ScheduleConfig - err = tu.ReadGetJSON(c, testDialClient, u, &scheduleConfig) - c.Assert(err, IsNil) + err = tu.ReadGetJSON(re, testDialClient, u, &scheduleConfig) + suite.NoError(err) originSchedulers := scheduleConfig.Schedulers scheduleConfig.Schedulers = config.SchedulerConfigs{config.SchedulerConfig{Type: "shuffle-leader", Disable: true}} body, err = json.Marshal(scheduleConfig) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, u, body, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, u, body, tu.StatusOK(re)) + suite.NoError(err) var schedulers []string - err = tu.ReadGetJSON(c, testDialClient, s.urlPrefix, &schedulers) - c.Assert(err, IsNil) - c.Assert(schedulers, HasLen, 1) - c.Assert(schedulers[0], Equals, name) + err = tu.ReadGetJSON(re, testDialClient, suite.urlPrefix, &schedulers) + suite.NoError(err) + suite.Len(schedulers, 1) + suite.Equal(name, schedulers[0]) - err = tu.ReadGetJSON(c, testDialClient, fmt.Sprintf("%s?status=disabled", s.urlPrefix), &schedulers) - c.Assert(err, IsNil) - c.Assert(schedulers, HasLen, 1) - c.Assert(schedulers[0], Equals, name) + err = tu.ReadGetJSON(re, testDialClient, fmt.Sprintf("%s?status=disabled", suite.urlPrefix), &schedulers) + suite.NoError(err) + suite.Len(schedulers, 1) + suite.Equal(name, schedulers[0]) // reset schedule config scheduleConfig.Schedulers = originSchedulers body, err = json.Marshal(scheduleConfig) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, u, body, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, u, body, tu.StatusOK(re)) + suite.NoError(err) - s.deleteScheduler(name, c) + suite.deleteScheduler(name) } -func (s *testScheduleSuite) addScheduler(name, createdName string, body []byte, extraTest func(string, *C), c *C) { - if createdName == "" { - createdName = name - } - err := tu.CheckPostJSON(testDialClient, s.urlPrefix, body, tu.StatusOK(c)) - c.Assert(err, IsNil) - - if extraTest != nil { - extraTest(createdName, c) - } +func (suite *scheduleTestSuite) addScheduler(body []byte) { + err := tu.CheckPostJSON(testDialClient, suite.urlPrefix, body, tu.StatusOK(suite.Require())) + suite.NoError(err) } -func (s *testScheduleSuite) deleteScheduler(createdName string, c *C) { - deleteURL := fmt.Sprintf("%s/%s", s.urlPrefix, createdName) +func (suite *scheduleTestSuite) deleteScheduler(createdName string) { + deleteURL := fmt.Sprintf("%s/%s", suite.urlPrefix, createdName) _, err := apiutil.DoDelete(testDialClient, deleteURL) - c.Assert(err, IsNil) + suite.NoError(err) } -func (s *testScheduleSuite) testPauseOrResume(name, createdName string, body []byte, extraTest func(string, *C), c *C) { +func (suite *scheduleTestSuite) testPauseOrResume(name, createdName string, body []byte) { if createdName == "" { createdName = name } - err := tu.CheckPostJSON(testDialClient, s.urlPrefix, body, tu.StatusOK(c)) - c.Assert(err, IsNil) - handler := s.svr.GetHandler() + re := suite.Require() + err := tu.CheckPostJSON(testDialClient, suite.urlPrefix, body, tu.StatusOK(re)) + suite.NoError(err) + handler := suite.svr.GetHandler() sches, err := handler.GetSchedulers() - c.Assert(err, IsNil) - c.Assert(sches[0], Equals, createdName) + suite.NoError(err) + suite.Equal(createdName, sches[0]) // test pause. input := make(map[string]interface{}) input["delay"] = 30 pauseArgs, err := json.Marshal(input) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/"+createdName, pauseArgs, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/"+createdName, pauseArgs, tu.StatusOK(re)) + suite.NoError(err) isPaused, err := handler.IsSchedulerPaused(createdName) - c.Assert(err, IsNil) - c.Assert(isPaused, IsTrue) + suite.NoError(err) + suite.True(isPaused) input["delay"] = 1 pauseArgs, err = json.Marshal(input) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/"+createdName, pauseArgs, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/"+createdName, pauseArgs, tu.StatusOK(re)) + suite.NoError(err) pausedAt, err := handler.GetPausedSchedulerDelayAt(createdName) - c.Assert(err, IsNil) + suite.NoError(err) resumeAt, err := handler.GetPausedSchedulerDelayUntil(createdName) - c.Assert(err, IsNil) - c.Assert(resumeAt-pausedAt, Equals, int64(1)) + suite.NoError(err) + suite.Equal(int64(1), resumeAt-pausedAt) time.Sleep(time.Second) isPaused, err = handler.IsSchedulerPaused(createdName) - c.Assert(err, IsNil) - c.Assert(isPaused, IsFalse) + suite.NoError(err) + suite.False(isPaused) // test resume. input = make(map[string]interface{}) input["delay"] = 30 pauseArgs, err = json.Marshal(input) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/"+createdName, pauseArgs, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/"+createdName, pauseArgs, tu.StatusOK(re)) + suite.NoError(err) input["delay"] = 0 pauseArgs, err = json.Marshal(input) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/"+createdName, pauseArgs, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/"+createdName, pauseArgs, tu.StatusOK(re)) + suite.NoError(err) isPaused, err = handler.IsSchedulerPaused(createdName) - c.Assert(err, IsNil) - c.Assert(isPaused, IsFalse) - - if extraTest != nil { - extraTest(createdName, c) - } - - s.deleteScheduler(createdName, c) + suite.NoError(err) + suite.False(isPaused) + suite.deleteScheduler(createdName) } diff --git a/server/api/server_test.go b/server/api/server_test.go index a4c6b6de6fb..273f62cab54 100644 --- a/server/api/server_test.go +++ b/server/api/server_test.go @@ -21,10 +21,11 @@ import ( "sync" "testing" - . "github.com/pingcap/check" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" "github.com/pingcap/log" + "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" "github.com/tikv/pd/pkg/apiutil" "github.com/tikv/pd/pkg/testutil" "github.com/tikv/pd/server" @@ -61,33 +62,29 @@ var ( } ) -func TestAPIServer(t *testing.T) { - TestingT(t) -} - func TestMain(m *testing.M) { goleak.VerifyTestMain(m, testutil.LeakOptions...) } type cleanUpFunc func() -func mustNewServer(c *C, opts ...func(cfg *config.Config)) (*server.Server, cleanUpFunc) { - _, svrs, cleanup := mustNewCluster(c, 1, opts...) +func mustNewServer(re *require.Assertions, opts ...func(cfg *config.Config)) (*server.Server, cleanUpFunc) { + _, svrs, cleanup := mustNewCluster(re, 1, opts...) return svrs[0], cleanup } var zapLogOnce sync.Once -func mustNewCluster(c *C, num int, opts ...func(cfg *config.Config)) ([]*config.Config, []*server.Server, cleanUpFunc) { +func mustNewCluster(re *require.Assertions, num int, opts ...func(cfg *config.Config)) ([]*config.Config, []*server.Server, cleanUpFunc) { ctx, cancel := context.WithCancel(context.Background()) svrs := make([]*server.Server, 0, num) - cfgs := server.NewTestMultiConfig(checkerWithNilAssert(c), num) + cfgs := server.NewTestMultiConfig(checkerWithNilAssert(re), num) ch := make(chan *server.Server, num) for _, cfg := range cfgs { go func(cfg *config.Config) { err := cfg.SetupLogger() - c.Assert(err, IsNil) + re.NoError(err) zapLogOnce.Do(func() { log.ReplaceGlobals(cfg.GetZapLogger(), cfg.GetZapLogProperties()) }) @@ -95,9 +92,9 @@ func mustNewCluster(c *C, num int, opts ...func(cfg *config.Config)) ([]*config. opt(cfg) } s, err := server.CreateServer(ctx, cfg, NewHandler) - c.Assert(err, IsNil) + re.NoError(err) err = s.Run() - c.Assert(err, IsNil) + re.NoError(err) ch <- s }(cfg) } @@ -108,7 +105,7 @@ func mustNewCluster(c *C, num int, opts ...func(cfg *config.Config)) ([]*config. } close(ch) // wait etcd and http servers - mustWaitLeader(c, svrs) + mustWaitLeader(re, svrs) // clean up clean := func() { @@ -124,8 +121,8 @@ func mustNewCluster(c *C, num int, opts ...func(cfg *config.Config)) ([]*config. return cfgs, svrs, clean } -func mustWaitLeader(c *C, svrs []*server.Server) { - testutil.WaitUntil(c, func() bool { +func mustWaitLeader(re *require.Assertions, svrs []*server.Server) { + testutil.Eventually(re, func() bool { var leader *pdpb.Member for _, svr := range svrs { l := svr.GetLeader() @@ -141,88 +138,92 @@ func mustWaitLeader(c *C, svrs []*server.Server) { }) } -func mustBootstrapCluster(c *C, s *server.Server) { - grpcPDClient := testutil.MustNewGrpcClient(c, s.GetAddr()) +func mustBootstrapCluster(re *require.Assertions, s *server.Server) { + grpcPDClient := testutil.MustNewGrpcClient(re, s.GetAddr()) req := &pdpb.BootstrapRequest{ Header: testutil.NewRequestHeader(s.ClusterID()), Store: store, Region: region, } resp, err := grpcPDClient.Bootstrap(context.Background(), req) - c.Assert(err, IsNil) - c.Assert(resp.GetHeader().GetError().GetType(), Equals, pdpb.ErrorType_OK) + re.NoError(err) + re.Equal(pdpb.ErrorType_OK, resp.GetHeader().GetError().GetType()) } -var _ = Suite(&testServiceSuite{}) - -type testServiceSuite struct { +type serviceTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc } -func (s *testServiceSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c) - mustWaitLeader(c, []*server.Server{s.svr}) +func TestServiceTestSuite(t *testing.T) { + suite.Run(t, new(serviceTestSuite)) +} + +func (suite *serviceTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re) + mustWaitLeader(re, []*server.Server{suite.svr}) - mustBootstrapCluster(c, s.svr) - mustPutStore(c, s.svr, 1, metapb.StoreState_Up, metapb.NodeState_Serving, nil) + mustBootstrapCluster(re, suite.svr) + mustPutStore(re, suite.svr, 1, metapb.StoreState_Up, metapb.NodeState_Serving, nil) } -func (s *testServiceSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *serviceTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *testServiceSuite) TestServiceLabels(c *C) { - accessPaths := s.svr.GetServiceLabels("Profile") - c.Assert(accessPaths, HasLen, 1) - c.Assert(accessPaths[0].Path, Equals, "/pd/api/v1/debug/pprof/profile") - c.Assert(accessPaths[0].Method, Equals, "") - serviceLabel := s.svr.GetAPIAccessServiceLabel( +func (suite *serviceTestSuite) TestServiceLabels() { + accessPaths := suite.svr.GetServiceLabels("Profile") + suite.Len(accessPaths, 1) + suite.Equal("/pd/api/v1/debug/pprof/profile", accessPaths[0].Path) + suite.Equal("", accessPaths[0].Method) + serviceLabel := suite.svr.GetAPIAccessServiceLabel( apiutil.NewAccessPath("/pd/api/v1/debug/pprof/profile", "")) - c.Assert(serviceLabel, Equals, "Profile") - serviceLabel = s.svr.GetAPIAccessServiceLabel( + suite.Equal("Profile", serviceLabel) + serviceLabel = suite.svr.GetAPIAccessServiceLabel( apiutil.NewAccessPath("/pd/api/v1/debug/pprof/profile", http.MethodGet)) - c.Assert(serviceLabel, Equals, "Profile") - - accessPaths = s.svr.GetServiceLabels("GetSchedulerConfig") - c.Assert(accessPaths, HasLen, 1) - c.Assert(accessPaths[0].Path, Equals, "/pd/api/v1/scheduler-config") - c.Assert(accessPaths[0].Method, Equals, "") - - accessPaths = s.svr.GetServiceLabels("ResignLeader") - c.Assert(accessPaths, HasLen, 1) - c.Assert(accessPaths[0].Path, Equals, "/pd/api/v1/leader/resign") - c.Assert(accessPaths[0].Method, Equals, http.MethodPost) - serviceLabel = s.svr.GetAPIAccessServiceLabel( + suite.Equal("Profile", serviceLabel) + + accessPaths = suite.svr.GetServiceLabels("GetSchedulerConfig") + suite.Len(accessPaths, 1) + suite.Equal("/pd/api/v1/scheduler-config", accessPaths[0].Path) + suite.Equal("", accessPaths[0].Method) + + accessPaths = suite.svr.GetServiceLabels("ResignLeader") + suite.Len(accessPaths, 1) + suite.Equal("/pd/api/v1/leader/resign", accessPaths[0].Path) + suite.Equal(http.MethodPost, accessPaths[0].Method) + serviceLabel = suite.svr.GetAPIAccessServiceLabel( apiutil.NewAccessPath("/pd/api/v1/leader/resign", http.MethodPost)) - c.Assert(serviceLabel, Equals, "ResignLeader") - serviceLabel = s.svr.GetAPIAccessServiceLabel( + suite.Equal("ResignLeader", serviceLabel) + serviceLabel = suite.svr.GetAPIAccessServiceLabel( apiutil.NewAccessPath("/pd/api/v1/leader/resign", http.MethodGet)) - c.Assert(serviceLabel, Equals, "") - serviceLabel = s.svr.GetAPIAccessServiceLabel( + suite.Equal("", serviceLabel) + serviceLabel = suite.svr.GetAPIAccessServiceLabel( apiutil.NewAccessPath("/pd/api/v1/leader/resign", "")) - c.Assert(serviceLabel, Equals, "") + suite.Equal("", serviceLabel) - accessPaths = s.svr.GetServiceLabels("QueryMetric") - c.Assert(accessPaths, HasLen, 4) + accessPaths = suite.svr.GetServiceLabels("QueryMetric") + suite.Len(accessPaths, 4) sort.Slice(accessPaths, func(i, j int) bool { if accessPaths[i].Path == accessPaths[j].Path { return accessPaths[i].Method < accessPaths[j].Method } return accessPaths[i].Path < accessPaths[j].Path }) - c.Assert(accessPaths[0].Path, Equals, "/pd/api/v1/metric/query") - c.Assert(accessPaths[0].Method, Equals, http.MethodGet) - c.Assert(accessPaths[1].Path, Equals, "/pd/api/v1/metric/query") - c.Assert(accessPaths[1].Method, Equals, http.MethodPost) - c.Assert(accessPaths[2].Path, Equals, "/pd/api/v1/metric/query_range") - c.Assert(accessPaths[2].Method, Equals, http.MethodGet) - c.Assert(accessPaths[3].Path, Equals, "/pd/api/v1/metric/query_range") - c.Assert(accessPaths[3].Method, Equals, http.MethodPost) - serviceLabel = s.svr.GetAPIAccessServiceLabel( + suite.Equal("/pd/api/v1/metric/query", accessPaths[0].Path) + suite.Equal(http.MethodGet, accessPaths[0].Method) + suite.Equal("/pd/api/v1/metric/query", accessPaths[1].Path) + suite.Equal(http.MethodPost, accessPaths[1].Method) + suite.Equal("/pd/api/v1/metric/query_range", accessPaths[2].Path) + suite.Equal(http.MethodGet, accessPaths[2].Method) + suite.Equal("/pd/api/v1/metric/query_range", accessPaths[3].Path) + suite.Equal(http.MethodPost, accessPaths[3].Method) + serviceLabel = suite.svr.GetAPIAccessServiceLabel( apiutil.NewAccessPath("/pd/api/v1/metric/query", http.MethodPost)) - c.Assert(serviceLabel, Equals, "QueryMetric") - serviceLabel = s.svr.GetAPIAccessServiceLabel( + suite.Equal("QueryMetric", serviceLabel) + serviceLabel = suite.svr.GetAPIAccessServiceLabel( apiutil.NewAccessPath("/pd/api/v1/metric/query", http.MethodGet)) - c.Assert(serviceLabel, Equals, "QueryMetric") + suite.Equal("QueryMetric", serviceLabel) } diff --git a/server/api/service_gc_safepoint_test.go b/server/api/service_gc_safepoint_test.go index ecfaa76bf55..291bba0fcaf 100644 --- a/server/api/service_gc_safepoint_test.go +++ b/server/api/service_gc_safepoint_test.go @@ -17,42 +17,47 @@ package api import ( "fmt" "net/http" + "testing" "time" - . "github.com/pingcap/check" "github.com/pingcap/kvproto/pkg/metapb" + "github.com/stretchr/testify/suite" "github.com/tikv/pd/pkg/apiutil" "github.com/tikv/pd/server" "github.com/tikv/pd/server/storage/endpoint" ) -var _ = Suite(&testServiceGCSafepointSuite{}) - -type testServiceGCSafepointSuite struct { +type serviceGCSafepointTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testServiceGCSafepointSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c) - mustWaitLeader(c, []*server.Server{s.svr}) +func TestServiceGCSafepointTestSuite(t *testing.T) { + suite.Run(t, new(serviceGCSafepointTestSuite)) +} + +func (suite *serviceGCSafepointTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) - mustBootstrapCluster(c, s.svr) - mustPutStore(c, s.svr, 1, metapb.StoreState_Up, metapb.NodeState_Serving, nil) + mustBootstrapCluster(re, suite.svr) + mustPutStore(re, suite.svr, 1, metapb.StoreState_Up, metapb.NodeState_Serving, nil) } -func (s *testServiceGCSafepointSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *serviceGCSafepointTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *testServiceGCSafepointSuite) TestServiceGCSafepoint(c *C) { - sspURL := s.urlPrefix + "/gc/safepoint" +func (suite *serviceGCSafepointTestSuite) TestServiceGCSafepoint() { + sspURL := suite.urlPrefix + "/gc/safepoint" - storage := s.svr.GetStorage() + storage := suite.svr.GetStorage() list := &listServiceGCSafepoint{ ServiceGCSafepoints: []*endpoint.ServiceSafePoint{ { @@ -75,23 +80,23 @@ func (s *testServiceGCSafepointSuite) TestServiceGCSafepoint(c *C) { } for _, ssp := range list.ServiceGCSafepoints { err := storage.SaveServiceGCSafePoint(ssp) - c.Assert(err, IsNil) + suite.NoError(err) } storage.SaveGCSafePoint(1) res, err := testDialClient.Get(sspURL) - c.Assert(err, IsNil) + suite.NoError(err) defer res.Body.Close() listResp := &listServiceGCSafepoint{} err = apiutil.ReadJSON(res.Body, listResp) - c.Assert(err, IsNil) - c.Assert(listResp, DeepEquals, list) + suite.NoError(err) + suite.Equal(list, listResp) statusCode, err := apiutil.DoDelete(testDialClient, sspURL+"/a") - c.Assert(err, IsNil) - c.Assert(statusCode, Equals, http.StatusOK) + suite.NoError(err) + suite.Equal(http.StatusOK, statusCode) left, err := storage.LoadAllServiceGCSafePoints() - c.Assert(err, IsNil) - c.Assert(left, DeepEquals, list.ServiceGCSafepoints[1:]) + suite.NoError(err) + suite.Equal(list.ServiceGCSafepoints[1:], left) } diff --git a/server/api/service_middleware_test.go b/server/api/service_middleware_test.go index 6ea0343f53b..ac188dd8759 100644 --- a/server/api/service_middleware_test.go +++ b/server/api/service_middleware_test.go @@ -18,185 +18,191 @@ import ( "encoding/json" "fmt" "net/http" + "testing" - . "github.com/pingcap/check" "github.com/pingcap/failpoint" + "github.com/stretchr/testify/suite" "github.com/tikv/pd/pkg/ratelimit" tu "github.com/tikv/pd/pkg/testutil" "github.com/tikv/pd/server" "github.com/tikv/pd/server/config" ) -var _ = Suite(&testAuditMiddlewareSuite{}) - -type testAuditMiddlewareSuite struct { +type auditMiddlewareTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testAuditMiddlewareSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c, func(cfg *config.Config) { +func TestAuditMiddlewareTestSuite(t *testing.T) { + suite.Run(t, new(auditMiddlewareTestSuite)) +} + +func (suite *auditMiddlewareTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re, func(cfg *config.Config) { cfg.Replication.EnablePlacementRules = false }) - mustWaitLeader(c, []*server.Server{s.svr}) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) } -func (s *testAuditMiddlewareSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *auditMiddlewareTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *testAuditMiddlewareSuite) TestConfigAuditSwitch(c *C) { - addr := fmt.Sprintf("%s/service-middleware/config", s.urlPrefix) - +func (suite *auditMiddlewareTestSuite) TestConfigAuditSwitch() { + addr := fmt.Sprintf("%s/service-middleware/config", suite.urlPrefix) sc := &config.ServiceMiddlewareConfig{} - c.Assert(tu.ReadGetJSON(c, testDialClient, addr, sc), IsNil) - c.Assert(sc.EnableAudit, Equals, false) + re := suite.Require() + suite.NoError(tu.ReadGetJSON(re, testDialClient, addr, sc)) + suite.False(sc.EnableAudit) ms := map[string]interface{}{ "enable-audit": "true", "enable-rate-limit": "true", } postData, err := json.Marshal(ms) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c)), IsNil) + suite.NoError(err) + suite.NoError(tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re))) sc = &config.ServiceMiddlewareConfig{} - c.Assert(tu.ReadGetJSON(c, testDialClient, addr, sc), IsNil) - c.Assert(sc.EnableAudit, Equals, true) - c.Assert(sc.EnableRateLimit, Equals, true) + suite.NoError(tu.ReadGetJSON(re, testDialClient, addr, sc)) + suite.True(sc.EnableAudit) + suite.True(sc.EnableRateLimit) ms = map[string]interface{}{ "audit.enable-audit": "false", "enable-rate-limit": "false", } postData, err = json.Marshal(ms) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c)), IsNil) + suite.NoError(err) + suite.NoError(tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re))) sc = &config.ServiceMiddlewareConfig{} - c.Assert(tu.ReadGetJSON(c, testDialClient, addr, sc), IsNil) - c.Assert(sc.EnableAudit, Equals, false) - c.Assert(sc.EnableRateLimit, Equals, false) + suite.NoError(tu.ReadGetJSON(re, testDialClient, addr, sc)) + suite.False(sc.EnableAudit) + suite.False(sc.EnableRateLimit) // test empty ms = map[string]interface{}{} postData, err = json.Marshal(ms) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c), tu.StringContain(c, "The input is empty.")), IsNil) - + suite.NoError(err) + suite.NoError(tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re), tu.StringContain(re, "The input is empty."))) ms = map[string]interface{}{ "audit": "false", } postData, err = json.Marshal(ms) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, addr, postData, tu.Status(c, http.StatusBadRequest), tu.StringEqual(c, "config item audit not found")), IsNil) - - c.Assert(failpoint.Enable("github.com/tikv/pd/server/config/persistServiceMiddlewareFail", "return(true)"), IsNil) + suite.NoError(err) + suite.NoError(tu.CheckPostJSON(testDialClient, addr, postData, tu.Status(re, http.StatusBadRequest), tu.StringEqual(re, "config item audit not found"))) + suite.NoError(failpoint.Enable("github.com/tikv/pd/server/config/persistServiceMiddlewareFail", "return(true)")) ms = map[string]interface{}{ "audit.enable-audit": "true", } postData, err = json.Marshal(ms) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, addr, postData, tu.Status(c, http.StatusBadRequest)), IsNil) - c.Assert(failpoint.Disable("github.com/tikv/pd/server/config/persistServiceMiddlewareFail"), IsNil) - + suite.NoError(err) + suite.NoError(tu.CheckPostJSON(testDialClient, addr, postData, tu.Status(re, http.StatusBadRequest))) + suite.NoError(failpoint.Disable("github.com/tikv/pd/server/config/persistServiceMiddlewareFail")) ms = map[string]interface{}{ "audit.audit": "false", } postData, err = json.Marshal(ms) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, addr, postData, tu.Status(c, http.StatusBadRequest), tu.StringEqual(c, "config item audit not found")), IsNil) + suite.NoError(err) + suite.NoError(tu.CheckPostJSON(testDialClient, addr, postData, tu.Status(re, http.StatusBadRequest), tu.StringEqual(re, "config item audit not found"))) } -var _ = Suite(&testRateLimitConfigSuite{}) - -type testRateLimitConfigSuite struct { +type rateLimitConfigTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testRateLimitConfigSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c) - mustWaitLeader(c, []*server.Server{s.svr}) - mustBootstrapCluster(c, s.svr) - s.urlPrefix = fmt.Sprintf("%s%s/api/v1", s.svr.GetAddr(), apiPrefix) +func TestRateLimitConfigTestSuite(t *testing.T) { + suite.Run(t, new(rateLimitConfigTestSuite)) } -func (s *testRateLimitConfigSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *rateLimitConfigTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re) + mustWaitLeader(re, []*server.Server{suite.svr}) + mustBootstrapCluster(re, suite.svr) + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1", suite.svr.GetAddr(), apiPrefix) } -func (s *testRateLimitConfigSuite) TestUpdateRateLimitConfig(c *C) { - urlPrefix := fmt.Sprintf("%s%s/api/v1/service-middleware/config/rate-limit", s.svr.GetAddr(), apiPrefix) +func (suite *rateLimitConfigTestSuite) TearDownSuite() { + suite.cleanup() +} + +func (suite *rateLimitConfigTestSuite) TestUpdateRateLimitConfig() { + urlPrefix := fmt.Sprintf("%s%s/api/v1/service-middleware/config/rate-limit", suite.svr.GetAddr(), apiPrefix) // test empty type input := make(map[string]interface{}) input["type"] = 123 jsonBody, err := json.Marshal(input) - c.Assert(err, IsNil) - + suite.NoError(err) + re := suite.Require() err = tu.CheckPostJSON(testDialClient, urlPrefix, jsonBody, - tu.Status(c, http.StatusBadRequest), tu.StringEqual(c, "\"The type is empty.\"\n")) - c.Assert(err, IsNil) + tu.Status(re, http.StatusBadRequest), tu.StringEqual(re, "\"The type is empty.\"\n")) + suite.NoError(err) // test invalid type input = make(map[string]interface{}) input["type"] = "url" jsonBody, err = json.Marshal(input) - c.Assert(err, IsNil) + suite.NoError(err) err = tu.CheckPostJSON(testDialClient, urlPrefix, jsonBody, - tu.Status(c, http.StatusBadRequest), tu.StringEqual(c, "\"The type is invalid.\"\n")) - c.Assert(err, IsNil) + tu.Status(re, http.StatusBadRequest), tu.StringEqual(re, "\"The type is invalid.\"\n")) + suite.NoError(err) // test empty label input = make(map[string]interface{}) input["type"] = "label" input["label"] = "" jsonBody, err = json.Marshal(input) - c.Assert(err, IsNil) + suite.NoError(err) err = tu.CheckPostJSON(testDialClient, urlPrefix, jsonBody, - tu.Status(c, http.StatusBadRequest), tu.StringEqual(c, "\"The label is empty.\"\n")) - c.Assert(err, IsNil) + tu.Status(re, http.StatusBadRequest), tu.StringEqual(re, "\"The label is empty.\"\n")) + suite.NoError(err) // test no label matched input = make(map[string]interface{}) input["type"] = "label" input["label"] = "TestLabel" jsonBody, err = json.Marshal(input) - c.Assert(err, IsNil) + suite.NoError(err) err = tu.CheckPostJSON(testDialClient, urlPrefix, jsonBody, - tu.Status(c, http.StatusBadRequest), tu.StringEqual(c, "\"There is no label matched.\"\n")) - c.Assert(err, IsNil) + tu.Status(re, http.StatusBadRequest), tu.StringEqual(re, "\"There is no label matched.\"\n")) + suite.NoError(err) // test empty path input = make(map[string]interface{}) input["type"] = "path" input["path"] = "" jsonBody, err = json.Marshal(input) - c.Assert(err, IsNil) + suite.NoError(err) err = tu.CheckPostJSON(testDialClient, urlPrefix, jsonBody, - tu.Status(c, http.StatusBadRequest), tu.StringEqual(c, "\"The path is empty.\"\n")) - c.Assert(err, IsNil) + tu.Status(re, http.StatusBadRequest), tu.StringEqual(re, "\"The path is empty.\"\n")) + suite.NoError(err) // test path but no label matched input = make(map[string]interface{}) input["type"] = "path" input["path"] = "/pd/api/v1/test" jsonBody, err = json.Marshal(input) - c.Assert(err, IsNil) + suite.NoError(err) err = tu.CheckPostJSON(testDialClient, urlPrefix, jsonBody, - tu.Status(c, http.StatusBadRequest), tu.StringEqual(c, "\"There is no label matched.\"\n")) - c.Assert(err, IsNil) + tu.Status(re, http.StatusBadRequest), tu.StringEqual(re, "\"There is no label matched.\"\n")) + suite.NoError(err) // no change input = make(map[string]interface{}) input["type"] = "label" input["label"] = "GetHealthStatus" jsonBody, err = json.Marshal(input) - c.Assert(err, IsNil) + suite.NoError(err) err = tu.CheckPostJSON(testDialClient, urlPrefix, jsonBody, - tu.StatusOK(c), tu.StringEqual(c, "\"No changed.\"\n")) - c.Assert(err, IsNil) + tu.StatusOK(re), tu.StringEqual(re, "\"No changed.\"\n")) + suite.NoError(err) // change concurrency input = make(map[string]interface{}) @@ -205,16 +211,16 @@ func (s *testRateLimitConfigSuite) TestUpdateRateLimitConfig(c *C) { input["method"] = "GET" input["concurrency"] = 100 jsonBody, err = json.Marshal(input) - c.Assert(err, IsNil) + suite.NoError(err) err = tu.CheckPostJSON(testDialClient, urlPrefix, jsonBody, - tu.StatusOK(c), tu.StringContain(c, "Concurrency limiter is changed.")) - c.Assert(err, IsNil) + tu.StatusOK(re), tu.StringContain(re, "Concurrency limiter is changed.")) + suite.NoError(err) input["concurrency"] = 0 jsonBody, err = json.Marshal(input) - c.Assert(err, IsNil) + suite.NoError(err) err = tu.CheckPostJSON(testDialClient, urlPrefix, jsonBody, - tu.StatusOK(c), tu.StringContain(c, "Concurrency limiter is deleted.")) - c.Assert(err, IsNil) + tu.StatusOK(re), tu.StringContain(re, "Concurrency limiter is deleted.")) + suite.NoError(err) // change qps input = make(map[string]interface{}) @@ -223,10 +229,10 @@ func (s *testRateLimitConfigSuite) TestUpdateRateLimitConfig(c *C) { input["method"] = "GET" input["qps"] = 100 jsonBody, err = json.Marshal(input) - c.Assert(err, IsNil) + suite.NoError(err) err = tu.CheckPostJSON(testDialClient, urlPrefix, jsonBody, - tu.StatusOK(c), tu.StringContain(c, "QPS rate limiter is changed.")) - c.Assert(err, IsNil) + tu.StatusOK(re), tu.StringContain(re, "QPS rate limiter is changed.")) + suite.NoError(err) input = make(map[string]interface{}) input["type"] = "path" @@ -234,18 +240,18 @@ func (s *testRateLimitConfigSuite) TestUpdateRateLimitConfig(c *C) { input["method"] = "GET" input["qps"] = 0.3 jsonBody, err = json.Marshal(input) - c.Assert(err, IsNil) + suite.NoError(err) err = tu.CheckPostJSON(testDialClient, urlPrefix, jsonBody, - tu.StatusOK(c), tu.StringContain(c, "QPS rate limiter is changed.")) - c.Assert(err, IsNil) - c.Assert(s.svr.GetRateLimitConfig().LimiterConfig["GetHealthStatus"].QPSBurst, Equals, 1) + tu.StatusOK(re), tu.StringContain(re, "QPS rate limiter is changed.")) + suite.NoError(err) + suite.Equal(1, suite.svr.GetRateLimitConfig().LimiterConfig["GetHealthStatus"].QPSBurst) input["qps"] = -1 jsonBody, err = json.Marshal(input) - c.Assert(err, IsNil) + suite.NoError(err) err = tu.CheckPostJSON(testDialClient, urlPrefix, jsonBody, - tu.StatusOK(c), tu.StringContain(c, "QPS rate limiter is deleted.")) - c.Assert(err, IsNil) + tu.StatusOK(re), tu.StringContain(re, "QPS rate limiter is deleted.")) + suite.NoError(err) // change both input = make(map[string]interface{}) @@ -254,19 +260,19 @@ func (s *testRateLimitConfigSuite) TestUpdateRateLimitConfig(c *C) { input["qps"] = 100 input["concurrency"] = 100 jsonBody, err = json.Marshal(input) - c.Assert(err, IsNil) + suite.NoError(err) result := rateLimitResult{} err = tu.CheckPostJSON(testDialClient, urlPrefix, jsonBody, - tu.StatusOK(c), tu.StringContain(c, "Concurrency limiter is changed."), - tu.StringContain(c, "QPS rate limiter is changed."), - tu.ExtractJSON(c, &result), + tu.StatusOK(re), tu.StringContain(re, "Concurrency limiter is changed."), + tu.StringContain(re, "QPS rate limiter is changed."), + tu.ExtractJSON(re, &result), ) - c.Assert(result.LimiterConfig["Profile"].QPS, Equals, 100.) - c.Assert(result.LimiterConfig["Profile"].QPSBurst, Equals, 100) - c.Assert(result.LimiterConfig["Profile"].ConcurrencyLimit, Equals, uint64(100)) - c.Assert(err, IsNil) + suite.Equal(100., result.LimiterConfig["Profile"].QPS) + suite.Equal(100, result.LimiterConfig["Profile"].QPSBurst) + suite.Equal(uint64(100), result.LimiterConfig["Profile"].ConcurrencyLimit) + suite.NoError(err) - limiter := s.svr.GetServiceRateLimiter() + limiter := suite.svr.GetServiceRateLimiter() limiter.Update("SetRatelimitConfig", ratelimit.AddLabelAllowList()) // Allow list @@ -276,71 +282,68 @@ func (s *testRateLimitConfigSuite) TestUpdateRateLimitConfig(c *C) { input["qps"] = 100 input["concurrency"] = 100 jsonBody, err = json.Marshal(input) - c.Assert(err, IsNil) + suite.NoError(err) err = tu.CheckPostJSON(testDialClient, urlPrefix, jsonBody, - tu.StatusNotOK(c), tu.StringEqual(c, "\"This service is in allow list whose config can not be changed.\"\n")) - c.Assert(err, IsNil) + tu.StatusNotOK(re), tu.StringEqual(re, "\"This service is in allow list whose config can not be changed.\"\n")) + suite.NoError(err) } -func (s *testRateLimitConfigSuite) TestConfigRateLimitSwitch(c *C) { - addr := fmt.Sprintf("%s/service-middleware/config", s.urlPrefix) - +func (suite *rateLimitConfigTestSuite) TestConfigRateLimitSwitch() { + addr := fmt.Sprintf("%s/service-middleware/config", suite.urlPrefix) sc := &config.ServiceMiddlewareConfig{} - c.Assert(tu.ReadGetJSON(c, testDialClient, addr, sc), IsNil) - c.Assert(sc.EnableRateLimit, Equals, false) + re := suite.Require() + suite.NoError(tu.ReadGetJSON(re, testDialClient, addr, sc)) + suite.False(sc.EnableRateLimit) ms := map[string]interface{}{ "enable-rate-limit": "true", } postData, err := json.Marshal(ms) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c)), IsNil) + suite.NoError(err) + suite.NoError(tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re))) sc = &config.ServiceMiddlewareConfig{} - c.Assert(tu.ReadGetJSON(c, testDialClient, addr, sc), IsNil) - c.Assert(sc.EnableRateLimit, Equals, true) + suite.NoError(tu.ReadGetJSON(re, testDialClient, addr, sc)) + suite.True(sc.EnableRateLimit) ms = map[string]interface{}{ "enable-rate-limit": "false", } postData, err = json.Marshal(ms) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c)), IsNil) + suite.NoError(err) + suite.NoError(tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re))) sc = &config.ServiceMiddlewareConfig{} - c.Assert(tu.ReadGetJSON(c, testDialClient, addr, sc), IsNil) - c.Assert(sc.EnableRateLimit, Equals, false) + suite.NoError(tu.ReadGetJSON(re, testDialClient, addr, sc)) + suite.False(sc.EnableRateLimit) // test empty ms = map[string]interface{}{} postData, err = json.Marshal(ms) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c), tu.StringContain(c, "The input is empty.")), IsNil) - + suite.NoError(err) + suite.NoError(tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re), tu.StringContain(re, "The input is empty."))) ms = map[string]interface{}{ "rate-limit": "false", } postData, err = json.Marshal(ms) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, addr, postData, tu.Status(c, http.StatusBadRequest), tu.StringEqual(c, "config item rate-limit not found")), IsNil) - - c.Assert(failpoint.Enable("github.com/tikv/pd/server/config/persistServiceMiddlewareFail", "return(true)"), IsNil) + suite.NoError(err) + suite.NoError(tu.CheckPostJSON(testDialClient, addr, postData, tu.Status(re, http.StatusBadRequest), tu.StringEqual(re, "config item rate-limit not found"))) + suite.NoError(failpoint.Enable("github.com/tikv/pd/server/config/persistServiceMiddlewareFail", "return(true)")) ms = map[string]interface{}{ "rate-limit.enable-rate-limit": "true", } postData, err = json.Marshal(ms) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, addr, postData, tu.Status(c, http.StatusBadRequest)), IsNil) - c.Assert(failpoint.Disable("github.com/tikv/pd/server/config/persistServiceMiddlewareFail"), IsNil) - + suite.NoError(err) + suite.NoError(tu.CheckPostJSON(testDialClient, addr, postData, tu.Status(re, http.StatusBadRequest))) + suite.NoError(failpoint.Disable("github.com/tikv/pd/server/config/persistServiceMiddlewareFail")) ms = map[string]interface{}{ "rate-limit.rate-limit": "false", } postData, err = json.Marshal(ms) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, addr, postData, tu.Status(c, http.StatusBadRequest), tu.StringEqual(c, "config item rate-limit not found")), IsNil) + suite.NoError(err) + suite.NoError(tu.CheckPostJSON(testDialClient, addr, postData, tu.Status(re, http.StatusBadRequest), tu.StringEqual(re, "config item rate-limit not found"))) } -func (s *testRateLimitConfigSuite) TestConfigLimiterConifgByOriginAPI(c *C) { +func (suite *rateLimitConfigTestSuite) TestConfigLimiterConifgByOriginAPI() { // this test case is used to test updating `limiter-config` by origin API simply - addr := fmt.Sprintf("%s/service-middleware/config", s.urlPrefix) + addr := fmt.Sprintf("%s/service-middleware/config", suite.urlPrefix) dimensionConfig := ratelimit.DimensionConfig{QPS: 1} limiterConfig := map[string]interface{}{ "CreateOperator": dimensionConfig, @@ -349,9 +352,10 @@ func (s *testRateLimitConfigSuite) TestConfigLimiterConifgByOriginAPI(c *C) { "limiter-config": limiterConfig, } postData, err := json.Marshal(ms) - c.Assert(err, IsNil) - c.Assert(tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(c)), IsNil) + suite.NoError(err) + re := suite.Require() + suite.NoError(tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re))) sc := &config.ServiceMiddlewareConfig{} - c.Assert(tu.ReadGetJSON(c, testDialClient, addr, sc), IsNil) - c.Assert(sc.RateLimitConfig.LimiterConfig["CreateOperator"].QPS, Equals, 1.) + suite.NoError(tu.ReadGetJSON(re, testDialClient, addr, sc)) + suite.Equal(1., sc.RateLimitConfig.LimiterConfig["CreateOperator"].QPS) } diff --git a/server/api/stats_test.go b/server/api/stats_test.go index b2fbbf1b7bf..77c35b19679 100644 --- a/server/api/stats_test.go +++ b/server/api/stats_test.go @@ -17,39 +17,44 @@ package api import ( "fmt" "net/url" + "testing" - . "github.com/pingcap/check" "github.com/pingcap/kvproto/pkg/metapb" + "github.com/stretchr/testify/suite" "github.com/tikv/pd/pkg/apiutil" "github.com/tikv/pd/server" "github.com/tikv/pd/server/core" "github.com/tikv/pd/server/statistics" ) -var _ = Suite(&testStatsSuite{}) - -type testStatsSuite struct { +type statsTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testStatsSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c) - mustWaitLeader(c, []*server.Server{s.svr}) +func TestStatsTestSuite(t *testing.T) { + suite.Run(t, new(statsTestSuite)) +} + +func (suite *statsTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) - mustBootstrapCluster(c, s.svr) + mustBootstrapCluster(re, suite.svr) } -func (s *testStatsSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *statsTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *testStatsSuite) TestRegionStats(c *C) { - statsURL := s.urlPrefix + "/stats/region" +func (suite *statsTestSuite) TestRegionStats() { + statsURL := suite.urlPrefix + "/stats/region" epoch := &metapb.RegionEpoch{ ConfVer: 1, Version: 1, @@ -117,8 +122,9 @@ func (s *testStatsSuite) TestRegionStats(c *C) { ), } + re := suite.Require() for _, r := range regions { - mustRegionHeartbeat(c, s.svr, r) + mustRegionHeartbeat(re, suite.svr, r) } // Distribution (L for leader, F for follower): @@ -141,21 +147,21 @@ func (s *testStatsSuite) TestRegionStats(c *C) { StorePeerKeys: map[uint64]int64{1: 201, 2: 50, 3: 50, 4: 170, 5: 151}, } res, err := testDialClient.Get(statsURL) - c.Assert(err, IsNil) + suite.NoError(err) defer res.Body.Close() stats := &statistics.RegionStats{} err = apiutil.ReadJSON(res.Body, stats) - c.Assert(err, IsNil) - c.Assert(stats, DeepEquals, statsAll) + suite.NoError(err) + suite.Equal(statsAll, stats) args := fmt.Sprintf("?start_key=%s&end_key=%s", url.QueryEscape("\x01\x02"), url.QueryEscape("xyz\x00\x00")) res, err = testDialClient.Get(statsURL + args) - c.Assert(err, IsNil) + suite.NoError(err) defer res.Body.Close() stats = &statistics.RegionStats{} err = apiutil.ReadJSON(res.Body, stats) - c.Assert(err, IsNil) - c.Assert(stats, DeepEquals, statsAll) + suite.NoError(err) + suite.Equal(statsAll, stats) stats23 := &statistics.RegionStats{ Count: 2, @@ -172,10 +178,10 @@ func (s *testStatsSuite) TestRegionStats(c *C) { args = fmt.Sprintf("?start_key=%s&end_key=%s", url.QueryEscape("a"), url.QueryEscape("x")) res, err = testDialClient.Get(statsURL + args) - c.Assert(err, IsNil) + suite.NoError(err) defer res.Body.Close() stats = &statistics.RegionStats{} err = apiutil.ReadJSON(res.Body, stats) - c.Assert(err, IsNil) - c.Assert(stats, DeepEquals, stats23) + suite.NoError(err) + suite.Equal(stats23, stats) } diff --git a/server/api/status_test.go b/server/api/status_test.go index 8f9c82069d2..bedf6c0e532 100644 --- a/server/api/status_test.go +++ b/server/api/status_test.go @@ -17,34 +17,32 @@ package api import ( "encoding/json" "io" + "testing" - . "github.com/pingcap/check" + "github.com/stretchr/testify/require" "github.com/tikv/pd/server/versioninfo" ) -var _ = Suite(&testStatusAPISuite{}) - -type testStatusAPISuite struct{} - -func checkStatusResponse(c *C, body []byte) { +func checkStatusResponse(re *require.Assertions, body []byte) { got := status{} - c.Assert(json.Unmarshal(body, &got), IsNil) - c.Assert(got.BuildTS, Equals, versioninfo.PDBuildTS) - c.Assert(got.GitHash, Equals, versioninfo.PDGitHash) - c.Assert(got.Version, Equals, versioninfo.PDReleaseVersion) + re.NoError(json.Unmarshal(body, &got)) + re.Equal(versioninfo.PDBuildTS, got.BuildTS) + re.Equal(versioninfo.PDGitHash, got.GitHash) + re.Equal(versioninfo.PDReleaseVersion, got.Version) } -func (s *testStatusAPISuite) TestStatus(c *C) { - cfgs, _, clean := mustNewCluster(c, 3) +func TestStatus(t *testing.T) { + re := require.New(t) + cfgs, _, clean := mustNewCluster(re, 3) defer clean() for _, cfg := range cfgs { addr := cfg.ClientUrls + apiPrefix + "/api/v1/status" resp, err := testDialClient.Get(addr) - c.Assert(err, IsNil) + re.NoError(err) buf, err := io.ReadAll(resp.Body) - c.Assert(err, IsNil) - checkStatusResponse(c, buf) + re.NoError(err) + checkStatusResponse(re, buf) resp.Body.Close() } } diff --git a/server/api/store_test.go b/server/api/store_test.go index 99875c8f6ea..64cb500164d 100644 --- a/server/api/store_test.go +++ b/server/api/store_test.go @@ -21,22 +21,23 @@ import ( "io" "net/http" "net/url" + "testing" "time" "github.com/docker/go-units" "github.com/gogo/protobuf/proto" - . "github.com/pingcap/check" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" + "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" tu "github.com/tikv/pd/pkg/testutil" "github.com/tikv/pd/server" "github.com/tikv/pd/server/config" "github.com/tikv/pd/server/core" ) -var _ = Suite(&testStoreSuite{}) - -type testStoreSuite struct { +type storeTestSuite struct { + suite.Suite svr *server.Server grpcSvr *server.GrpcServer cleanup cleanUpFunc @@ -44,20 +45,24 @@ type testStoreSuite struct { stores []*metapb.Store } -func requestStatusBody(c *C, client *http.Client, method string, url string) int { +func TestStoreTestSuite(t *testing.T) { + suite.Run(t, new(storeTestSuite)) +} + +func (suite *storeTestSuite) requestStatusBody(client *http.Client, method string, url string) int { req, err := http.NewRequest(method, url, nil) - c.Assert(err, IsNil) + suite.NoError(err) resp, err := client.Do(req) - c.Assert(err, IsNil) + suite.NoError(err) _, err = io.ReadAll(resp.Body) - c.Assert(err, IsNil) + suite.NoError(err) err = resp.Body.Close() - c.Assert(err, IsNil) + suite.NoError(err) return resp.StatusCode } -func (s *testStoreSuite) SetUpSuite(c *C) { - s.stores = []*metapb.Store{ +func (suite *storeTestSuite) SetupSuite() { + suite.stores = []*metapb.Store{ { // metapb.StoreState_Up == 0 Id: 1, @@ -91,26 +96,27 @@ func (s *testStoreSuite) SetUpSuite(c *C) { }, } // TODO: enable placmentrules - s.svr, s.cleanup = mustNewServer(c, func(cfg *config.Config) { cfg.Replication.EnablePlacementRules = false }) - mustWaitLeader(c, []*server.Server{s.svr}) + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re, func(cfg *config.Config) { cfg.Replication.EnablePlacementRules = false }) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.grpcSvr = &server.GrpcServer{Server: s.svr} - s.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.grpcSvr = &server.GrpcServer{Server: suite.svr} + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) - mustBootstrapCluster(c, s.svr) + mustBootstrapCluster(re, suite.svr) - for _, store := range s.stores { - mustPutStore(c, s.svr, store.Id, store.State, store.NodeState, nil) + for _, store := range suite.stores { + mustPutStore(re, suite.svr, store.Id, store.State, store.NodeState, nil) } } -func (s *testStoreSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *storeTestSuite) TearDownSuite() { + suite.cleanup() } -func checkStoresInfo(c *C, ss []*StoreInfo, want []*metapb.Store) { - c.Assert(len(ss), Equals, len(want)) +func checkStoresInfo(re *require.Assertions, ss []*StoreInfo, want []*metapb.Store) { + re.Len(ss, len(want)) mapWant := make(map[uint64]*metapb.Store) for _, s := range want { if _, ok := mapWant[s.Id]; !ok { @@ -122,35 +128,36 @@ func checkStoresInfo(c *C, ss []*StoreInfo, want []*metapb.Store) { expected := proto.Clone(mapWant[obtained.Id]).(*metapb.Store) // Ignore lastHeartbeat obtained.LastHeartbeat, expected.LastHeartbeat = 0, 0 - c.Assert(obtained, DeepEquals, expected) + re.Equal(expected, obtained) } } -func (s *testStoreSuite) TestStoresList(c *C) { - url := fmt.Sprintf("%s/stores", s.urlPrefix) +func (suite *storeTestSuite) TestStoresList() { + url := fmt.Sprintf("%s/stores", suite.urlPrefix) info := new(StoresInfo) - err := tu.ReadGetJSON(c, testDialClient, url, info) - c.Assert(err, IsNil) - checkStoresInfo(c, info.Stores, s.stores[:3]) + re := suite.Require() + err := tu.ReadGetJSON(re, testDialClient, url, info) + suite.NoError(err) + checkStoresInfo(re, info.Stores, suite.stores[:3]) - url = fmt.Sprintf("%s/stores?state=0", s.urlPrefix) + url = fmt.Sprintf("%s/stores?state=0", suite.urlPrefix) info = new(StoresInfo) - err = tu.ReadGetJSON(c, testDialClient, url, info) - c.Assert(err, IsNil) - checkStoresInfo(c, info.Stores, s.stores[:2]) + err = tu.ReadGetJSON(re, testDialClient, url, info) + suite.NoError(err) + checkStoresInfo(re, info.Stores, suite.stores[:2]) - url = fmt.Sprintf("%s/stores?state=1", s.urlPrefix) + url = fmt.Sprintf("%s/stores?state=1", suite.urlPrefix) info = new(StoresInfo) - err = tu.ReadGetJSON(c, testDialClient, url, info) - c.Assert(err, IsNil) - checkStoresInfo(c, info.Stores, s.stores[2:3]) + err = tu.ReadGetJSON(re, testDialClient, url, info) + suite.NoError(err) + checkStoresInfo(re, info.Stores, suite.stores[2:3]) } -func (s *testStoreSuite) TestStoreGet(c *C) { - url := fmt.Sprintf("%s/store/1", s.urlPrefix) - s.grpcSvr.StoreHeartbeat( +func (suite *storeTestSuite) TestStoreGet() { + url := fmt.Sprintf("%s/store/1", suite.urlPrefix) + suite.grpcSvr.StoreHeartbeat( context.Background(), &pdpb.StoreHeartbeatRequest{ - Header: &pdpb.RequestHeader{ClusterId: s.svr.ClusterID()}, + Header: &pdpb.RequestHeader{ClusterId: suite.svr.ClusterID()}, Stats: &pdpb.StoreStats{ StoreId: 1, Capacity: 1798985089024, @@ -160,92 +167,94 @@ func (s *testStoreSuite) TestStoreGet(c *C) { }, ) info := new(StoreInfo) - err := tu.ReadGetJSON(c, testDialClient, url, info) - c.Assert(err, IsNil) + err := tu.ReadGetJSON(suite.Require(), testDialClient, url, info) + suite.NoError(err) capacity, _ := units.RAMInBytes("1.636TiB") available, _ := units.RAMInBytes("1.555TiB") - c.Assert(int64(info.Status.Capacity), Equals, capacity) - c.Assert(int64(info.Status.Available), Equals, available) - checkStoresInfo(c, []*StoreInfo{info}, s.stores[:1]) + suite.Equal(capacity, int64(info.Status.Capacity)) + suite.Equal(available, int64(info.Status.Available)) + checkStoresInfo(suite.Require(), []*StoreInfo{info}, suite.stores[:1]) } -func (s *testStoreSuite) TestStoreLabel(c *C) { - url := fmt.Sprintf("%s/store/1", s.urlPrefix) +func (suite *storeTestSuite) TestStoreLabel() { + url := fmt.Sprintf("%s/store/1", suite.urlPrefix) + re := suite.Require() var info StoreInfo - err := tu.ReadGetJSON(c, testDialClient, url, &info) - c.Assert(err, IsNil) - c.Assert(info.Store.Labels, HasLen, 0) + err := tu.ReadGetJSON(re, testDialClient, url, &info) + suite.NoError(err) + suite.Len(info.Store.Labels, 0) // Test merge. // enable label match check. labelCheck := map[string]string{"strictly-match-label": "true"} lc, _ := json.Marshal(labelCheck) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/config", lc, tu.StatusOK(c)) - c.Assert(err, IsNil) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/config", lc, tu.StatusOK(re)) + suite.NoError(err) // Test set. labels := map[string]string{"zone": "cn", "host": "local"} b, err := json.Marshal(labels) - c.Assert(err, IsNil) + suite.NoError(err) // TODO: supports strictly match check in placement rules err = tu.CheckPostJSON(testDialClient, url+"/label", b, - tu.StatusNotOK(c), - tu.StringContain(c, "key matching the label was not found")) - c.Assert(err, IsNil) + tu.StatusNotOK(re), + tu.StringContain(re, "key matching the label was not found")) + suite.NoError(err) locationLabels := map[string]string{"location-labels": "zone,host"} ll, _ := json.Marshal(locationLabels) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/config", ll, tu.StatusOK(c)) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, url+"/label", b, tu.StatusOK(c)) - c.Assert(err, IsNil) - - err = tu.ReadGetJSON(c, testDialClient, url, &info) - c.Assert(err, IsNil) - c.Assert(info.Store.Labels, HasLen, len(labels)) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/config", ll, tu.StatusOK(re)) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, url+"/label", b, tu.StatusOK(re)) + suite.NoError(err) + + err = tu.ReadGetJSON(re, testDialClient, url, &info) + suite.NoError(err) + suite.Len(info.Store.Labels, len(labels)) for _, l := range info.Store.Labels { - c.Assert(labels[l.Key], Equals, l.Value) + suite.Equal(l.Value, labels[l.Key]) } // Test merge. // disable label match check. labelCheck = map[string]string{"strictly-match-label": "false"} lc, _ = json.Marshal(labelCheck) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/config", lc, tu.StatusOK(c)) - c.Assert(err, IsNil) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/config", lc, tu.StatusOK(re)) + suite.NoError(err) labels = map[string]string{"zack": "zack1", "Host": "host1"} b, err = json.Marshal(labels) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, url+"/label", b, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, url+"/label", b, tu.StatusOK(re)) + suite.NoError(err) expectLabel := map[string]string{"zone": "cn", "zack": "zack1", "host": "host1"} - err = tu.ReadGetJSON(c, testDialClient, url, &info) - c.Assert(err, IsNil) - c.Assert(info.Store.Labels, HasLen, len(expectLabel)) + err = tu.ReadGetJSON(re, testDialClient, url, &info) + suite.NoError(err) + suite.Len(info.Store.Labels, len(expectLabel)) for _, l := range info.Store.Labels { - c.Assert(expectLabel[l.Key], Equals, l.Value) + suite.Equal(expectLabel[l.Key], l.Value) } // delete label b, err = json.Marshal(map[string]string{"host": ""}) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, url+"/label", b, tu.StatusOK(c)) - c.Assert(err, IsNil) - err = tu.ReadGetJSON(c, testDialClient, url, &info) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, url+"/label", b, tu.StatusOK(re)) + suite.NoError(err) + err = tu.ReadGetJSON(re, testDialClient, url, &info) + suite.NoError(err) delete(expectLabel, "host") - c.Assert(info.Store.Labels, HasLen, len(expectLabel)) + suite.Len(info.Store.Labels, len(expectLabel)) for _, l := range info.Store.Labels { - c.Assert(expectLabel[l.Key], Equals, l.Value) + suite.Equal(expectLabel[l.Key], l.Value) } - s.stores[0].Labels = info.Store.Labels + suite.stores[0].Labels = info.Store.Labels } -func (s *testStoreSuite) TestStoreDelete(c *C) { +func (suite *storeTestSuite) TestStoreDelete() { + re := suite.Require() // prepare enough online stores to store replica. for id := 1111; id <= 1115; id++ { - mustPutStore(c, s.svr, uint64(id), metapb.StoreState_Up, metapb.NodeState_Serving, nil) + mustPutStore(re, suite.svr, uint64(id), metapb.StoreState_Up, metapb.NodeState_Serving, nil) } table := []struct { id int @@ -261,135 +270,136 @@ func (s *testStoreSuite) TestStoreDelete(c *C) { }, } for _, t := range table { - url := fmt.Sprintf("%s/store/%d", s.urlPrefix, t.id) - status := requestStatusBody(c, testDialClient, http.MethodDelete, url) - c.Assert(status, Equals, t.status) + url := fmt.Sprintf("%s/store/%d", suite.urlPrefix, t.id) + status := suite.requestStatusBody(testDialClient, http.MethodDelete, url) + suite.Equal(t.status, status) } // store 6 origin status:offline - url := fmt.Sprintf("%s/store/6", s.urlPrefix) + url := fmt.Sprintf("%s/store/6", suite.urlPrefix) store := new(StoreInfo) - err := tu.ReadGetJSON(c, testDialClient, url, store) - c.Assert(err, IsNil) - c.Assert(store.Store.PhysicallyDestroyed, IsFalse) - c.Assert(store.Store.State, Equals, metapb.StoreState_Offline) + err := tu.ReadGetJSON(re, testDialClient, url, store) + suite.NoError(err) + suite.False(store.Store.PhysicallyDestroyed) + suite.Equal(metapb.StoreState_Offline, store.Store.State) // up store success because it is offline but not physically destroyed - status := requestStatusBody(c, testDialClient, http.MethodPost, fmt.Sprintf("%s/state?state=Up", url)) - c.Assert(status, Equals, http.StatusOK) + status := suite.requestStatusBody(testDialClient, http.MethodPost, fmt.Sprintf("%s/state?state=Up", url)) + suite.Equal(http.StatusOK, status) - status = requestStatusBody(c, testDialClient, http.MethodGet, url) - c.Assert(status, Equals, http.StatusOK) + status = suite.requestStatusBody(testDialClient, http.MethodGet, url) + suite.Equal(http.StatusOK, status) store = new(StoreInfo) - err = tu.ReadGetJSON(c, testDialClient, url, store) - c.Assert(err, IsNil) - c.Assert(store.Store.State, Equals, metapb.StoreState_Up) - c.Assert(store.Store.PhysicallyDestroyed, IsFalse) + err = tu.ReadGetJSON(re, testDialClient, url, store) + suite.NoError(err) + suite.Equal(metapb.StoreState_Up, store.Store.State) + suite.False(store.Store.PhysicallyDestroyed) // offline store with physically destroyed - status = requestStatusBody(c, testDialClient, http.MethodDelete, fmt.Sprintf("%s?force=true", url)) - c.Assert(status, Equals, http.StatusOK) - err = tu.ReadGetJSON(c, testDialClient, url, store) - c.Assert(err, IsNil) - c.Assert(store.Store.State, Equals, metapb.StoreState_Offline) - c.Assert(store.Store.PhysicallyDestroyed, IsTrue) + status = suite.requestStatusBody(testDialClient, http.MethodDelete, fmt.Sprintf("%s?force=true", url)) + suite.Equal(http.StatusOK, status) + err = tu.ReadGetJSON(re, testDialClient, url, store) + suite.NoError(err) + suite.Equal(metapb.StoreState_Offline, store.Store.State) + suite.True(store.Store.PhysicallyDestroyed) // try to up store again failed because it is physically destroyed - status = requestStatusBody(c, testDialClient, http.MethodPost, fmt.Sprintf("%s/state?state=Up", url)) - c.Assert(status, Equals, http.StatusBadRequest) + status = suite.requestStatusBody(testDialClient, http.MethodPost, fmt.Sprintf("%s/state?state=Up", url)) + suite.Equal(http.StatusBadRequest, status) // reset store 6 - s.cleanup() - s.SetUpSuite(c) + suite.cleanup() + suite.SetupSuite() } -func (s *testStoreSuite) TestStoreSetState(c *C) { +func (suite *storeTestSuite) TestStoreSetState() { + re := suite.Require() // prepare enough online stores to store replica. for id := 1111; id <= 1115; id++ { - mustPutStore(c, s.svr, uint64(id), metapb.StoreState_Up, metapb.NodeState_Serving, nil) + mustPutStore(re, suite.svr, uint64(id), metapb.StoreState_Up, metapb.NodeState_Serving, nil) } - url := fmt.Sprintf("%s/store/1", s.urlPrefix) + url := fmt.Sprintf("%s/store/1", suite.urlPrefix) info := StoreInfo{} - err := tu.ReadGetJSON(c, testDialClient, url, &info) - c.Assert(err, IsNil) - c.Assert(info.Store.State, Equals, metapb.StoreState_Up) + err := tu.ReadGetJSON(re, testDialClient, url, &info) + suite.NoError(err) + suite.Equal(metapb.StoreState_Up, info.Store.State) // Set to Offline. info = StoreInfo{} - err = tu.CheckPostJSON(testDialClient, url+"/state?state=Offline", nil, tu.StatusOK(c)) - c.Assert(err, IsNil) - err = tu.ReadGetJSON(c, testDialClient, url, &info) - c.Assert(err, IsNil) - c.Assert(info.Store.State, Equals, metapb.StoreState_Offline) + err = tu.CheckPostJSON(testDialClient, url+"/state?state=Offline", nil, tu.StatusOK(re)) + suite.NoError(err) + err = tu.ReadGetJSON(re, testDialClient, url, &info) + suite.NoError(err) + suite.Equal(metapb.StoreState_Offline, info.Store.State) // store not found info = StoreInfo{} - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/store/10086/state?state=Offline", nil, tu.StatusNotOK(c)) - c.Assert(err, IsNil) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/store/10086/state?state=Offline", nil, tu.StatusNotOK(re)) + suite.NoError(err) // Invalid state. invalidStates := []string{"Foo", "Tombstone"} for _, state := range invalidStates { info = StoreInfo{} - err = tu.CheckPostJSON(testDialClient, url+"/state?state="+state, nil, tu.StatusNotOK(c)) - c.Assert(err, IsNil) - err := tu.ReadGetJSON(c, testDialClient, url, &info) - c.Assert(err, IsNil) - c.Assert(info.Store.State, Equals, metapb.StoreState_Offline) + err = tu.CheckPostJSON(testDialClient, url+"/state?state="+state, nil, tu.StatusNotOK(re)) + suite.NoError(err) + err := tu.ReadGetJSON(re, testDialClient, url, &info) + suite.NoError(err) + suite.Equal(metapb.StoreState_Offline, info.Store.State) } // Set back to Up. info = StoreInfo{} - err = tu.CheckPostJSON(testDialClient, url+"/state?state=Up", nil, tu.StatusOK(c)) - c.Assert(err, IsNil) - err = tu.ReadGetJSON(c, testDialClient, url, &info) - c.Assert(err, IsNil) - c.Assert(info.Store.State, Equals, metapb.StoreState_Up) - s.cleanup() - s.SetUpSuite(c) + err = tu.CheckPostJSON(testDialClient, url+"/state?state=Up", nil, tu.StatusOK(re)) + suite.NoError(err) + err = tu.ReadGetJSON(re, testDialClient, url, &info) + suite.NoError(err) + suite.Equal(metapb.StoreState_Up, info.Store.State) + suite.cleanup() + suite.SetupSuite() } -func (s *testStoreSuite) TestUrlStoreFilter(c *C) { +func (suite *storeTestSuite) TestUrlStoreFilter() { table := []struct { u string want []*metapb.Store }{ { u: "http://localhost:2379/pd/api/v1/stores", - want: s.stores[:3], + want: suite.stores[:3], }, { u: "http://localhost:2379/pd/api/v1/stores?state=2", - want: s.stores[3:], + want: suite.stores[3:], }, { u: "http://localhost:2379/pd/api/v1/stores?state=0", - want: s.stores[:2], + want: suite.stores[:2], }, { u: "http://localhost:2379/pd/api/v1/stores?state=2&state=1", - want: s.stores[2:], + want: suite.stores[2:], }, } for _, t := range table { uu, err := url.Parse(t.u) - c.Assert(err, IsNil) + suite.NoError(err) f, err := newStoreStateFilter(uu) - c.Assert(err, IsNil) - c.Assert(f.filter(s.stores), DeepEquals, t.want) + suite.NoError(err) + suite.Equal(t.want, f.filter(suite.stores)) } u, err := url.Parse("http://localhost:2379/pd/api/v1/stores?state=foo") - c.Assert(err, IsNil) + suite.NoError(err) _, err = newStoreStateFilter(u) - c.Assert(err, NotNil) + suite.Error(err) u, err = url.Parse("http://localhost:2379/pd/api/v1/stores?state=999999") - c.Assert(err, IsNil) + suite.NoError(err) _, err = newStoreStateFilter(u) - c.Assert(err, NotNil) + suite.Error(err) } -func (s *testStoreSuite) TestDownState(c *C) { +func (suite *storeTestSuite) TestDownState() { store := core.NewStoreInfo( &metapb.Store{ State: metapb.StoreState_Up, @@ -397,27 +407,27 @@ func (s *testStoreSuite) TestDownState(c *C) { core.SetStoreStats(&pdpb.StoreStats{}), core.SetLastHeartbeatTS(time.Now()), ) - storeInfo := newStoreInfo(s.svr.GetScheduleConfig(), store) - c.Assert(storeInfo.Store.StateName, Equals, metapb.StoreState_Up.String()) + storeInfo := newStoreInfo(suite.svr.GetScheduleConfig(), store) + suite.Equal(metapb.StoreState_Up.String(), storeInfo.Store.StateName) newStore := store.Clone(core.SetLastHeartbeatTS(time.Now().Add(-time.Minute * 2))) - storeInfo = newStoreInfo(s.svr.GetScheduleConfig(), newStore) - c.Assert(storeInfo.Store.StateName, Equals, disconnectedName) + storeInfo = newStoreInfo(suite.svr.GetScheduleConfig(), newStore) + suite.Equal(disconnectedName, storeInfo.Store.StateName) newStore = store.Clone(core.SetLastHeartbeatTS(time.Now().Add(-time.Hour * 2))) - storeInfo = newStoreInfo(s.svr.GetScheduleConfig(), newStore) - c.Assert(storeInfo.Store.StateName, Equals, downStateName) + storeInfo = newStoreInfo(suite.svr.GetScheduleConfig(), newStore) + suite.Equal(downStateName, storeInfo.Store.StateName) } -func (s *testStoreSuite) TestGetAllLimit(c *C) { - testcases := []struct { +func (suite *storeTestSuite) TestGetAllLimit() { + testCases := []struct { name string url string expectedStores map[uint64]struct{} }{ { name: "includeTombstone", - url: fmt.Sprintf("%s/stores/limit?include_tombstone=true", s.urlPrefix), + url: fmt.Sprintf("%s/stores/limit?include_tombstone=true", suite.urlPrefix), expectedStores: map[uint64]struct{}{ 1: {}, 4: {}, @@ -427,7 +437,7 @@ func (s *testStoreSuite) TestGetAllLimit(c *C) { }, { name: "excludeTombStone", - url: fmt.Sprintf("%s/stores/limit?include_tombstone=false", s.urlPrefix), + url: fmt.Sprintf("%s/stores/limit?include_tombstone=false", suite.urlPrefix), expectedStores: map[uint64]struct{}{ 1: {}, 4: {}, @@ -436,7 +446,7 @@ func (s *testStoreSuite) TestGetAllLimit(c *C) { }, { name: "default", - url: fmt.Sprintf("%s/stores/limit", s.urlPrefix), + url: fmt.Sprintf("%s/stores/limit", suite.urlPrefix), expectedStores: map[uint64]struct{}{ 1: {}, 4: {}, @@ -445,66 +455,68 @@ func (s *testStoreSuite) TestGetAllLimit(c *C) { }, } - for _, testcase := range testcases { - c.Logf(testcase.name) + re := suite.Require() + for _, testCase := range testCases { + suite.T().Logf(testCase.name) info := make(map[uint64]interface{}, 4) - err := tu.ReadGetJSON(c, testDialClient, testcase.url, &info) - c.Assert(err, IsNil) - c.Assert(len(info), Equals, len(testcase.expectedStores)) - for id := range testcase.expectedStores { + err := tu.ReadGetJSON(re, testDialClient, testCase.url, &info) + suite.NoError(err) + suite.Len(testCase.expectedStores, len(info)) + for id := range testCase.expectedStores { _, ok := info[id] - c.Assert(ok, IsTrue) + suite.True(ok) } } } -func (s *testStoreSuite) TestStoreLimitTTL(c *C) { +func (suite *storeTestSuite) TestStoreLimitTTL() { // add peer - url := fmt.Sprintf("%s/store/1/limit?ttlSecond=%v", s.urlPrefix, 5) + url := fmt.Sprintf("%s/store/1/limit?ttlSecond=%v", suite.urlPrefix, 5) data := map[string]interface{}{ "type": "add-peer", "rate": 999, } postData, err := json.Marshal(data) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, url, postData, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + re := suite.Require() + err = tu.CheckPostJSON(testDialClient, url, postData, tu.StatusOK(re)) + suite.NoError(err) // remove peer data = map[string]interface{}{ "type": "remove-peer", "rate": 998, } postData, err = json.Marshal(data) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, url, postData, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, url, postData, tu.StatusOK(re)) + suite.NoError(err) // all store limit add peer - url = fmt.Sprintf("%s/stores/limit?ttlSecond=%v", s.urlPrefix, 3) + url = fmt.Sprintf("%s/stores/limit?ttlSecond=%v", suite.urlPrefix, 3) data = map[string]interface{}{ "type": "add-peer", "rate": 997, } postData, err = json.Marshal(data) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, url, postData, tu.StatusOK(c)) - c.Assert(err, IsNil) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, url, postData, tu.StatusOK(re)) + suite.NoError(err) // all store limit remove peer data = map[string]interface{}{ "type": "remove-peer", "rate": 996, } postData, err = json.Marshal(data) - c.Assert(err, IsNil) - err = tu.CheckPostJSON(testDialClient, url, postData, tu.StatusOK(c)) - c.Assert(err, IsNil) - - c.Assert(s.svr.GetPersistOptions().GetStoreLimit(uint64(1)).AddPeer, Equals, float64(999)) - c.Assert(s.svr.GetPersistOptions().GetStoreLimit(uint64(1)).RemovePeer, Equals, float64(998)) - c.Assert(s.svr.GetPersistOptions().GetStoreLimit(uint64(2)).AddPeer, Equals, float64(997)) - c.Assert(s.svr.GetPersistOptions().GetStoreLimit(uint64(2)).RemovePeer, Equals, float64(996)) + suite.NoError(err) + err = tu.CheckPostJSON(testDialClient, url, postData, tu.StatusOK(re)) + suite.NoError(err) + + suite.Equal(float64(999), suite.svr.GetPersistOptions().GetStoreLimit(uint64(1)).AddPeer) + suite.Equal(float64(998), suite.svr.GetPersistOptions().GetStoreLimit(uint64(1)).RemovePeer) + suite.Equal(float64(997), suite.svr.GetPersistOptions().GetStoreLimit(uint64(2)).AddPeer) + suite.Equal(float64(996), suite.svr.GetPersistOptions().GetStoreLimit(uint64(2)).RemovePeer) time.Sleep(5 * time.Second) - c.Assert(s.svr.GetPersistOptions().GetStoreLimit(uint64(1)).AddPeer, Not(Equals), float64(999)) - c.Assert(s.svr.GetPersistOptions().GetStoreLimit(uint64(1)).RemovePeer, Not(Equals), float64(998)) - c.Assert(s.svr.GetPersistOptions().GetStoreLimit(uint64(2)).AddPeer, Not(Equals), float64(997)) - c.Assert(s.svr.GetPersistOptions().GetStoreLimit(uint64(2)).RemovePeer, Not(Equals), float64(996)) + suite.NotEqual(float64(999), suite.svr.GetPersistOptions().GetStoreLimit(uint64(1)).AddPeer) + suite.NotEqual(float64(998), suite.svr.GetPersistOptions().GetStoreLimit(uint64(1)).RemovePeer) + suite.NotEqual(float64(997), suite.svr.GetPersistOptions().GetStoreLimit(uint64(2)).AddPeer) + suite.NotEqual(float64(996), suite.svr.GetPersistOptions().GetStoreLimit(uint64(2)).RemovePeer) } diff --git a/server/api/trend_test.go b/server/api/trend_test.go index 6e5d565573e..972af465ef9 100644 --- a/server/api/trend_test.go +++ b/server/api/trend_test.go @@ -16,76 +16,73 @@ package api import ( "fmt" + "testing" "time" - . "github.com/pingcap/check" "github.com/pingcap/kvproto/pkg/metapb" + "github.com/stretchr/testify/require" tu "github.com/tikv/pd/pkg/testutil" "github.com/tikv/pd/server" "github.com/tikv/pd/server/core" "github.com/tikv/pd/server/schedule/operator" ) -var _ = Suite(&testTrendSuite{}) - -type testTrendSuite struct{} - -func (s *testTrendSuite) TestTrend(c *C) { - svr, cleanup := mustNewServer(c) +func TestTrend(t *testing.T) { + re := require.New(t) + svr, cleanup := mustNewServer(re) defer cleanup() - mustWaitLeader(c, []*server.Server{svr}) + mustWaitLeader(re, []*server.Server{svr}) - mustBootstrapCluster(c, svr) + mustBootstrapCluster(re, svr) for i := 1; i <= 3; i++ { - mustPutStore(c, svr, uint64(i), metapb.StoreState_Up, metapb.NodeState_Serving, nil) + mustPutStore(re, svr, uint64(i), metapb.StoreState_Up, metapb.NodeState_Serving, nil) } // Create 3 regions, all peers on store1 and store2, and the leaders are all on store1. - region4 := s.newRegionInfo(4, "", "a", 2, 2, []uint64{1, 2}, nil, 1) - region5 := s.newRegionInfo(5, "a", "b", 2, 2, []uint64{1, 2}, nil, 1) - region6 := s.newRegionInfo(6, "b", "", 2, 2, []uint64{1, 2}, nil, 1) - mustRegionHeartbeat(c, svr, region4) - mustRegionHeartbeat(c, svr, region5) - mustRegionHeartbeat(c, svr, region6) + region4 := newRegionInfo(4, "", "a", 2, 2, []uint64{1, 2}, nil, 1) + region5 := newRegionInfo(5, "a", "b", 2, 2, []uint64{1, 2}, nil, 1) + region6 := newRegionInfo(6, "b", "", 2, 2, []uint64{1, 2}, nil, 1) + mustRegionHeartbeat(re, svr, region4) + mustRegionHeartbeat(re, svr, region5) + mustRegionHeartbeat(re, svr, region6) // Create 3 operators that transfers leader, moves follower, moves leader. - c.Assert(svr.GetHandler().AddTransferLeaderOperator(4, 2), IsNil) - c.Assert(svr.GetHandler().AddTransferPeerOperator(5, 2, 3), IsNil) + re.NoError(svr.GetHandler().AddTransferLeaderOperator(4, 2)) + re.NoError(svr.GetHandler().AddTransferPeerOperator(5, 2, 3)) time.Sleep(1 * time.Second) - c.Assert(svr.GetHandler().AddTransferPeerOperator(6, 1, 3), IsNil) - + re.NoError(svr.GetHandler().AddTransferPeerOperator(6, 1, 3)) // Complete the operators. - mustRegionHeartbeat(c, svr, region4.Clone(core.WithLeader(region4.GetStorePeer(2)))) + mustRegionHeartbeat(re, svr, region4.Clone(core.WithLeader(region4.GetStorePeer(2)))) op, err := svr.GetHandler().GetOperator(5) - c.Assert(err, IsNil) - c.Assert(op, NotNil) + re.NoError(err) + re.NotNil(op) newPeerID := op.Step(0).(operator.AddLearner).PeerID region5 = region5.Clone(core.WithAddPeer(&metapb.Peer{Id: newPeerID, StoreId: 3, Role: metapb.PeerRole_Learner}), core.WithIncConfVer()) - mustRegionHeartbeat(c, svr, region5) + mustRegionHeartbeat(re, svr, region5) region5 = region5.Clone(core.WithPromoteLearner(newPeerID), core.WithRemoveStorePeer(2), core.WithIncConfVer()) - mustRegionHeartbeat(c, svr, region5) + mustRegionHeartbeat(re, svr, region5) op, err = svr.GetHandler().GetOperator(6) - c.Assert(err, IsNil) - c.Assert(op, NotNil) + re.NoError(err) + re.NotNil(op) newPeerID = op.Step(0).(operator.AddLearner).PeerID region6 = region6.Clone(core.WithAddPeer(&metapb.Peer{Id: newPeerID, StoreId: 3, Role: metapb.PeerRole_Learner}), core.WithIncConfVer()) - mustRegionHeartbeat(c, svr, region6) + mustRegionHeartbeat(re, svr, region6) region6 = region6.Clone(core.WithPromoteLearner(newPeerID), core.WithLeader(region6.GetStorePeer(2)), core.WithRemoveStorePeer(1), core.WithIncConfVer()) - mustRegionHeartbeat(c, svr, region6) + mustRegionHeartbeat(re, svr, region6) var trend Trend - err = tu.ReadGetJSON(c, testDialClient, fmt.Sprintf("%s%s/api/v1/trend", svr.GetAddr(), apiPrefix), &trend) - c.Assert(err, IsNil) + err = tu.ReadGetJSON(re, testDialClient, fmt.Sprintf("%s%s/api/v1/trend", svr.GetAddr(), apiPrefix), &trend) + re.NoError(err) // Check store states. expectLeaderCount := map[uint64]int{1: 1, 2: 2, 3: 0} expectRegionCount := map[uint64]int{1: 2, 2: 2, 3: 2} - c.Assert(trend.Stores, HasLen, 3) + re.Len(trend.Stores, 3) for _, store := range trend.Stores { - c.Assert(store.LeaderCount, Equals, expectLeaderCount[store.ID]) - c.Assert(store.RegionCount, Equals, expectRegionCount[store.ID]) + re.Equal(expectLeaderCount[store.ID], store.LeaderCount) + re.Equal(expectRegionCount[store.ID], store.RegionCount) } // Check history. @@ -94,13 +91,13 @@ func (s *testTrendSuite) TestTrend(c *C) { {From: 1, To: 3, Kind: "region"}: 1, {From: 2, To: 3, Kind: "region"}: 1, } - c.Assert(trend.History.Entries, HasLen, 3) + re.Len(trend.History.Entries, 3) for _, history := range trend.History.Entries { - c.Assert(history.Count, Equals, expectHistory[trendHistoryEntry{From: history.From, To: history.To, Kind: history.Kind}]) + re.Equal(expectHistory[trendHistoryEntry{From: history.From, To: history.To, Kind: history.Kind}], history.Count) } } -func (s *testTrendSuite) newRegionInfo(id uint64, startKey, endKey string, confVer, ver uint64, voters []uint64, learners []uint64, leaderStore uint64) *core.RegionInfo { +func newRegionInfo(id uint64, startKey, endKey string, confVer, ver uint64, voters []uint64, learners []uint64, leaderStore uint64) *core.RegionInfo { var ( peers = make([]*metapb.Peer, 0, len(voters)+len(learners)) leader *metapb.Peer diff --git a/server/api/tso_test.go b/server/api/tso_test.go index af73fd1ded0..2f59a2ecf07 100644 --- a/server/api/tso_test.go +++ b/server/api/tso_test.go @@ -16,44 +16,50 @@ package api import ( "fmt" + "testing" "time" - . "github.com/pingcap/check" + "github.com/stretchr/testify/suite" tu "github.com/tikv/pd/pkg/testutil" "github.com/tikv/pd/server" "github.com/tikv/pd/server/config" ) -var _ = Suite(&testTsoSuite{}) - -type testTsoSuite struct { +type tsoTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testTsoSuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c, func(cfg *config.Config) { +func TestTSOTestSuite(t *testing.T) { + suite.Run(t, new(tsoTestSuite)) +} + +func (suite *tsoTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re, func(cfg *config.Config) { cfg.EnableLocalTSO = true cfg.Labels[config.ZoneLabel] = "dc-1" }) - mustWaitLeader(c, []*server.Server{s.svr}) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1", addr, apiPrefix) } -func (s *testTsoSuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *tsoTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *testTsoSuite) TestTransferAllocator(c *C) { - tu.WaitUntil(c, func() bool { - s.svr.GetTSOAllocatorManager().ClusterDCLocationChecker() - _, err := s.svr.GetTSOAllocatorManager().GetAllocator("dc-1") +func (suite *tsoTestSuite) TestTransferAllocator() { + re := suite.Require() + tu.Eventually(re, func() bool { + suite.svr.GetTSOAllocatorManager().ClusterDCLocationChecker() + _, err := suite.svr.GetTSOAllocatorManager().GetAllocator("dc-1") return err == nil }, tu.WithRetryTimes(5), tu.WithSleepInterval(3*time.Second)) - addr := s.urlPrefix + "/tso/allocator/transfer/pd1?dcLocation=dc-1" - err := tu.CheckPostJSON(testDialClient, addr, nil, tu.StatusOK(c)) - c.Assert(err, IsNil) + addr := suite.urlPrefix + "/tso/allocator/transfer/pd1?dcLocation=dc-1" + err := tu.CheckPostJSON(testDialClient, addr, nil, tu.StatusOK(re)) + suite.NoError(err) } diff --git a/server/api/unsafe_operation_test.go b/server/api/unsafe_operation_test.go index f9d060d2fe3..62df25c6b68 100644 --- a/server/api/unsafe_operation_test.go +++ b/server/api/unsafe_operation_test.go @@ -17,63 +17,69 @@ package api import ( "encoding/json" "fmt" + "testing" - . "github.com/pingcap/check" "github.com/pingcap/kvproto/pkg/metapb" + "github.com/stretchr/testify/suite" tu "github.com/tikv/pd/pkg/testutil" "github.com/tikv/pd/server" "github.com/tikv/pd/server/cluster" ) -var _ = Suite(&testUnsafeAPISuite{}) - -type testUnsafeAPISuite struct { +type unsafeOperationTestSuite struct { + suite.Suite svr *server.Server cleanup cleanUpFunc urlPrefix string } -func (s *testUnsafeAPISuite) SetUpSuite(c *C) { - s.svr, s.cleanup = mustNewServer(c) - mustWaitLeader(c, []*server.Server{s.svr}) +func TestUnsafeOperationTestSuite(t *testing.T) { + suite.Run(t, new(unsafeOperationTestSuite)) +} + +func (suite *unsafeOperationTestSuite) SetupSuite() { + re := suite.Require() + suite.svr, suite.cleanup = mustNewServer(re) + mustWaitLeader(re, []*server.Server{suite.svr}) - addr := s.svr.GetAddr() - s.urlPrefix = fmt.Sprintf("%s%s/api/v1/admin/unsafe", addr, apiPrefix) + addr := suite.svr.GetAddr() + suite.urlPrefix = fmt.Sprintf("%s%s/api/v1/admin/unsafe", addr, apiPrefix) - mustBootstrapCluster(c, s.svr) - mustPutStore(c, s.svr, 1, metapb.StoreState_Offline, metapb.NodeState_Removing, nil) + mustBootstrapCluster(re, suite.svr) + mustPutStore(re, suite.svr, 1, metapb.StoreState_Offline, metapb.NodeState_Removing, nil) } -func (s *testUnsafeAPISuite) TearDownSuite(c *C) { - s.cleanup() +func (suite *unsafeOperationTestSuite) TearDownSuite() { + suite.cleanup() } -func (s *testUnsafeAPISuite) TestRemoveFailedStores(c *C) { +func (suite *unsafeOperationTestSuite) TestRemoveFailedStores() { input := map[string]interface{}{"stores": []uint64{}} data, _ := json.Marshal(input) - err := tu.CheckPostJSON(testDialClient, s.urlPrefix+"/remove-failed-stores", data, tu.StatusNotOK(c), - tu.StringEqual(c, "\"[PD:unsaferecovery:ErrUnsafeRecoveryInvalidInput]invalid input no store specified\"\n")) - c.Assert(err, IsNil) + re := suite.Require() + err := tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/remove-failed-stores", data, tu.StatusNotOK(re), + tu.StringEqual(re, "\"[PD:unsaferecovery:ErrUnsafeRecoveryInvalidInput]invalid input no store specified\"\n")) + suite.NoError(err) input = map[string]interface{}{"stores": []string{"abc", "def"}} data, _ = json.Marshal(input) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/remove-failed-stores", data, tu.StatusNotOK(c), - tu.StringEqual(c, "\"Store ids are invalid\"\n")) - c.Assert(err, IsNil) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/remove-failed-stores", data, tu.StatusNotOK(re), + tu.StringEqual(re, "\"Store ids are invalid\"\n")) + suite.NoError(err) input = map[string]interface{}{"stores": []uint64{1, 2}} data, _ = json.Marshal(input) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/remove-failed-stores", data, tu.StatusNotOK(c), - tu.StringEqual(c, "\"[PD:unsaferecovery:ErrUnsafeRecoveryInvalidInput]invalid input store 2 doesn't exist\"\n")) - c.Assert(err, IsNil) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/remove-failed-stores", data, tu.StatusNotOK(re), + tu.StringEqual(re, "\"[PD:unsaferecovery:ErrUnsafeRecoveryInvalidInput]invalid input store 2 doesn't exist\"\n")) + suite.NoError(err) input = map[string]interface{}{"stores": []uint64{1}} data, _ = json.Marshal(input) - err = tu.CheckPostJSON(testDialClient, s.urlPrefix+"/remove-failed-stores", data, tu.StatusOK(c)) - c.Assert(err, IsNil) + err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/remove-failed-stores", data, tu.StatusOK(re)) + suite.NoError(err) // Test show var output []cluster.StageOutput - err = tu.ReadGetJSON(c, testDialClient, s.urlPrefix+"/remove-failed-stores/show", &output) - c.Assert(err, IsNil) + err = tu.ReadGetJSON(re, testDialClient, suite.urlPrefix+"/remove-failed-stores/show", &output) + suite.NoError(err) } diff --git a/server/api/version_test.go b/server/api/version_test.go index 7cbbab688cf..41254649c34 100644 --- a/server/api/version_test.go +++ b/server/api/version_test.go @@ -19,70 +19,67 @@ import ( "io" "os" "path/filepath" - "strings" + "testing" "time" - . "github.com/pingcap/check" "github.com/pingcap/failpoint" + "github.com/stretchr/testify/require" "github.com/tikv/pd/pkg/assertutil" "github.com/tikv/pd/pkg/testutil" "github.com/tikv/pd/server" "github.com/tikv/pd/server/config" ) -var _ = Suite(&testVersionSuite{}) - -func checkerWithNilAssert(c *C) *assertutil.Checker { +func checkerWithNilAssert(re *require.Assertions) *assertutil.Checker { checker := assertutil.NewChecker() checker.FailNow = func() { - c.FailNow() + re.FailNow("should be nil") } checker.IsNil = func(obtained interface{}) { - c.Assert(obtained, IsNil) + re.Nil(obtained) } return checker } -type testVersionSuite struct{} - -func (s *testVersionSuite) TestGetVersion(c *C) { +func TestGetVersion(t *testing.T) { // TODO: enable it. - c.Skip("Temporary disable. See issue: https://github.com/tikv/pd/issues/1893") + t.Skip("Temporary disable. See issue: https://github.com/tikv/pd/issues/1893") + re := require.New(t) fname := filepath.Join(os.TempDir(), "stdout") old := os.Stdout temp, _ := os.Create(fname) os.Stdout = temp - cfg := server.NewTestSingleConfig(checkerWithNilAssert(c)) + cfg := server.NewTestSingleConfig(checkerWithNilAssert(re)) reqCh := make(chan struct{}) go func() { <-reqCh time.Sleep(200 * time.Millisecond) addr := cfg.ClientUrls + apiPrefix + "/api/v1/version" resp, err := testDialClient.Get(addr) - c.Assert(err, IsNil) + re.NoError(err) defer resp.Body.Close() _, err = io.ReadAll(resp.Body) - c.Assert(err, IsNil) + re.NoError(err) }() ctx, cancel := context.WithCancel(context.Background()) ch := make(chan *server.Server) go func(cfg *config.Config) { s, err := server.CreateServer(ctx, cfg, NewHandler) - c.Assert(err, IsNil) - c.Assert(failpoint.Enable("github.com/tikv/pd/server/memberNil", `return(true)`), IsNil) + re.NoError(err) + re.NoError(failpoint.Enable("github.com/tikv/pd/server/memberNil", `return(true)`)) reqCh <- struct{}{} err = s.Run() - c.Assert(err, IsNil) + re.NoError(err) ch <- s }(cfg) svr := <-ch close(ch) out, _ := os.ReadFile(fname) - c.Assert(strings.Contains(string(out), "PANIC"), IsFalse) + re.NotContains(string(out), "PANIC") // clean up func() { @@ -93,5 +90,5 @@ func (s *testVersionSuite) TestGetVersion(c *C) { cancel() testutil.CleanServer(cfg.DataDir) }() - c.Assert(failpoint.Disable("github.com/tikv/pd/server/memberNil"), IsNil) + re.NoError(failpoint.Disable("github.com/tikv/pd/server/memberNil")) } diff --git a/server/schedule/placement/region_rule_cache_test.go b/server/schedule/placement/region_rule_cache_test.go index 7c578a11e34..a9224c49162 100644 --- a/server/schedule/placement/region_rule_cache_test.go +++ b/server/schedule/placement/region_rule_cache_test.go @@ -181,7 +181,7 @@ func TestRegionRuleFitCache(t *testing.T) { } for _, testCase := range testCases { t.Log(testCase.name) - re.Equal(false, cache.IsUnchanged(testCase.region, testCase.rules, mockStoresNoHeartbeat(3))) + re.False(cache.IsUnchanged(testCase.region, testCase.rules, mockStoresNoHeartbeat(3))) } // Invalid Input4 re.False(cache.IsUnchanged(mockRegion(3, 0), addExtraRules(0), nil)) diff --git a/tests/client/client_test.go b/tests/client/client_test.go index c6c4f45ee47..003b4f73c32 100644 --- a/tests/client/client_test.go +++ b/tests/client/client_test.go @@ -692,7 +692,7 @@ func (suite *clientTestSuite) SetupSuite() { re := suite.Require() suite.srv, suite.cleanup, err = server.NewTestServer(suite.checkerWithNilAssert()) suite.NoError(err) - suite.grpcPDClient = testutil.MustNewGrpcClientWithTestify(re, suite.srv.GetAddr()) + suite.grpcPDClient = testutil.MustNewGrpcClient(re, suite.srv.GetAddr()) suite.grpcSvr = &server.GrpcServer{Server: suite.srv} suite.mustWaitLeader(map[string]*server.Server{suite.srv.GetAddr(): suite.srv}) diff --git a/tests/pdctl/helper.go b/tests/pdctl/helper.go index bbfa351cc32..9a6adf566a3 100644 --- a/tests/pdctl/helper.go +++ b/tests/pdctl/helper.go @@ -43,9 +43,9 @@ func ExecuteCommand(root *cobra.Command, args ...string) (output []byte, err err } // CheckStoresInfo is used to check the test results. -// CheckStoresInfo will not check Store.State because this field has been omitted pdctl output +// CheckStoresInfo will not check Store.State because this field has been omitted pd-ctl output func CheckStoresInfo(re *require.Assertions, stores []*api.StoreInfo, want []*api.StoreInfo) { - re.Equal(len(want), len(stores)) + re.Len(stores, len(want)) mapWant := make(map[uint64]*api.StoreInfo) for _, s := range want { if _, ok := mapWant[s.Store.Id]; !ok { @@ -70,7 +70,7 @@ func CheckStoresInfo(re *require.Assertions, stores []*api.StoreInfo, want []*ap // CheckRegionInfo is used to check the test results. func CheckRegionInfo(re *require.Assertions, output *api.RegionInfo, expected *core.RegionInfo) { - region := api.NewRegionInfo(expected) + region := api.NewAPIRegionInfo(expected) output.Adjust() re.Equal(region, output) } diff --git a/tests/server/api/api_test.go b/tests/server/api/api_test.go index 49f8026e2af..012c09b287e 100644 --- a/tests/server/api/api_test.go +++ b/tests/server/api/api_test.go @@ -507,7 +507,7 @@ func TestRemovingProgress(t *testing.T) { cluster.WaitLeader() leader := cluster.GetServer(cluster.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leader.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leader.GetAddr()) clusterID := leader.GetClusterID() req := &pdpb.BootstrapRequest{ Header: testutil.NewRequestHeader(clusterID), @@ -624,7 +624,7 @@ func TestPreparingProgress(t *testing.T) { cluster.WaitLeader() leader := cluster.GetServer(cluster.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leader.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leader.GetAddr()) clusterID := leader.GetClusterID() req := &pdpb.BootstrapRequest{ Header: testutil.NewRequestHeader(clusterID), diff --git a/tests/server/cluster/cluster_test.go b/tests/server/cluster/cluster_test.go index 1bf2ecad485..d5f623712ae 100644 --- a/tests/server/cluster/cluster_test.go +++ b/tests/server/cluster/cluster_test.go @@ -68,7 +68,7 @@ func TestBootstrap(t *testing.T) { tc.WaitLeader() leaderServer := tc.GetServer(tc.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) clusterID := leaderServer.GetClusterID() // IsBootstrapped returns false. @@ -108,7 +108,7 @@ func TestDamagedRegion(t *testing.T) { tc.WaitLeader() leaderServer := tc.GetServer(tc.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) clusterID := leaderServer.GetClusterID() bootstrapCluster(re, clusterID, grpcPDClient) rc := leaderServer.GetRaftCluster() @@ -187,7 +187,7 @@ func TestGetPutConfig(t *testing.T) { tc.WaitLeader() leaderServer := tc.GetServer(tc.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) clusterID := leaderServer.GetClusterID() bootstrapCluster(re, clusterID, grpcPDClient) rc := leaderServer.GetRaftCluster() @@ -407,7 +407,7 @@ func TestRaftClusterRestart(t *testing.T) { tc.WaitLeader() leaderServer := tc.GetServer(tc.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) clusterID := leaderServer.GetClusterID() bootstrapCluster(re, clusterID, grpcPDClient) @@ -437,7 +437,7 @@ func TestRaftClusterMultipleRestart(t *testing.T) { tc.WaitLeader() leaderServer := tc.GetServer(tc.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) clusterID := leaderServer.GetClusterID() bootstrapCluster(re, clusterID, grpcPDClient) // add an offline store @@ -480,7 +480,7 @@ func TestGetPDMembers(t *testing.T) { tc.WaitLeader() leaderServer := tc.GetServer(tc.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) clusterID := leaderServer.GetClusterID() req := &pdpb.GetMembersRequest{Header: testutil.NewRequestHeader(clusterID)} resp, err := grpcPDClient.GetMembers(context.Background(), req) @@ -499,7 +499,7 @@ func TestNotLeader(t *testing.T) { re.NoError(tc.RunInitialServers()) tc.WaitLeader() followerServer := tc.GetServer(tc.GetFollower()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, followerServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, followerServer.GetAddr()) clusterID := followerServer.GetClusterID() req := &pdpb.AllocIDRequest{Header: testutil.NewRequestHeader(clusterID)} resp, err := grpcPDClient.AllocID(context.Background(), req) @@ -523,7 +523,7 @@ func TestStoreVersionChange(t *testing.T) { tc.WaitLeader() leaderServer := tc.GetServer(tc.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) clusterID := leaderServer.GetClusterID() bootstrapCluster(re, clusterID, grpcPDClient) svr := leaderServer.GetServer() @@ -560,7 +560,7 @@ func TestConcurrentHandleRegion(t *testing.T) { re.NoError(err) tc.WaitLeader() leaderServer := tc.GetServer(tc.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) clusterID := leaderServer.GetClusterID() bootstrapCluster(re, clusterID, grpcPDClient) storeAddrs := []string{"127.0.1.1:0", "127.0.1.1:1", "127.0.1.1:2"} @@ -676,7 +676,7 @@ func TestSetScheduleOpt(t *testing.T) { tc.WaitLeader() leaderServer := tc.GetServer(tc.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) clusterID := leaderServer.GetClusterID() bootstrapCluster(re, clusterID, grpcPDClient) @@ -836,7 +836,7 @@ func TestTiFlashWithPlacementRules(t *testing.T) { re.NoError(err) tc.WaitLeader() leaderServer := tc.GetServer(tc.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) clusterID := leaderServer.GetClusterID() bootstrapCluster(re, clusterID, grpcPDClient) @@ -886,7 +886,7 @@ func TestReplicationModeStatus(t *testing.T) { re.NoError(err) tc.WaitLeader() leaderServer := tc.GetServer(tc.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) clusterID := leaderServer.GetClusterID() req := newBootstrapRequest(clusterID) res, err := grpcPDClient.Bootstrap(context.Background(), req) @@ -984,7 +984,7 @@ func TestOfflineStoreLimit(t *testing.T) { re.NoError(err) tc.WaitLeader() leaderServer := tc.GetServer(tc.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) clusterID := leaderServer.GetClusterID() bootstrapCluster(re, clusterID, grpcPDClient) storeAddrs := []string{"127.0.1.1:0", "127.0.1.1:1"} @@ -1076,7 +1076,7 @@ func TestUpgradeStoreLimit(t *testing.T) { re.NoError(err) tc.WaitLeader() leaderServer := tc.GetServer(tc.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) clusterID := leaderServer.GetClusterID() bootstrapCluster(re, clusterID, grpcPDClient) rc := leaderServer.GetRaftCluster() @@ -1135,7 +1135,7 @@ func TestStaleTermHeartbeat(t *testing.T) { re.NoError(err) tc.WaitLeader() leaderServer := tc.GetServer(tc.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) clusterID := leaderServer.GetClusterID() bootstrapCluster(re, clusterID, grpcPDClient) storeAddrs := []string{"127.0.1.1:0", "127.0.1.1:1", "127.0.1.1:2"} @@ -1255,7 +1255,7 @@ func TestMinResolvedTS(t *testing.T) { tc.WaitLeader() leaderServer := tc.GetServer(tc.GetLeader()) id := leaderServer.GetAllocator() - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) clusterID := leaderServer.GetClusterID() bootstrapCluster(re, clusterID, grpcPDClient) rc := leaderServer.GetRaftCluster() diff --git a/tests/server/cluster/cluster_work_test.go b/tests/server/cluster/cluster_work_test.go index 5dee7da02cd..6b41a3a92c8 100644 --- a/tests/server/cluster/cluster_work_test.go +++ b/tests/server/cluster/cluster_work_test.go @@ -41,7 +41,7 @@ func TestValidRequestRegion(t *testing.T) { cluster.WaitLeader() leaderServer := cluster.GetServer(cluster.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) clusterID := leaderServer.GetClusterID() bootstrapCluster(re, clusterID, grpcPDClient) rc := leaderServer.GetRaftCluster() @@ -85,7 +85,7 @@ func TestAskSplit(t *testing.T) { cluster.WaitLeader() leaderServer := cluster.GetServer(cluster.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) clusterID := leaderServer.GetClusterID() bootstrapCluster(re, clusterID, grpcPDClient) rc := leaderServer.GetRaftCluster() @@ -133,7 +133,7 @@ func TestSuspectRegions(t *testing.T) { cluster.WaitLeader() leaderServer := cluster.GetServer(cluster.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) clusterID := leaderServer.GetClusterID() bootstrapCluster(re, clusterID, grpcPDClient) rc := leaderServer.GetRaftCluster() diff --git a/tests/server/config/config_test.go b/tests/server/config/config_test.go index f375397a9f3..3f333c1722b 100644 --- a/tests/server/config/config_test.go +++ b/tests/server/config/config_test.go @@ -21,7 +21,7 @@ import ( "net/http" "testing" - . "github.com/pingcap/check" + "github.com/stretchr/testify/require" "github.com/tikv/pd/pkg/ratelimit" "github.com/tikv/pd/pkg/testutil" "github.com/tikv/pd/server" @@ -35,36 +35,18 @@ var dialClient = &http.Client{ }, } -func Test(t *testing.T) { - TestingT(t) -} - -var _ = Suite(&testConfigPresistSuite{}) - -type testConfigPresistSuite struct { - cleanup func() - cluster *tests.TestCluster -} - -func (s *testConfigPresistSuite) SetUpSuite(c *C) { +func TestRateLimitConfigReload(t *testing.T) { + re := require.New(t) ctx, cancel := context.WithCancel(context.Background()) - s.cleanup = cancel + defer cancel() cluster, err := tests.NewTestCluster(ctx, 3) - c.Assert(err, IsNil) - c.Assert(cluster.RunInitialServers(), IsNil) - c.Assert(cluster.WaitLeader(), Not(HasLen), 0) - s.cluster = cluster -} - -func (s *testConfigPresistSuite) TearDownSuite(c *C) { - s.cleanup() - s.cluster.Destroy() -} - -func (s *testConfigPresistSuite) TestRateLimitConfigReload(c *C) { - leader := s.cluster.GetServer(s.cluster.GetLeader()) + re.NoError(err) + defer cluster.Destroy() + re.NoError(cluster.RunInitialServers()) + re.NotEmpty(cluster.WaitLeader()) + leader := cluster.GetServer(cluster.GetLeader()) - c.Assert(leader.GetServer().GetServiceMiddlewareConfig().RateLimitConfig.LimiterConfig, HasLen, 0) + re.Len(leader.GetServer().GetServiceMiddlewareConfig().RateLimitConfig.LimiterConfig, 0) limitCfg := make(map[string]ratelimit.DimensionConfig) limitCfg["GetRegions"] = ratelimit.DimensionConfig{QPS: 1} @@ -73,29 +55,29 @@ func (s *testConfigPresistSuite) TestRateLimitConfigReload(c *C) { "limiter-config": limitCfg, } data, err := json.Marshal(input) - c.Assert(err, IsNil) + re.NoError(err) req, _ := http.NewRequest("POST", leader.GetAddr()+"/pd/api/v1/service-middleware/config", bytes.NewBuffer(data)) resp, err := dialClient.Do(req) - c.Assert(err, IsNil) + re.NoError(err) resp.Body.Close() - c.Assert(leader.GetServer().GetServiceMiddlewarePersistOptions().IsRateLimitEnabled(), Equals, true) - c.Assert(leader.GetServer().GetServiceMiddlewarePersistOptions().GetRateLimitConfig().LimiterConfig, HasLen, 1) + re.True(leader.GetServer().GetServiceMiddlewarePersistOptions().IsRateLimitEnabled()) + re.Len(leader.GetServer().GetServiceMiddlewarePersistOptions().GetRateLimitConfig().LimiterConfig, 1) oldLeaderName := leader.GetServer().Name() leader.GetServer().GetMember().ResignEtcdLeader(leader.GetServer().Context(), oldLeaderName, "") - mustWaitLeader(c, s.cluster.GetServers()) - leader = s.cluster.GetServer(s.cluster.GetLeader()) + mustWaitLeader(re, cluster.GetServers()) + leader = cluster.GetServer(cluster.GetLeader()) - c.Assert(leader.GetServer().GetServiceMiddlewarePersistOptions().IsRateLimitEnabled(), Equals, true) - c.Assert(leader.GetServer().GetServiceMiddlewarePersistOptions().GetRateLimitConfig().LimiterConfig, HasLen, 1) + re.True(leader.GetServer().GetServiceMiddlewarePersistOptions().IsRateLimitEnabled()) + re.Len(leader.GetServer().GetServiceMiddlewarePersistOptions().GetRateLimitConfig().LimiterConfig, 1) } -func mustWaitLeader(c *C, svrs map[string]*tests.TestServer) *server.Server { +func mustWaitLeader(re *require.Assertions, svrs map[string]*tests.TestServer) *server.Server { var leader *server.Server - testutil.WaitUntil(c, func() bool { - for _, s := range svrs { - if !s.GetServer().IsClosed() && s.GetServer().GetMember().IsLeader() { - leader = s.GetServer() + testutil.Eventually(re, func() bool { + for _, svr := range svrs { + if !svr.GetServer().IsClosed() && svr.GetServer().GetMember().IsLeader() { + leader = svr.GetServer() return true } } diff --git a/tests/server/id/id_test.go b/tests/server/id/id_test.go index d9279cd3616..3375cc55adb 100644 --- a/tests/server/id/id_test.go +++ b/tests/server/id/id_test.go @@ -93,7 +93,7 @@ func TestCommand(t *testing.T) { leaderServer := cluster.GetServer(cluster.GetLeader()) req := &pdpb.AllocIDRequest{Header: testutil.NewRequestHeader(leaderServer.GetClusterID())} - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) var last uint64 for i := uint64(0); i < 2*allocStep; i++ { resp, err := grpcPDClient.AllocID(context.Background(), req) diff --git a/tests/server/member/member_test.go b/tests/server/member/member_test.go index 1864500df74..552a2d0c221 100644 --- a/tests/server/member/member_test.go +++ b/tests/server/member/member_test.go @@ -348,7 +348,7 @@ func sendRequest(re *require.Assertions, wg *sync.WaitGroup, done <-chan bool, a default: // We don't need to check the response and error, // just make sure the server will not panic. - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, addr) + grpcPDClient := testutil.MustNewGrpcClient(re, addr) if grpcPDClient != nil { _, _ = grpcPDClient.AllocID(context.Background(), req) } diff --git a/tests/server/tso/consistency_test.go b/tests/server/tso/consistency_test.go index 430160cd5ac..6e1fe54c7c8 100644 --- a/tests/server/tso/consistency_test.go +++ b/tests/server/tso/consistency_test.go @@ -70,7 +70,7 @@ func (suite *tsoConsistencyTestSuite) TestNormalGlobalTSO() { cluster.WaitLeader() leaderServer := cluster.GetServer(cluster.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(suite.Require(), leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(suite.Require(), leaderServer.GetAddr()) clusterID := leaderServer.GetClusterID() req := &pdpb.TsoRequest{ Header: testutil.NewRequestHeader(clusterID), @@ -143,10 +143,10 @@ func (suite *tsoConsistencyTestSuite) TestSynchronizedGlobalTSO() { suite.leaderServer = cluster.GetServer(cluster.GetLeader()) suite.NotNil(suite.leaderServer) - suite.dcClientMap[tso.GlobalDCLocation] = testutil.MustNewGrpcClientWithTestify(re, suite.leaderServer.GetAddr()) + suite.dcClientMap[tso.GlobalDCLocation] = testutil.MustNewGrpcClient(re, suite.leaderServer.GetAddr()) for _, dcLocation := range dcLocationConfig { pdName := suite.leaderServer.GetAllocatorLeader(dcLocation).GetName() - suite.dcClientMap[dcLocation] = testutil.MustNewGrpcClientWithTestify(re, cluster.GetServer(pdName).GetAddr()) + suite.dcClientMap[dcLocation] = testutil.MustNewGrpcClient(re, cluster.GetServer(pdName).GetAddr()) } ctx, cancel := context.WithCancel(context.Background()) @@ -218,10 +218,10 @@ func (suite *tsoConsistencyTestSuite) TestSynchronizedGlobalTSOOverflow() { suite.leaderServer = cluster.GetServer(cluster.GetLeader()) suite.NotNil(suite.leaderServer) - suite.dcClientMap[tso.GlobalDCLocation] = testutil.MustNewGrpcClientWithTestify(re, suite.leaderServer.GetAddr()) + suite.dcClientMap[tso.GlobalDCLocation] = testutil.MustNewGrpcClient(re, suite.leaderServer.GetAddr()) for _, dcLocation := range dcLocationConfig { pdName := suite.leaderServer.GetAllocatorLeader(dcLocation).GetName() - suite.dcClientMap[dcLocation] = testutil.MustNewGrpcClientWithTestify(re, cluster.GetServer(pdName).GetAddr()) + suite.dcClientMap[dcLocation] = testutil.MustNewGrpcClient(re, cluster.GetServer(pdName).GetAddr()) } ctx, cancel := context.WithCancel(context.Background()) @@ -250,10 +250,10 @@ func (suite *tsoConsistencyTestSuite) TestLocalAllocatorLeaderChange() { suite.leaderServer = cluster.GetServer(cluster.GetLeader()) suite.NotNil(suite.leaderServer) - suite.dcClientMap[tso.GlobalDCLocation] = testutil.MustNewGrpcClientWithTestify(re, suite.leaderServer.GetAddr()) + suite.dcClientMap[tso.GlobalDCLocation] = testutil.MustNewGrpcClient(re, suite.leaderServer.GetAddr()) for _, dcLocation := range dcLocationConfig { pdName := suite.leaderServer.GetAllocatorLeader(dcLocation).GetName() - suite.dcClientMap[dcLocation] = testutil.MustNewGrpcClientWithTestify(re, cluster.GetServer(pdName).GetAddr()) + suite.dcClientMap[dcLocation] = testutil.MustNewGrpcClient(re, cluster.GetServer(pdName).GetAddr()) } ctx, cancel := context.WithCancel(context.Background()) @@ -311,7 +311,7 @@ func (suite *tsoConsistencyTestSuite) TestLocalTSOAfterMemberChanged() { cluster.WaitAllLeaders(re, dcLocationConfig) leaderServer := cluster.GetServer(cluster.GetLeader()) - leaderCli := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + leaderCli := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) req := &pdpb.TsoRequest{ Header: testutil.NewRequestHeader(cluster.GetCluster().GetId()), Count: tsoCount, @@ -352,7 +352,7 @@ func (suite *tsoConsistencyTestSuite) testTSO(cluster *tests.TestCluster, dcLoca dcClientMap := make(map[string]pdpb.PDClient) for _, dcLocation := range dcLocationConfig { pdName := leaderServer.GetAllocatorLeader(dcLocation).GetName() - dcClientMap[dcLocation] = testutil.MustNewGrpcClientWithTestify(re, cluster.GetServer(pdName).GetAddr()) + dcClientMap[dcLocation] = testutil.MustNewGrpcClient(re, cluster.GetServer(pdName).GetAddr()) } var wg sync.WaitGroup @@ -412,7 +412,7 @@ func TestFallbackTSOConsistency(t *testing.T) { cluster.WaitLeader() server := cluster.GetServer(cluster.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, server.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, server.GetAddr()) svr := server.GetServer() svr.Close() re.NoError(failpoint.Disable("github.com/tikv/pd/server/tso/fallBackSync")) diff --git a/tests/server/tso/global_tso_test.go b/tests/server/tso/global_tso_test.go index 795841b6830..d89b341d7c1 100644 --- a/tests/server/tso/global_tso_test.go +++ b/tests/server/tso/global_tso_test.go @@ -82,7 +82,7 @@ func TestZeroTSOCount(t *testing.T) { cluster.WaitLeader() leaderServer := cluster.GetServer(cluster.GetLeader()) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, leaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, leaderServer.GetAddr()) clusterID := leaderServer.GetClusterID() req := &pdpb.TsoRequest{ @@ -116,7 +116,7 @@ func TestRequestFollower(t *testing.T) { } re.NotNil(followerServer) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, followerServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, followerServer.GetAddr()) clusterID := followerServer.GetClusterID() req := &pdpb.TsoRequest{ Header: testutil.NewRequestHeader(clusterID), @@ -161,7 +161,7 @@ func TestDelaySyncTimestamp(t *testing.T) { } re.NotNil(nextLeaderServer) - grpcPDClient := testutil.MustNewGrpcClientWithTestify(re, nextLeaderServer.GetAddr()) + grpcPDClient := testutil.MustNewGrpcClient(re, nextLeaderServer.GetAddr()) clusterID := nextLeaderServer.GetClusterID() req := &pdpb.TsoRequest{ Header: testutil.NewRequestHeader(clusterID), diff --git a/tests/server/tso/tso_test.go b/tests/server/tso/tso_test.go index 8cb6b6d837f..1ac0a285940 100644 --- a/tests/server/tso/tso_test.go +++ b/tests/server/tso/tso_test.go @@ -78,7 +78,7 @@ func requestLocalTSOs(re *require.Assertions, cluster *tests.TestCluster, dcLoca leaderServer := cluster.GetServer(cluster.GetLeader()) for _, dcLocation := range dcLocationConfig { pdName := leaderServer.GetAllocatorLeader(dcLocation).GetName() - dcClientMap[dcLocation] = testutil.MustNewGrpcClientWithTestify(re, cluster.GetServer(pdName).GetAddr()) + dcClientMap[dcLocation] = testutil.MustNewGrpcClient(re, cluster.GetServer(pdName).GetAddr()) } for _, dcLocation := range dcLocationConfig { req := &pdpb.TsoRequest{