package validate import ( "errors" "fmt" "testing" ) func ExampleMaxLength() { testMaxLength := MaxLength(8) fmt.Println(testMaxLength("this string is too long")) // Output: must contain no more than 8 characters } func ExampleMinLength() { testMinLength := MinLength(8) fmt.Println(testMinLength("2short")) // Output: must contain at least 8 characters } func TestMaxLength(t *testing.T) { testCases := map[int]map[string]error{ 8: { "abcd": nil, "abcdefgh": nil, "abcd efg": nil, "abcdéfgh": nil, // 8 runes, 9 bytes "abcdefghi": ErrMustBeShorter.With(8), "abcdéfghi": ErrMustBeShorter.With(8), // 9 runes, 10 bytes }, } for setup, values := range testCases { testMaxLength := MaxLength(setup) for input, want := range values { t.Run(fmt.Sprintf("%d/%s", setup, input), func(t *testing.T) { got := testMaxLength(input) if !errors.Is(got, want) { t.Error("got", got) t.Error("want", want) } }) } } } func TestMinLength(t *testing.T) { testCases := map[int]map[string]error{ 8: { "abcd": ErrMustBeLonger.With(8), "abcdéfg": ErrMustBeLonger.With(8), // 7 runes, 8 bytes "abcdefgh": nil, "abcdéfgh": nil, // 8 runes, 9 bytes "abcd efg": nil, "abcdefghi": nil, }, } for setup, values := range testCases { testMinLength := MinLength(setup) for input, want := range values { t.Run(fmt.Sprintf("%d/%s", setup, input), func(t *testing.T) { got := testMinLength(input) if !errors.Is(got, want) { t.Error("got", got) t.Error("want", want) } }) } } } func ExampleMaxLengthBytes() { testMaxLengthBytes := MaxLengthBytes(8) fmt.Println(testMaxLengthBytes("cafés round the world")) // Output: must have no more than 8 bytes } func ExampleMinLengthBytes() { testMinLengthBytes := MinLengthBytes(8) fmt.Println(testMinLengthBytes("2short")) // Output: must have at least 8 bytes } func TestMaxLengthBytes(t *testing.T) { testCases := map[int]map[string]error{ 8: { "abcd": nil, "abcdefgh": nil, "abcdéfg": nil, // 7 runes, 8 bytes "abcdéfgh": ErrMustHaveFewerBytes.With(8), // 8 runes, 9 bytes "abcdefghi": ErrMustHaveFewerBytes.With(8), }, } for setup, values := range testCases { testMaxLengthBytes := MaxLengthBytes(setup) for input, want := range values { t.Run(fmt.Sprintf("%d/%s", setup, input), func(t *testing.T) { got := testMaxLengthBytes(input) if !errors.Is(got, want) { t.Error("got", got) t.Error("want", want) } }) } } } func TestMinLengthBytes(t *testing.T) { testCases := map[int]map[string]error{ 8: { "abcd": ErrMustHaveMoreBytes.With(8), "abcdefg": ErrMustHaveMoreBytes.With(8), "abcdéf": ErrMustHaveMoreBytes.With(8), // 6 runes, 7 bytes "abcdéfg": nil, // 7 runes, 8 bytes "abcdefgh": nil, }, } for setup, values := range testCases { testMinLengthBytes := MinLengthBytes(setup) for input, want := range values { t.Run(fmt.Sprintf("%d/%s", setup, input), func(t *testing.T) { got := testMinLengthBytes(input) if !errors.Is(got, want) { t.Error("got", got) t.Error("want", want) } }) } } }