dsn_test.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package dsn
  2. import (
  3. "net/url"
  4. "reflect"
  5. "testing"
  6. "time"
  7. xtime "go-common/library/time"
  8. )
  9. type config struct {
  10. Network string `dsn:"network"`
  11. Addresses []string `dsn:"address"`
  12. Username string `dsn:"username"`
  13. Password string `dsn:"password"`
  14. Timeout xtime.Duration `dsn:"query.timeout"`
  15. Sub Sub `dsn:"query.sub"`
  16. Def string `dsn:"query.def,hello"`
  17. }
  18. type Sub struct {
  19. Foo int `dsn:"query.foo"`
  20. }
  21. func TestBind(t *testing.T) {
  22. var cfg config
  23. rawdsn := "tcp://root:toor@172.12.23.34,178.23.34.45?timeout=1s&sub.foo=1&hello=world"
  24. dsn, err := Parse(rawdsn)
  25. if err != nil {
  26. t.Fatal(err)
  27. }
  28. values, err := dsn.Bind(&cfg)
  29. if err != nil {
  30. t.Error(err)
  31. }
  32. if !reflect.DeepEqual(values, url.Values{"hello": {"world"}}) {
  33. t.Errorf("unexpect values get %v", values)
  34. }
  35. cfg2 := config{
  36. Network: "tcp",
  37. Addresses: []string{"172.12.23.34", "178.23.34.45"},
  38. Password: "toor",
  39. Username: "root",
  40. Sub: Sub{Foo: 1},
  41. Timeout: xtime.Duration(time.Second),
  42. Def: "hello",
  43. }
  44. if !reflect.DeepEqual(cfg, cfg2) {
  45. t.Errorf("unexpect config get %v, expect %v", cfg, cfg2)
  46. }
  47. }
  48. type config2 struct {
  49. Network string `dsn:"network"`
  50. Address string `dsn:"address"`
  51. Timeout xtime.Duration `dsn:"query.timeout"`
  52. }
  53. func TestUnix(t *testing.T) {
  54. var cfg config2
  55. rawdsn := "unix:///run/xxx.sock?timeout=1s&sub.foo=1&hello=world"
  56. dsn, err := Parse(rawdsn)
  57. if err != nil {
  58. t.Fatal(err)
  59. }
  60. _, err = dsn.Bind(&cfg)
  61. if err != nil {
  62. t.Error(err)
  63. }
  64. cfg2 := config2{
  65. Network: "unix",
  66. Address: "/run/xxx.sock",
  67. Timeout: xtime.Duration(time.Second),
  68. }
  69. if !reflect.DeepEqual(cfg, cfg2) {
  70. t.Errorf("unexpect config2 get %v, expect %v", cfg, cfg2)
  71. }
  72. }