utils_test.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. // Go MySQL Driver - A MySQL-Driver for Go's database/sql package
  2. //
  3. // Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved.
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public
  6. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  7. // You can obtain one at http://mozilla.org/MPL/2.0/.
  8. package mysql
  9. import (
  10. "bytes"
  11. "crypto/tls"
  12. "encoding/binary"
  13. "fmt"
  14. "testing"
  15. "time"
  16. )
  17. var testDSNs = []struct {
  18. in string
  19. out string
  20. loc *time.Location
  21. }{
  22. {"username:password@protocol(address)/dbname?param=value", "&{user:username passwd:password net:protocol addr:address dbname:dbname params:map[param:value] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false substitutePlaceholder:false}", time.UTC},
  23. {"user@unix(/path/to/socket)/dbname?charset=utf8", "&{user:user passwd: net:unix addr:/path/to/socket dbname:dbname params:map[charset:utf8] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false substitutePlaceholder:false}", time.UTC},
  24. {"user:password@tcp(localhost:5555)/dbname?charset=utf8&tls=true", "&{user:user passwd:password net:tcp addr:localhost:5555 dbname:dbname params:map[charset:utf8] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false substitutePlaceholder:false}", time.UTC},
  25. {"user:password@tcp(localhost:5555)/dbname?charset=utf8mb4,utf8&tls=skip-verify", "&{user:user passwd:password net:tcp addr:localhost:5555 dbname:dbname params:map[charset:utf8mb4,utf8] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false substitutePlaceholder:false}", time.UTC},
  26. {"user:password@/dbname?loc=UTC&timeout=30s&allowAllFiles=1&clientFoundRows=true&allowOldPasswords=TRUE&collation=utf8mb4_unicode_ci", "&{user:user passwd:password net:tcp addr:127.0.0.1:3306 dbname:dbname params:map[] loc:%p tls:<nil> timeout:30000000000 collation:224 allowAllFiles:true allowOldPasswords:true clientFoundRows:true substitutePlaceholder:false}", time.UTC},
  27. {"user:p@ss(word)@tcp([de:ad:be:ef::ca:fe]:80)/dbname?loc=Local", "&{user:user passwd:p@ss(word) net:tcp addr:[de:ad:be:ef::ca:fe]:80 dbname:dbname params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false substitutePlaceholder:false}", time.Local},
  28. {"/dbname", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname:dbname params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false substitutePlaceholder:false}", time.UTC},
  29. {"@/", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false substitutePlaceholder:false}", time.UTC},
  30. {"/", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false substitutePlaceholder:false}", time.UTC},
  31. {"", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false substitutePlaceholder:false}", time.UTC},
  32. {"user:p@/ssword@/", "&{user:user passwd:p@/ssword net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false substitutePlaceholder:false}", time.UTC},
  33. {"unix/?arg=%2Fsome%2Fpath.ext", "&{user: passwd: net:unix addr:/tmp/mysql.sock dbname: params:map[arg:/some/path.ext] loc:%p tls:<nil> timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false substitutePlaceholder:false}", time.UTC},
  34. }
  35. func TestDSNParser(t *testing.T) {
  36. var cfg *config
  37. var err error
  38. var res string
  39. for i, tst := range testDSNs {
  40. cfg, err = parseDSN(tst.in)
  41. if err != nil {
  42. t.Error(err.Error())
  43. }
  44. // pointer not static
  45. cfg.tls = nil
  46. res = fmt.Sprintf("%+v", cfg)
  47. if res != fmt.Sprintf(tst.out, tst.loc) {
  48. t.Errorf("%d. parseDSN(%q) => %q, want %q", i, tst.in, res, fmt.Sprintf(tst.out, tst.loc))
  49. }
  50. }
  51. }
  52. func TestDSNParserInvalid(t *testing.T) {
  53. var invalidDSNs = []string{
  54. "@net(addr/", // no closing brace
  55. "@tcp(/", // no closing brace
  56. "tcp(/", // no closing brace
  57. "(/", // no closing brace
  58. "net(addr)//", // unescaped
  59. "user:pass@tcp(1.2.3.4:3306)", // no trailing slash
  60. //"/dbname?arg=/some/unescaped/path",
  61. }
  62. for i, tst := range invalidDSNs {
  63. if _, err := parseDSN(tst); err == nil {
  64. t.Errorf("invalid DSN #%d. (%s) didn't error!", i, tst)
  65. }
  66. }
  67. }
  68. func TestDSNWithCustomTLS(t *testing.T) {
  69. baseDSN := "user:password@tcp(localhost:5555)/dbname?tls="
  70. tlsCfg := tls.Config{}
  71. RegisterTLSConfig("utils_test", &tlsCfg)
  72. // Custom TLS is missing
  73. tst := baseDSN + "invalid_tls"
  74. cfg, err := parseDSN(tst)
  75. if err == nil {
  76. t.Errorf("Invalid custom TLS in DSN (%s) but did not error. Got config: %#v", tst, cfg)
  77. }
  78. tst = baseDSN + "utils_test"
  79. // Custom TLS with a server name
  80. name := "foohost"
  81. tlsCfg.ServerName = name
  82. cfg, err = parseDSN(tst)
  83. if err != nil {
  84. t.Error(err.Error())
  85. } else if cfg.tls.ServerName != name {
  86. t.Errorf("Did not get the correct TLS ServerName (%s) parsing DSN (%s).", name, tst)
  87. }
  88. // Custom TLS without a server name
  89. name = "localhost"
  90. tlsCfg.ServerName = ""
  91. cfg, err = parseDSN(tst)
  92. if err != nil {
  93. t.Error(err.Error())
  94. } else if cfg.tls.ServerName != name {
  95. t.Errorf("Did not get the correct ServerName (%s) parsing DSN (%s).", name, tst)
  96. }
  97. DeregisterTLSConfig("utils_test")
  98. }
  99. func BenchmarkParseDSN(b *testing.B) {
  100. b.ReportAllocs()
  101. for i := 0; i < b.N; i++ {
  102. for _, tst := range testDSNs {
  103. if _, err := parseDSN(tst.in); err != nil {
  104. b.Error(err.Error())
  105. }
  106. }
  107. }
  108. }
  109. func TestScanNullTime(t *testing.T) {
  110. var scanTests = []struct {
  111. in interface{}
  112. error bool
  113. valid bool
  114. time time.Time
  115. }{
  116. {tDate, false, true, tDate},
  117. {sDate, false, true, tDate},
  118. {[]byte(sDate), false, true, tDate},
  119. {tDateTime, false, true, tDateTime},
  120. {sDateTime, false, true, tDateTime},
  121. {[]byte(sDateTime), false, true, tDateTime},
  122. {tDate0, false, true, tDate0},
  123. {sDate0, false, true, tDate0},
  124. {[]byte(sDate0), false, true, tDate0},
  125. {sDateTime0, false, true, tDate0},
  126. {[]byte(sDateTime0), false, true, tDate0},
  127. {"", true, false, tDate0},
  128. {"1234", true, false, tDate0},
  129. {0, true, false, tDate0},
  130. }
  131. var nt = NullTime{}
  132. var err error
  133. for _, tst := range scanTests {
  134. err = nt.Scan(tst.in)
  135. if (err != nil) != tst.error {
  136. t.Errorf("%v: expected error status %t, got %t", tst.in, tst.error, (err != nil))
  137. }
  138. if nt.Valid != tst.valid {
  139. t.Errorf("%v: expected valid status %t, got %t", tst.in, tst.valid, nt.Valid)
  140. }
  141. if nt.Time != tst.time {
  142. t.Errorf("%v: expected time %v, got %v", tst.in, tst.time, nt.Time)
  143. }
  144. }
  145. }
  146. func TestLengthEncodedInteger(t *testing.T) {
  147. var integerTests = []struct {
  148. num uint64
  149. encoded []byte
  150. }{
  151. {0x0000000000000000, []byte{0x00}},
  152. {0x0000000000000012, []byte{0x12}},
  153. {0x00000000000000fa, []byte{0xfa}},
  154. {0x0000000000000100, []byte{0xfc, 0x00, 0x01}},
  155. {0x0000000000001234, []byte{0xfc, 0x34, 0x12}},
  156. {0x000000000000ffff, []byte{0xfc, 0xff, 0xff}},
  157. {0x0000000000010000, []byte{0xfd, 0x00, 0x00, 0x01}},
  158. {0x0000000000123456, []byte{0xfd, 0x56, 0x34, 0x12}},
  159. {0x0000000000ffffff, []byte{0xfd, 0xff, 0xff, 0xff}},
  160. {0x0000000001000000, []byte{0xfe, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00}},
  161. {0x123456789abcdef0, []byte{0xfe, 0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12}},
  162. {0xffffffffffffffff, []byte{0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
  163. }
  164. for _, tst := range integerTests {
  165. num, isNull, numLen := readLengthEncodedInteger(tst.encoded)
  166. if isNull {
  167. t.Errorf("%x: expected %d, got NULL", tst.encoded, tst.num)
  168. }
  169. if num != tst.num {
  170. t.Errorf("%x: expected %d, got %d", tst.encoded, tst.num, num)
  171. }
  172. if numLen != len(tst.encoded) {
  173. t.Errorf("%x: expected size %d, got %d", tst.encoded, len(tst.encoded), numLen)
  174. }
  175. encoded := appendLengthEncodedInteger(nil, num)
  176. if !bytes.Equal(encoded, tst.encoded) {
  177. t.Errorf("%v: expected %x, got %x", num, tst.encoded, encoded)
  178. }
  179. }
  180. }
  181. func TestOldPass(t *testing.T) {
  182. scramble := []byte{9, 8, 7, 6, 5, 4, 3, 2}
  183. vectors := []struct {
  184. pass string
  185. out string
  186. }{
  187. {" pass", "47575c5a435b4251"},
  188. {"pass ", "47575c5a435b4251"},
  189. {"123\t456", "575c47505b5b5559"},
  190. {"C0mpl!ca ted#PASS123", "5d5d554849584a45"},
  191. }
  192. for _, tuple := range vectors {
  193. ours := scrambleOldPassword(scramble, []byte(tuple.pass))
  194. if tuple.out != fmt.Sprintf("%x", ours) {
  195. t.Errorf("Failed old password %q", tuple.pass)
  196. }
  197. }
  198. }
  199. func TestFormatBinaryDateTime(t *testing.T) {
  200. rawDate := [11]byte{}
  201. binary.LittleEndian.PutUint16(rawDate[:2], 1978) // years
  202. rawDate[2] = 12 // months
  203. rawDate[3] = 30 // days
  204. rawDate[4] = 15 // hours
  205. rawDate[5] = 46 // minutes
  206. rawDate[6] = 23 // seconds
  207. binary.LittleEndian.PutUint32(rawDate[7:], 987654) // microseconds
  208. expect := func(expected string, inlen, outlen uint8) {
  209. actual, _ := formatBinaryDateTime(rawDate[:inlen], outlen, false)
  210. bytes, ok := actual.([]byte)
  211. if !ok {
  212. t.Errorf("formatBinaryDateTime must return []byte, was %T", actual)
  213. }
  214. if string(bytes) != expected {
  215. t.Errorf(
  216. "expected %q, got %q for length in %d, out %d",
  217. bytes, actual, inlen, outlen,
  218. )
  219. }
  220. }
  221. expect("0000-00-00", 0, 10)
  222. expect("0000-00-00 00:00:00", 0, 19)
  223. expect("1978-12-30", 4, 10)
  224. expect("1978-12-30 15:46:23", 7, 19)
  225. expect("1978-12-30 15:46:23.987654", 11, 26)
  226. }