diff options
| author | Eugene Agafonov <[email protected]> | 2018-03-28 15:42:34 +0300 |
|---|---|---|
| committer | Eric Paris <[email protected]> | 2018-03-28 05:42:34 -0700 |
| commit | 45e82a3a9c6b20fe3159b3dc2eb28d80a3b2ee67 (patch) | |
| tree | 1c2fc66aae710372b6bb42fbc30c373600fb7928 /bytes_test.go | |
| parent | ee5fd03fd6acfd43e44aea0b4135958546ed8e73 (diff) | |
Implement BytesHex type of argument (#115)
BytesHex is an []byte represented as HEX-string
--bytes=010203040506070809 states for []bytes{1,2,3,4,5,6,7,8,9}
Diffstat (limited to 'bytes_test.go')
| -rw-r--r-- | bytes_test.go | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/bytes_test.go b/bytes_test.go new file mode 100644 index 0000000..cc4a769 --- /dev/null +++ b/bytes_test.go @@ -0,0 +1,72 @@ +package pflag + +import ( + "fmt" + "os" + "testing" +) + +func setUpBytesHex(bytesHex *[]byte) *FlagSet { + f := NewFlagSet("test", ContinueOnError) + f.BytesHexVar(bytesHex, "bytes", []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, "Some bytes in HEX") + f.BytesHexVarP(bytesHex, "bytes2", "B", []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, "Some bytes in HEX") + return f +} + +func TestBytesHex(t *testing.T) { + testCases := []struct { + input string + success bool + expected string + }{ + /// Positive cases + {"", true, ""}, // Is empty string OK ? + {"01", true, "01"}, + {"0101", true, "0101"}, + {"1234567890abcdef", true, "1234567890ABCDEF"}, + {"1234567890ABCDEF", true, "1234567890ABCDEF"}, + + // Negative cases + {"0", false, ""}, // Short string + {"000", false, ""}, /// Odd-length string + {"qq", false, ""}, /// non-hex character + } + + devnull, _ := os.Open(os.DevNull) + os.Stderr = devnull + + for i := range testCases { + var bytesHex []byte + f := setUpBytesHex(&bytesHex) + + tc := &testCases[i] + + // --bytes + args := []string{ + fmt.Sprintf("--bytes=%s", tc.input), + fmt.Sprintf("-B %s", tc.input), + fmt.Sprintf("--bytes2=%s", tc.input), + } + + for _, arg := range args { + err := f.Parse([]string{arg}) + + if err != nil && tc.success == true { + t.Errorf("expected success, got %q", err) + continue + } else if err == nil && tc.success == false { + // bytesHex, err := f.GetBytesHex("bytes") + t.Errorf("expected failure while processing %q", tc.input) + continue + } else if tc.success { + bytesHex, err := f.GetBytesHex("bytes") + if err != nil { + t.Errorf("Got error trying to fetch the IP flag: %v", err) + } + if fmt.Sprintf("%X", bytesHex) != tc.expected { + t.Errorf("expected %q, got '%X'", tc.expected, bytesHex) + } + } + } + } +} |
