mysql_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package sqlx
  2. import (
  3. "errors"
  4. "reflect"
  5. "testing"
  6. "git.i2edu.net/i2/go-zero/core/breaker"
  7. "git.i2edu.net/i2/go-zero/core/logx"
  8. "git.i2edu.net/i2/go-zero/core/stat"
  9. "github.com/go-sql-driver/mysql"
  10. "github.com/stretchr/testify/assert"
  11. )
  12. func init() {
  13. stat.SetReporter(nil)
  14. }
  15. func TestBreakerOnDuplicateEntry(t *testing.T) {
  16. logx.Disable()
  17. err := tryOnDuplicateEntryError(t, mysqlAcceptable)
  18. assert.Equal(t, duplicateEntryCode, err.(*mysql.MySQLError).Number)
  19. }
  20. func TestBreakerOnNotHandlingDuplicateEntry(t *testing.T) {
  21. logx.Disable()
  22. var found bool
  23. for i := 0; i < 100; i++ {
  24. if tryOnDuplicateEntryError(t, nil) == breaker.ErrServiceUnavailable {
  25. found = true
  26. }
  27. }
  28. assert.True(t, found)
  29. }
  30. func TestMysqlAcceptable(t *testing.T) {
  31. conn := NewMysql("nomysql").(*commonSqlConn)
  32. withMysqlAcceptable()(conn)
  33. assert.EqualValues(t, reflect.ValueOf(mysqlAcceptable).Pointer(), reflect.ValueOf(conn.accept).Pointer())
  34. assert.True(t, mysqlAcceptable(nil))
  35. assert.False(t, mysqlAcceptable(errors.New("any")))
  36. assert.False(t, mysqlAcceptable(new(mysql.MySQLError)))
  37. }
  38. func tryOnDuplicateEntryError(t *testing.T, accept func(error) bool) error {
  39. logx.Disable()
  40. conn := commonSqlConn{
  41. brk: breaker.NewBreaker(),
  42. accept: accept,
  43. }
  44. for i := 0; i < 1000; i++ {
  45. assert.NotNil(t, conn.brk.DoWithAcceptable(func() error {
  46. return &mysql.MySQLError{
  47. Number: duplicateEntryCode,
  48. }
  49. }, conn.acceptable))
  50. }
  51. return conn.brk.DoWithAcceptable(func() error {
  52. return &mysql.MySQLError{
  53. Number: duplicateEntryCode,
  54. }
  55. }, conn.acceptable)
  56. }