package errors import ( "fmt" "testing" ) func TestValidationError(t *testing.T) { e := ErrInvalidEventID if string(e.Code()) != "INVALID_ID" { t.Fatal("wrong code") } if string(e.Category()) != "validation" { t.Fatal("wrong category") } if e.IsRetryable() { t.Fatal("should not be retryable") } if string(e.Field) != "id" { t.Fatal("wrong field") } } func TestAuthorizationError(t *testing.T) { e := ErrAuthRequired if !e.NeedsAuth() { t.Fatal("should need auth") } if string(e.Code()) != "AUTH_REQUIRED" { t.Fatal("wrong code") } e2 := e.WithPubkey([]byte("abc")) if string(e2.Pubkey) != "abc" { t.Fatal("wrong pubkey") } } func TestProcessingError(t *testing.T) { e := ErrDuplicate if string(e.Code()) != "DUPLICATE" { t.Fatal("wrong code") } e2 := e.WithKind(1) if e2.Kind != 1 { t.Fatal("wrong kind") } } func TestWithCause(t *testing.T) { cause := fmt.Errorf("disk full") e := ErrStorageFull.WithCause(cause) if e.Unwrap() != cause { t.Fatal("cause not set") } s := e.Error() if !containsStr(s, "disk full") { t.Fatalf("cause not in error string: %s", s) } } func TestHelpers(t *testing.T) { if !Is(ErrDuplicate, ErrDuplicate) { t.Fatal("Is should match same code") } if Is(ErrDuplicate, ErrRateLimited) { t.Fatal("Is should not match different code") } if !IsValidation(ErrInvalidJSON) { t.Fatal("should be validation") } if !IsAuthorization(ErrBanned) { t.Fatal("should be authorization") } if !IsProcessing(ErrDuplicate) { t.Fatal("should be processing") } if !IsPolicy(ErrKindBlocked) { t.Fatal("should be policy") } if !IsStorage(ErrStorageFull) { t.Fatal("should be storage") } if !IsRetryable(ErrRateLimited) { t.Fatal("rate limited should be retryable") } if IsRetryable(ErrDuplicate) { t.Fatal("duplicate should not be retryable") } if !NeedsAuth(ErrAuthRequired) { t.Fatal("auth required should need auth") } if NeedsAuth(ErrBanned) { t.Fatal("banned should not need auth") } } func TestCodeNil(t *testing.T) { c := Code(fmt.Errorf("plain")) if c != nil { t.Fatal("non-domain error should return nil code") } } func containsStr(s, sub string) bool { for i := 0; i <= len(s)-len(sub); i++ { if s[i:i+len(sub)] == sub { return true } } return false }