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