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
+33 -15
View File
@@ -2,27 +2,45 @@ package validate
import (
"errors"
"fmt"
"testing"
)
func TestEmail(t *testing.T) {
type TestCase struct {
Input string
Err error
}
func ExampleEmail() {
fmt.Println(Email("not an email"))
// Output: invalid email address
}
testCases := []TestCase{
{Input: "test@example.com"},
{Input: "testexample.com", Err: ErrInvalidEmail},
}
func FuzzEmail(f *testing.F) {
want := ErrInvalidEmail
for n, tc := range testCases {
t.Logf("(%d) Testing %q", n, tc.Input)
f.Fuzz(func(t *testing.T, input string) {
got := Email(input)
err := Email(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 TestEmail(t *testing.T) {
testCases := map[string]error{
"test@example.com": nil,
"firstname.lastname@some-website.co.uk": nil,
"not an email": ErrInvalidEmail,
"testexample.com": ErrInvalidEmail,
}
for input, want := range testCases {
t.Run(input, func(t *testing.T) {
got := Email(input)
if !errors.Is(got, want) {
t.Error("got", got)
t.Error("want", want)
}
})
}
}