marshal_test.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package flags
  2. import (
  3. "fmt"
  4. "testing"
  5. )
  6. type marshalled bool
  7. func (m *marshalled) UnmarshalFlag(value string) error {
  8. if value == "yes" {
  9. *m = true
  10. } else if value == "no" {
  11. *m = false
  12. } else {
  13. return fmt.Errorf("`%s' is not a valid value, please specify `yes' or `no'", value)
  14. }
  15. return nil
  16. }
  17. func (m marshalled) MarshalFlag() string {
  18. if m {
  19. return "yes"
  20. }
  21. return "no"
  22. }
  23. func TestMarshal(t *testing.T) {
  24. var opts = struct {
  25. Value marshalled `short:"v"`
  26. }{}
  27. ret := assertParseSuccess(t, &opts, "-v=yes")
  28. assertStringArray(t, ret, []string{})
  29. if !opts.Value {
  30. t.Errorf("Expected Value to be true")
  31. }
  32. }
  33. func TestMarshalDefault(t *testing.T) {
  34. var opts = struct {
  35. Value marshalled `short:"v" default:"yes"`
  36. }{}
  37. ret := assertParseSuccess(t, &opts)
  38. assertStringArray(t, ret, []string{})
  39. if !opts.Value {
  40. t.Errorf("Expected Value to be true")
  41. }
  42. }
  43. func TestMarshalOptional(t *testing.T) {
  44. var opts = struct {
  45. Value marshalled `short:"v" optional:"yes" optional-value:"yes"`
  46. }{}
  47. ret := assertParseSuccess(t, &opts, "-v")
  48. assertStringArray(t, ret, []string{})
  49. if !opts.Value {
  50. t.Errorf("Expected Value to be true")
  51. }
  52. }
  53. func TestMarshalError(t *testing.T) {
  54. var opts = struct {
  55. Value marshalled `short:"v"`
  56. }{}
  57. assertParseFail(t, ErrMarshal, "invalid argument for flag `-v' (expected flags.marshalled): `invalid' is not a valid value, please specify `yes' or `no'", &opts, "-vinvalid")
  58. }