bytes_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package pflag
  2. import (
  3. "fmt"
  4. "os"
  5. "testing"
  6. )
  7. func setUpBytesHex(bytesHex *[]byte) *FlagSet {
  8. f := NewFlagSet("test", ContinueOnError)
  9. f.BytesHexVar(bytesHex, "bytes", []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, "Some bytes in HEX")
  10. f.BytesHexVarP(bytesHex, "bytes2", "B", []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, "Some bytes in HEX")
  11. return f
  12. }
  13. func TestBytesHex(t *testing.T) {
  14. testCases := []struct {
  15. input string
  16. success bool
  17. expected string
  18. }{
  19. /// Positive cases
  20. {"", true, ""}, // Is empty string OK ?
  21. {"01", true, "01"},
  22. {"0101", true, "0101"},
  23. {"1234567890abcdef", true, "1234567890ABCDEF"},
  24. {"1234567890ABCDEF", true, "1234567890ABCDEF"},
  25. // Negative cases
  26. {"0", false, ""}, // Short string
  27. {"000", false, ""}, /// Odd-length string
  28. {"qq", false, ""}, /// non-hex character
  29. }
  30. devnull, _ := os.Open(os.DevNull)
  31. os.Stderr = devnull
  32. for i := range testCases {
  33. var bytesHex []byte
  34. f := setUpBytesHex(&bytesHex)
  35. tc := &testCases[i]
  36. // --bytes
  37. args := []string{
  38. fmt.Sprintf("--bytes=%s", tc.input),
  39. fmt.Sprintf("-B %s", tc.input),
  40. fmt.Sprintf("--bytes2=%s", tc.input),
  41. }
  42. for _, arg := range args {
  43. err := f.Parse([]string{arg})
  44. if err != nil && tc.success == true {
  45. t.Errorf("expected success, got %q", err)
  46. continue
  47. } else if err == nil && tc.success == false {
  48. // bytesHex, err := f.GetBytesHex("bytes")
  49. t.Errorf("expected failure while processing %q", tc.input)
  50. continue
  51. } else if tc.success {
  52. bytesHex, err := f.GetBytesHex("bytes")
  53. if err != nil {
  54. t.Errorf("Got error trying to fetch the IP flag: %v", err)
  55. }
  56. if fmt.Sprintf("%X", bytesHex) != tc.expected {
  57. t.Errorf("expected %q, got '%X'", tc.expected, bytesHex)
  58. }
  59. }
  60. }
  61. }
  62. }