improve validate testing with examples

also simplified structure of test cases and failure logging
This commit is contained in:
Aneurin Barker Snook
2024-07-18 06:53:20 +01:00
parent 4c99b5a654
commit a9c1184d6b
14 changed files with 417 additions and 428 deletions
+28 -28
View File
@@ -2,48 +2,48 @@ package validate
import (
"errors"
"fmt"
"testing"
)
func TestErrorIs(t *testing.T) {
type TestCase struct {
Err error
Target error
Is bool
A error
B error
Want bool
}
testCases := []TestCase{
// Is any validation error
{Err: Err, Target: Err, Is: true},
{Err: ErrDisallowedChars, Target: Err, Is: true},
{Err: ErrMustBeGreater, Target: Err, Is: true},
// Want any validation error
{A: Err, B: Err, Want: true},
{A: ErrDisallowedChars, B: Err, Want: true},
{A: ErrMustBeGreater, B: Err, Want: true},
// Is specific validation error
{Err: ErrDisallowedChars, Target: ErrDisallowedChars, Is: true},
{Err: ErrMustBeGreater, Target: ErrMustBeGreater, Is: true},
// Want specific validation error
{A: ErrDisallowedChars, B: ErrDisallowedChars, Want: true},
{A: ErrMustBeGreater, B: ErrMustBeGreater, Want: true},
// Is not specific validation error
{Err: Err, Target: ErrDisallowedChars},
{Err: Err, Target: ErrMustBeGreater},
{Err: ErrMustBeGreater, Target: ErrDisallowedChars},
{Err: ErrDisallowedChars, Target: ErrMustBeGreater},
// Want not specific validation error
{A: Err, B: ErrDisallowedChars},
{A: Err, B: ErrMustBeGreater},
{A: ErrMustBeGreater, B: ErrDisallowedChars},
{A: ErrDisallowedChars, B: ErrMustBeGreater},
// Is not any other error
{Err: ErrDisallowedChars, Target: errors.New("contains disallowed characters")},
{Err: ErrMustBeGreater, Target: errors.New("must be greater than %v")},
// Want not any other error
{A: ErrDisallowedChars, B: errors.New("contains disallowed characters")},
{A: ErrMustBeGreater, B: errors.New("must be greater than %v")},
}
for i, tc := range testCases {
t.Logf("(%d) Testing %v against %v", i, tc.Err, tc.Target)
for _, testCase := range testCases {
a, b, want := testCase.A, testCase.B, testCase.Want
if errors.Is(tc.Err, tc.Target) {
if !tc.Is {
t.Errorf("%v should not equal %v", tc.Err, tc.Target)
t.Run(fmt.Sprintf("%v/%v", a, b), func(t *testing.T) {
got := errors.Is(a, b)
if got != want {
t.Error("got", got)
t.Error("want", want)
}
} else {
if tc.Is {
t.Errorf("%v should equal %v", tc.Err, tc.Target)
}
}
})
}
}