improve validate testing with examples
also simplified structure of test cases and failure logging
This commit is contained in:
+25
-22
@@ -2,40 +2,43 @@ package validate
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAll(t *testing.T) {
|
||||
type TestCase[T any] struct {
|
||||
Input T
|
||||
F func(T) error
|
||||
Err error
|
||||
}
|
||||
func ExampleAll() {
|
||||
testAll := All(MinLength(4), Chars("0123456789abcdef"))
|
||||
fmt.Println(testAll("invalid input"))
|
||||
// Output: contains disallowed characters
|
||||
}
|
||||
|
||||
f := All(
|
||||
func TestAll(t *testing.T) {
|
||||
testAll := All(
|
||||
MinLength(4),
|
||||
MaxLength(8),
|
||||
Chars("0123456789abcdef"),
|
||||
In("abcd", "abcdef", "12345678"),
|
||||
)
|
||||
|
||||
testCases := []TestCase[string]{
|
||||
{Input: "abcd", F: f},
|
||||
{Input: "abcdef", F: f},
|
||||
{Input: "12345678", F: f},
|
||||
{Input: "abc", F: f, Err: ErrMustBeLonger},
|
||||
{Input: "abcdef012", F: f, Err: ErrMustBeShorter},
|
||||
{Input: "abcdefgh", F: f, Err: ErrDisallowedChars},
|
||||
{Input: "01abcd", F: f, Err: ErrValueNotAllowed},
|
||||
testCases := map[string]error{
|
||||
"abcd": nil,
|
||||
"abcdef": nil,
|
||||
"12345678": nil,
|
||||
|
||||
"abc": ErrMustBeLonger.With(4),
|
||||
"abcdef012": ErrMustBeShorter.With(8),
|
||||
"abcdefgh": ErrDisallowedChars,
|
||||
"01abcd": ErrValueNotAllowed,
|
||||
}
|
||||
|
||||
for n, tc := range testCases {
|
||||
t.Logf("(%d) Testing %q", n, tc.Input)
|
||||
for input, want := range testCases {
|
||||
t.Run(input, func(t *testing.T) {
|
||||
got := testAll(input)
|
||||
|
||||
err := tc.F(tc.Input)
|
||||
|
||||
if !errors.Is(err, tc.Err) {
|
||||
t.Errorf("Expected error %v, got %v", tc.Err, err)
|
||||
}
|
||||
if !errors.Is(got, want) {
|
||||
t.Error("got", got)
|
||||
t.Error("want", want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user