sqlconn_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package sqlx
  2. import (
  3. "database/sql"
  4. "io"
  5. "testing"
  6. "github.com/DATA-DOG/go-sqlmock"
  7. "github.com/stretchr/testify/assert"
  8. "github.com/tal-tech/go-zero/core/logx"
  9. )
  10. const mockedDatasource = "sqlmock"
  11. func init() {
  12. logx.Disable()
  13. }
  14. func TestSqlConn(t *testing.T) {
  15. mock := buildConn()
  16. mock.ExpectExec("any")
  17. mock.ExpectQuery("any").WillReturnRows(sqlmock.NewRows([]string{"foo"}))
  18. conn := NewMysql(mockedDatasource)
  19. badConn := NewMysql("badsql")
  20. _, err := conn.Exec("any", "value")
  21. assert.NotNil(t, err)
  22. _, err = badConn.Exec("any", "value")
  23. assert.NotNil(t, err)
  24. _, err = conn.Prepare("any")
  25. assert.NotNil(t, err)
  26. _, err = badConn.Prepare("any")
  27. assert.NotNil(t, err)
  28. var val string
  29. assert.NotNil(t, conn.QueryRow(&val, "any"))
  30. assert.NotNil(t, badConn.QueryRow(&val, "any"))
  31. assert.NotNil(t, conn.QueryRowPartial(&val, "any"))
  32. assert.NotNil(t, badConn.QueryRowPartial(&val, "any"))
  33. assert.NotNil(t, conn.QueryRows(&val, "any"))
  34. assert.NotNil(t, badConn.QueryRows(&val, "any"))
  35. assert.NotNil(t, conn.QueryRowsPartial(&val, "any"))
  36. assert.NotNil(t, badConn.QueryRowsPartial(&val, "any"))
  37. assert.NotNil(t, conn.Transact(func(session Session) error {
  38. return nil
  39. }))
  40. assert.NotNil(t, badConn.Transact(func(session Session) error {
  41. return nil
  42. }))
  43. }
  44. func buildConn() (mock sqlmock.Sqlmock) {
  45. connManager.GetResource(mockedDatasource, func() (io.Closer, error) {
  46. var db *sql.DB
  47. var err error
  48. db, mock, err = sqlmock.New()
  49. return &pingedDB{
  50. DB: db,
  51. }, err
  52. })
  53. return
  54. }