parsers_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package kingpin
  2. import (
  3. "io/ioutil"
  4. "net"
  5. "net/url"
  6. "os"
  7. "github.com/stretchr/testify/assert"
  8. "testing"
  9. )
  10. func TestParseStrings(t *testing.T) {
  11. p := parserMixin{}
  12. v := p.Strings()
  13. p.value.Set("a")
  14. p.value.Set("b")
  15. assert.Equal(t, []string{"a", "b"}, *v)
  16. }
  17. func TestStringsStringer(t *testing.T) {
  18. target := []string{}
  19. v := newAccumulator(&target, func(v interface{}) Value { return newStringValue(v.(*string)) })
  20. v.Set("hello")
  21. v.Set("world")
  22. assert.Equal(t, "hello,world", v.String())
  23. }
  24. func TestParseStringMap(t *testing.T) {
  25. p := parserMixin{}
  26. v := p.StringMap()
  27. p.value.Set("a:b")
  28. p.value.Set("b:c")
  29. assert.Equal(t, map[string]string{"a": "b", "b": "c"}, *v)
  30. }
  31. func TestParseIP(t *testing.T) {
  32. p := parserMixin{}
  33. v := p.IP()
  34. p.value.Set("10.1.1.2")
  35. ip := net.ParseIP("10.1.1.2")
  36. assert.Equal(t, ip, *v)
  37. }
  38. func TestParseURL(t *testing.T) {
  39. p := parserMixin{}
  40. v := p.URL()
  41. p.value.Set("http://w3.org")
  42. u, err := url.Parse("http://w3.org")
  43. assert.NoError(t, err)
  44. assert.Equal(t, *u, **v)
  45. }
  46. func TestParseExistingFile(t *testing.T) {
  47. f, err := ioutil.TempFile("", "")
  48. if err != nil {
  49. t.Fatal(err)
  50. }
  51. defer f.Close()
  52. defer os.Remove(f.Name())
  53. p := parserMixin{}
  54. v := p.ExistingFile()
  55. err = p.value.Set(f.Name())
  56. assert.NoError(t, err)
  57. assert.Equal(t, f.Name(), *v)
  58. err = p.value.Set("/etc/hostsDEFINITELYMISSING")
  59. assert.Error(t, err)
  60. }
  61. func TestParseTCPAddr(t *testing.T) {
  62. p := parserMixin{}
  63. v := p.TCP()
  64. err := p.value.Set("127.0.0.1:1234")
  65. assert.NoError(t, err)
  66. expected, err := net.ResolveTCPAddr("tcp", "127.0.0.1:1234")
  67. assert.NoError(t, err)
  68. assert.Equal(t, *expected, **v)
  69. }
  70. func TestParseTCPAddrList(t *testing.T) {
  71. p := parserMixin{}
  72. _ = p.TCPList()
  73. err := p.value.Set("127.0.0.1:1234")
  74. assert.NoError(t, err)
  75. err = p.value.Set("127.0.0.1:1235")
  76. assert.NoError(t, err)
  77. assert.Equal(t, "127.0.0.1:1234,127.0.0.1:1235", p.value.String())
  78. }
  79. func TestFloat32(t *testing.T) {
  80. p := parserMixin{}
  81. v := p.Float32()
  82. err := p.value.Set("123.45")
  83. assert.NoError(t, err)
  84. assert.InEpsilon(t, 123.45, *v, 0.001)
  85. }