length_test.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package validate
  2. import (
  3. "errors"
  4. "fmt"
  5. "testing"
  6. )
  7. func ExampleMaxLength() {
  8. testMaxLength := MaxLength(8)
  9. fmt.Println(testMaxLength("this string is too long"))
  10. // Output: must contain no more than 8 characters
  11. }
  12. func ExampleMinLength() {
  13. testMinLength := MinLength(8)
  14. fmt.Println(testMinLength("2short"))
  15. // Output: must contain at least 8 characters
  16. }
  17. func TestMaxLength(t *testing.T) {
  18. testCases := map[int]map[string]error{
  19. 8: {"abcd": nil, "abcdefgh": nil, "abcd efg": nil, "abcdefghi": ErrMustBeShorter.With(8)},
  20. }
  21. for setup, values := range testCases {
  22. testMaxLength := MaxLength(setup)
  23. for input, want := range values {
  24. t.Run(fmt.Sprintf("%d/%s", setup, input), func(t *testing.T) {
  25. got := testMaxLength(input)
  26. if !errors.Is(got, want) {
  27. t.Error("got", got)
  28. t.Error("want", want)
  29. }
  30. })
  31. }
  32. }
  33. }
  34. func TestMinLength(t *testing.T) {
  35. testCases := map[int]map[string]error{
  36. 8: {"abcd": ErrMustBeLonger.With(8), "abcdefgh": nil, "abcd efg": nil, "abcdefghi": nil},
  37. }
  38. for setup, values := range testCases {
  39. testMinLength := MinLength(setup)
  40. for input, want := range values {
  41. t.Run(fmt.Sprintf("%d/%s", setup, input), func(t *testing.T) {
  42. got := testMinLength(input)
  43. if !errors.Is(got, want) {
  44. t.Error("got", got)
  45. t.Error("want", want)
  46. }
  47. })
  48. }
  49. }
  50. }