From 5fafe10f8bc77fd1782f342fe37fc84c7aef67b6 Mon Sep 17 00:00:00 2001 From: tison Date: Thu, 23 Sep 2021 22:28:35 +0800 Subject: [PATCH 1/5] seqtest: migrate test-infra testify; issue-28076 Signed-off-by: tison --- executor/seqtest/main_test.go | 37 ++ ...epared_test.go => prepared_serial_test.go} | 497 +++++++++------- ...or_test.go => seq_executor_serial_test.go} | 559 +++++++++--------- testkit/testkit.go | 20 +- util/testkit/testkit.go | 1 + 5 files changed, 603 insertions(+), 511 deletions(-) create mode 100644 executor/seqtest/main_test.go rename executor/seqtest/{prepared_test.go => prepared_serial_test.go} (65%) rename executor/seqtest/{seq_executor_test.go => seq_executor_serial_test.go} (80%) diff --git a/executor/seqtest/main_test.go b/executor/seqtest/main_test.go new file mode 100644 index 0000000000000..0a85b8ca61055 --- /dev/null +++ b/executor/seqtest/main_test.go @@ -0,0 +1,37 @@ +// Copyright 2021 PingCAP, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package executor + +import ( + "testing" + + "github.com/pingcap/tidb/util/testbridge" + "github.com/tikv/client-go/v2/config" + "go.uber.org/goleak" +) + +func TestMain(m *testing.M) { + testbridge.WorkaroundGoCheckFlags() + config.UpdateGlobal(func(conf *config.Config) { + conf.TiKVClient.AsyncCommit.SafeWindow = 0 + conf.TiKVClient.AsyncCommit.AllowedClockDrift = 0 + }) + opts := []goleak.Option{ + goleak.IgnoreTopFunction("github.com/pingcap/tidb/executor.readProjectionInput"), + goleak.IgnoreTopFunction("go.etcd.io/etcd/pkg/logutil.(*MergeLogger).outputLoop"), + goleak.IgnoreTopFunction("go.opencensus.io/stats/view.(*worker).start"), + } + goleak.VerifyTestMain(m, opts...) +} diff --git a/executor/seqtest/prepared_test.go b/executor/seqtest/prepared_serial_test.go similarity index 65% rename from executor/seqtest/prepared_test.go rename to executor/seqtest/prepared_serial_test.go index 879325267f2b2..fca8e91300f72 100644 --- a/executor/seqtest/prepared_test.go +++ b/executor/seqtest/prepared_serial_test.go @@ -17,10 +17,11 @@ package executor_test import ( "context" "crypto/tls" + "fmt" "math" + "testing" "time" - . "github.com/pingcap/check" "github.com/pingcap/parser/mysql" "github.com/pingcap/tidb/executor" "github.com/pingcap/tidb/infoschema" @@ -28,14 +29,18 @@ import ( plannercore "github.com/pingcap/tidb/planner/core" "github.com/pingcap/tidb/session" "github.com/pingcap/tidb/session/txninfo" + "github.com/pingcap/tidb/testkit" "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util" "github.com/pingcap/tidb/util/kvcache" - "github.com/pingcap/tidb/util/testkit" dto "github.com/prometheus/client_model/go" + "github.com/stretchr/testify/require" ) -func (s *seqTestSuite) TestPrepared(c *C) { +func TestPrepared(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + orgEnable := plannercore.PreparedPlanCacheEnabled() defer func() { plannercore.SetPreparedPlanCache(orgEnable) @@ -44,14 +49,14 @@ func (s *seqTestSuite) TestPrepared(c *C) { flags := []bool{false, true} ctx := context.Background() for _, flag := range flags { - var err error plannercore.SetPreparedPlanCache(flag) - tk := testkit.NewTestKit(c, s.store) - tk.Se, err = session.CreateSession4TestWithOpt(s.store, &session.Opt{ + tk := testkit.NewTestKit(t, store) + se, err := session.CreateSession4TestWithOpt(store, &session.Opt{ PreparedPlanCache: kvcache.NewSimpleLRUCache(100, 0.1, math.MaxUint64), }) - c.Assert(err, IsNil) + require.NoError(t, err) + tk.SetSession(se) tk.MustExec("use test") tk.MustExec("drop table if exists prepare_test") @@ -64,28 +69,28 @@ func (s *seqTestSuite) TestPrepared(c *C) { tk.MustExec(`prepare stmt_test_2 from 'select 1'`) // Prepare multiple statement is not allowed. _, err = tk.Exec(`prepare stmt_test_3 from 'select id from prepare_test where id > ?;select id from prepare_test where id > ?;'`) - c.Assert(executor.ErrPrepareMulti.Equal(err), IsTrue) + require.True(t, executor.ErrPrepareMulti.Equal(err)) // The variable count does not match. tk.MustExec(`prepare stmt_test_4 from 'select id from prepare_test where id > ? and id < ?';`) tk.MustExec(`set @a = 1;`) _, err = tk.Exec(`execute stmt_test_4 using @a;`) - c.Assert(plannercore.ErrWrongParamCount.Equal(err), IsTrue) + require.True(t, plannercore.ErrWrongParamCount.Equal(err)) // Prepare and deallocate prepared statement immediately. tk.MustExec(`prepare stmt_test_5 from 'select id from prepare_test where id > ?';`) tk.MustExec(`deallocate prepare stmt_test_5;`) // Statement not found. _, err = tk.Exec("deallocate prepare stmt_test_5") - c.Assert(plannercore.ErrStmtNotFound.Equal(err), IsTrue) + require.True(t, plannercore.ErrStmtNotFound.Equal(err)) // incorrect SQLs in prepare. issue #3738, SQL in prepare stmt is parsed in DoPrepare. _, err = tk.Exec(`prepare p from "delete from t where a = 7 or 1=1/*' and b = 'p'";`) - c.Assert(err.Error(), Equals, `[parser:1064]You have an error in your SQL syntax; check the manual that corresponds to your TiDB version for the right syntax to use near '/*' and b = 'p'' at line 1`) + require.EqualError(t, err, `[parser:1064]You have an error in your SQL syntax; check the manual that corresponds to your TiDB version for the right syntax to use near '/*' and b = 'p'' at line 1`) // The `stmt_test5` should not be found. _, err = tk.Exec(`set @a = 1; execute stmt_test_5 using @a;`) - c.Assert(plannercore.ErrStmtNotFound.Equal(err), IsTrue) + require.True(t, plannercore.ErrStmtNotFound.Equal(err)) // Use parameter marker with argument will run prepared statement. result := tk.MustQuery("select distinct c1, c2 from prepare_test where c1 = ?", 1) @@ -93,197 +98,200 @@ func (s *seqTestSuite) TestPrepared(c *C) { // Call Session PrepareStmt directly to get stmtID. query := "select c1, c2 from prepare_test where c1 = ?" - stmtID, _, _, err := tk.Se.PrepareStmt(query) - c.Assert(err, IsNil) - rs, err := tk.Se.ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(1)}) - c.Assert(err, IsNil) - tk.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("1 ")) + stmtID, _, _, err := tk.Session().PrepareStmt(query) + require.NoError(t, err) + rs, err := tk.Session().ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(1)}) + require.NoError(t, err) + tk.ResultSetToResult(rs, fmt.Sprintf("%v", rs)).Check(testkit.Rows("1 ")) tk.MustExec("delete from prepare_test") query = "select c1 from prepare_test where c1 = (select c1 from prepare_test where c1 = ?)" - stmtID, _, _, err = tk.Se.PrepareStmt(query) - c.Assert(err, IsNil) + stmtID, _, _, err = tk.Session().PrepareStmt(query) + require.NoError(t, err) - tk1 := testkit.NewTestKit(c, s.store) - tk1.Se, err = session.CreateSession4TestWithOpt(s.store, &session.Opt{ + tk1 := testkit.NewTestKit(t, store) + se, err = session.CreateSession4TestWithOpt(store, &session.Opt{ PreparedPlanCache: kvcache.NewSimpleLRUCache(100, 0.1, math.MaxUint64), }) - c.Assert(err, IsNil) + require.NoError(t, err) + tk1.SetSession(se) tk1.MustExec("use test") tk1.MustExec("insert prepare_test (c1) values (3)") - rs, err = tk.Se.ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(3)}) - c.Assert(err, IsNil) - tk.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("3")) + rs, err = tk.Session().ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(3)}) + require.NoError(t, err) + tk.ResultSetToResult(rs, fmt.Sprintf("%v", rs)).Check(testkit.Rows("3")) tk.MustExec("delete from prepare_test") query = "select c1 from prepare_test where c1 = (select c1 from prepare_test where c1 = ?)" - stmtID, _, _, err = tk.Se.PrepareStmt(query) - c.Assert(err, IsNil) - rs, err = tk.Se.ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(3)}) - c.Assert(err, IsNil) - c.Assert(rs.Close(), IsNil) + stmtID, _, _, err = tk.Session().PrepareStmt(query) + require.NoError(t, err) + rs, err = tk.Session().ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(3)}) + require.NoError(t, err) + require.NoError(t, rs.Close()) tk1.MustExec("insert prepare_test (c1) values (3)") - rs, err = tk.Se.ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(3)}) - c.Assert(err, IsNil) - tk.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("3")) + rs, err = tk.Session().ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(3)}) + require.NoError(t, err) + tk.ResultSetToResult(rs, fmt.Sprintf("%v", rs)).Check(testkit.Rows("3")) tk.MustExec("delete from prepare_test") query = "select c1 from prepare_test where c1 in (select c1 from prepare_test where c1 = ?)" - stmtID, _, _, err = tk.Se.PrepareStmt(query) - c.Assert(err, IsNil) - rs, err = tk.Se.ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(3)}) - c.Assert(err, IsNil) - c.Assert(rs.Close(), IsNil) + stmtID, _, _, err = tk.Session().PrepareStmt(query) + require.NoError(t, err) + rs, err = tk.Session().ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(3)}) + require.NoError(t, err) + require.NoError(t, rs.Close()) tk1.MustExec("insert prepare_test (c1) values (3)") - rs, err = tk.Se.ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(3)}) - c.Assert(err, IsNil) - tk.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("3")) + rs, err = tk.Session().ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(3)}) + require.NoError(t, err) + tk.ResultSetToResult(rs, fmt.Sprintf("%v", rs)).Check(testkit.Rows("3")) tk.MustExec("begin") tk.MustExec("insert prepare_test (c1) values (4)") query = "select c1, c2 from prepare_test where c1 = ?" - stmtID, _, _, err = tk.Se.PrepareStmt(query) - c.Assert(err, IsNil) + stmtID, _, _, err = tk.Session().PrepareStmt(query) + require.NoError(t, err) tk.MustExec("rollback") - rs, err = tk.Se.ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(4)}) - c.Assert(err, IsNil) - tk.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows()) + rs, err = tk.Session().ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(4)}) + require.NoError(t, err) + tk.ResultSetToResult(rs, fmt.Sprintf("%v", rs)).Check(testkit.Rows()) // Check that ast.Statement created by executor.CompileExecutePreparedStmt has query text. - stmt, _, _, err := executor.CompileExecutePreparedStmt(context.TODO(), tk.Se, stmtID, - tk.Se.GetInfoSchema().(infoschema.InfoSchema), 0, []types.Datum{types.NewDatum(1)}) - c.Assert(err, IsNil) - c.Assert(stmt.OriginText(), Equals, query) + stmt, _, _, err := executor.CompileExecutePreparedStmt(context.TODO(), tk.Session(), stmtID, + tk.Session().GetInfoSchema().(infoschema.InfoSchema), 0, []types.Datum{types.NewDatum(1)}) + require.NoError(t, err) + require.Equal(t, query, stmt.OriginText()) // Check that rebuild plan works. - tk.Se.PrepareTxnCtx(ctx) + tk.Session().PrepareTxnCtx(ctx) _, err = stmt.RebuildPlan(ctx) - c.Assert(err, IsNil) + require.NoError(t, err) rs, err = stmt.Exec(ctx) - c.Assert(err, IsNil) + require.NoError(t, err) req := rs.NewChunk() err = rs.Next(ctx, req) - c.Assert(err, IsNil) - c.Assert(rs.Close(), IsNil) + require.NoError(t, err) + require.NoError(t, rs.Close()) // Make schema change. tk.MustExec("drop table if exists prepare2") _, err = tk.Exec("create table prepare2 (a int)") - c.Assert(err, IsNil) + require.NoError(t, err) // Should success as the changed schema do not affect the prepared statement. - rs, err = tk.Se.ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(1)}) - c.Assert(err, IsNil) + rs, err = tk.Session().ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(1)}) + require.NoError(t, err) if rs != nil { - rs.Close() + require.NoError(t, rs.Close()) } // Drop a column so the prepared statement become invalid. query = "select c1, c2 from prepare_test where c1 = ?" - stmtID, _, _, err = tk.Se.PrepareStmt(query) - c.Assert(err, IsNil) + stmtID, _, _, err = tk.Session().PrepareStmt(query) + require.NoError(t, err) tk.MustExec("alter table prepare_test drop column c2") - _, err = tk.Se.ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(1)}) - c.Assert(plannercore.ErrUnknownColumn.Equal(err), IsTrue) + _, err = tk.Session().ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(1)}) + require.True(t, plannercore.ErrUnknownColumn.Equal(err)) tk.MustExec("drop table prepare_test") - _, err = tk.Se.ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(1)}) - c.Assert(plannercore.ErrSchemaChanged.Equal(err), IsTrue) + _, err = tk.Session().ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(1)}) + require.True(t, plannercore.ErrSchemaChanged.Equal(err)) // issue 3381 tk.MustExec("drop table if exists prepare3") tk.MustExec("create table prepare3 (a decimal(1))") tk.MustExec("prepare stmt from 'insert into prepare3 value(123)'") _, err = tk.Exec("execute stmt") - c.Assert(err, NotNil) - - _, _, fields, err := tk.Se.PrepareStmt("select a from prepare3") - c.Assert(err, IsNil) - c.Assert(fields[0].DBName.L, Equals, "test") - c.Assert(fields[0].TableAsName.L, Equals, "prepare3") - c.Assert(fields[0].ColumnAsName.L, Equals, "a") - - _, _, fields, err = tk.Se.PrepareStmt("select a from prepare3 where ?") - c.Assert(err, IsNil) - c.Assert(fields[0].DBName.L, Equals, "test") - c.Assert(fields[0].TableAsName.L, Equals, "prepare3") - c.Assert(fields[0].ColumnAsName.L, Equals, "a") - - _, _, fields, err = tk.Se.PrepareStmt("select (1,1) in (select 1,1)") - c.Assert(err, IsNil) - c.Assert(fields[0].DBName.L, Equals, "") - c.Assert(fields[0].TableAsName.L, Equals, "") - c.Assert(fields[0].ColumnAsName.L, Equals, "(1,1) in (select 1,1)") - - _, _, fields, err = tk.Se.PrepareStmt("select a from prepare3 where a = (" + + require.Error(t, err) + + _, _, fields, err := tk.Session().PrepareStmt("select a from prepare3") + require.NoError(t, err) + require.Equal(t, "test", fields[0].DBName.L) + require.Equal(t, "prepare3", fields[0].TableAsName.L) + require.Equal(t, "a", fields[0].ColumnAsName.L) + + _, _, fields, err = tk.Session().PrepareStmt("select a from prepare3 where ?") + require.NoError(t, err) + require.Equal(t, "test", fields[0].DBName.L) + require.Equal(t, "prepare3", fields[0].TableAsName.L) + require.Equal(t, "a", fields[0].ColumnAsName.L) + + _, _, fields, err = tk.Session().PrepareStmt("select (1,1) in (select 1,1)") + require.NoError(t, err) + require.Equal(t, "", fields[0].DBName.L) + require.Equal(t, "", fields[0].TableAsName.L) + require.Equal(t, "(1,1) in (select 1,1)", fields[0].ColumnAsName.L) + + _, _, fields, err = tk.Session().PrepareStmt("select a from prepare3 where a = (" + "select a from prepare2 where a = ?)") - c.Assert(err, IsNil) - c.Assert(fields[0].DBName.L, Equals, "test") - c.Assert(fields[0].TableAsName.L, Equals, "prepare3") - c.Assert(fields[0].ColumnAsName.L, Equals, "a") - - _, _, fields, err = tk.Se.PrepareStmt("select * from prepare3 as t1 join prepare3 as t2") - c.Assert(err, IsNil) - c.Assert(fields[0].DBName.L, Equals, "test") - c.Assert(fields[0].TableAsName.L, Equals, "t1") - c.Assert(fields[0].ColumnAsName.L, Equals, "a") - c.Assert(fields[1].DBName.L, Equals, "test") - c.Assert(fields[1].TableAsName.L, Equals, "t2") - c.Assert(fields[1].ColumnAsName.L, Equals, "a") - - _, _, fields, err = tk.Se.PrepareStmt("update prepare3 set a = ?") - c.Assert(err, IsNil) - c.Assert(len(fields), Equals, 0) + require.NoError(t, err) + require.Equal(t, "test", fields[0].DBName.L) + require.Equal(t, "prepare3", fields[0].TableAsName.L) + require.Equal(t, "a", fields[0].ColumnAsName.L) + + _, _, fields, err = tk.Session().PrepareStmt("select * from prepare3 as t1 join prepare3 as t2") + require.NoError(t, err) + require.Equal(t, "test", fields[0].DBName.L) + require.Equal(t, "t1", fields[0].TableAsName.L) + require.Equal(t, "a", fields[0].ColumnAsName.L) + require.Equal(t, "test", fields[1].DBName.L) + require.Equal(t, "t2", fields[1].TableAsName.L) + require.Equal(t, "a", fields[1].ColumnAsName.L) + + _, _, fields, err = tk.Session().PrepareStmt("update prepare3 set a = ?") + require.NoError(t, err) + require.Len(t, fields, 0) // issue 8074 tk.MustExec("drop table if exists prepare1;") tk.MustExec("create table prepare1 (a decimal(1))") tk.MustExec("insert into prepare1 values(1);") _, err = tk.Exec("prepare stmt FROM @sql1") - c.Assert(err.Error(), Equals, "[parser:1064]You have an error in your SQL syntax; check the manual that corresponds to your TiDB version for the right syntax to use line 1 column 4 near \"NULL\" ") + require.EqualError(t, err, "[parser:1064]You have an error in your SQL syntax; check the manual that corresponds to your TiDB version for the right syntax to use line 1 column 4 near \"NULL\" ") tk.MustExec("SET @sql = 'update prepare1 set a=5 where a=?';") _, err = tk.Exec("prepare stmt FROM @sql") - c.Assert(err, IsNil) + require.NoError(t, err) tk.MustExec("set @var=1;") _, err = tk.Exec("execute stmt using @var") - c.Assert(err, IsNil) + require.NoError(t, err) tk.MustQuery("select a from prepare1;").Check(testkit.Rows("5")) // issue 19371 tk.MustExec("SET @sql = 'update prepare1 set a=a+1';") _, err = tk.Exec("prepare stmt FROM @SQL") - c.Assert(err, IsNil) + require.NoError(t, err) _, err = tk.Exec("execute stmt") - c.Assert(err, IsNil) + require.NoError(t, err) tk.MustQuery("select a from prepare1;").Check(testkit.Rows("6")) _, err = tk.Exec("prepare stmt FROM @Sql") - c.Assert(err, IsNil) + require.NoError(t, err) _, err = tk.Exec("execute stmt") - c.Assert(err, IsNil) + require.NoError(t, err) tk.MustQuery("select a from prepare1;").Check(testkit.Rows("7")) // Coverage. exec := &executor.ExecuteExec{} err = exec.Next(ctx, nil) - c.Assert(err, IsNil) + require.NoError(t, err) err = exec.Close() - c.Assert(err, IsNil) + require.NoError(t, err) // issue 8065 - stmtID, _, _, err = tk.Se.PrepareStmt("select ? from dual") - c.Assert(err, IsNil) - _, err = tk.Se.ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(1)}) - c.Assert(err, IsNil) - stmtID, _, _, err = tk.Se.PrepareStmt("update prepare1 set a = ? where a = ?") - c.Assert(err, IsNil) - _, err = tk.Se.ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(1), types.NewDatum(1)}) - c.Assert(err, IsNil) + stmtID, _, _, err = tk.Session().PrepareStmt("select ? from dual") + require.NoError(t, err) + _, err = tk.Session().ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(1)}) + require.NoError(t, err) + stmtID, _, _, err = tk.Session().PrepareStmt("update prepare1 set a = ? where a = ?") + require.NoError(t, err) + _, err = tk.Session().ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(1), types.NewDatum(1)}) + require.NoError(t, err) } } -func (s *seqTestSuite) TestPreparedLimitOffset(c *C) { +func TestPreparedLimitOffset(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() orgEnable := plannercore.PreparedPlanCacheEnabled() defer func() { plannercore.SetPreparedPlanCache(orgEnable) @@ -291,14 +299,14 @@ func (s *seqTestSuite) TestPreparedLimitOffset(c *C) { flags := []bool{false, true} ctx := context.Background() for _, flag := range flags { - var err error plannercore.SetPreparedPlanCache(flag) - tk := testkit.NewTestKit(c, s.store) - tk.Se, err = session.CreateSession4TestWithOpt(s.store, &session.Opt{ + tk := testkit.NewTestKit(t, store) + se, err := session.CreateSession4TestWithOpt(store, &session.Opt{ PreparedPlanCache: kvcache.NewSimpleLRUCache(100, 0.1, math.MaxUint64), }) - c.Assert(err, IsNil) + require.NoError(t, err) + tk.SetSession(se) tk.MustExec("use test") tk.MustExec("drop table if exists prepare_test") @@ -314,16 +322,18 @@ func (s *seqTestSuite) TestPreparedLimitOffset(c *C) { tk.MustExec(`set @c="-1"`) _, err = tk.Exec("execute stmt_test_1 using @c, @c") - c.Assert(plannercore.ErrWrongArguments.Equal(err), IsTrue) + require.True(t, plannercore.ErrWrongArguments.Equal(err)) - stmtID, _, _, err := tk.Se.PrepareStmt("select id from prepare_test limit ?") - c.Assert(err, IsNil) - _, err = tk.Se.ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(1)}) - c.Assert(err, IsNil) + stmtID, _, _, err := tk.Session().PrepareStmt("select id from prepare_test limit ?") + require.NoError(t, err) + _, err = tk.Session().ExecutePreparedStmt(ctx, stmtID, []types.Datum{types.NewDatum(1)}) + require.NoError(t, err) } } -func (s *seqTestSuite) TestPreparedNullParam(c *C) { +func TestPreparedNullParam(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() orgEnable := plannercore.PreparedPlanCacheEnabled() defer func() { plannercore.SetPreparedPlanCache(orgEnable) @@ -331,12 +341,13 @@ func (s *seqTestSuite) TestPreparedNullParam(c *C) { flags := []bool{false, true} for _, flag := range flags { plannercore.SetPreparedPlanCache(flag) - tk := testkit.NewTestKit(c, s.store) - var err error - tk.Se, err = session.CreateSession4TestWithOpt(s.store, &session.Opt{ + tk := testkit.NewTestKit(t, store) + + se, err := session.CreateSession4TestWithOpt(store, &session.Opt{ PreparedPlanCache: kvcache.NewSimpleLRUCache(100, 0.1, math.MaxUint64), }) - c.Assert(err, IsNil) + require.NoError(t, err) + tk.SetSession(se) tk.MustExec("use test") tk.MustExec("drop table if exists t") @@ -362,7 +373,9 @@ func (s *seqTestSuite) TestPreparedNullParam(c *C) { } } -func (s *seqTestSuite) TestPrepareWithAggregation(c *C) { +func TestPrepareWithAggregation(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() orgEnable := plannercore.PreparedPlanCacheEnabled() defer func() { plannercore.SetPreparedPlanCache(orgEnable) @@ -370,12 +383,13 @@ func (s *seqTestSuite) TestPrepareWithAggregation(c *C) { flags := []bool{false, true} for _, flag := range flags { plannercore.SetPreparedPlanCache(flag) - tk := testkit.NewTestKit(c, s.store) - var err error - tk.Se, err = session.CreateSession4TestWithOpt(s.store, &session.Opt{ + tk := testkit.NewTestKit(t, store) + + se, err := session.CreateSession4TestWithOpt(store, &session.Opt{ PreparedPlanCache: kvcache.NewSimpleLRUCache(100, 0.1, math.MaxUint64), }) - c.Assert(err, IsNil) + require.NoError(t, err) + tk.SetSession(se) tk.MustExec("use test") tk.MustExec("drop table if exists t") @@ -392,7 +406,9 @@ func (s *seqTestSuite) TestPrepareWithAggregation(c *C) { } } -func (s *seqTestSuite) TestPreparedIssue7579(c *C) { +func TestPreparedIssue7579(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() orgEnable := plannercore.PreparedPlanCacheEnabled() defer func() { plannercore.SetPreparedPlanCache(orgEnable) @@ -400,12 +416,13 @@ func (s *seqTestSuite) TestPreparedIssue7579(c *C) { flags := []bool{false, true} for _, flag := range flags { plannercore.SetPreparedPlanCache(flag) - tk := testkit.NewTestKit(c, s.store) - var err error - tk.Se, err = session.CreateSession4TestWithOpt(s.store, &session.Opt{ + tk := testkit.NewTestKit(t, store) + + se, err := session.CreateSession4TestWithOpt(store, &session.Opt{ PreparedPlanCache: kvcache.NewSimpleLRUCache(100, 0.1, math.MaxUint64), }) - c.Assert(err, IsNil) + require.NoError(t, err) + tk.SetSession(se) tk.MustExec("use test") tk.MustExec("drop table if exists t") @@ -438,7 +455,9 @@ func (s *seqTestSuite) TestPreparedIssue7579(c *C) { } } -func (s *seqTestSuite) TestPreparedInsert(c *C) { +func TestPreparedInsert(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() orgEnable := plannercore.PreparedPlanCacheEnabled() defer func() { plannercore.SetPreparedPlanCache(orgEnable) @@ -450,12 +469,13 @@ func (s *seqTestSuite) TestPreparedInsert(c *C) { flags := []bool{false, true} for _, flag := range flags { plannercore.SetPreparedPlanCache(flag) - tk := testkit.NewTestKit(c, s.store) - var err error - tk.Se, err = session.CreateSession4TestWithOpt(s.store, &session.Opt{ + tk := testkit.NewTestKit(t, store) + + se, err := session.CreateSession4TestWithOpt(store, &session.Opt{ PreparedPlanCache: kvcache.NewSimpleLRUCache(100, 0.1, math.MaxUint64), }) - c.Assert(err, IsNil) + require.NoError(t, err) + tk.SetSession(se) tk.MustExec("use test") tk.MustExec("drop table if exists prepare_test") @@ -464,23 +484,23 @@ func (s *seqTestSuite) TestPreparedInsert(c *C) { tk.MustExec(`set @a=1,@b=1; execute stmt_insert using @a, @b;`) if flag { err = counter.Write(pb) - c.Assert(err, IsNil) + require.NoError(t, err) hit := pb.GetCounter().GetValue() - c.Check(hit, Equals, float64(0)) + require.Equal(t, float64(0), hit) } tk.MustExec(`set @a=2,@b=2; execute stmt_insert using @a, @b;`) if flag { err = counter.Write(pb) - c.Assert(err, IsNil) + require.NoError(t, err) hit := pb.GetCounter().GetValue() - c.Check(hit, Equals, float64(1)) + require.Equal(t, float64(1), hit) } tk.MustExec(`set @a=3,@b=3; execute stmt_insert using @a, @b;`) if flag { err = counter.Write(pb) - c.Assert(err, IsNil) + require.NoError(t, err) hit := pb.GetCounter().GetValue() - c.Check(hit, Equals, float64(2)) + require.Equal(t, float64(2), hit) } result := tk.MustQuery("select id, c1 from prepare_test where id = ?", 1) @@ -494,23 +514,23 @@ func (s *seqTestSuite) TestPreparedInsert(c *C) { tk.MustExec(`set @a=1; execute stmt_insert_select using @a;`) if flag { err = counter.Write(pb) - c.Assert(err, IsNil) + require.NoError(t, err) hit := pb.GetCounter().GetValue() - c.Check(hit, Equals, float64(2)) + require.Equal(t, float64(2), hit) } tk.MustExec(`set @a=2; execute stmt_insert_select using @a;`) if flag { err = counter.Write(pb) - c.Assert(err, IsNil) + require.NoError(t, err) hit := pb.GetCounter().GetValue() - c.Check(hit, Equals, float64(2)) + require.Equal(t, float64(2), hit) } tk.MustExec(`set @a=3; execute stmt_insert_select using @a;`) if flag { err = counter.Write(pb) - c.Assert(err, IsNil) + require.NoError(t, err) hit := pb.GetCounter().GetValue() - c.Check(hit, Equals, float64(2)) + require.Equal(t, float64(2), hit) } result = tk.MustQuery("select id, c1 from prepare_test where id = ?", 101) @@ -522,7 +542,9 @@ func (s *seqTestSuite) TestPreparedInsert(c *C) { } } -func (s *seqTestSuite) TestPreparedUpdate(c *C) { +func TestPreparedUpdate(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() orgEnable := plannercore.PreparedPlanCacheEnabled() defer func() { plannercore.SetPreparedPlanCache(orgEnable) @@ -534,12 +556,13 @@ func (s *seqTestSuite) TestPreparedUpdate(c *C) { flags := []bool{false, true} for _, flag := range flags { plannercore.SetPreparedPlanCache(flag) - tk := testkit.NewTestKit(c, s.store) - var err error - tk.Se, err = session.CreateSession4TestWithOpt(s.store, &session.Opt{ + tk := testkit.NewTestKit(t, store) + + se, err := session.CreateSession4TestWithOpt(store, &session.Opt{ PreparedPlanCache: kvcache.NewSimpleLRUCache(100, 0.1, math.MaxUint64), }) - c.Assert(err, IsNil) + require.NoError(t, err) + tk.SetSession(se) tk.MustExec("use test") tk.MustExec("drop table if exists prepare_test") @@ -552,23 +575,23 @@ func (s *seqTestSuite) TestPreparedUpdate(c *C) { tk.MustExec(`set @a=1,@b=100; execute stmt_update using @b,@a;`) if flag { err = counter.Write(pb) - c.Assert(err, IsNil) + require.NoError(t, err) hit := pb.GetCounter().GetValue() - c.Check(hit, Equals, float64(0)) + require.Equal(t, float64(0), hit) } tk.MustExec(`set @a=2,@b=200; execute stmt_update using @b,@a;`) if flag { err = counter.Write(pb) - c.Assert(err, IsNil) + require.NoError(t, err) hit := pb.GetCounter().GetValue() - c.Check(hit, Equals, float64(1)) + require.Equal(t, float64(1), hit) } tk.MustExec(`set @a=3,@b=300; execute stmt_update using @b,@a;`) if flag { err = counter.Write(pb) - c.Assert(err, IsNil) + require.NoError(t, err) hit := pb.GetCounter().GetValue() - c.Check(hit, Equals, float64(2)) + require.Equal(t, float64(2), hit) } result := tk.MustQuery("select id, c1 from prepare_test where id = ?", 1) @@ -580,14 +603,16 @@ func (s *seqTestSuite) TestPreparedUpdate(c *C) { } } -func (s *seqTestSuite) TestIssue21884(c *C) { +func TestIssue21884(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() orgEnable := plannercore.PreparedPlanCacheEnabled() defer func() { plannercore.SetPreparedPlanCache(orgEnable) }() plannercore.SetPreparedPlanCache(false) - tk := testkit.NewTestKit(c, s.store) + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("drop table if exists prepare_test") @@ -601,10 +626,12 @@ func (s *seqTestSuite) TestIssue21884(c *C) { time.Sleep(1 * time.Second) tk.MustExec("execute stmt using @status") newUpdateTime := tk.MustQuery("select last_update_time from prepare_test").Rows()[0][0] - c.Assert(updateTime == newUpdateTime, IsFalse) + require.NotEqual(t, newUpdateTime, updateTime) } -func (s *seqTestSuite) TestPreparedDelete(c *C) { +func TestPreparedDelete(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() orgEnable := plannercore.PreparedPlanCacheEnabled() defer func() { plannercore.SetPreparedPlanCache(orgEnable) @@ -616,12 +643,13 @@ func (s *seqTestSuite) TestPreparedDelete(c *C) { flags := []bool{false, true} for _, flag := range flags { plannercore.SetPreparedPlanCache(flag) - tk := testkit.NewTestKit(c, s.store) - var err error - tk.Se, err = session.CreateSession4TestWithOpt(s.store, &session.Opt{ + tk := testkit.NewTestKit(t, store) + + se, err := session.CreateSession4TestWithOpt(store, &session.Opt{ PreparedPlanCache: kvcache.NewSimpleLRUCache(100, 0.1, math.MaxUint64), }) - c.Assert(err, IsNil) + require.NoError(t, err) + tk.SetSession(se) tk.MustExec("use test") tk.MustExec("drop table if exists prepare_test") @@ -634,23 +662,23 @@ func (s *seqTestSuite) TestPreparedDelete(c *C) { tk.MustExec(`set @a=1; execute stmt_delete using @a;`) if flag { err = counter.Write(pb) - c.Assert(err, IsNil) + require.NoError(t, err) hit := pb.GetCounter().GetValue() - c.Check(hit, Equals, float64(0)) + require.Equal(t, float64(0), hit) } tk.MustExec(`set @a=2; execute stmt_delete using @a;`) if flag { err = counter.Write(pb) - c.Assert(err, IsNil) + require.NoError(t, err) hit := pb.GetCounter().GetValue() - c.Check(hit, Equals, float64(1)) + require.Equal(t, float64(1), hit) } tk.MustExec(`set @a=3; execute stmt_delete using @a;`) if flag { err = counter.Write(pb) - c.Assert(err, IsNil) + require.NoError(t, err) hit := pb.GetCounter().GetValue() - c.Check(hit, Equals, float64(2)) + require.Equal(t, float64(2), hit) } result := tk.MustQuery("select id, c1 from prepare_test where id = ?", 1) @@ -662,25 +690,28 @@ func (s *seqTestSuite) TestPreparedDelete(c *C) { } } -func (s *seqTestSuite) TestPrepareDealloc(c *C) { +func TestPrepareDealloc(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() orgEnable := plannercore.PreparedPlanCacheEnabled() defer func() { plannercore.SetPreparedPlanCache(orgEnable) }() plannercore.SetPreparedPlanCache(true) - tk := testkit.NewTestKit(c, s.store) - var err error - tk.Se, err = session.CreateSession4TestWithOpt(s.store, &session.Opt{ + tk := testkit.NewTestKit(t, store) + + se, err := session.CreateSession4TestWithOpt(store, &session.Opt{ PreparedPlanCache: kvcache.NewSimpleLRUCache(3, 0.1, math.MaxUint64), }) - c.Assert(err, IsNil) + require.NoError(t, err) + tk.SetSession(se) tk.MustExec("use test") tk.MustExec("drop table if exists prepare_test") tk.MustExec("create table prepare_test (id int PRIMARY KEY, c1 int)") - c.Assert(tk.Se.PreparedPlanCache().Size(), Equals, 0) + require.Equal(t, 0, tk.Session().PreparedPlanCache().Size()) tk.MustExec(`prepare stmt1 from 'select * from prepare_test'`) tk.MustExec("execute stmt1") tk.MustExec(`prepare stmt2 from 'select * from prepare_test'`) @@ -689,30 +720,33 @@ func (s *seqTestSuite) TestPrepareDealloc(c *C) { tk.MustExec("execute stmt3") tk.MustExec(`prepare stmt4 from 'select * from prepare_test'`) tk.MustExec("execute stmt4") - c.Assert(tk.Se.PreparedPlanCache().Size(), Equals, 3) + require.Equal(t, 3, tk.Session().PreparedPlanCache().Size()) tk.MustExec("deallocate prepare stmt1") - c.Assert(tk.Se.PreparedPlanCache().Size(), Equals, 3) + require.Equal(t, 3, tk.Session().PreparedPlanCache().Size()) tk.MustExec("deallocate prepare stmt2") tk.MustExec("deallocate prepare stmt3") tk.MustExec("deallocate prepare stmt4") - c.Assert(tk.Se.PreparedPlanCache().Size(), Equals, 0) + require.Equal(t, 0, tk.Session().PreparedPlanCache().Size()) } -func (s *seqTestSuite) TestPreparedIssue8153(c *C) { +func TestPreparedIssue8153(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() orgEnable := plannercore.PreparedPlanCacheEnabled() defer func() { plannercore.SetPreparedPlanCache(orgEnable) }() flags := []bool{false, true} for _, flag := range flags { - var err error plannercore.SetPreparedPlanCache(flag) - tk := testkit.NewTestKit(c, s.store) - tk.Se, err = session.CreateSession4TestWithOpt(s.store, &session.Opt{ + tk := testkit.NewTestKit(t, store) + + se, err := session.CreateSession4TestWithOpt(store, &session.Opt{ PreparedPlanCache: kvcache.NewSimpleLRUCache(100, 0.1, math.MaxUint64), }) - c.Assert(err, IsNil) + require.NoError(t, err) + tk.SetSession(se) tk.MustExec("use test") tk.MustExec("drop table if exists t") @@ -733,7 +767,7 @@ func (s *seqTestSuite) TestPreparedIssue8153(c *C) { tk.MustExec(`set @param = 3`) _, err = tk.Exec(`execute stmt using @param;`) - c.Assert(err.Error(), Equals, "[planner:1054]Unknown column '?' in 'order clause'") + require.EqualError(t, err, "[planner:1054]Unknown column '?' in 'order clause'") tk.MustExec(`set @param = '##'`) r = tk.MustQuery(`execute stmt using @param;`) @@ -748,11 +782,13 @@ func (s *seqTestSuite) TestPreparedIssue8153(c *C) { tk.MustExec(`set @a=1,@b=2`) _, err = tk.Exec(`execute stmt using @a,@b;`) - c.Assert(err.Error(), Equals, "[planner:1056]Can't group on 'sum(a)'") + require.EqualError(t, err, "[planner:1056]Can't group on 'sum(a)'") } } -func (s *seqTestSuite) TestPreparedIssue8644(c *C) { +func TestPreparedIssue8644(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() orgEnable := plannercore.PreparedPlanCacheEnabled() defer func() { plannercore.SetPreparedPlanCache(orgEnable) @@ -760,12 +796,13 @@ func (s *seqTestSuite) TestPreparedIssue8644(c *C) { flags := []bool{false, true} for _, flag := range flags { plannercore.SetPreparedPlanCache(flag) - tk := testkit.NewTestKit(c, s.store) - var err error - tk.Se, err = session.CreateSession4TestWithOpt(s.store, &session.Opt{ + tk := testkit.NewTestKit(t, store) + + se, err := session.CreateSession4TestWithOpt(store, &session.Opt{ PreparedPlanCache: kvcache.NewSimpleLRUCache(100, 0.1, math.MaxUint64), }) - c.Assert(err, IsNil) + require.NoError(t, err) + tk.SetSession(se) tk.MustExec("use test") @@ -819,13 +856,13 @@ func (msm *mockSessionManager1) ShowProcessList() map[uint64]*util.ProcessInfo { return ret } -func (msm *mockSessionManager1) GetProcessInfo(id uint64) (*util.ProcessInfo, bool) { +func (msm *mockSessionManager1) GetProcessInfo(_ uint64) (*util.ProcessInfo, bool) { pi := msm.Se.ShowProcess() return pi, true } // Kill implements the SessionManager.Kill interface. -func (msm *mockSessionManager1) Kill(cid uint64, query bool) {} +func (msm *mockSessionManager1) Kill(_ uint64, _ bool) {} func (msm *mockSessionManager1) KillAllConnections() {} @@ -833,43 +870,45 @@ func (msm *mockSessionManager1) ServerID() uint64 { return 1 } -func (msm *mockSessionManager1) UpdateTLSConfig(cfg *tls.Config) {} +func (msm *mockSessionManager1) UpdateTLSConfig(_ *tls.Config) {} -func (s *seqTestSuite) TestPreparedIssue17419(c *C) { +func TestPreparedIssue17419(t *testing.T) { + store, dom, clean := testkit.CreateMockStoreAndDomain(t) + defer clean() ctx := context.Background() - tk := testkit.NewTestKit(c, s.store) + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("drop table if exists t") tk.MustExec("create table t (a int)") tk.MustExec("insert into t (a) values (1), (2), (3)") - tk1 := testkit.NewTestKit(c, s.store) + tk1 := testkit.NewTestKit(t, store) - var err error - tk1.Se, err = session.CreateSession4Test(s.store) - c.Assert(err, IsNil) - tk1.GetConnectionID() + se, err := session.CreateSession4Test(store) + require.NoError(t, err) + tk1.SetSession(se) + tk1.RefreshConnectionID() query := "select * from test.t" - stmtID, _, _, err := tk1.Se.PrepareStmt(query) - c.Assert(err, IsNil) + stmtID, _, _, err := tk1.Session().PrepareStmt(query) + require.NoError(t, err) sm := &mockSessionManager1{ - Se: tk1.Se, + Se: tk1.Session(), } - tk1.Se.SetSessionManager(sm) - s.domain.ExpensiveQueryHandle().SetSessionManager(sm) + tk1.Session().SetSessionManager(sm) + dom.ExpensiveQueryHandle().SetSessionManager(sm) - rs, err := tk1.Se.ExecutePreparedStmt(ctx, stmtID, []types.Datum{}) - c.Assert(err, IsNil) - tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("1", "2", "3")) - tk1.Se.SetProcessInfo("", time.Now(), mysql.ComStmtExecute, 0) + rs, err := tk1.Session().ExecutePreparedStmt(ctx, stmtID, []types.Datum{}) + require.NoError(t, err) + tk1.ResultSetToResult(rs, fmt.Sprintf("%v", rs)).Check(testkit.Rows("1", "2", "3")) + tk1.Session().SetProcessInfo("", time.Now(), mysql.ComStmtExecute, 0) - s.domain.ExpensiveQueryHandle().LogOnQueryExceedMemQuota(tk.Se.GetSessionVars().ConnectionID) + dom.ExpensiveQueryHandle().LogOnQueryExceedMemQuota(tk.Session().GetSessionVars().ConnectionID) // After entirely fixing https://github.com/pingcap/tidb/issues/17419 // c.Assert(tk1.Se.ShowProcess().Plan, NotNil) // _, ok := tk1.Se.ShowProcess().Plan.(*plannercore.Execute) - // c.Assert(ok, IsTrue) + // require.True(t, ok) } diff --git a/executor/seqtest/seq_executor_test.go b/executor/seqtest/seq_executor_serial_test.go similarity index 80% rename from executor/seqtest/seq_executor_test.go rename to executor/seqtest/seq_executor_serial_test.go index bb81ab9c9d270..f49757a0f260d 100644 --- a/executor/seqtest/seq_executor_test.go +++ b/executor/seqtest/seq_executor_serial_test.go @@ -19,10 +19,8 @@ package executor_test import ( "bytes" "context" - "flag" "fmt" "math" - "os" "runtime/pprof" "strconv" "strings" @@ -31,11 +29,9 @@ import ( "testing" "time" - . "github.com/pingcap/check" "github.com/pingcap/errors" "github.com/pingcap/failpoint" "github.com/pingcap/kvproto/pkg/kvrpcpb" - "github.com/pingcap/parser" "github.com/pingcap/parser/model" "github.com/pingcap/parser/mysql" "github.com/pingcap/parser/terror" @@ -54,71 +50,25 @@ import ( "github.com/pingcap/tidb/store/copr" "github.com/pingcap/tidb/store/mockstore" "github.com/pingcap/tidb/tablecodec" + "github.com/pingcap/tidb/testkit" "github.com/pingcap/tidb/util/collate" "github.com/pingcap/tidb/util/gcutil" - "github.com/pingcap/tidb/util/logutil" - "github.com/pingcap/tidb/util/testkit" "github.com/pingcap/tidb/util/testutil" + "github.com/stretchr/testify/require" "github.com/tikv/client-go/v2/testutils" "github.com/tikv/client-go/v2/tikv" "github.com/tikv/client-go/v2/tikvrpc" ) -func TestT(t *testing.T) { - CustomVerboseFlag = true - logLevel := os.Getenv("log_level") - err := logutil.InitLogger(logutil.NewLogConfig(logLevel, logutil.DefaultLogFormat, "", logutil.EmptyFileLogConfig, false)) - if err != nil { - t.Fatal(err) - } - config.UpdateGlobal(func(conf *config.Config) { - conf.TiKVClient.AsyncCommit.SafeWindow = 0 - conf.TiKVClient.AsyncCommit.AllowedClockDrift = 0 - }) - TestingT(t) -} - -var _ = SerialSuites(&seqTestSuite{}) -var _ = SerialSuites(&seqTestSuite1{}) - -type seqTestSuite struct { - cluster testutils.Cluster - store kv.Storage - domain *domain.Domain - *parser.Parser -} - -var mockTikv = flag.Bool("mockTikv", true, "use mock tikv store in executor test") - -func (s *seqTestSuite) SetUpSuite(c *C) { - s.Parser = parser.New() - flag.Lookup("mockTikv") - useMockTikv := *mockTikv - if useMockTikv { - var err error - s.store, err = mockstore.NewMockStore( - mockstore.WithClusterInspector(func(c testutils.Cluster) { - mockstore.BootstrapWithSingleStore(c) - s.cluster = c - }), - ) - c.Assert(err, IsNil) - session.SetSchemaLease(0) - session.DisableStats4Test() - } - d, err := session.BootstrapSession(s.store) - c.Assert(err, IsNil) - d.SetStatsUpdating(true) - s.domain = d -} - -func (s *seqTestSuite) TearDownSuite(c *C) { - s.domain.Close() - c.Assert(s.store.Close(), IsNil) -} +func TestEarlyClose(t *testing.T) { + var cluster testutils.Cluster + store, clean := testkit.CreateMockStore(t, mockstore.WithClusterInspector(func(c testutils.Cluster) { + mockstore.BootstrapWithSingleStore(c) + cluster = c + })) + defer clean() -func (s *seqTestSuite) TestEarlyClose(c *C) { - tk := testkit.NewTestKit(c, s.store) + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("create table earlyclose (id int primary key)") @@ -131,47 +81,46 @@ func (s *seqTestSuite) TestEarlyClose(c *C) { tk.MustExec("insert earlyclose values " + strings.Join(values, ",")) // Get table ID for split. - dom := domain.GetDomain(tk.Se) + dom := domain.GetDomain(tk.Session()) is := dom.InfoSchema() tbl, err := is.TableByName(model.NewCIStr("test"), model.NewCIStr("earlyclose")) - c.Assert(err, IsNil) + require.NoError(t, err) tblID := tbl.Meta().ID // Split the table. tableStart := tablecodec.GenTableRecordPrefix(tblID) - s.cluster.SplitKeys(tableStart, tableStart.PrefixNext(), N/2) + cluster.SplitKeys(tableStart, tableStart.PrefixNext(), N/2) ctx := context.Background() for i := 0; i < N/2; i++ { - rss, err1 := tk.Se.Execute(ctx, "select * from earlyclose order by id") - c.Assert(err1, IsNil) + rss, err := tk.Session().Execute(ctx, "select * from earlyclose order by id") + require.NoError(t, err) rs := rss[0] req := rs.NewChunk() - err = rs.Next(ctx, req) - c.Assert(err, IsNil) - rs.Close() + require.NoError(t, rs.Next(ctx, req)) + require.NoError(t, rs.Close()) } // Goroutine should not leak when error happen. - c.Assert(failpoint.Enable("github.com/pingcap/tidb/store/copr/handleTaskOnceError", `return(true)`), IsNil) + require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/store/copr/handleTaskOnceError", `return(true)`)) defer func() { - c.Assert(failpoint.Disable("github.com/pingcap/tidb/store/copr/handleTaskOnceError"), IsNil) + require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/store/copr/handleTaskOnceError")) }() - rss, err := tk.Se.Execute(ctx, "select * from earlyclose") - c.Assert(err, IsNil) + rss, err := tk.Session().Execute(ctx, "select * from earlyclose") + require.NoError(t, err) rs := rss[0] req := rs.NewChunk() err = rs.Next(ctx, req) - c.Assert(err, NotNil) - rs.Close() + require.Error(t, err) + require.NoError(t, rs.Close()) } type stats struct { } -func (s stats) GetScope(status string) variable.ScopeFlag { return variable.DefaultStatusVarScopeFlag } +func (s stats) GetScope(_ string) variable.ScopeFlag { return variable.DefaultStatusVarScopeFlag } -func (s stats) Stats(vars *variable.SessionVars) (map[string]interface{}, error) { +func (s stats) Stats(_ *variable.SessionVars) (map[string]interface{}, error) { m := make(map[string]interface{}) var a, b interface{} b = "123" @@ -181,8 +130,11 @@ func (s stats) Stats(vars *variable.SessionVars) (map[string]interface{}, error) return m, nil } -func (s *seqTestSuite) TestShow(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestShow(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") testSQL := `drop table if exists show_test` @@ -192,17 +144,17 @@ func (s *seqTestSuite) TestShow(c *C) { testSQL = "show columns from show_test;" result := tk.MustQuery(testSQL) - c.Check(result.Rows(), HasLen, 6) + require.Len(t, result.Rows(), 6) testSQL = "show create table show_test;" result = tk.MustQuery(testSQL) - c.Check(result.Rows(), HasLen, 1) + require.Len(t, result.Rows(), 1) row := result.Rows()[0] // For issue https://github.com/pingcap/tidb/issues/1061 expectedRow := []interface{}{ "SHOW_test", "CREATE TABLE `SHOW_test` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `c1` int(11) DEFAULT NULL COMMENT 'c1_comment',\n `c2` int(11) DEFAULT NULL,\n `c3` int(11) DEFAULT '1',\n `c4` text DEFAULT NULL,\n `c5` tinyint(1) DEFAULT NULL,\n PRIMARY KEY (`id`) /*T![clustered_index] CLUSTERED */,\n KEY `idx_wide_c4` (`c3`,`c4`(10))\n) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=28934 COMMENT='table_comment'"} for i, r := range row { - c.Check(r, Equals, expectedRow[i]) + require.Equal(t, expectedRow[i], r) } // For issue https://github.com/pingcap/tidb/issues/1918 @@ -217,12 +169,12 @@ func (s *seqTestSuite) TestShow(c *C) { tk.MustExec(testSQL) testSQL = "show create table ptest;" result = tk.MustQuery(testSQL) - c.Check(result.Rows(), HasLen, 1) + require.Len(t, result.Rows(), 1) row = result.Rows()[0] expectedRow = []interface{}{ "ptest", "CREATE TABLE `ptest` (\n `a` int(11) NOT NULL,\n `b` double NOT NULL DEFAULT '2.0',\n `c` varchar(10) NOT NULL,\n `d` time DEFAULT NULL,\n `e` timestamp NULL DEFAULT NULL,\n `f` timestamp NULL DEFAULT NULL,\n PRIMARY KEY (`a`) /*T![clustered_index] CLUSTERED */,\n UNIQUE KEY `d` (`d`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"} for i, r := range row { - c.Check(r, Equals, expectedRow[i]) + require.Equal(t, expectedRow[i], r) } // Issue #4684. @@ -237,7 +189,7 @@ func (s *seqTestSuite) TestShow(c *C) { tk.MustExec(testSQL) testSQL = "show create table t1" result = tk.MustQuery(testSQL) - c.Check(result.Rows(), HasLen, 1) + require.Len(t, result.Rows(), 1) row = result.Rows()[0] expectedRow = []interface{}{ "t1", "CREATE TABLE `t1` (\n" + @@ -248,7 +200,7 @@ func (s *seqTestSuite) TestShow(c *C) { " `c5` bigint(20) unsigned DEFAULT NULL\n" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"} for i, r := range row { - c.Check(r, Equals, expectedRow[i]) + require.Equal(t, expectedRow[i], r) } // Issue #7665 @@ -257,14 +209,14 @@ func (s *seqTestSuite) TestShow(c *C) { tk.MustExec(testSQL) testSQL = "show create table decimalschema" result = tk.MustQuery(testSQL) - c.Check(result.Rows(), HasLen, 1) + require.Len(t, result.Rows(), 1) row = result.Rows()[0] expectedRow = []interface{}{ "decimalschema", "CREATE TABLE `decimalschema` (\n" + " `c1` decimal(10,0) DEFAULT NULL\n" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"} for i, r := range row { - c.Check(r, Equals, expectedRow[i]) + require.Equal(t, expectedRow[i], r) } tk.MustExec("drop table if exists `decimalschema`") @@ -272,14 +224,14 @@ func (s *seqTestSuite) TestShow(c *C) { tk.MustExec(testSQL) testSQL = "show create table decimalschema" result = tk.MustQuery(testSQL) - c.Check(result.Rows(), HasLen, 1) + require.Len(t, result.Rows(), 1) row = result.Rows()[0] expectedRow = []interface{}{ "decimalschema", "CREATE TABLE `decimalschema` (\n" + " `c1` decimal(15,0) DEFAULT NULL\n" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"} for i, r := range row { - c.Check(r, Equals, expectedRow[i]) + require.Equal(t, expectedRow[i], r) } // test SHOW CREATE TABLE with invisible index @@ -307,7 +259,7 @@ func (s *seqTestSuite) TestShow(c *C) { testSQL = "SHOW VARIABLES LIKE 'character_set_results';" result = tk.MustQuery(testSQL) - c.Check(result.Rows(), HasLen, 1) + require.Len(t, result.Rows(), 1) // Test case for index type and comment tk.MustExec(`create table show_index (id int, c int, primary key (id), index cIdx using hash (c) comment "index_comment_for_cIdx");`) @@ -341,14 +293,14 @@ func (s *seqTestSuite) TestShow(c *C) { testSQL = `show tables like 'SHOW\_test'` result = tk.MustQuery(testSQL) rows := result.Rows() - c.Check(rows, HasLen, 1) - c.Check(rows[0], DeepEquals, []interface{}{"SHOW_test"}) + require.Len(t, rows, 1) + require.Equal(t, []interface{}{"SHOW_test"}, rows[0]) var ss stats variable.RegisterStatistics(ss) testSQL = "show status like 'character_set_results';" result = tk.MustQuery(testSQL) - c.Check(result.Rows(), NotNil) + require.NotNil(t, result.Rows()) tk.MustQuery("SHOW PROCEDURE STATUS WHERE Db='test'").Check(testkit.Rows()) tk.MustQuery("SHOW TRIGGERS WHERE `Trigger` ='test'").Check(testkit.Rows()) @@ -364,10 +316,10 @@ func (s *seqTestSuite) TestShow(c *C) { // | tidb-binlog | 400668057259474944 | | | | // +-------------+--------------------+--------------+------------------+-------------------+ result = tk.MustQuery("SHOW MASTER STATUS") - c.Check(result.Rows(), HasLen, 1) + require.Len(t, result.Rows(), 1) row = result.Rows()[0] - c.Check(row, HasLen, 5) - c.Assert(row[1].(string) != "0", IsTrue) + require.Len(t, row, 5) + require.NotEqual(t, "0", row[1].(string)) tk.MustQuery("SHOW PRIVILEGES") @@ -385,7 +337,7 @@ func (s *seqTestSuite) TestShow(c *C) { tk.MustExec("use show_test_DB") result = tk.MustQuery("SHOW index from show_index from test where Column_name = 'c'") - c.Check(result.Rows(), HasLen, 1) + require.Len(t, result.Rows(), 1) // Test show full columns // for issue https://github.com/pingcap/tidb/issues/4224 @@ -455,12 +407,12 @@ func (s *seqTestSuite) TestShow(c *C) { tk.MustExec(testSQL) testSQL = "show create table show_test;" result = tk.MustQuery(testSQL) - c.Check(result.Rows(), HasLen, 1) + require.Len(t, result.Rows(), 1) row = result.Rows()[0] expectedRow = []interface{}{ "show_test", "CREATE TABLE `show_test` (\n `a` varchar(10) DEFAULT NULL COMMENT 'a\\nb\\rc d\\0e'\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='a\\nb\\rc d\\0e'"} for i, r := range row { - c.Check(r, Equals, expectedRow[i]) + require.Equal(t, expectedRow[i], r) } // for issue https://github.com/pingcap/tidb/issues/4425 @@ -471,12 +423,12 @@ func (s *seqTestSuite) TestShow(c *C) { tk.MustExec(testSQL) testSQL = "show create table show_test;" result = tk.MustQuery(testSQL) - c.Check(result.Rows(), HasLen, 1) + require.Len(t, result.Rows(), 1) row = result.Rows()[0] expectedRow = []interface{}{ "show_test", "CREATE TABLE `show_test` (\n `a` varchar(10) DEFAULT 'a\\nb\\rc d\\0e'\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"} for i, r := range row { - c.Check(r, Equals, expectedRow[i]) + require.Equal(t, expectedRow[i], r) } // for issue https://github.com/pingcap/tidb/issues/4426 @@ -490,12 +442,12 @@ func (s *seqTestSuite) TestShow(c *C) { tk.MustExec(testSQL) testSQL = "show create table show_test;" result = tk.MustQuery(testSQL) - c.Check(result.Rows(), HasLen, 1) + require.Len(t, result.Rows(), 1) row = result.Rows()[0] expectedRow = []interface{}{ "show_test", "CREATE TABLE `show_test` (\n `a` bit(1) DEFAULT NULL,\n `b` bit(32) DEFAULT b'0',\n `c` bit(1) DEFAULT b'1',\n `d` bit(10) DEFAULT b'1010'\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"} for i, r := range row { - c.Check(r, Equals, expectedRow[i]) + require.Equal(t, expectedRow[i], r) } // for issue #4255 @@ -511,7 +463,7 @@ func (s *seqTestSuite) TestShow(c *C) { tk.MustExec(testSQL) testSQL = `show create table t;` result = tk.MustQuery(testSQL) - c.Check(result.Rows(), HasLen, 1) + require.Len(t, result.Rows(), 1) row = result.Rows()[0] expectedRow = []interface{}{ "t", @@ -524,7 +476,7 @@ func (s *seqTestSuite) TestShow(c *C) { ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin", } for i, r := range row { - c.Check(r, Equals, expectedRow[i]) + require.Equal(t, expectedRow[i], r) } // Test get default collate for a specified charset. @@ -553,7 +505,7 @@ func (s *seqTestSuite) TestShow(c *C) { PARTITION p0 VALUES LESS THAN (10), PARTITION p1 VALUES LESS THAN (20), PARTITION p2 VALUES LESS THAN (MAXVALUE))`) - c.Assert(err, NotNil) + require.Error(t, err) // Test range columns partition tk.MustExec(`drop table if exists t`) @@ -647,15 +599,18 @@ func (s *seqTestSuite) TestShow(c *C) { for _, sql := range sqls { res := tk.MustQuery(sql) - c.Assert(res, NotNil) + require.NotNil(t, res) sorted := tk.MustQuery(sql).Sort() - c.Assert(sorted, NotNil) - c.Check(res, DeepEquals, sorted) + require.NotNil(t, sorted) + require.Equal(t, sorted, res) } } -func (s *seqTestSuite) TestShowStatsHealthy(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestShowStatsHealthy(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("drop table if exists t") tk.MustExec("create table t (a int)") @@ -663,37 +618,40 @@ func (s *seqTestSuite) TestShowStatsHealthy(c *C) { tk.MustExec("analyze table t") tk.MustQuery("show stats_healthy").Check(testkit.Rows("test t 100")) tk.MustExec("insert into t values (1), (2)") - do, _ := session.GetDomain(s.store) + do, _ := session.GetDomain(store) err := do.StatsHandle().DumpStatsDeltaToKV(handle.DumpAll) - c.Assert(err, IsNil) + require.NoError(t, err) tk.MustExec("analyze table t") tk.MustQuery("show stats_healthy").Check(testkit.Rows("test t 100")) tk.MustExec("insert into t values (3), (4), (5), (6), (7), (8), (9), (10)") err = do.StatsHandle().DumpStatsDeltaToKV(handle.DumpAll) - c.Assert(err, IsNil) + require.NoError(t, err) err = do.StatsHandle().Update(do.InfoSchema()) - c.Assert(err, IsNil) + require.NoError(t, err) tk.MustQuery("show stats_healthy").Check(testkit.Rows("test t 19")) tk.MustExec("analyze table t") tk.MustQuery("show stats_healthy").Check(testkit.Rows("test t 100")) tk.MustExec("delete from t") err = do.StatsHandle().DumpStatsDeltaToKV(handle.DumpAll) - c.Assert(err, IsNil) + require.NoError(t, err) err = do.StatsHandle().Update(do.InfoSchema()) - c.Assert(err, IsNil) + require.NoError(t, err) tk.MustQuery("show stats_healthy").Check(testkit.Rows("test t 0")) } // TestIndexDoubleReadClose checks that when a index double read returns before reading all the rows, the goroutine doesn't // leak. For testing distsql with multiple regions, we need to manually split a mock TiKV. -func (s *seqTestSuite) TestIndexDoubleReadClose(c *C) { - if _, ok := s.store.GetClient().(*copr.CopClient); !ok { +func TestIndexDoubleReadClose(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + + if _, ok := store.GetClient().(*copr.CopClient); !ok { // Make sure the store is tikv store. return } originSize := atomic.LoadInt32(&executor.LookupTableTaskChannelSize) atomic.StoreInt32(&executor.LookupTableTaskChannelSize, 1) - tk := testkit.NewTestKit(c, s.store) + tk := testkit.NewTestKit(t, store) tk.MustExec("set @@tidb_index_lookup_size = '10'") tk.MustExec("use test") tk.MustExec("create table dist (id int primary key, c_idx int, c_col int, index (c_idx))") @@ -706,40 +664,45 @@ func (s *seqTestSuite) TestIndexDoubleReadClose(c *C) { tk.MustExec("insert dist values " + strings.Join(values, ",")) rs, err := tk.Exec("select * from dist where c_idx between 0 and 100") - c.Assert(err, IsNil) + require.NoError(t, err) req := rs.NewChunk() err = rs.Next(context.Background(), req) - c.Assert(err, IsNil) - c.Assert(err, IsNil) + require.NoError(t, err) + require.NoError(t, err) keyword := "pickAndExecTask" - c.Assert(rs.Close(), IsNil) + require.NoError(t, rs.Close()) time.Sleep(time.Millisecond * 10) - c.Check(checkGoroutineExists(keyword), IsFalse) + require.False(t, checkGoroutineExists(keyword)) atomic.StoreInt32(&executor.LookupTableTaskChannelSize, originSize) } // TestIndexMergeReaderClose checks that when a partial index worker failed to start, the goroutine doesn't // leak. -func (s *seqTestSuite) TestIndexMergeReaderClose(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestIndexMergeReaderClose(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("drop table if exists t") tk.MustExec("create table t (a int, b int)") tk.MustExec("create index idx1 on t(a)") tk.MustExec("create index idx2 on t(b)") - c.Assert(failpoint.Enable("github.com/pingcap/tidb/executor/startPartialIndexWorkerErr", "return"), IsNil) + require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/executor/startPartialIndexWorkerErr", "return")) err := tk.QueryToErr("select /*+ USE_INDEX_MERGE(t, idx1, idx2) */ * from t where a > 10 or b < 100") - c.Assert(failpoint.Disable("github.com/pingcap/tidb/executor/startPartialIndexWorkerErr"), IsNil) - c.Assert(err, NotNil) - c.Check(checkGoroutineExists("fetchLoop"), IsFalse) - c.Check(checkGoroutineExists("fetchHandles"), IsFalse) - c.Check(checkGoroutineExists("waitPartialWorkersAndCloseFetchChan"), IsFalse) + require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/executor/startPartialIndexWorkerErr")) + require.Error(t, err) + require.False(t, checkGoroutineExists("fetchLoop")) + require.False(t, checkGoroutineExists("fetchHandles")) + require.False(t, checkGoroutineExists("waitPartialWorkersAndCloseFetchChan")) } -func (s *seqTestSuite) TestParallelHashAggClose(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) - tk.MustExec(`use test;`) - tk.MustExec(`drop table if exists t;`) +func TestParallelHashAggClose(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) + tk.MustExec(`use test`) + tk.MustExec(`drop table if exists t`) tk.MustExec("create table t(a int, b int)") tk.MustExec("insert into t values(1,1),(2,2)") // desc select sum(a) from (select cast(t.a as signed) as a, b from t) t group by b @@ -749,38 +712,40 @@ func (s *seqTestSuite) TestParallelHashAggClose(c *C) { // └─TableFullScan_10 | 3.00 | cop[tikv] | table:t, keep order:fa$se, stats:pseudo | // Goroutine should not leak when error happen. - c.Assert(failpoint.Enable("github.com/pingcap/tidb/executor/parallelHashAggError", `return(true)`), IsNil) + require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/executor/parallelHashAggError", `return(true)`)) defer func() { - c.Assert(failpoint.Disable("github.com/pingcap/tidb/executor/parallelHashAggError"), IsNil) + require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/executor/parallelHashAggError")) }() ctx := context.Background() - rss, err := tk.Se.Execute(ctx, "select sum(a) from (select cast(t.a as signed) as a, b from t) t group by b;") - c.Assert(err, IsNil) + rss, err := tk.Session().Execute(ctx, "select sum(a) from (select cast(t.a as signed) as a, b from t) t group by b;") + require.NoError(t, err) rs := rss[0] req := rs.NewChunk() err = rs.Next(ctx, req) - c.Assert(err.Error(), Equals, "HashAggExec.parallelExec error") + require.EqualError(t, err, "HashAggExec.parallelExec error") } -func (s *seqTestSuite) TestUnparallelHashAggClose(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) - tk.MustExec(`use test;`) - tk.MustExec(`drop table if exists t;`) +func TestUnparallelHashAggClose(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) + tk.MustExec(`use test`) + tk.MustExec(`drop table if exists t`) tk.MustExec("create table t(a int, b int)") tk.MustExec("insert into t values(1,1),(2,2)") // Goroutine should not leak when error happen. - c.Assert(failpoint.Enable("github.com/pingcap/tidb/executor/unparallelHashAggError", `return(true)`), IsNil) + require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/executor/unparallelHashAggError", `return(true)`)) defer func() { - c.Assert(failpoint.Disable("github.com/pingcap/tidb/executor/unparallelHashAggError"), IsNil) + require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/executor/unparallelHashAggError")) }() ctx := context.Background() - rss, err := tk.Se.Execute(ctx, "select sum(distinct a) from (select cast(t.a as signed) as a, b from t) t group by b;") - c.Assert(err, IsNil) + rss, err := tk.Session().Execute(ctx, "select sum(distinct a) from (select cast(t.a as signed) as a, b from t) t group by b;") + require.NoError(t, err) rs := rss[0] req := rs.NewChunk() err = rs.Next(ctx, req) - c.Assert(err.Error(), Equals, "HashAggExec.unparallelExec error") + require.EqualError(t, err, "HashAggExec.unparallelExec error") } func checkGoroutineExists(keyword string) bool { @@ -794,21 +759,24 @@ func checkGoroutineExists(keyword string) bool { return strings.Contains(str, keyword) } -func (s *seqTestSuite) TestAdminShowNextID(c *C) { - HelperTestAdminShowNextID(c, s, `admin show `) - HelperTestAdminShowNextID(c, s, `show table `) +func TestAdminShowNextID(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + + HelperTestAdminShowNextID(t, store, `admin show `) + HelperTestAdminShowNextID(t, store, `show table `) } -func HelperTestAdminShowNextID(c *C, s *seqTestSuite, str string) { - c.Assert(failpoint.Enable("github.com/pingcap/tidb/meta/autoid/mockAutoIDChange", `return(true)`), IsNil) +func HelperTestAdminShowNextID(t *testing.T, store kv.Storage, str string) { + require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/meta/autoid/mockAutoIDChange", `return(true)`)) defer func() { - c.Assert(failpoint.Disable("github.com/pingcap/tidb/meta/autoid/mockAutoIDChange"), IsNil) + require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/meta/autoid/mockAutoIDChange")) }() step := int64(10) autoIDStep := autoid.GetStep() autoid.SetStep(step) defer autoid.SetStep(autoIDStep) - tk := testkit.NewTestKit(c, s.store) + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("drop table if exists t,tt") tk.MustExec("create table t(id int, c int)") @@ -882,8 +850,11 @@ func HelperTestAdminShowNextID(c *C, s *seqTestSuite, str string) { r.Check(testkit.Rows("test1 seq1 _tidb_rowid 1 AUTO_INCREMENT", "test1 seq1 97 SEQUENCE")) } -func (s *seqTestSuite) TestNoHistoryWhenDisableRetry(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestNoHistoryWhenDisableRetry(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("drop table if exists history") tk.MustExec("create table history (a int)") @@ -892,46 +863,49 @@ func (s *seqTestSuite) TestNoHistoryWhenDisableRetry(c *C) { // retry_limit = 0 will not add history. tk.MustExec("set @@tidb_retry_limit = 0") tk.MustExec("insert history values (1)") - c.Assert(session.GetHistory(tk.Se).Count(), Equals, 0) + require.Equal(t, 0, session.GetHistory(tk.Session()).Count()) // Disable auto_retry will add history for auto committed only tk.MustExec("set @@autocommit = 1") tk.MustExec("set @@tidb_retry_limit = 10") tk.MustExec("set @@tidb_disable_txn_auto_retry = 1") - c.Assert(failpoint.Enable("github.com/pingcap/tidb/session/keepHistory", `return(true)`), IsNil) + require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/session/keepHistory", `return(true)`)) tk.MustExec("insert history values (1)") - c.Assert(session.GetHistory(tk.Se).Count(), Equals, 1) - c.Assert(failpoint.Disable("github.com/pingcap/tidb/session/keepHistory"), IsNil) + require.Equal(t, 1, session.GetHistory(tk.Session()).Count()) + require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/session/keepHistory")) tk.MustExec("begin") tk.MustExec("insert history values (1)") - c.Assert(session.GetHistory(tk.Se).Count(), Equals, 0) + require.Equal(t, 0, session.GetHistory(tk.Session()).Count()) tk.MustExec("commit") // Enable auto_retry will add history for both. tk.MustExec("set @@tidb_disable_txn_auto_retry = 0") - c.Assert(failpoint.Enable("github.com/pingcap/tidb/session/keepHistory", `return(true)`), IsNil) + require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/session/keepHistory", `return(true)`)) tk.MustExec("insert history values (1)") - c.Assert(failpoint.Disable("github.com/pingcap/tidb/session/keepHistory"), IsNil) - c.Assert(session.GetHistory(tk.Se).Count(), Equals, 1) + require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/session/keepHistory")) + require.Equal(t, 1, session.GetHistory(tk.Session()).Count()) tk.MustExec("begin") tk.MustExec("insert history values (1)") - c.Assert(session.GetHistory(tk.Se).Count(), Equals, 2) + require.Equal(t, 2, session.GetHistory(tk.Session()).Count()) tk.MustExec("commit") } -func (s *seqTestSuite) TestPrepareMaxParamCountCheck(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestPrepareMaxParamCountCheck(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("drop table if exists t") tk.MustExec("create table t (v int)") normalSQL, normalParams := generateBatchSQL(math.MaxUint16) _, err := tk.Exec(normalSQL, normalParams...) - c.Assert(err, IsNil) + require.NoError(t, err) bigSQL, bigParams := generateBatchSQL(math.MaxUint16 + 2) _, err = tk.Exec(bigSQL, bigParams...) - c.Assert(err, NotNil) - c.Assert(err.Error(), Equals, "[executor:1390]Prepared statement contains too many placeholders") + require.Error(t, err) + require.EqualError(t, err, "[executor:1390]Prepared statement contains too many placeholders") } func generateBatchSQL(paramCount int) (sql string, paramSlice []interface{}) { @@ -944,22 +918,28 @@ func generateBatchSQL(paramCount int) (sql string, paramSlice []interface{}) { return "insert into t values " + strings.Join(placeholders, ","), params } -func (s *seqTestSuite) TestCartesianProduct(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestCartesianProduct(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("drop table if exists t") tk.MustExec("create table t(c1 int)") plannercore.AllowCartesianProduct.Store(false) err := tk.ExecToErr("select * from t t1, t t2") - c.Check(plannercore.ErrCartesianProductUnsupported.Equal(err), IsTrue) + require.True(t, plannercore.ErrCartesianProductUnsupported.Equal(err)) err = tk.ExecToErr("select * from t t1 left join t t2 on 1") - c.Check(plannercore.ErrCartesianProductUnsupported.Equal(err), IsTrue) + require.True(t, plannercore.ErrCartesianProductUnsupported.Equal(err)) err = tk.ExecToErr("select * from t t1 right join t t2 on 1") - c.Check(plannercore.ErrCartesianProductUnsupported.Equal(err), IsTrue) + require.True(t, plannercore.ErrCartesianProductUnsupported.Equal(err)) plannercore.AllowCartesianProduct.Store(true) } -func (s *seqTestSuite) TestBatchInsertDelete(c *C) { +func TestBatchInsertDelete(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + originLimit := atomic.LoadUint64(&kv.TxnTotalSizeLimit) defer func() { atomic.StoreUint64(&kv.TxnTotalSizeLimit, originLimit) @@ -967,7 +947,7 @@ func (s *seqTestSuite) TestBatchInsertDelete(c *C) { // Set the limitation to a small value, make it easier to reach the limitation. atomic.StoreUint64(&kv.TxnTotalSizeLimit, 5500) - tk := testkit.NewTestKit(c, s.store) + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("drop table if exists batch_insert") tk.MustExec("create table batch_insert (c int)") @@ -1005,23 +985,23 @@ func (s *seqTestSuite) TestBatchInsertDelete(c *C) { // This will meet txn too large error. _, err := tk.Exec("insert into batch_insert (c) select * from batch_insert;") - c.Assert(err, NotNil) - c.Assert(kv.ErrTxnTooLarge.Equal(err), IsTrue) + require.Error(t, err) + require.True(t, kv.ErrTxnTooLarge.Equal(err)) r = tk.MustQuery("select count(*) from batch_insert;") r.Check(testkit.Rows("320")) // Test tidb_batch_insert could not work if enable-batch-dml is disabled. tk.MustExec("set @@session.tidb_batch_insert=1;") _, err = tk.Exec("insert into batch_insert (c) select * from batch_insert;") - c.Assert(err, NotNil) - c.Assert(kv.ErrTxnTooLarge.Equal(err), IsTrue) + require.Error(t, err) + require.True(t, kv.ErrTxnTooLarge.Equal(err)) tk.MustExec("set @@session.tidb_batch_insert=0;") // for on duplicate key _, err = tk.Exec(`insert into batch_insert_on_duplicate select * from batch_insert_on_duplicate as tt on duplicate key update batch_insert_on_duplicate.id=batch_insert_on_duplicate.id+1000;`) - c.Assert(err, NotNil) - c.Assert(kv.ErrTxnTooLarge.Equal(err), IsTrue, Commentf("%v", err)) + require.Error(t, err) + require.Truef(t, kv.ErrTxnTooLarge.Equal(err), "%v", err) r = tk.MustQuery("select count(*) from batch_insert;") r.Check(testkit.Rows("320")) @@ -1041,8 +1021,8 @@ func (s *seqTestSuite) TestBatchInsertDelete(c *C) { // So the insert will meet error. tk.MustExec("set @@session.tidb_dml_batch_size=600;") _, err = tk.Exec("insert into batch_insert (c) select * from batch_insert;") - c.Assert(err, NotNil) - c.Assert(kv.ErrTxnTooLarge.Equal(err), IsTrue) + require.Error(t, err) + require.True(t, kv.ErrTxnTooLarge.Equal(err)) r = tk.MustQuery("select count(*) from batch_insert;") r.Check(testkit.Rows("640")) // Set it back to 50. @@ -1051,15 +1031,15 @@ func (s *seqTestSuite) TestBatchInsertDelete(c *C) { // for on duplicate key _, err = tk.Exec(`insert into batch_insert_on_duplicate select * from batch_insert_on_duplicate as tt on duplicate key update batch_insert_on_duplicate.id=batch_insert_on_duplicate.id+1000;`) - c.Assert(err, IsNil) + require.NoError(t, err) r = tk.MustQuery("select count(*) from batch_insert_on_duplicate;") r.Check(testkit.Rows("320")) // Disable BachInsert mode in transition. tk.MustExec("begin;") _, err = tk.Exec("insert into batch_insert (c) select * from batch_insert;") - c.Assert(err, NotNil) - c.Assert(kv.ErrTxnTooLarge.Equal(err), IsTrue) + require.Error(t, err) + require.True(t, kv.ErrTxnTooLarge.Equal(err)) tk.MustExec("rollback;") r = tk.MustQuery("select count(*) from batch_insert;") r.Check(testkit.Rows("640")) @@ -1078,8 +1058,8 @@ func (s *seqTestSuite) TestBatchInsertDelete(c *C) { // Test case for batch delete. // This will meet txn too large error. _, err = tk.Exec("delete from batch_insert;") - c.Assert(err, NotNil) - c.Assert(kv.ErrTxnTooLarge.Equal(err), IsTrue) + require.Error(t, err) + require.True(t, kv.ErrTxnTooLarge.Equal(err)) r = tk.MustQuery("select count(*) from batch_insert;") r.Check(testkit.Rows("640")) // Enable batch delete and set batch size to 50. @@ -1125,36 +1105,15 @@ func (c *checkPrioClient) SendRequest(ctx context.Context, addr string, req *tik return resp, err } -type seqTestSuite1 struct { - store kv.Storage - dom *domain.Domain - cli *checkPrioClient -} - -func (s *seqTestSuite1) SetUpSuite(c *C) { +func TestCoprocessorPriority(t *testing.T) { cli := &checkPrioClient{} - hijackClient := func(c tikv.Client) tikv.Client { + store, clean := testkit.CreateMockStore(t, mockstore.WithClientHijacker(func(c tikv.Client) tikv.Client { cli.Client = c return cli - } - s.cli = cli - - var err error - s.store, err = mockstore.NewMockStore( - mockstore.WithClientHijacker(hijackClient), - ) - c.Assert(err, IsNil) - s.dom, err = session.BootstrapSession(s.store) - c.Assert(err, IsNil) -} - -func (s *seqTestSuite1) TearDownSuite(c *C) { - s.dom.Close() - s.store.Close() -} + })) + defer clean() -func (s *seqTestSuite1) TestCoprocessorPriority(c *C) { - tk := testkit.NewTestKit(c, s.store) + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("create table t (id int primary key)") tk.MustExec("create table t1 (id int, v int, unique index i_id (id))") @@ -1167,7 +1126,6 @@ func (s *seqTestSuite1) TestCoprocessorPriority(c *C) { tk.MustExec(fmt.Sprintf("insert into t1 values (%d, %d)", i, i)) } - cli := s.cli cli.mu.Lock() cli.mu.checkPrio = true cli.mu.Unlock() @@ -1238,11 +1196,14 @@ func (s *seqTestSuite1) TestCoprocessorPriority(c *C) { cli.mu.Unlock() } -func (s *seqTestSuite) TestShowForNewCollations(c *C) { +func TestShowForNewCollations(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + collate.SetNewCollationEnabledForTest(true) defer collate.SetNewCollationEnabledForTest(false) - tk := testkit.NewTestKit(c, s.store) + tk := testkit.NewTestKit(t, store) expectRows := testkit.Rows( "ascii_bin ascii 65 Yes Yes 1", "binary binary 63 Yes Yes 1", @@ -1258,11 +1219,14 @@ func (s *seqTestSuite) TestShowForNewCollations(c *C) { tk.MustQuery("select * from information_schema.COLLATIONS").Check(expectRows) } -func (s *seqTestSuite) TestForbidUnsupportedCollations(c *C) { +func TestForbidUnsupportedCollations(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + collate.SetNewCollationEnabledForTest(true) defer collate.SetNewCollationEnabledForTest(false) - tk := testkit.NewTestKit(c, s.store) + tk := testkit.NewTestKit(t, store) mustGetUnsupportedCollation := func(sql string, coll string) { tk.MustGetErrMsg(sql, fmt.Sprintf("[ddl:1273]Unsupported collation when new collation is enabled: '%s'", coll)) } @@ -1278,8 +1242,12 @@ func (s *seqTestSuite) TestForbidUnsupportedCollations(c *C) { mustGetUnsupportedCollation("set global collation_connection = 'utf8_roman_ci'", "utf8_roman_ci") } -func (s *seqTestSuite) TestAutoIncIDInRetry(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestAutoIncIDInRetry(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + + tk := testkit.NewTestKit(t, store) + tk.MustExec("use test") tk.MustExec("drop table if exists t;") tk.MustExec("create table t (id int not null auto_increment primary key)") @@ -1289,16 +1257,20 @@ func (s *seqTestSuite) TestAutoIncIDInRetry(c *C) { tk.MustExec("insert into t values (),()") tk.MustExec("insert into t values ()") - c.Assert(failpoint.Enable("github.com/pingcap/tidb/session/mockCommitRetryForAutoIncID", `return(true)`), IsNil) + require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/session/mockCommitRetryForAutoIncID", `return(true)`)) tk.MustExec("commit") - c.Assert(failpoint.Disable("github.com/pingcap/tidb/session/mockCommitRetryForAutoIncID"), IsNil) + require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/session/mockCommitRetryForAutoIncID")) tk.MustExec("insert into t values ()") tk.MustQuery(`select * from t`).Check(testkit.Rows("1", "2", "3", "4", "5")) } -func (s *seqTestSuite) TestPessimisticConflictRetryAutoID(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestPessimisticConflictRetryAutoID(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + + tk := testkit.NewTestKit(t, store) + tk.MustExec("use test") tk.MustExec("drop table if exists t;") tk.MustExec("create table t (id int not null auto_increment unique key, idx int unique key, c int);") concurrency := 2 @@ -1307,7 +1279,8 @@ func (s *seqTestSuite) TestPessimisticConflictRetryAutoID(c *C) { wg.Add(concurrency) err = make([]error, concurrency) for i := 0; i < concurrency; i++ { - tk := testkit.NewTestKitWithInit(c, s.store) + tk := testkit.NewTestKit(t, store) + tk.MustExec("use test") tk.MustExec("set tidb_txn_mode = 'pessimistic'") tk.MustExec("set autocommit = 1") go func(idx int) { @@ -1325,12 +1298,16 @@ func (s *seqTestSuite) TestPessimisticConflictRetryAutoID(c *C) { } wg.Wait() for _, e := range err { - c.Assert(e, IsNil) + require.NoError(t, e) } } -func (s *seqTestSuite) TestInsertFromSelectConflictRetryAutoID(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestInsertFromSelectConflictRetryAutoID(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + + tk := testkit.NewTestKit(t, store) + tk.MustExec("use test") tk.MustExec("drop table if exists t;") tk.MustExec("create table t (id int not null auto_increment unique key, idx int unique key, c int);") tk.MustExec("create table src (a int);") @@ -1341,7 +1318,8 @@ func (s *seqTestSuite) TestInsertFromSelectConflictRetryAutoID(c *C) { wg.Add(wgCount) err = make([]error, concurrency) for i := 0; i < concurrency; i++ { - tk := testkit.NewTestKitWithInit(c, s.store) + tk := testkit.NewTestKit(t, store) + tk.MustExec("use test") go func(idx int) { for i := 0; i < 10; i++ { sql := fmt.Sprintf("insert into t(idx, c) select 1 as idx, 1 as c from src on duplicate key update c = %[1]d", i) @@ -1357,7 +1335,8 @@ func (s *seqTestSuite) TestInsertFromSelectConflictRetryAutoID(c *C) { } var insertErr error go func() { - tk := testkit.NewTestKitWithInit(c, s.store) + tk := testkit.NewTestKit(t, store) + tk.MustExec("use test") for i := 0; i < 10; i++ { _, e := tk.Exec("insert into src values (null);") if e != nil { @@ -1370,22 +1349,25 @@ func (s *seqTestSuite) TestInsertFromSelectConflictRetryAutoID(c *C) { }() wg.Wait() for _, e := range err { - c.Assert(e, IsNil) + require.NoError(t, e) } - c.Assert(insertErr, IsNil) + require.NoError(t, insertErr) } -func (s *seqTestSuite) TestAutoRandIDRetry(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestAutoRandIDRetry(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) + tk.MustExec("use test") tk.MustExec("create database if not exists auto_random_retry") tk.MustExec("use auto_random_retry") tk.MustExec("drop table if exists t") tk.MustExec("create table t (id bigint auto_random(3) primary key clustered)") extractMaskedOrderedHandles := func() []int64 { - handles, err := ddltestutil.ExtractAllTableHandles(tk.Se, "auto_random_retry", "t") - c.Assert(err, IsNil) + handles, err := ddltestutil.ExtractAllTableHandles(tk.Session(), "auto_random_retry", "t") + require.NoError(t, err) return testutil.MaskSortHandles(handles, 3, mysql.TypeLong) } @@ -1398,28 +1380,31 @@ func (s *seqTestSuite) TestAutoRandIDRetry(c *C) { session.ResetMockAutoRandIDRetryCount(5) fpName := "github.com/pingcap/tidb/session/mockCommitRetryForAutoRandID" - c.Assert(failpoint.Enable(fpName, `return(true)`), IsNil) + require.NoError(t, failpoint.Enable(fpName, `return(true)`)) tk.MustExec("commit") - c.Assert(failpoint.Disable(fpName), IsNil) + require.NoError(t, failpoint.Disable(fpName)) tk.MustExec("insert into t values ()") maskedHandles := extractMaskedOrderedHandles() - c.Assert(maskedHandles, DeepEquals, []int64{1, 2, 3, 4, 5}) + require.Equal(t, []int64{1, 2, 3, 4, 5}, maskedHandles) session.ResetMockAutoRandIDRetryCount(11) tk.MustExec("begin") tk.MustExec("insert into t values ()") - c.Assert(failpoint.Enable(fpName, `return(true)`), IsNil) + require.NoError(t, failpoint.Enable(fpName, `return(true)`)) // Insertion failure will skip the 6 in retryInfo. tk.MustGetErrCode("commit", errno.ErrTxnRetryable) - c.Assert(failpoint.Disable(fpName), IsNil) + require.NoError(t, failpoint.Disable(fpName)) tk.MustExec("insert into t values ()") maskedHandles = extractMaskedOrderedHandles() - c.Assert(maskedHandles, DeepEquals, []int64{1, 2, 3, 4, 5, 7}) + require.Equal(t, []int64{1, 2, 3, 4, 5, 7}, maskedHandles) } -func (s *seqTestSuite) TestAutoRandRecoverTable(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestAutoRandRecoverTable(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + + tk := testkit.NewTestKit(t, store) tk.MustExec("create database if not exists test_recover") tk.MustExec("use test_recover") tk.MustExec("drop table if exists t_recover_auto_rand") @@ -1432,7 +1417,7 @@ func (s *seqTestSuite) TestAutoRandRecoverTable(c *C) { }(ddl.IsEmulatorGCEnable()) // Disable emulator GC. - // Otherwise emulator GC will delete table record as soon as possible after execute drop table ddl. + // Otherwise, emulator GC will delete table record as soon as possible after execute drop table ddl. ddl.EmulatorGCDisable() gcTimeFormat := "20060102-15:04:05 -0700 MST" timeBeforeDrop := time.Now().Add(0 - 48*60*60*time.Second).Format(gcTimeFormat) @@ -1442,12 +1427,12 @@ func (s *seqTestSuite) TestAutoRandRecoverTable(c *C) { // Set GC safe point. tk.MustExec(fmt.Sprintf(safePointSQL, timeBeforeDrop)) - err := gcutil.EnableGC(tk.Se) - c.Assert(err, IsNil) + err := gcutil.EnableGC(tk.Session()) + require.NoError(t, err) - c.Assert(failpoint.Enable("github.com/pingcap/tidb/meta/autoid/mockAutoIDChange", `return(true)`), IsNil) + require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/meta/autoid/mockAutoIDChange", `return(true)`)) defer func() { - c.Assert(failpoint.Disable("github.com/pingcap/tidb/meta/autoid/mockAutoIDChange"), IsNil) + require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/meta/autoid/mockAutoIDChange")) }() const autoRandIDStep = 5000 stp := autoid.GetStep() @@ -1460,56 +1445,65 @@ func (s *seqTestSuite) TestAutoRandRecoverTable(c *C) { tk.MustExec("drop table t_recover_auto_rand") tk.MustExec("recover table t_recover_auto_rand") tk.MustExec("insert into t_recover_auto_rand values (),(),()") - hs, err := ddltestutil.ExtractAllTableHandles(tk.Se, "test_recover", "t_recover_auto_rand") - c.Assert(err, IsNil) + hs, err := ddltestutil.ExtractAllTableHandles(tk.Session(), "test_recover", "t_recover_auto_rand") + require.NoError(t, err) ordered := testutil.MaskSortHandles(hs, 5, mysql.TypeLong) - c.Assert(ordered, DeepEquals, []int64{1, 2, 3, autoRandIDStep + 1, autoRandIDStep + 2, autoRandIDStep + 3}) + require.Equal(t, []int64{1, 2, 3, autoRandIDStep + 1, autoRandIDStep + 2, autoRandIDStep + 3}, ordered) } -func (s *seqTestSuite) TestMaxDeltaSchemaCount(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestMaxDeltaSchemaCount(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") - c.Assert(variable.GetMaxDeltaSchemaCount(), Equals, int64(variable.DefTiDBMaxDeltaSchemaCount)) + require.Equal(t, int64(variable.DefTiDBMaxDeltaSchemaCount), variable.GetMaxDeltaSchemaCount()) tk.MustExec("set @@global.tidb_max_delta_schema_count= -1") tk.MustQuery("show warnings;").Check(testkit.Rows("Warning 1292 Truncated incorrect tidb_max_delta_schema_count value: '-1'")) // Make sure a new session will load global variables. - tk.Se = nil + tk.RefreshSession() tk.MustExec("use test") - c.Assert(variable.GetMaxDeltaSchemaCount(), Equals, int64(100)) + require.Equal(t, int64(100), variable.GetMaxDeltaSchemaCount()) tk.MustExec(fmt.Sprintf("set @@global.tidb_max_delta_schema_count= %v", uint64(math.MaxInt64))) tk.MustQuery("show warnings;").Check(testkit.Rows(fmt.Sprintf("Warning 1292 Truncated incorrect tidb_max_delta_schema_count value: '%d'", uint64(math.MaxInt64)))) - tk.Se = nil + tk.RefreshSession() tk.MustExec("use test") - c.Assert(variable.GetMaxDeltaSchemaCount(), Equals, int64(16384)) + require.Equal(t, int64(16384), variable.GetMaxDeltaSchemaCount()) _, err := tk.Exec("set @@global.tidb_max_delta_schema_count= invalid_val") - c.Assert(terror.ErrorEqual(err, variable.ErrWrongTypeForVar), IsTrue, Commentf("err %v", err)) + require.Truef(t, terror.ErrorEqual(err, variable.ErrWrongTypeForVar), "err %v", err) tk.MustExec("set @@global.tidb_max_delta_schema_count= 2048") - tk.Se = nil + tk.RefreshSession() tk.MustExec("use test") - c.Assert(variable.GetMaxDeltaSchemaCount(), Equals, int64(2048)) + require.Equal(t, int64(2048), variable.GetMaxDeltaSchemaCount()) tk.MustQuery("select @@global.tidb_max_delta_schema_count").Check(testkit.Rows("2048")) } -func (s *seqTestSuite) TestOOMPanicInHashJoinWhenFetchBuildRows(c *C) { +func TestOOMPanicInHashJoinWhenFetchBuildRows(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + fpName := "github.com/pingcap/tidb/executor/errorFetchBuildSideRowsMockOOMPanic" - c.Assert(failpoint.Enable(fpName, `panic("ERROR 1105 (HY000): Out Of Memory Quota![conn_id=1]")`), IsNil) + require.NoError(t, failpoint.Enable(fpName, `panic("ERROR 1105 (HY000): Out Of Memory Quota![conn_id=1]")`)) defer func() { - c.Assert(failpoint.Disable(fpName), IsNil) + require.NoError(t, failpoint.Disable(fpName)) }() - tk := testkit.NewTestKit(c, s.store) + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("drop table if exists t") tk.MustExec("create table t(c1 int, c2 int)") tk.MustExec("insert into t values(1,1),(2,2)") err := tk.QueryToErr("select * from t as t2 join t as t1 where t1.c1=t2.c1") - c.Assert(err.Error(), Equals, "failpoint panic: ERROR 1105 (HY000): Out Of Memory Quota![conn_id=1]") + require.EqualError(t, err, "failpoint panic: ERROR 1105 (HY000): Out Of Memory Quota![conn_id=1]") } -func (s *seqTestSuite) TestIssue18744(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestIssue18744(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + + tk := testkit.NewTestKit(t, store) tk.MustExec(`use test;`) tk.MustExec(`drop table if exists t, t1;`) tk.MustExec(`CREATE TABLE t ( @@ -1547,16 +1541,19 @@ func (s *seqTestSuite) TestIssue18744(c *C) { tk.MustExec(`insert into t values(1 , NULL , NULL , NULL , NULL , NULL , NULL);`) tk.MustExec(`insert into t values(2 , 2012 , "2012-01-01 01:01:00" , "2012-01-01 01:01:00" , 2012 , 2012 , 2012.000000);`) tk.MustExec(`set tidb_index_lookup_join_concurrency=1`) - c.Assert(failpoint.Enable("github.com/pingcap/tidb/executor/testIndexHashJoinOuterWorkerErr", "return"), IsNil) + require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/executor/testIndexHashJoinOuterWorkerErr", "return")) defer func() { - c.Assert(failpoint.Disable("github.com/pingcap/tidb/executor/testIndexHashJoinOuterWorkerErr"), IsNil) + require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/executor/testIndexHashJoinOuterWorkerErr")) }() err := tk.QueryToErr(`select /*+ inl_hash_join(t2) */ t1.id, t2.id from t1 join t t2 on t1.a = t2.a order by t1.a ASC limit 1;`) - c.Assert(err.Error(), Equals, "mockIndexHashJoinOuterWorkerErr") + require.EqualError(t, err, "mockIndexHashJoinOuterWorkerErr") } -func (s *seqTestSuite) TestIssue19410(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestIssue19410(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("drop table if exists t, t1, t2, t3;") tk.MustExec("create table t(a int, b enum('A', 'B'));") diff --git a/testkit/testkit.go b/testkit/testkit.go index 273b10f25294a..ea4a1f6a58623 100644 --- a/testkit/testkit.go +++ b/testkit/testkit.go @@ -39,6 +39,7 @@ var testKitIDGenerator atomic.Uint64 type TestKit struct { require *require.Assertions assert *assert.Assertions + t *testing.T store kv.Storage session session.Session } @@ -48,12 +49,22 @@ func NewTestKit(t *testing.T, store kv.Storage) *TestKit { return &TestKit{ require: require.New(t), assert: assert.New(t), + t: t, store: store, session: newSession(t, store), } } -// Session return a session +func (tk *TestKit) RefreshSession() { + tk.session = newSession(tk.t, tk.store) +} + +// SetSession set the session of testkit +func (tk *TestKit) SetSession(session session.Session) { + tk.session = session +} + +// Session return the session associated with the testkit func (tk *TestKit) Session() session.Session { return tk.session } @@ -178,6 +189,13 @@ func newSession(t *testing.T, store kv.Storage) session.Session { return se } +// RefreshConnectionID refresh the connection ID for session of the testkit +func (tk *TestKit) RefreshConnectionID() { + if tk.session != nil { + tk.session.SetConnectionID(testKitIDGenerator.Inc()) + } +} + // MustGetErrCode executes a sql statement and assert it's error code. func (tk *TestKit) MustGetErrCode(sql string, errCode int) { _, err := tk.Exec(sql) diff --git a/util/testkit/testkit.go b/util/testkit/testkit.go index 529011ee05fbb..5a670db4b5eb6 100644 --- a/util/testkit/testkit.go +++ b/util/testkit/testkit.go @@ -168,6 +168,7 @@ func MockGC(tk *TestKit) (string, string, string, func()) { var connectionID uint64 // GetConnectionID get the connection ID for tk.Se +// NOTE: Use RefreshConnectionID when migrate to pingcap/tidb/testkit func (tk *TestKit) GetConnectionID() { if tk.Se != nil { id := atomic.AddUint64(&connectionID, 1) From d4ec3be1495aea25c99dfd3f253feb86685c8289 Mon Sep 17 00:00:00 2001 From: tison Date: Thu, 23 Sep 2021 23:00:26 +0800 Subject: [PATCH 2/5] fix comment Signed-off-by: tison --- testkit/testkit.go | 1 + 1 file changed, 1 insertion(+) diff --git a/testkit/testkit.go b/testkit/testkit.go index ea4a1f6a58623..ac8670312bb81 100644 --- a/testkit/testkit.go +++ b/testkit/testkit.go @@ -55,6 +55,7 @@ func NewTestKit(t *testing.T, store kv.Storage) *TestKit { } } +// RefreshSession set a new session for the testkit func (tk *TestKit) RefreshSession() { tk.session = newSession(tk.t, tk.store) } From 8050194e20491f06adcad55514bc9954bdcb97e0 Mon Sep 17 00:00:00 2001 From: tison Date: Thu, 23 Sep 2021 23:39:51 +0800 Subject: [PATCH 3/5] turn on checks that is valid now Signed-off-by: tison --- executor/seqtest/prepared_serial_test.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/executor/seqtest/prepared_serial_test.go b/executor/seqtest/prepared_serial_test.go index fca8e91300f72..3fd458ec4e3b9 100644 --- a/executor/seqtest/prepared_serial_test.go +++ b/executor/seqtest/prepared_serial_test.go @@ -907,8 +907,7 @@ func TestPreparedIssue17419(t *testing.T) { dom.ExpensiveQueryHandle().LogOnQueryExceedMemQuota(tk.Session().GetSessionVars().ConnectionID) - // After entirely fixing https://github.com/pingcap/tidb/issues/17419 - // c.Assert(tk1.Se.ShowProcess().Plan, NotNil) - // _, ok := tk1.Se.ShowProcess().Plan.(*plannercore.Execute) - // require.True(t, ok) + require.NotNil(t, tk1.Session().ShowProcess().Plan) + _, ok := tk1.Session().ShowProcess().Plan.(*plannercore.Execute) + require.True(t, ok) } From 680993fed52d1ccfc92a2b4ec47a6ae1f865ceb3 Mon Sep 17 00:00:00 2001 From: tison Date: Thu, 23 Sep 2021 23:52:58 +0800 Subject: [PATCH 4/5] not fix yet Signed-off-by: tison --- executor/seqtest/prepared_serial_test.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/executor/seqtest/prepared_serial_test.go b/executor/seqtest/prepared_serial_test.go index 3fd458ec4e3b9..41530153e401b 100644 --- a/executor/seqtest/prepared_serial_test.go +++ b/executor/seqtest/prepared_serial_test.go @@ -907,7 +907,8 @@ func TestPreparedIssue17419(t *testing.T) { dom.ExpensiveQueryHandle().LogOnQueryExceedMemQuota(tk.Session().GetSessionVars().ConnectionID) - require.NotNil(t, tk1.Session().ShowProcess().Plan) - _, ok := tk1.Session().ShowProcess().Plan.(*plannercore.Execute) - require.True(t, ok) + // After entirely fixing https://github.com/pingcap/tidb/issues/17419 + // require.NotNil(t, tk1.Session().ShowProcess().Plan) + // _, ok := tk1.Session().ShowProcess().Plan.(*plannercore.Execute) + // require.True(t, ok) } From 9972081469ef2e96ec841330af8c767c50e8046f Mon Sep 17 00:00:00 2001 From: tison Date: Tue, 28 Sep 2021 07:22:42 +0800 Subject: [PATCH 5/5] remove redundant setup Signed-off-by: tison --- executor/seqtest/prepared_serial_test.go | 5 ----- testkit/testkit.go | 7 ------- util/testkit/testkit.go | 1 - 3 files changed, 13 deletions(-) diff --git a/executor/seqtest/prepared_serial_test.go b/executor/seqtest/prepared_serial_test.go index 41530153e401b..138f8515f008a 100644 --- a/executor/seqtest/prepared_serial_test.go +++ b/executor/seqtest/prepared_serial_test.go @@ -885,11 +885,6 @@ func TestPreparedIssue17419(t *testing.T) { tk1 := testkit.NewTestKit(t, store) - se, err := session.CreateSession4Test(store) - require.NoError(t, err) - tk1.SetSession(se) - tk1.RefreshConnectionID() - query := "select * from test.t" stmtID, _, _, err := tk1.Session().PrepareStmt(query) require.NoError(t, err) diff --git a/testkit/testkit.go b/testkit/testkit.go index ac8670312bb81..a6dc01c5076f9 100644 --- a/testkit/testkit.go +++ b/testkit/testkit.go @@ -190,13 +190,6 @@ func newSession(t *testing.T, store kv.Storage) session.Session { return se } -// RefreshConnectionID refresh the connection ID for session of the testkit -func (tk *TestKit) RefreshConnectionID() { - if tk.session != nil { - tk.session.SetConnectionID(testKitIDGenerator.Inc()) - } -} - // MustGetErrCode executes a sql statement and assert it's error code. func (tk *TestKit) MustGetErrCode(sql string, errCode int) { _, err := tk.Exec(sql) diff --git a/util/testkit/testkit.go b/util/testkit/testkit.go index 5a670db4b5eb6..529011ee05fbb 100644 --- a/util/testkit/testkit.go +++ b/util/testkit/testkit.go @@ -168,7 +168,6 @@ func MockGC(tk *TestKit) (string, string, string, func()) { var connectionID uint64 // GetConnectionID get the connection ID for tk.Se -// NOTE: Use RefreshConnectionID when migrate to pingcap/tidb/testkit func (tk *TestKit) GetConnectionID() { if tk.Se != nil { id := atomic.AddUint64(&connectionID, 1)