diff --git a/go.mod b/go.mod index 875eb6efe7c..5eeb2656499 100644 --- a/go.mod +++ b/go.mod @@ -38,6 +38,7 @@ require ( github.com/sasha-s/go-deadlock v0.2.0 github.com/spf13/cobra v1.0.0 github.com/spf13/pflag v1.0.5 + github.com/stretchr/testify v1.7.0 github.com/swaggo/http-swagger v0.0.0-20200308142732-58ac5e232fba github.com/swaggo/swag v1.6.6-0.20200529100950-7c765ddd0476 github.com/syndtr/goleveldb v1.0.1-0.20190318030020-c3a204f8e965 diff --git a/pkg/apiutil/apiutil_test.go b/pkg/apiutil/apiutil_test.go index ab418f3f5cf..94cf96c3f26 100644 --- a/pkg/apiutil/apiutil_test.go +++ b/pkg/apiutil/apiutil_test.go @@ -20,19 +20,11 @@ import ( "net/http/httptest" "testing" - . "github.com/pingcap/check" + "github.com/stretchr/testify/require" "github.com/unrolled/render" ) -func Test(t *testing.T) { - TestingT(t) -} - -var _ = Suite(&testUtilSuite{}) - -type testUtilSuite struct{} - -func (s *testUtilSuite) TestJsonRespondErrorOk(c *C) { +func TestJsonRespondErrorOk(t *testing.T) { rd := render.New(render.Options{ IndentJSON: true, }) @@ -41,15 +33,15 @@ func (s *testUtilSuite) TestJsonRespondErrorOk(c *C) { var input map[string]string output := map[string]string{"zone": "cn", "host": "local"} err := ReadJSONRespondError(rd, response, body, &input) - c.Assert(err, IsNil) - c.Assert(input["zone"], Equals, output["zone"]) - c.Assert(input["host"], Equals, output["host"]) + require.NoError(t, err) + require.Equal(t, output["zone"], input["zone"]) + require.Equal(t, output["host"], input["host"]) result := response.Result() defer result.Body.Close() - c.Assert(result.StatusCode, Equals, 200) + require.Equal(t, 200, result.StatusCode) } -func (s *testUtilSuite) TestJsonRespondErrorBadInput(c *C) { +func TestJsonRespondErrorBadInput(t *testing.T) { rd := render.New(render.Options{ IndentJSON: true, }) @@ -57,20 +49,18 @@ func (s *testUtilSuite) TestJsonRespondErrorBadInput(c *C) { body := io.NopCloser(bytes.NewBufferString("{\"zone\":\"cn\", \"host\":\"local\"}")) var input []string err := ReadJSONRespondError(rd, response, body, &input) - c.Assert(err, NotNil) - c.Assert(err.Error(), Equals, "json: cannot unmarshal object into Go value of type []string") + require.EqualError(t, err, "json: cannot unmarshal object into Go value of type []string") result := response.Result() defer result.Body.Close() - c.Assert(result.StatusCode, Equals, 400) + require.Equal(t, 400, result.StatusCode) { body := io.NopCloser(bytes.NewBufferString("{\"zone\":\"cn\",")) var input []string err := ReadJSONRespondError(rd, response, body, &input) - c.Assert(err, NotNil) - c.Assert(err.Error(), Equals, "unexpected end of JSON input") + require.EqualError(t, err, "unexpected end of JSON input") result := response.Result() defer result.Body.Close() - c.Assert(result.StatusCode, Equals, 400) + require.Equal(t, 400, result.StatusCode) } } diff --git a/pkg/audit/audit_test.go b/pkg/audit/audit_test.go index b5951231f3d..66df5298b8b 100644 --- a/pkg/audit/audit_test.go +++ b/pkg/audit/audit_test.go @@ -24,32 +24,22 @@ import ( "testing" "time" - . "github.com/pingcap/check" "github.com/pingcap/log" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/stretchr/testify/require" "github.com/tikv/pd/pkg/requestutil" ) -func Test(t *testing.T) { - TestingT(t) -} - -var _ = Suite(&testAuditSuite{}) - -type testAuditSuite struct { -} - -func (s *testAuditSuite) TestLabelMatcher(c *C) { +func TestLabelMatcher(t *testing.T) { matcher := &LabelMatcher{"testSuccess"} labels1 := &BackendLabels{Labels: []string{"testFail", "testSuccess"}} - c.Assert(matcher.Match(labels1), Equals, true) - + require.True(t, matcher.Match(labels1)) labels2 := &BackendLabels{Labels: []string{"testFail"}} - c.Assert(matcher.Match(labels2), Equals, false) + require.False(t, matcher.Match(labels2)) } -func (s *testAuditSuite) TestPrometheusHistogramBackend(c *C) { +func TestPrometheusHistogramBackend(t *testing.T) { serviceAuditHistogramTest := prometheus.NewHistogramVec( prometheus.HistogramOpts{ Namespace: "pd", @@ -70,44 +60,48 @@ func (s *testAuditSuite) TestPrometheusHistogramBackend(c *C) { info.ServiceLabel = "test" info.Component = "user1" req = req.WithContext(requestutil.WithRequestInfo(req.Context(), info)) - c.Assert(backend.ProcessHTTPRequest(req), Equals, false) + require.False(t, backend.ProcessHTTPRequest(req)) endTime := time.Now().Unix() + 20 req = req.WithContext(requestutil.WithEndTime(req.Context(), endTime)) - c.Assert(backend.ProcessHTTPRequest(req), Equals, true) - c.Assert(backend.ProcessHTTPRequest(req), Equals, true) + require.True(t, backend.ProcessHTTPRequest(req)) + require.True(t, backend.ProcessHTTPRequest(req)) info.Component = "user2" req = req.WithContext(requestutil.WithRequestInfo(req.Context(), info)) - c.Assert(backend.ProcessHTTPRequest(req), Equals, true) + require.True(t, backend.ProcessHTTPRequest(req)) // For test, sleep time needs longer than the push interval time.Sleep(1 * time.Second) req, _ = http.NewRequest("GET", ts.URL, nil) resp, err := http.DefaultClient.Do(req) - c.Assert(err, IsNil) + require.NoError(t, err) defer resp.Body.Close() content, _ := io.ReadAll(resp.Body) output := string(content) - c.Assert(strings.Contains(output, "pd_service_audit_handling_seconds_test_count{component=\"user1\",method=\"HTTP\",service=\"test\"} 2"), Equals, true) - c.Assert(strings.Contains(output, "pd_service_audit_handling_seconds_test_count{component=\"user2\",method=\"HTTP\",service=\"test\"} 1"), Equals, true) + require.Contains(t, output, "pd_service_audit_handling_seconds_test_count{component=\"user1\",method=\"HTTP\",service=\"test\"} 2") + require.Contains(t, output, "pd_service_audit_handling_seconds_test_count{component=\"user2\",method=\"HTTP\",service=\"test\"} 1") } -func (s *testAuditSuite) TestLocalLogBackendUsingFile(c *C) { +func TestLocalLogBackendUsingFile(t *testing.T) { backend := NewLocalLogBackend(true) fname := initLog() defer os.Remove(fname) req, _ := http.NewRequest("GET", "http://127.0.0.1:2379/test?test=test", strings.NewReader("testBody")) - c.Assert(backend.ProcessHTTPRequest(req), Equals, false) + require.False(t, backend.ProcessHTTPRequest(req)) info := requestutil.GetRequestInfo(req) req = req.WithContext(requestutil.WithRequestInfo(req.Context(), info)) - c.Assert(backend.ProcessHTTPRequest(req), Equals, true) + require.True(t, backend.ProcessHTTPRequest(req)) b, _ := os.ReadFile(fname) output := strings.SplitN(string(b), "]", 4) - c.Assert(output[3], Equals, fmt.Sprintf(" [\"Audit Log\"] [service-info=\"{ServiceLabel:, Method:HTTP/1.1/GET:/test, Component:anonymous, IP:, "+ - "StartTime:%s, URLParam:{\\\"test\\\":[\\\"test\\\"]}, BodyParam:testBody}\"]\n", - time.Unix(info.StartTimeStamp, 0).String())) + require.Equal( + t, + fmt.Sprintf(" [\"Audit Log\"] [service-info=\"{ServiceLabel:, Method:HTTP/1.1/GET:/test, Component:anonymous, IP:, "+ + "StartTime:%s, URLParam:{\\\"test\\\":[\\\"test\\\"]}, BodyParam:testBody}\"]\n", + time.Unix(info.StartTimeStamp, 0).String()), + output[3], + ) } func BenchmarkLocalLogAuditUsingTerminal(b *testing.B) { diff --git a/pkg/autoscaling/calculation_test.go b/pkg/autoscaling/calculation_test.go index 958b44926ef..8334c96ecc5 100644 --- a/pkg/autoscaling/calculation_test.go +++ b/pkg/autoscaling/calculation_test.go @@ -19,37 +19,21 @@ import ( "encoding/json" "fmt" "math" + "reflect" "testing" "time" - . "github.com/pingcap/check" + "github.com/stretchr/testify/require" "github.com/tikv/pd/pkg/mock/mockcluster" "github.com/tikv/pd/server/config" "github.com/tikv/pd/server/core" ) -func Test(t *testing.T) { - TestingT(t) -} - -var _ = Suite(&calculationTestSuite{}) - -type calculationTestSuite struct { - ctx context.Context - cancel context.CancelFunc -} - -func (s *calculationTestSuite) SetUpSuite(c *C) { - s.ctx, s.cancel = context.WithCancel(context.Background()) -} - -func (s *calculationTestSuite) TearDownTest(c *C) { - s.cancel() -} - -func (s *calculationTestSuite) TestGetScaledTiKVGroups(c *C) { +func TestGetScaledTiKVGroups(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() // case1 indicates the tikv cluster with not any group existed - case1 := mockcluster.NewCluster(s.ctx, config.NewTestOptions()) + case1 := mockcluster.NewCluster(ctx, config.NewTestOptions()) case1.AddLabelsStore(1, 1, map[string]string{}) case1.AddLabelsStore(2, 1, map[string]string{ "foo": "bar", @@ -59,7 +43,7 @@ func (s *calculationTestSuite) TestGetScaledTiKVGroups(c *C) { }) // case2 indicates the tikv cluster with 1 auto-scaling group existed - case2 := mockcluster.NewCluster(s.ctx, config.NewTestOptions()) + case2 := mockcluster.NewCluster(ctx, config.NewTestOptions()) case2.AddLabelsStore(1, 1, map[string]string{}) case2.AddLabelsStore(2, 1, map[string]string{ groupLabelKey: fmt.Sprintf("%s-%s-0", autoScalingGroupLabelKeyPrefix, TiKV.String()), @@ -71,7 +55,7 @@ func (s *calculationTestSuite) TestGetScaledTiKVGroups(c *C) { }) // case3 indicates the tikv cluster with other group existed - case3 := mockcluster.NewCluster(s.ctx, config.NewTestOptions()) + case3 := mockcluster.NewCluster(ctx, config.NewTestOptions()) case3.AddLabelsStore(1, 1, map[string]string{}) case3.AddLabelsStore(2, 1, map[string]string{ groupLabelKey: "foo", @@ -80,12 +64,12 @@ func (s *calculationTestSuite) TestGetScaledTiKVGroups(c *C) { groupLabelKey: "foo", }) - testcases := []struct { + testCases := []struct { name string informer core.StoreSetInformer healthyInstances []instance expectedPlan []*Plan - errChecker Checker + noError bool }{ { name: "no scaled tikv group", @@ -105,7 +89,7 @@ func (s *calculationTestSuite) TestGetScaledTiKVGroups(c *C) { }, }, expectedPlan: nil, - errChecker: IsNil, + noError: true, }, { name: "exist 1 scaled tikv group", @@ -135,7 +119,7 @@ func (s *calculationTestSuite) TestGetScaledTiKVGroups(c *C) { }, }, }, - errChecker: IsNil, + noError: true, }, { name: "exist 1 tikv scaled group with inconsistency healthy instances", @@ -155,7 +139,7 @@ func (s *calculationTestSuite) TestGetScaledTiKVGroups(c *C) { }, }, expectedPlan: nil, - errChecker: NotNil, + noError: false, }, { name: "exist 1 tikv scaled group with less healthy instances", @@ -181,7 +165,7 @@ func (s *calculationTestSuite) TestGetScaledTiKVGroups(c *C) { }, }, }, - errChecker: IsNil, + noError: true, }, { name: "existed other tikv group", @@ -201,18 +185,18 @@ func (s *calculationTestSuite) TestGetScaledTiKVGroups(c *C) { }, }, expectedPlan: nil, - errChecker: IsNil, + noError: true, }, } - for _, testcase := range testcases { - c.Log(testcase.name) - plans, err := getScaledTiKVGroups(testcase.informer, testcase.healthyInstances) - if testcase.expectedPlan == nil { - c.Assert(plans, HasLen, 0) - c.Assert(err, testcase.errChecker) + for _, testCase := range testCases { + t.Log(testCase.name) + plans, err := getScaledTiKVGroups(testCase.informer, testCase.healthyInstances) + if testCase.expectedPlan == nil { + require.Len(t, plans, 0) + require.Equal(t, testCase.noError, err == nil) } else { - c.Assert(plans, DeepEquals, testcase.expectedPlan) + require.True(t, reflect.DeepEqual(testCase.expectedPlan, plans)) } } } @@ -228,7 +212,7 @@ func (q *mockQuerier) Query(options *QueryOptions) (QueryResult, error) { return result, nil } -func (s *calculationTestSuite) TestGetTotalCPUUseTime(c *C) { +func TestGetTotalCPUUseTime(t *testing.T) { querier := &mockQuerier{} instances := []instance{ { @@ -246,10 +230,10 @@ func (s *calculationTestSuite) TestGetTotalCPUUseTime(c *C) { } totalCPUUseTime, _ := getTotalCPUUseTime(querier, TiDB, instances, time.Now(), 0) expected := mockResultValue * float64(len(instances)) - c.Assert(math.Abs(expected-totalCPUUseTime) < 1e-6, IsTrue) + require.True(t, math.Abs(expected-totalCPUUseTime) < 1e-6) } -func (s *calculationTestSuite) TestGetTotalCPUQuota(c *C) { +func TestGetTotalCPUQuota(t *testing.T) { querier := &mockQuerier{} instances := []instance{ { @@ -267,10 +251,10 @@ func (s *calculationTestSuite) TestGetTotalCPUQuota(c *C) { } totalCPUQuota, _ := getTotalCPUQuota(querier, TiDB, instances, time.Now()) expected := uint64(mockResultValue * float64(len(instances)*milliCores)) - c.Assert(totalCPUQuota, Equals, expected) + require.Equal(t, expected, totalCPUQuota) } -func (s *calculationTestSuite) TestScaleOutGroupLabel(c *C) { +func TestScaleOutGroupLabel(t *testing.T) { var jsonStr = []byte(` { "rules":[ @@ -304,14 +288,14 @@ func (s *calculationTestSuite) TestScaleOutGroupLabel(c *C) { }`) strategy := &Strategy{} err := json.Unmarshal(jsonStr, strategy) - c.Assert(err, IsNil) + require.NoError(t, err) plan := findBestGroupToScaleOut(strategy, nil, TiKV) - c.Assert(plan.Labels["specialUse"], Equals, "hotRegion") + require.Equal(t, "hotRegion", plan.Labels["specialUse"]) plan = findBestGroupToScaleOut(strategy, nil, TiDB) - c.Assert(plan.Labels["specialUse"], Equals, "") + require.Equal(t, "", plan.Labels["specialUse"]) } -func (s *calculationTestSuite) TestStrategyChangeCount(c *C) { +func TestStrategyChangeCount(t *testing.T) { var count uint64 = 2 strategy := &Strategy{ Rules: []*Rule{ @@ -336,7 +320,9 @@ func (s *calculationTestSuite) TestStrategyChangeCount(c *C) { } // tikv cluster with 1 auto-scaling group existed - cluster := mockcluster.NewCluster(s.ctx, config.NewTestOptions()) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + cluster := mockcluster.NewCluster(ctx, config.NewTestOptions()) cluster.AddLabelsStore(1, 1, map[string]string{}) cluster.AddLabelsStore(2, 1, map[string]string{ groupLabelKey: fmt.Sprintf("%s-%s-0", autoScalingGroupLabelKeyPrefix, TiKV.String()), @@ -357,21 +343,21 @@ func (s *calculationTestSuite) TestStrategyChangeCount(c *C) { // exist two scaled TiKVs and plan does not change due to the limit of resource count groups, err := getScaledTiKVGroups(cluster, instances) - c.Assert(err, IsNil) + require.NoError(t, err) plans := calculateScaleOutPlan(strategy, TiKV, scaleOutQuota, groups) - c.Assert(plans[0].Count, Equals, uint64(2)) + require.Equal(t, uint64(2), plans[0].Count) // change the resource count to 3 and plan increates one more tikv groups, err = getScaledTiKVGroups(cluster, instances) - c.Assert(err, IsNil) + require.NoError(t, err) *strategy.Resources[0].Count = 3 plans = calculateScaleOutPlan(strategy, TiKV, scaleOutQuota, groups) - c.Assert(plans[0].Count, Equals, uint64(3)) + require.Equal(t, uint64(3), plans[0].Count) // change the resource count to 1 and plan decreases to 1 tikv due to the limit of resource count groups, err = getScaledTiKVGroups(cluster, instances) - c.Assert(err, IsNil) + require.NoError(t, err) *strategy.Resources[0].Count = 1 plans = calculateScaleOutPlan(strategy, TiKV, scaleOutQuota, groups) - c.Assert(plans[0].Count, Equals, uint64(1)) + require.Equal(t, uint64(1), plans[0].Count) } diff --git a/pkg/autoscaling/prometheus_test.go b/pkg/autoscaling/prometheus_test.go index 284d780e297..2c541446d2b 100644 --- a/pkg/autoscaling/prometheus_test.go +++ b/pkg/autoscaling/prometheus_test.go @@ -24,10 +24,11 @@ import ( "net/http" "net/url" "strings" + "testing" "time" - . "github.com/pingcap/check" promClient "github.com/prometheus/client_golang/api" + "github.com/stretchr/testify/require" ) const ( @@ -41,8 +42,6 @@ const ( instanceCount = 3 ) -var _ = Suite(&testPrometheusQuerierSuite{}) - var podNameTemplate = map[ComponentType]string{ TiDB: mockTiDBInstanceNamePattern, TiKV: mockTiKVInstanceNamePattern, @@ -76,8 +75,6 @@ var podAddresses = map[ComponentType][]string{ TiKV: generateAddresses(TiKV), } -type testPrometheusQuerierSuite struct{} - // For building mock data only type response struct { Status string `json:"status"` @@ -183,7 +180,7 @@ func (c *normalClient) Do(_ context.Context, req *http.Request) (response *http. return } -func (s *testPrometheusQuerierSuite) TestRetrieveCPUMetrics(c *C) { +func TestRetrieveCPUMetrics(t *testing.T) { client := &normalClient{ mockData: make(map[string]*response), } @@ -194,15 +191,15 @@ func (s *testPrometheusQuerierSuite) TestRetrieveCPUMetrics(c *C) { for _, metric := range metrics { options := NewQueryOptions(component, metric, addresses[:len(addresses)-1], time.Now(), mockDuration) result, err := querier.Query(options) - c.Assert(err, IsNil) + require.NoError(t, err) for i := 0; i < len(addresses)-1; i++ { value, ok := result[addresses[i]] - c.Assert(ok, IsTrue) - c.Assert(math.Abs(value-mockResultValue) < 1e-6, IsTrue) + require.True(t, ok) + require.True(t, math.Abs(value-mockResultValue) < 1e-6) } _, ok := result[addresses[len(addresses)-1]] - c.Assert(ok, IsFalse) + require.False(t, ok) } } } @@ -226,13 +223,13 @@ func (c *emptyResponseClient) Do(_ context.Context, req *http.Request) (r *http. return } -func (s *testPrometheusQuerierSuite) TestEmptyResponse(c *C) { +func TestEmptyResponse(t *testing.T) { client := &emptyResponseClient{} querier := NewPrometheusQuerier(client) options := NewQueryOptions(TiDB, CPUUsage, podAddresses[TiDB], time.Now(), mockDuration) result, err := querier.Query(options) - c.Assert(result, IsNil) - c.Assert(err, NotNil) + require.Nil(t, result) + require.Error(t, err) } type errorHTTPStatusClient struct{} @@ -252,13 +249,13 @@ func (c *errorHTTPStatusClient) Do(_ context.Context, req *http.Request) (r *htt return } -func (s *testPrometheusQuerierSuite) TestErrorHTTPStatus(c *C) { +func TestErrorHTTPStatus(t *testing.T) { client := &errorHTTPStatusClient{} querier := NewPrometheusQuerier(client) options := NewQueryOptions(TiDB, CPUUsage, podAddresses[TiDB], time.Now(), mockDuration) result, err := querier.Query(options) - c.Assert(result, IsNil) - c.Assert(err, NotNil) + require.Nil(t, result) + require.Error(t, err) } type errorPrometheusStatusClient struct{} @@ -276,17 +273,17 @@ func (c *errorPrometheusStatusClient) Do(_ context.Context, req *http.Request) ( return } -func (s *testPrometheusQuerierSuite) TestErrorPrometheusStatus(c *C) { +func TestErrorPrometheusStatus(t *testing.T) { client := &errorPrometheusStatusClient{} querier := NewPrometheusQuerier(client) options := NewQueryOptions(TiDB, CPUUsage, podAddresses[TiDB], time.Now(), mockDuration) result, err := querier.Query(options) - c.Assert(result, IsNil) - c.Assert(err, NotNil) + require.Nil(t, result) + require.Error(t, err) } -func (s *testPrometheusQuerierSuite) TestGetInstanceNameFromAddress(c *C) { - testcases := []struct { +func TestGetInstanceNameFromAddress(t *testing.T) { + testCases := []struct { address string expectedInstanceName string }{ @@ -311,18 +308,18 @@ func (s *testPrometheusQuerierSuite) TestGetInstanceNameFromAddress(c *C) { expectedInstanceName: "", }, } - for _, testcase := range testcases { - instanceName, err := getInstanceNameFromAddress(testcase.address) - if testcase.expectedInstanceName == "" { - c.Assert(err, NotNil) + for _, testCase := range testCases { + instanceName, err := getInstanceNameFromAddress(testCase.address) + if testCase.expectedInstanceName == "" { + require.Error(t, err) } else { - c.Assert(instanceName, Equals, testcase.expectedInstanceName) + require.Equal(t, testCase.expectedInstanceName, instanceName) } } } -func (s *testPrometheusQuerierSuite) TestGetDurationExpression(c *C) { - testcases := []struct { +func TestGetDurationExpression(t *testing.T) { + testCases := []struct { duration time.Duration expectedExpression string }{ @@ -344,8 +341,8 @@ func (s *testPrometheusQuerierSuite) TestGetDurationExpression(c *C) { }, } - for _, testcase := range testcases { - expression := getDurationExpression(testcase.duration) - c.Assert(expression, Equals, testcase.expectedExpression) + for _, testCase := range testCases { + expression := getDurationExpression(testCase.duration) + require.Equal(t, testCase.expectedExpression, expression) } } diff --git a/pkg/cache/cache_test.go b/pkg/cache/cache_test.go index df508e39cd1..bd633fef525 100644 --- a/pkg/cache/cache_test.go +++ b/pkg/cache/cache_test.go @@ -16,53 +16,45 @@ package cache import ( "context" + "reflect" "sort" "testing" "time" - . "github.com/pingcap/check" + "github.com/stretchr/testify/require" ) -func TestCore(t *testing.T) { - TestingT(t) -} - -var _ = Suite(&testRegionCacheSuite{}) - -type testRegionCacheSuite struct { -} - -func (s *testRegionCacheSuite) TestExpireRegionCache(c *C) { +func TestExpireRegionCache(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() cache := NewIDTTL(ctx, time.Second, 2*time.Second) // Test Pop cache.PutWithTTL(9, "9", 5*time.Second) cache.PutWithTTL(10, "10", 5*time.Second) - c.Assert(cache.Len(), Equals, 2) + require.Equal(t, 2, cache.Len()) k, v, success := cache.pop() - c.Assert(success, IsTrue) - c.Assert(cache.Len(), Equals, 1) + require.True(t, success) + require.Equal(t, 1, cache.Len()) k2, v2, success := cache.pop() - c.Assert(success, IsTrue) + require.True(t, success) // we can't ensure the order which the key/value pop from cache, so we save into a map kvMap := map[uint64]string{ 9: "9", 10: "10", } expV, ok := kvMap[k.(uint64)] - c.Assert(ok, IsTrue) - c.Assert(expV, Equals, v.(string)) + require.True(t, ok) + require.Equal(t, expV, v.(string)) expV, ok = kvMap[k2.(uint64)] - c.Assert(ok, IsTrue) - c.Assert(expV, Equals, v2.(string)) + require.True(t, ok) + require.Equal(t, expV, v2.(string)) cache.PutWithTTL(11, "11", 1*time.Second) time.Sleep(5 * time.Second) k, v, success = cache.pop() - c.Assert(success, IsFalse) - c.Assert(k, IsNil) - c.Assert(v, IsNil) + require.False(t, success) + require.Nil(t, k) + require.Nil(t, v) // Test Get cache.PutWithTTL(1, 1, 1*time.Second) @@ -70,50 +62,50 @@ func (s *testRegionCacheSuite) TestExpireRegionCache(c *C) { cache.PutWithTTL(3, 3.0, 5*time.Second) value, ok := cache.Get(1) - c.Assert(ok, IsTrue) - c.Assert(value, Equals, 1) + require.True(t, ok) + require.Equal(t, 1, value) value, ok = cache.Get(2) - c.Assert(ok, IsTrue) - c.Assert(value, Equals, "v2") + require.True(t, ok) + require.Equal(t, "v2", value) value, ok = cache.Get(3) - c.Assert(ok, IsTrue) - c.Assert(value, Equals, 3.0) + require.True(t, ok) + require.Equal(t, 3.0, value) - c.Assert(cache.Len(), Equals, 3) + require.Equal(t, 3, cache.Len()) - c.Assert(sortIDs(cache.GetAllID()), DeepEquals, []uint64{1, 2, 3}) + require.True(t, reflect.DeepEqual(sortIDs(cache.GetAllID()), []uint64{1, 2, 3})) time.Sleep(2 * time.Second) value, ok = cache.Get(1) - c.Assert(ok, IsFalse) - c.Assert(value, IsNil) + require.False(t, ok) + require.Nil(t, value) value, ok = cache.Get(2) - c.Assert(ok, IsTrue) - c.Assert(value, Equals, "v2") + require.True(t, ok) + require.Equal(t, "v2", value) value, ok = cache.Get(3) - c.Assert(ok, IsTrue) - c.Assert(value, Equals, 3.0) + require.True(t, ok) + require.Equal(t, 3.0, value) - c.Assert(cache.Len(), Equals, 2) - c.Assert(sortIDs(cache.GetAllID()), DeepEquals, []uint64{2, 3}) + require.Equal(t, 2, cache.Len()) + require.True(t, reflect.DeepEqual(sortIDs(cache.GetAllID()), []uint64{2, 3})) cache.Remove(2) value, ok = cache.Get(2) - c.Assert(ok, IsFalse) - c.Assert(value, IsNil) + require.False(t, ok) + require.Nil(t, value) value, ok = cache.Get(3) - c.Assert(ok, IsTrue) - c.Assert(value, Equals, 3.0) + require.True(t, ok) + require.Equal(t, 3.0, value) - c.Assert(cache.Len(), Equals, 1) - c.Assert(sortIDs(cache.GetAllID()), DeepEquals, []uint64{3}) + require.Equal(t, 1, cache.Len()) + require.True(t, reflect.DeepEqual(sortIDs(cache.GetAllID()), []uint64{3})) } func sortIDs(ids []uint64) []uint64 { @@ -122,7 +114,7 @@ func sortIDs(ids []uint64) []uint64 { return ids } -func (s *testRegionCacheSuite) TestLRUCache(c *C) { +func TestLRUCache(t *testing.T) { cache := newLRU(3) cache.Put(1, "1") @@ -130,173 +122,173 @@ func (s *testRegionCacheSuite) TestLRUCache(c *C) { cache.Put(3, "3") val, ok := cache.Get(3) - c.Assert(ok, IsTrue) - c.Assert(val, DeepEquals, "3") + require.True(t, ok) + require.True(t, reflect.DeepEqual(val, "3")) val, ok = cache.Get(2) - c.Assert(ok, IsTrue) - c.Assert(val, DeepEquals, "2") + require.True(t, ok) + require.True(t, reflect.DeepEqual(val, "2")) val, ok = cache.Get(1) - c.Assert(ok, IsTrue) - c.Assert(val, DeepEquals, "1") + require.True(t, ok) + require.True(t, reflect.DeepEqual(val, "1")) - c.Assert(cache.Len(), Equals, 3) + require.Equal(t, 3, cache.Len()) cache.Put(4, "4") - c.Assert(cache.Len(), Equals, 3) + require.Equal(t, 3, cache.Len()) val, ok = cache.Get(3) - c.Assert(ok, IsFalse) - c.Assert(val, IsNil) + require.False(t, ok) + require.Nil(t, val) val, ok = cache.Get(1) - c.Assert(ok, IsTrue) - c.Assert(val, DeepEquals, "1") + require.True(t, ok) + require.True(t, reflect.DeepEqual(val, "1")) val, ok = cache.Get(2) - c.Assert(ok, IsTrue) - c.Assert(val, DeepEquals, "2") + require.True(t, ok) + require.True(t, reflect.DeepEqual(val, "2")) val, ok = cache.Get(4) - c.Assert(ok, IsTrue) - c.Assert(val, DeepEquals, "4") + require.True(t, ok) + require.True(t, reflect.DeepEqual(val, "4")) - c.Assert(cache.Len(), Equals, 3) + require.Equal(t, 3, cache.Len()) val, ok = cache.Peek(1) - c.Assert(ok, IsTrue) - c.Assert(val, DeepEquals, "1") + require.True(t, ok) + require.True(t, reflect.DeepEqual(val, "1")) elems := cache.Elems() - c.Assert(elems, HasLen, 3) - c.Assert(elems[0].Value, DeepEquals, "4") - c.Assert(elems[1].Value, DeepEquals, "2") - c.Assert(elems[2].Value, DeepEquals, "1") + require.Len(t, elems, 3) + require.True(t, reflect.DeepEqual(elems[0].Value, "4")) + require.True(t, reflect.DeepEqual(elems[1].Value, "2")) + require.True(t, reflect.DeepEqual(elems[2].Value, "1")) cache.Remove(1) cache.Remove(2) cache.Remove(4) - c.Assert(cache.Len(), Equals, 0) + require.Equal(t, 0, cache.Len()) val, ok = cache.Get(1) - c.Assert(ok, IsFalse) - c.Assert(val, IsNil) + require.False(t, ok) + require.Nil(t, val) val, ok = cache.Get(2) - c.Assert(ok, IsFalse) - c.Assert(val, IsNil) + require.False(t, ok) + require.Nil(t, val) val, ok = cache.Get(3) - c.Assert(ok, IsFalse) - c.Assert(val, IsNil) + require.False(t, ok) + require.Nil(t, val) val, ok = cache.Get(4) - c.Assert(ok, IsFalse) - c.Assert(val, IsNil) + require.False(t, ok) + require.Nil(t, val) } -func (s *testRegionCacheSuite) TestFifoCache(c *C) { +func TestFifoCache(t *testing.T) { cache := NewFIFO(3) cache.Put(1, "1") cache.Put(2, "2") cache.Put(3, "3") - c.Assert(cache.Len(), Equals, 3) + require.Equal(t, 3, cache.Len()) cache.Put(4, "4") - c.Assert(cache.Len(), Equals, 3) + require.Equal(t, 3, cache.Len()) elems := cache.Elems() - c.Assert(elems, HasLen, 3) - c.Assert(elems[0].Value, DeepEquals, "2") - c.Assert(elems[1].Value, DeepEquals, "3") - c.Assert(elems[2].Value, DeepEquals, "4") + require.Len(t, elems, 3) + require.True(t, reflect.DeepEqual(elems[0].Value, "2")) + require.True(t, reflect.DeepEqual(elems[1].Value, "3")) + require.True(t, reflect.DeepEqual(elems[2].Value, "4")) elems = cache.FromElems(3) - c.Assert(elems, HasLen, 1) - c.Assert(elems[0].Value, DeepEquals, "4") + require.Len(t, elems, 1) + require.True(t, reflect.DeepEqual(elems[0].Value, "4")) cache.Remove() cache.Remove() cache.Remove() - c.Assert(cache.Len(), Equals, 0) + require.Equal(t, 0, cache.Len()) } -func (s *testRegionCacheSuite) TestTwoQueueCache(c *C) { +func TestTwoQueueCache(t *testing.T) { cache := newTwoQueue(3) cache.Put(1, "1") cache.Put(2, "2") cache.Put(3, "3") val, ok := cache.Get(3) - c.Assert(ok, IsTrue) - c.Assert(val, DeepEquals, "3") + require.True(t, ok) + require.True(t, reflect.DeepEqual(val, "3")) val, ok = cache.Get(2) - c.Assert(ok, IsTrue) - c.Assert(val, DeepEquals, "2") + require.True(t, ok) + require.True(t, reflect.DeepEqual(val, "2")) val, ok = cache.Get(1) - c.Assert(ok, IsTrue) - c.Assert(val, DeepEquals, "1") + require.True(t, ok) + require.True(t, reflect.DeepEqual(val, "1")) - c.Assert(cache.Len(), Equals, 3) + require.Equal(t, 3, cache.Len()) cache.Put(4, "4") - c.Assert(cache.Len(), Equals, 3) + require.Equal(t, 3, cache.Len()) val, ok = cache.Get(3) - c.Assert(ok, IsFalse) - c.Assert(val, IsNil) + require.False(t, ok) + require.Nil(t, val) val, ok = cache.Get(1) - c.Assert(ok, IsTrue) - c.Assert(val, DeepEquals, "1") + require.True(t, ok) + require.True(t, reflect.DeepEqual(val, "1")) val, ok = cache.Get(2) - c.Assert(ok, IsTrue) - c.Assert(val, DeepEquals, "2") + require.True(t, ok) + require.True(t, reflect.DeepEqual(val, "2")) val, ok = cache.Get(4) - c.Assert(ok, IsTrue) - c.Assert(val, DeepEquals, "4") + require.True(t, ok) + require.True(t, reflect.DeepEqual(val, "4")) - c.Assert(cache.Len(), Equals, 3) + require.Equal(t, 3, cache.Len()) val, ok = cache.Peek(1) - c.Assert(ok, IsTrue) - c.Assert(val, DeepEquals, "1") + require.True(t, ok) + require.True(t, reflect.DeepEqual(val, "1")) elems := cache.Elems() - c.Assert(elems, HasLen, 3) - c.Assert(elems[0].Value, DeepEquals, "4") - c.Assert(elems[1].Value, DeepEquals, "2") - c.Assert(elems[2].Value, DeepEquals, "1") + require.Len(t, elems, 3) + require.True(t, reflect.DeepEqual(elems[0].Value, "4")) + require.True(t, reflect.DeepEqual(elems[1].Value, "2")) + require.True(t, reflect.DeepEqual(elems[2].Value, "1")) cache.Remove(1) cache.Remove(2) cache.Remove(4) - c.Assert(cache.Len(), Equals, 0) + require.Equal(t, 0, cache.Len()) val, ok = cache.Get(1) - c.Assert(ok, IsFalse) - c.Assert(val, IsNil) + require.False(t, ok) + require.Nil(t, val) val, ok = cache.Get(2) - c.Assert(ok, IsFalse) - c.Assert(val, IsNil) + require.False(t, ok) + require.Nil(t, val) val, ok = cache.Get(3) - c.Assert(ok, IsFalse) - c.Assert(val, IsNil) + require.False(t, ok) + require.Nil(t, val) val, ok = cache.Get(4) - c.Assert(ok, IsFalse) - c.Assert(val, IsNil) + require.False(t, ok) + require.Nil(t, val) } var _ PriorityQueueItem = PriorityQueueItemTest(0) @@ -307,54 +299,54 @@ func (pq PriorityQueueItemTest) ID() uint64 { return uint64(pq) } -func (s *testRegionCacheSuite) TestPriorityQueue(c *C) { +func TestPriorityQueue(t *testing.T) { testData := []PriorityQueueItemTest{0, 1, 2, 3, 4, 5} pq := NewPriorityQueue(0) - c.Assert(pq.Put(1, testData[1]), IsFalse) + require.False(t, pq.Put(1, testData[1])) // it will have priority-value pair as 1-1 2-2 3-3 pq = NewPriorityQueue(3) - c.Assert(pq.Put(1, testData[1]), IsTrue) - c.Assert(pq.Put(2, testData[2]), IsTrue) - c.Assert(pq.Put(3, testData[4]), IsTrue) - c.Assert(pq.Put(5, testData[4]), IsTrue) - c.Assert(pq.Put(5, testData[5]), IsFalse) - c.Assert(pq.Put(3, testData[3]), IsTrue) - c.Assert(pq.Put(3, testData[3]), IsTrue) - c.Assert(pq.Get(4), IsNil) - c.Assert(pq.Len(), Equals, 3) + require.True(t, pq.Put(1, testData[1])) + require.True(t, pq.Put(2, testData[2])) + require.True(t, pq.Put(3, testData[4])) + require.True(t, pq.Put(5, testData[4])) + require.False(t, pq.Put(5, testData[5])) + require.True(t, pq.Put(3, testData[3])) + require.True(t, pq.Put(3, testData[3])) + require.Nil(t, pq.Get(4)) + require.Equal(t, 3, pq.Len()) // case1 test getAll, the highest element should be the first entries := pq.Elems() - c.Assert(entries, HasLen, 3) - c.Assert(entries[0].Priority, Equals, 1) - c.Assert(entries[0].Value, Equals, testData[1]) - c.Assert(entries[1].Priority, Equals, 2) - c.Assert(entries[1].Value, Equals, testData[2]) - c.Assert(entries[2].Priority, Equals, 3) - c.Assert(entries[2].Value, Equals, testData[3]) + require.Len(t, entries, 3) + require.Equal(t, 1, entries[0].Priority) + require.Equal(t, testData[1], entries[0].Value) + require.Equal(t, 2, entries[1].Priority) + require.Equal(t, testData[2], entries[1].Value) + require.Equal(t, 3, entries[2].Priority) + require.Equal(t, testData[3], entries[2].Value) // case2 test remove the high element, and the second element should be the first pq.Remove(uint64(1)) - c.Assert(pq.Get(1), IsNil) - c.Assert(pq.Len(), Equals, 2) + require.Nil(t, pq.Get(1)) + require.Equal(t, 2, pq.Len()) entry := pq.Peek() - c.Assert(entry.Priority, Equals, 2) - c.Assert(entry.Value, Equals, testData[2]) + require.Equal(t, 2, entry.Priority) + require.Equal(t, testData[2], entry.Value) // case3 update 3's priority to highest pq.Put(-1, testData[3]) entry = pq.Peek() - c.Assert(entry.Priority, Equals, -1) - c.Assert(entry.Value, Equals, testData[3]) + require.Equal(t, -1, entry.Priority) + require.Equal(t, testData[3], entry.Value) pq.Remove(entry.Value.ID()) - c.Assert(pq.Peek().Value, Equals, testData[2]) - c.Assert(pq.Len(), Equals, 1) + require.Equal(t, testData[2], pq.Peek().Value) + require.Equal(t, 1, pq.Len()) // case4 remove all element pq.Remove(uint64(2)) - c.Assert(pq.Len(), Equals, 0) - c.Assert(pq.items, HasLen, 0) - c.Assert(pq.Peek(), IsNil) - c.Assert(pq.Tail(), IsNil) + require.Equal(t, 0, pq.Len()) + require.Len(t, pq.items, 0) + require.Nil(t, pq.Peek()) + require.Nil(t, pq.Tail()) }