47 lines
992 B
Go
47 lines
992 B
Go
package validate
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"errors"
|
||
|
|
"fmt"
|
||
|
|
"testing"
|
||
|
|
)
|
||
|
|
|
||
|
|
func ExampleRequired() {
|
||
|
|
notBlank := Required[string]()
|
||
|
|
fmt.Println(notBlank(""))
|
||
|
|
// Output: is required
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestRequired(t *testing.T) {
|
||
|
|
t.Run("string", func(t *testing.T) {
|
||
|
|
v := Required[string]()
|
||
|
|
if err := v(""); !errors.Is(err, ErrRequired) {
|
||
|
|
t.Error("empty string should be required, got", err)
|
||
|
|
}
|
||
|
|
if err := v("x"); err != nil {
|
||
|
|
t.Error("non-empty string should pass, got", err)
|
||
|
|
}
|
||
|
|
})
|
||
|
|
|
||
|
|
t.Run("int", func(t *testing.T) {
|
||
|
|
v := Required[int]()
|
||
|
|
if err := v(0); !errors.Is(err, ErrRequired) {
|
||
|
|
t.Error("zero should be required, got", err)
|
||
|
|
}
|
||
|
|
if err := v(1); err != nil {
|
||
|
|
t.Error("non-zero should pass, got", err)
|
||
|
|
}
|
||
|
|
})
|
||
|
|
|
||
|
|
t.Run("pointer", func(t *testing.T) {
|
||
|
|
v := Required[*int]()
|
||
|
|
if err := v(nil); !errors.Is(err, ErrRequired) {
|
||
|
|
t.Error("nil pointer should be required, got", err)
|
||
|
|
}
|
||
|
|
n := 0
|
||
|
|
if err := v(&n); err != nil {
|
||
|
|
t.Error("non-nil pointer should pass, got", err)
|
||
|
|
}
|
||
|
|
})
|
||
|
|
}
|