Files

56 lines
1.2 KiB
Go
Raw Permalink Normal View History

package validate
import (
"errors"
"fmt"
"testing"
)
func ExampleCollect() {
v := Collect(MinLength(4), Chars("0123456789abcdef"))
fmt.Println(v("xy"))
// Output:
// must contain at least 4 characters
// contains disallowed characters
}
func TestCollect(t *testing.T) {
v := Collect(
MinLength(4),
MaxLength(8),
Chars("0123456789abcdef"),
)
t.Run("no failures returns nil", func(t *testing.T) {
if err := v("abc123"); err != nil {
t.Fatalf("got %v, want nil", err)
}
})
t.Run("every failure is reported", func(t *testing.T) {
// too long (>8) and contains disallowed characters; not too short.
err := v("xyz!!!!!!!!")
if errors.Is(err, ErrMustBeLonger) {
t.Error("did not expect ErrMustBeLonger in", err)
}
if !errors.Is(err, ErrMustBeShorter) {
t.Error("want ErrMustBeShorter in", err)
}
if !errors.Is(err, ErrDisallowedChars) {
t.Error("want ErrDisallowedChars in", err)
}
})
t.Run("a single failure still matches with errors.Is", func(t *testing.T) {
err := v("12") // only too short
if !errors.Is(err, ErrMustBeLonger) {
t.Error("want ErrMustBeLonger in", err)
}
if errors.Is(err, ErrDisallowedChars) {
t.Error("did not expect ErrDisallowedChars in", err)
}
})
}