Skip to content

Commit 43548cc

Browse files
committed
add tests for charset parameter on live connection
The charset parameter is only tested in the dsn parser. Add tests on the database connection. This is currently broken for fallback charsets.
1 parent a2cbf81 commit 43548cc

File tree

1 file changed

+51
-1
lines changed

1 file changed

+51
-1
lines changed

driver_test.go

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
)
1313

1414
var (
15+
charset string
1516
dsn string
1617
netAddr string
1718
run bool
@@ -43,8 +44,9 @@ func getEnv() bool {
4344
dbname = "gotest"
4445
}
4546

47+
charset = "charset=utf8"
4648
netAddr = fmt.Sprintf("%s(%s)", prot, addr)
47-
dsn = fmt.Sprintf("%s:%s@%s/%s?timeout=30s&charset=utf8", user, pass, netAddr, dbname)
49+
dsn = fmt.Sprintf("%s:%s@%s/%s?timeout=30s&"+charset, user, pass, netAddr, dbname)
4850

4951
c, err := net.Dial(prot, addr)
5052
if err == nil {
@@ -78,6 +80,54 @@ func mustQuery(t *testing.T, db *sql.DB, query string, args ...interface{}) (row
7880
return
7981
}
8082

83+
func mustSetCharset(t *testing.T, charsetParam, expected string) {
84+
db, err := sql.Open("mysql", strings.Replace(dsn, charset, charsetParam, 1))
85+
if err != nil {
86+
t.Fatalf("Error connecting: %v", err)
87+
}
88+
89+
rows := mustQuery(t, db, ("SELECT @@character_set_connection"))
90+
if !rows.Next() {
91+
t.Fatalf("Error getting connection charset: %v", err)
92+
}
93+
94+
var got string
95+
rows.Scan(&got)
96+
97+
if got != expected {
98+
t.Fatalf("Expected connection charset %s but got %s", expected, got)
99+
}
100+
db.Close()
101+
}
102+
103+
func TestCharset(t *testing.T) {
104+
if !getEnv() {
105+
t.Logf("MySQL-Server not running on %s. Skipping TestCharset", netAddr)
106+
return
107+
}
108+
109+
// non utf8 test
110+
mustSetCharset(t, "charset=ascii", "ascii")
111+
}
112+
113+
func TestFallbackCharset(t *testing.T) {
114+
if !getEnv() {
115+
t.Logf("MySQL-Server not running on %s. Skipping TestCharsets", netAddr)
116+
return
117+
}
118+
119+
// when the first charset is invalid, use the second
120+
mustSetCharset(t, "charset=none,utf8", "utf8")
121+
122+
// when the first charset is valid, use it
123+
charsets := []string{"ascii", "utf8"}
124+
for i := range charsets {
125+
expected := charsets[i]
126+
other := charsets[1-i]
127+
mustSetCharset(t, "charset="+expected+","+other, expected)
128+
}
129+
}
130+
81131
func TestCRUD(t *testing.T) {
82132
if !getEnv() {
83133
t.Logf("MySQL-Server not running on %s. Skipping TestCRUD", netAddr)

0 commit comments

Comments
 (0)