test(errors): add errors test (#1739)

* test(errors): add errors test

* fix lint
pull/1742/head
haiyux 3 years ago committed by GitHub
parent f38cd9875f
commit 4d3092b7aa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 42
      errors/errors_test.go
  2. 8
      errors/types_test.go
  3. 23
      errors/wrap_test.go

@ -6,6 +6,7 @@ import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/grpc/test/grpc_testing"
@ -57,4 +58,45 @@ func TestError(t *testing.T) {
if se2.Code != http.StatusBadRequest {
t.Errorf("convert code err, got %d want %d", UnknownCode, http.StatusBadRequest)
}
assert.Nil(t, FromError(nil))
e := FromError(errors.New("test"))
assert.Equal(t, e.Code, int32(UnknownCode))
}
func TestIs(t *testing.T) {
tests := []struct {
name string
e *Error
err error
want bool
}{
{
name: "true",
e: &Error{Reason: "test"},
err: New(http.StatusNotFound, "test", ""),
want: true,
},
{
name: "false",
e: &Error{Reason: "test"},
err: errors.New("test"),
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if ok := tt.e.Is(tt.err); ok != tt.want {
t.Errorf("Error.Error() = %v, want %v", ok, tt.want)
}
})
}
}
func TestOther(t *testing.T) {
assert.Equal(t, Code(nil), 200)
assert.Equal(t, Code(errors.New("test")), UnknownCode)
assert.Equal(t, Reason(errors.New("test")), UnknownReason)
err := Errorf(10001, "test code 10001", "message")
assert.Equal(t, Code(err), 10001)
assert.Equal(t, Reason(err), "test code 10001")
}

@ -1,6 +1,8 @@
package errors
import "testing"
import (
"testing"
)
func TestTypes(t *testing.T) {
var (
@ -12,6 +14,8 @@ func TestTypes(t *testing.T) {
Conflict("reason_409", "message_409"),
InternalServer("reason_500", "message_500"),
ServiceUnavailable("reason_503", "message_503"),
GatewayTimeout("reason_504", "message_504"),
ClientClosed("reason_499", "message_499"),
}
output = []func(error) bool{
IsBadRequest,
@ -21,6 +25,8 @@ func TestTypes(t *testing.T) {
IsConflict,
IsInternalServer,
IsServiceUnavailable,
IsGatewayTimeout,
IsClientClosed,
}
)

@ -0,0 +1,23 @@
package errors
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
type mockErr struct{}
func (*mockErr) Error() string {
return "mock error"
}
func TestWarp(t *testing.T) {
var err error = &mockErr{}
err2 := fmt.Errorf("wrap %w", err)
assert.Equal(t, err, Unwrap(err2))
assert.True(t, Is(err2, err))
err3 := &mockErr{}
assert.True(t, As(err2, &err3))
}
Loading…
Cancel
Save