Files
go-zero/core/stores/sqlx/mysql_test.go

67 lines
1.6 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package sqlx
import (
"errors"
"reflect"
2020-07-26 17:09:05 +08:00
"testing"
"github.com/go-sql-driver/mysql"
"github.com/stretchr/testify/assert"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/core/breaker"
"github.com/tal-tech/go-zero/core/logx"
"github.com/tal-tech/go-zero/core/stat"
2020-07-26 17:09:05 +08:00
)
func init() {
stat.SetReporter(nil)
}
func TestBreakerOnDuplicateEntry(t *testing.T) {
logx.Disable()
err := tryOnDuplicateEntryError(t, mysqlAcceptable)
assert.Equal(t, duplicateEntryCode, err.(*mysql.MySQLError).Number)
}
func TestBreakerOnNotHandlingDuplicateEntry(t *testing.T) {
logx.Disable()
var found bool
for i := 0; i < 100; i++ {
if tryOnDuplicateEntryError(t, nil) == breaker.ErrServiceUnavailable {
found = true
}
}
assert.True(t, found)
}
func TestMysqlAcceptable(t *testing.T) {
conn := NewMysql("nomysql").(*commonSqlConn)
withMysqlAcceptable()(conn)
assert.EqualValues(t, reflect.ValueOf(mysqlAcceptable).Pointer(), reflect.ValueOf(conn.accept).Pointer())
assert.True(t, mysqlAcceptable(nil))
assert.False(t, mysqlAcceptable(errors.New("any")))
assert.False(t, mysqlAcceptable(new(mysql.MySQLError)))
}
2020-07-26 17:09:05 +08:00
func tryOnDuplicateEntryError(t *testing.T, accept func(error) bool) error {
logx.Disable()
conn := commonSqlConn{
brk: breaker.NewBreaker(),
accept: accept,
}
for i := 0; i < 1000; i++ {
assert.NotNil(t, conn.brk.DoWithAcceptable(func() error {
return &mysql.MySQLError{
Number: duplicateEntryCode,
}
}, conn.acceptable))
}
return conn.brk.DoWithAcceptable(func() error {
return &mysql.MySQLError{
Number: duplicateEntryCode,
}
}, conn.acceptable)
}