utils_test.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package sqlx
  2. import (
  3. "strings"
  4. "testing"
  5. "github.com/stretchr/testify/assert"
  6. )
  7. func TestEscape(t *testing.T) {
  8. s := "a\x00\n\r\\'\"\x1ab"
  9. out := escape(s)
  10. assert.Equal(t, `a\x00\n\r\\\'\"\x1ab`, out)
  11. }
  12. func TestDesensitize(t *testing.T) {
  13. datasource := "user:pass@tcp(111.222.333.44:3306)/any_table?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai"
  14. datasource = desensitize(datasource)
  15. assert.False(t, strings.Contains(datasource, "user"))
  16. assert.False(t, strings.Contains(datasource, "pass"))
  17. assert.True(t, strings.Contains(datasource, "tcp(111.222.333.44:3306)"))
  18. }
  19. func TestDesensitize_WithoutAccount(t *testing.T) {
  20. datasource := "tcp(111.222.333.44:3306)/any_table?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai"
  21. datasource = desensitize(datasource)
  22. assert.True(t, strings.Contains(datasource, "tcp(111.222.333.44:3306)"))
  23. }
  24. func TestFormat(t *testing.T) {
  25. tests := []struct {
  26. name string
  27. query string
  28. args []interface{}
  29. expect string
  30. hasErr bool
  31. }{
  32. {
  33. name: "mysql normal",
  34. query: "select name, age from users where bool=? and phone=?",
  35. args: []interface{}{true, "133"},
  36. expect: "select name, age from users where bool=1 and phone='133'",
  37. },
  38. {
  39. name: "mysql normal",
  40. query: "select name, age from users where bool=? and phone=?",
  41. args: []interface{}{false, "133"},
  42. expect: "select name, age from users where bool=0 and phone='133'",
  43. },
  44. {
  45. name: "pg normal",
  46. query: "select name, age from users where bool=$1 and phone=$2",
  47. args: []interface{}{true, "133"},
  48. expect: "select name, age from users where bool=1 and phone='133'",
  49. },
  50. {
  51. name: "pg normal reverse",
  52. query: "select name, age from users where bool=$2 and phone=$1",
  53. args: []interface{}{"133", false},
  54. expect: "select name, age from users where bool=0 and phone='133'",
  55. },
  56. {
  57. name: "pg error not number",
  58. query: "select name, age from users where bool=$a and phone=$1",
  59. args: []interface{}{"133", false},
  60. hasErr: true,
  61. },
  62. {
  63. name: "pg error more args",
  64. query: "select name, age from users where bool=$2 and phone=$1 and nickname=$3",
  65. args: []interface{}{"133", false},
  66. hasErr: true,
  67. },
  68. }
  69. for _, test := range tests {
  70. test := test
  71. t.Run(test.name, func(t *testing.T) {
  72. t.Parallel()
  73. actual, err := format(test.query, test.args...)
  74. if test.hasErr {
  75. assert.NotNil(t, err)
  76. } else {
  77. assert.Equal(t, test.expect, actual)
  78. }
  79. })
  80. }
  81. }