tx_test.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package sqlx
  2. import (
  3. "database/sql"
  4. "errors"
  5. "testing"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. const (
  9. mockCommit = 1
  10. mockRollback = 2
  11. )
  12. type mockTx struct {
  13. status int
  14. }
  15. func (mt *mockTx) Commit() error {
  16. mt.status |= mockCommit
  17. return nil
  18. }
  19. func (mt *mockTx) Exec(q string, args ...interface{}) (sql.Result, error) {
  20. return nil, nil
  21. }
  22. func (mt *mockTx) Prepare(query string) (StmtSession, error) {
  23. return nil, nil
  24. }
  25. func (mt *mockTx) QueryRow(v interface{}, q string, args ...interface{}) error {
  26. return nil
  27. }
  28. func (mt *mockTx) QueryRowPartial(v interface{}, q string, args ...interface{}) error {
  29. return nil
  30. }
  31. func (mt *mockTx) QueryRows(v interface{}, q string, args ...interface{}) error {
  32. return nil
  33. }
  34. func (mt *mockTx) QueryRowsPartial(v interface{}, q string, args ...interface{}) error {
  35. return nil
  36. }
  37. func (mt *mockTx) Rollback() error {
  38. mt.status |= mockRollback
  39. return nil
  40. }
  41. func beginMock(mock *mockTx) beginnable {
  42. return func(*sql.DB) (trans, error) {
  43. return mock, nil
  44. }
  45. }
  46. func TestTransactCommit(t *testing.T) {
  47. mock := &mockTx{}
  48. err := transactOnConn(nil, beginMock(mock), func(Session) error {
  49. return nil
  50. })
  51. assert.Equal(t, mockCommit, mock.status)
  52. assert.Nil(t, err)
  53. }
  54. func TestTransactRollback(t *testing.T) {
  55. mock := &mockTx{}
  56. err := transactOnConn(nil, beginMock(mock), func(Session) error {
  57. return errors.New("rollback")
  58. })
  59. assert.Equal(t, mockRollback, mock.status)
  60. assert.NotNil(t, err)
  61. }