improve validate testing with examples
also simplified structure of test cases and failure logging
This commit is contained in:
+37
-34
@@ -2,57 +2,60 @@ 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) {
|
||||
type TestCase struct {
|
||||
Input string
|
||||
L int
|
||||
Err error
|
||||
testCases := map[int]map[string]error{
|
||||
8: {"abcd": nil, "abcdefgh": nil, "abcd efg": nil, "abcdefghi": ErrMustBeShorter.With(8)},
|
||||
}
|
||||
|
||||
testCases := []TestCase{
|
||||
{Input: "abcd", L: 8},
|
||||
{Input: "abcdefgh", L: 8},
|
||||
{Input: "abcd efg", L: 8},
|
||||
{Input: "abcdefghi", L: 8, Err: ErrMustBeShorter},
|
||||
}
|
||||
for setup, values := range testCases {
|
||||
testMaxLength := MaxLength(setup)
|
||||
|
||||
for n, tc := range testCases {
|
||||
t.Logf("(%d) Testing %q against maximum length of %d", n, tc.Input, tc.L)
|
||||
for input, want := range values {
|
||||
t.Run(fmt.Sprintf("%d/%s", setup, input), func(t *testing.T) {
|
||||
got := testMaxLength(input)
|
||||
|
||||
f := MaxLength(tc.L)
|
||||
err := 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMinLength(t *testing.T) {
|
||||
type TestCase struct {
|
||||
Input string
|
||||
L int
|
||||
Err error
|
||||
testCases := map[int]map[string]error{
|
||||
8: {"abcd": ErrMustBeLonger.With(8), "abcdefgh": nil, "abcd efg": nil, "abcdefghi": nil},
|
||||
}
|
||||
|
||||
testCases := []TestCase{
|
||||
{Input: "abcd", L: 8, Err: ErrMustBeLonger},
|
||||
{Input: "abcdefgh", L: 8},
|
||||
{Input: "abcd efg", L: 8},
|
||||
{Input: "abcdefghi", L: 8},
|
||||
}
|
||||
for setup, values := range testCases {
|
||||
testMinLength := MinLength(setup)
|
||||
|
||||
for n, tc := range testCases {
|
||||
t.Logf("(%d) Testing %q against minimum length of %d", n, tc.Input, tc.L)
|
||||
for input, want := range values {
|
||||
t.Run(fmt.Sprintf("%d/%s", setup, input), func(t *testing.T) {
|
||||
got := testMinLength(input)
|
||||
|
||||
f := MinLength(tc.L)
|
||||
err := 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