-
Notifications
You must be signed in to change notification settings - Fork 5.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
executor: migrate TestBatchInsertWithOnDuplicate to testify #26712
Merged
+332
−291
Merged
Changes from 15 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
99e7967
executor: introduce TestMain
tisonkun 49f6a1a
factor out CreateMockStore
tisonkun 570a4e5
executor: migrate TestBatchInsertWithOnDuplicate to testify
tisonkun fbe2f7e
go fmt
tisonkun 602d8dc
golinter
tisonkun c110a9d
Merge branch 'master' into issue-26160
ti-chi-bot 09407d7
Merge branch 'master' into issue-26160
ti-chi-bot 166b8cc
Merge branch 'master' into issue-26160
ti-chi-bot 912f1ba
Merge branch 'master' into issue-26160
ti-chi-bot dff0345
ignore new leak assertTemporaryTableNoNetwork.func2
tisonkun 4458f19
ignore new leak assertTemporaryTableNoNetwork.func2
tisonkun 96783c8
Merge branch 'master' into issue-26160
tisonkun 4bdc7ee
goleak verify only TestBatchInsertWithOnDuplicate for now
tisonkun f6b55b2
ignore functions
tisonkun f70c4ae
remove goleak
tisonkun 3fae080
Merge branch 'master' into issue-26160
ti-chi-bot 03ca5a3
Merge branch 'master' into issue-26160
ti-chi-bot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
// 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, | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package executor | ||
|
||
import ( | ||
"os" | ||
"testing" | ||
|
||
"github.com/pingcap/tidb/util/testbridge" | ||
) | ||
|
||
func TestMain(m *testing.M) { | ||
testbridge.WorkaroundGoCheckFlags() | ||
os.Exit(m.Run()) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,226 @@ | ||
// 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, | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
// +build !codes | ||
|
||
package testkit | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"testing" | ||
|
||
"github.com/pingcap/errors" | ||
"github.com/pingcap/tidb/kv" | ||
"github.com/pingcap/tidb/session" | ||
"github.com/pingcap/tidb/types" | ||
"github.com/pingcap/tidb/util" | ||
"github.com/pingcap/tidb/util/sqlexec" | ||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
"go.uber.org/atomic" | ||
) | ||
|
||
var asyncTestKitIDGenerator atomic.Uint64 | ||
|
||
// AsyncTestKit is a utility to run sql concurrently. | ||
type AsyncTestKit struct { | ||
require *require.Assertions | ||
assert *assert.Assertions | ||
store kv.Storage | ||
} | ||
|
||
// NewAsyncTestKit returns a new *AsyncTestKit. | ||
func NewAsyncTestKit(t *testing.T, store kv.Storage) *AsyncTestKit { | ||
return &AsyncTestKit{ | ||
require: require.New(t), | ||
assert: assert.New(t), | ||
store: store, | ||
} | ||
} | ||
|
||
// OpenSession opens new session ctx if no exists one and use db. | ||
func (tk *AsyncTestKit) OpenSession(ctx context.Context, db string) context.Context { | ||
if tryRetrieveSession(ctx) == nil { | ||
se, err := session.CreateSession4Test(tk.store) | ||
tk.require.NoError(err) | ||
se.SetConnectionID(asyncTestKitIDGenerator.Inc()) | ||
ctx = context.WithValue(ctx, sessionKey, se) | ||
} | ||
tk.MustExec(ctx, fmt.Sprintf("use %s", db)) | ||
return ctx | ||
} | ||
|
||
// CloseSession closes exists session from ctx. | ||
func (tk *AsyncTestKit) CloseSession(ctx context.Context) { | ||
se := tryRetrieveSession(ctx) | ||
tk.require.NotNil(se) | ||
se.Close() | ||
} | ||
|
||
// ConcurrentRun run test in current. | ||
// - concurrent: controls the concurrent worker count. | ||
// - loops: controls run test how much times. | ||
// - prepareFunc: provide test data and will be called for every loop. | ||
// - checkFunc: used to do some check after all workers done. | ||
// works like create table better be put in front of this method calling. | ||
// see more example at TestBatchInsertWithOnDuplicate | ||
func (tk *AsyncTestKit) ConcurrentRun( | ||
concurrent int, | ||
loops int, | ||
prepareFunc func(ctx context.Context, tk *AsyncTestKit, concurrent int, currentLoop int) [][][]interface{}, | ||
writeFunc func(ctx context.Context, tk *AsyncTestKit, input [][]interface{}), | ||
checkFunc func(ctx context.Context, tk *AsyncTestKit), | ||
) { | ||
channel := make([]chan [][]interface{}, concurrent) | ||
contextList := make([]context.Context, concurrent) | ||
doneList := make([]context.CancelFunc, concurrent) | ||
|
||
for i := 0; i < concurrent; i++ { | ||
w := i | ||
channel[w] = make(chan [][]interface{}, 1) | ||
contextList[w], doneList[w] = context.WithCancel(context.Background()) | ||
contextList[w] = tk.OpenSession(contextList[w], "test") | ||
go func() { | ||
defer func() { | ||
r := recover() | ||
tk.require.Nil(r, string(util.GetStack())) | ||
doneList[w]() | ||
}() | ||
|
||
for input := range channel[w] { | ||
writeFunc(contextList[w], tk, input) | ||
} | ||
}() | ||
} | ||
|
||
defer func() { | ||
for i := 0; i < concurrent; i++ { | ||
tk.CloseSession(contextList[i]) | ||
} | ||
}() | ||
|
||
ctx := tk.OpenSession(context.Background(), "test") | ||
defer tk.CloseSession(ctx) | ||
tk.MustExec(ctx, "use test") | ||
|
||
for j := 0; j < loops; j++ { | ||
data := prepareFunc(ctx, tk, concurrent, j) | ||
for i := 0; i < concurrent; i++ { | ||
channel[i] <- data[i] | ||
} | ||
} | ||
|
||
for i := 0; i < concurrent; i++ { | ||
close(channel[i]) | ||
} | ||
|
||
for i := 0; i < concurrent; i++ { | ||
<-contextList[i].Done() | ||
} | ||
checkFunc(ctx, tk) | ||
} | ||
|
||
// Exec executes a sql statement. | ||
func (tk *AsyncTestKit) Exec(ctx context.Context, sql string, args ...interface{}) (sqlexec.RecordSet, error) { | ||
se := tryRetrieveSession(ctx) | ||
tk.require.NotNil(se) | ||
|
||
if len(args) == 0 { | ||
rss, err := se.Execute(ctx, sql) | ||
if err == nil && len(rss) > 0 { | ||
return rss[0], nil | ||
} | ||
return nil, err | ||
} | ||
|
||
stmtID, _, _, err := se.PrepareStmt(sql) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
params := make([]types.Datum, len(args)) | ||
for i := 0; i < len(params); i++ { | ||
params[i] = types.NewDatum(args[i]) | ||
} | ||
|
||
rs, err := se.ExecutePreparedStmt(ctx, stmtID, params) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
err = se.DropPreparedStmt(stmtID) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
return rs, nil | ||
} | ||
|
||
// MustExec executes a sql statement and asserts nil error. | ||
func (tk *AsyncTestKit) MustExec(ctx context.Context, sql string, args ...interface{}) { | ||
res, err := tk.Exec(ctx, sql, args...) | ||
tk.require.NoErrorf(err, "sql:%s, %v, error stack %v", sql, args, errors.ErrorStack(err)) | ||
if res != nil { | ||
tk.require.NoError(res.Close()) | ||
} | ||
} | ||
|
||
// MustQuery query the statements and returns result rows. | ||
// If expected result is set it asserts the query result equals expected result. | ||
func (tk *AsyncTestKit) MustQuery(ctx context.Context, sql string, args ...interface{}) *Result { | ||
comment := fmt.Sprintf("sql:%s, args:%v", sql, args) | ||
rs, err := tk.Exec(ctx, sql, args...) | ||
tk.require.NoError(err, comment) | ||
tk.require.NotNil(rs, comment) | ||
return tk.resultSetToResult(ctx, rs, comment) | ||
} | ||
|
||
// resultSetToResult converts ast.RecordSet to testkit.Result. | ||
// It is used to check results of execute statement in binary mode. | ||
func (tk *AsyncTestKit) resultSetToResult(ctx context.Context, rs sqlexec.RecordSet, comment string) *Result { | ||
rows, err := session.GetRows4Test(context.Background(), tryRetrieveSession(ctx), rs) | ||
tk.require.NoError(err, comment) | ||
|
||
err = rs.Close() | ||
tk.require.NoError(err, comment) | ||
|
||
result := make([][]string, len(rows)) | ||
for i := range rows { | ||
row := rows[i] | ||
resultRow := make([]string, row.Len()) | ||
for j := 0; j < row.Len(); j++ { | ||
if row.IsNull(j) { | ||
resultRow[j] = "<nil>" | ||
} else { | ||
d := row.GetDatum(j, &rs.Fields()[j].Column.FieldType) | ||
resultRow[j], err = d.ToString() | ||
tk.require.NoError(err, comment) | ||
} | ||
} | ||
result[i] = resultRow | ||
} | ||
return &Result{rows: result, comment: comment, assert: tk.assert, require: tk.require} | ||
} | ||
|
||
type sessionCtxKeyType struct{} | ||
|
||
var sessionKey = sessionCtxKeyType{} | ||
|
||
func tryRetrieveSession(ctx context.Context) session.Session { | ||
s := ctx.Value(sessionKey) | ||
if s == nil { | ||
return nil | ||
} | ||
return s.(session.Session) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
// 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, | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
// +build !codes | ||
|
||
package testkit | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/pingcap/tidb/kv" | ||
"github.com/pingcap/tidb/session" | ||
"github.com/pingcap/tidb/store/mockstore" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
// CreateMockStore return a new mock kv.Storage. | ||
func CreateMockStore(t *testing.T) (store kv.Storage, clean func()) { | ||
store, err := mockstore.NewMockStore() | ||
require.NoError(t, err) | ||
|
||
session.SetSchemaLease(0) | ||
session.DisableStats4Test() | ||
d, err := session.BootstrapSession(store) | ||
require.NoError(t, err) | ||
|
||
d.SetStatsUpdating(true) | ||
|
||
clean = func() { | ||
d.Close() | ||
err := store.Close() | ||
require.NoError(t, err) | ||
} | ||
|
||
return | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I have a concern this will make our CI take a lot of time than before.
In the past, one test suite create one store/domain.
If after the refactor, each test case create one store/domain, the operation is heavier than before...
session.BootstrapSession
is not cheap.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We can solve it later, through~
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
OK. I'll think of reusing store/domain between tests. Maybe we come back to batch several tests in serial with testify suite.