2023-10-06 11:58:24 +01:00
|
|
|
package validate
|
|
|
|
|
|
2023-11-19 20:27:33 +00:00
|
|
|
import (
|
|
|
|
|
"errors"
|
2024-07-18 06:53:20 +01:00
|
|
|
"fmt"
|
2023-11-19 20:27:33 +00:00
|
|
|
"testing"
|
|
|
|
|
)
|
2023-10-06 11:58:24 +01:00
|
|
|
|
2024-07-18 06:53:20 +01:00
|
|
|
func ExampleEmail() {
|
|
|
|
|
fmt.Println(Email("not an email"))
|
|
|
|
|
// Output: invalid email address
|
|
|
|
|
}
|
2023-10-06 11:58:24 +01:00
|
|
|
|
2024-07-18 06:53:20 +01:00
|
|
|
func FuzzEmail(f *testing.F) {
|
2026-09-07 13:21:17 +01:00
|
|
|
for _, seed := range []string{
|
|
|
|
|
"", "alice@example.com", "not an email", "a@b",
|
|
|
|
|
"Alice <alice@example.com>", "alice@example.com ",
|
|
|
|
|
} {
|
|
|
|
|
f.Add(seed)
|
|
|
|
|
}
|
2023-10-06 11:58:24 +01:00
|
|
|
|
2024-07-18 06:53:20 +01:00
|
|
|
f.Fuzz(func(t *testing.T, input string) {
|
2026-09-07 13:21:17 +01:00
|
|
|
err := Email(input)
|
2023-10-08 15:21:02 +01:00
|
|
|
|
2026-09-07 13:21:17 +01:00
|
|
|
// The only error Email ever returns is ErrInvalidEmail.
|
|
|
|
|
if err != nil && !errors.Is(err, ErrInvalidEmail) {
|
|
|
|
|
t.Fatalf("unexpected error for %q: %v", input, err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// A verdict of "valid" must be stable on re-validation.
|
|
|
|
|
if err == nil {
|
|
|
|
|
if err2 := Email(input); err2 != nil {
|
|
|
|
|
t.Fatalf("inconsistent verdict for %q: first nil, then %v", input, err2)
|
|
|
|
|
}
|
2023-10-06 11:58:24 +01:00
|
|
|
}
|
2024-07-18 06:53:20 +01:00
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestEmail(t *testing.T) {
|
|
|
|
|
testCases := map[string]error{
|
|
|
|
|
"test@example.com": nil,
|
|
|
|
|
"firstname.lastname@some-website.co.uk": nil,
|
2026-09-07 13:21:17 +01:00
|
|
|
"alice+tag@example.com": nil,
|
|
|
|
|
"alice@localhost": nil, // ParseAddress does not require a dotted domain
|
2024-07-18 06:53:20 +01:00
|
|
|
|
2026-09-07 13:21:17 +01:00
|
|
|
"not an email": ErrInvalidEmail,
|
|
|
|
|
"testexample.com": ErrInvalidEmail,
|
|
|
|
|
"Alice <alice@example.com>": ErrInvalidEmail, // display name
|
|
|
|
|
"<alice@example.com>": ErrInvalidEmail, // angle brackets
|
|
|
|
|
"alice@example.com ": ErrInvalidEmail, // trailing space
|
|
|
|
|
"a@b.com, c@d.com": ErrInvalidEmail, // address list
|
2024-07-18 06:53:20 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
}
|
|
|
|
|
})
|
2023-10-06 11:58:24 +01:00
|
|
|
}
|
|
|
|
|
}
|