snapshot of https://github.com/grpc/grpc-go.git (master, 2026-09-15; blobs > 131072B omitted)
Some checks failed
codecov / upload (push) Failing after 13m59s
CodeQL / Analyze (push) Failing after 1s
Testing / vet-proto (push) Failing after 1s
Testing / tests (arm, latest) (push) Waiting to run
Testing / extras (latest) (push) Failing after 1s
Testing / static checks (latest-1) (push) Failing after 1s
Testing / tests (-race, latest) (push) Failing after 1s
Testing / tests (i386, latest) (push) Failing after 1s
Testing / tests (latest) (push) Failing after 1s
Testing / tests (latest-1) (push) Failing after 1s
Lock Threads / lock (push) Failing after 1s
govulncheck / govulncheck (.) (push) Failing after 1s
govulncheck / govulncheck (./cmd/protoc-gen-go-grpc) (push) Failing after 1s
govulncheck / govulncheck (./gcp/observability) (push) Failing after 1s
govulncheck / govulncheck (./security/advancedtls) (push) Failing after 1s
govulncheck / govulncheck (./stats/opencensus) (push) Failing after 1s
Stale bot / stale (push) Failing after 1s
Some checks failed
codecov / upload (push) Failing after 13m59s
CodeQL / Analyze (push) Failing after 1s
Testing / vet-proto (push) Failing after 1s
Testing / tests (arm, latest) (push) Waiting to run
Testing / extras (latest) (push) Failing after 1s
Testing / static checks (latest-1) (push) Failing after 1s
Testing / tests (-race, latest) (push) Failing after 1s
Testing / tests (i386, latest) (push) Failing after 1s
Testing / tests (latest) (push) Failing after 1s
Testing / tests (latest-1) (push) Failing after 1s
Lock Threads / lock (push) Failing after 1s
govulncheck / govulncheck (.) (push) Failing after 1s
govulncheck / govulncheck (./cmd/protoc-gen-go-grpc) (push) Failing after 1s
govulncheck / govulncheck (./gcp/observability) (push) Failing after 1s
govulncheck / govulncheck (./security/advancedtls) (push) Failing after 1s
govulncheck / govulncheck (./stats/opencensus) (push) Failing after 1s
Stale bot / stale (push) Failing after 1s
This commit is contained in:
162
status/status.go
Normal file
162
status/status.go
Normal file
@@ -0,0 +1,162 @@
|
||||
/*
|
||||
*
|
||||
* Copyright 2017 gRPC authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
// Package status implements errors returned by gRPC. These errors are
|
||||
// serialized and transmitted on the wire between server and client, and allow
|
||||
// for additional data to be transmitted via the Details field in the status
|
||||
// proto. gRPC service handlers should return an error created by this
|
||||
// package, and gRPC clients should expect a corresponding error to be
|
||||
// returned from the RPC call.
|
||||
//
|
||||
// This package upholds the invariants that a non-nil error may not
|
||||
// contain an OK code, and an OK code must result in a nil error.
|
||||
package status
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
spb "google.golang.org/genproto/googleapis/rpc/status"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/internal/status"
|
||||
)
|
||||
|
||||
// Status references google.golang.org/grpc/internal/status. It represents an
|
||||
// RPC status code, message, and details. It is immutable and should be
|
||||
// created with New, Newf, or FromProto.
|
||||
// https://godoc.org/google.golang.org/grpc/internal/status
|
||||
type Status = status.Status
|
||||
|
||||
// New returns a Status representing c and msg.
|
||||
func New(c codes.Code, msg string) *Status {
|
||||
return status.New(c, msg)
|
||||
}
|
||||
|
||||
// Newf returns New(c, fmt.Sprintf(format, a...)).
|
||||
func Newf(c codes.Code, format string, a ...any) *Status {
|
||||
return New(c, fmt.Sprintf(format, a...))
|
||||
}
|
||||
|
||||
// Error returns an error representing c and msg. If c is OK, returns nil.
|
||||
func Error(c codes.Code, msg string) error {
|
||||
return New(c, msg).Err()
|
||||
}
|
||||
|
||||
// Errorf returns Error(c, fmt.Sprintf(format, a...)).
|
||||
func Errorf(c codes.Code, format string, a ...any) error {
|
||||
return Error(c, fmt.Sprintf(format, a...))
|
||||
}
|
||||
|
||||
// ErrorProto returns an error representing s. If s.Code is OK, returns nil.
|
||||
func ErrorProto(s *spb.Status) error {
|
||||
return FromProto(s).Err()
|
||||
}
|
||||
|
||||
// FromProto returns a Status representing s.
|
||||
func FromProto(s *spb.Status) *Status {
|
||||
return status.FromProto(s)
|
||||
}
|
||||
|
||||
// FromError returns a Status representation of err.
|
||||
//
|
||||
// - If err was produced by this package or implements the method `GRPCStatus()
|
||||
// *Status` and `GRPCStatus()` does not return nil, or if err wraps a type
|
||||
// satisfying this, the Status from `GRPCStatus()` is returned. For wrapped
|
||||
// errors, the message returned contains the entire err.Error() text and not
|
||||
// just the wrapped status. In that case, ok is true.
|
||||
//
|
||||
// - If err is nil, a Status is returned with codes.OK and no message, and ok
|
||||
// is true.
|
||||
//
|
||||
// - If err implements the method `GRPCStatus() *Status` and `GRPCStatus()`
|
||||
// returns nil (which maps to Codes.OK), or if err wraps a type
|
||||
// satisfying this, a Status is returned with codes.Unknown and err's
|
||||
// Error() message, and ok is false.
|
||||
//
|
||||
// - Otherwise, err is an error not compatible with this package. In this
|
||||
// case, a Status is returned with codes.Unknown and err's Error() message,
|
||||
// and ok is false.
|
||||
func FromError(err error) (s *Status, ok bool) {
|
||||
if err == nil {
|
||||
return nil, true
|
||||
}
|
||||
type grpcstatus interface{ GRPCStatus() *Status }
|
||||
if gs, ok := err.(grpcstatus); ok {
|
||||
grpcStatus := gs.GRPCStatus()
|
||||
if grpcStatus == nil {
|
||||
// Error has status nil, which maps to codes.OK. There
|
||||
// is no sensible behavior for this, so we turn it into
|
||||
// an error with codes.Unknown and discard the existing
|
||||
// status.
|
||||
return New(codes.Unknown, err.Error()), false
|
||||
}
|
||||
return grpcStatus, true
|
||||
}
|
||||
var gs grpcstatus
|
||||
if errors.As(err, &gs) {
|
||||
grpcStatus := gs.GRPCStatus()
|
||||
if grpcStatus == nil {
|
||||
// Error wraps an error that has status nil, which maps
|
||||
// to codes.OK. There is no sensible behavior for this,
|
||||
// so we turn it into an error with codes.Unknown and
|
||||
// discard the existing status.
|
||||
return New(codes.Unknown, err.Error()), false
|
||||
}
|
||||
p := grpcStatus.Proto()
|
||||
p.Message = err.Error()
|
||||
return status.FromProto(p), true
|
||||
}
|
||||
return New(codes.Unknown, err.Error()), false
|
||||
}
|
||||
|
||||
// Convert is a convenience function which removes the need to handle the
|
||||
// boolean return value from FromError.
|
||||
func Convert(err error) *Status {
|
||||
s, _ := FromError(err)
|
||||
return s
|
||||
}
|
||||
|
||||
// Code returns the Code of the error if it is a Status error or if it wraps a
|
||||
// Status error. If that is not the case, it returns codes.OK if err is nil, or
|
||||
// codes.Unknown otherwise.
|
||||
func Code(err error) codes.Code {
|
||||
// Don't use FromError to avoid allocation of OK status.
|
||||
if err == nil {
|
||||
return codes.OK
|
||||
}
|
||||
|
||||
return Convert(err).Code()
|
||||
}
|
||||
|
||||
// FromContextError converts a context error or wrapped context error into a
|
||||
// Status. It returns a Status with codes.OK if err is nil, or a Status with
|
||||
// codes.Unknown if err is non-nil and not a context error.
|
||||
func FromContextError(err error) *Status {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return New(codes.DeadlineExceeded, err.Error())
|
||||
}
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return New(codes.Canceled, err.Error())
|
||||
}
|
||||
return New(codes.Unknown, err.Error())
|
||||
}
|
||||
317
status/status_ext_test.go
Normal file
317
status/status_ext_test.go
Normal file
@@ -0,0 +1,317 @@
|
||||
/*
|
||||
*
|
||||
* Copyright 2019 gRPC authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package status_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/internal/grpctest"
|
||||
"google.golang.org/grpc/internal/stubserver"
|
||||
"google.golang.org/grpc/internal/testutils"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"google.golang.org/protobuf/protoadapt"
|
||||
"google.golang.org/protobuf/testing/protocmp"
|
||||
|
||||
testpb "google.golang.org/grpc/interop/grpc_testing"
|
||||
tpb "google.golang.org/grpc/testdata/grpc_testing_not_regenerated"
|
||||
)
|
||||
|
||||
const defaultTestTimeout = 10 * time.Second
|
||||
|
||||
type s struct {
|
||||
grpctest.Tester
|
||||
}
|
||||
|
||||
func Test(t *testing.T) {
|
||||
grpctest.RunSubTests(t, s{})
|
||||
}
|
||||
|
||||
func errWithDetails(t *testing.T, s *status.Status, details ...protoadapt.MessageV1) error {
|
||||
t.Helper()
|
||||
res, err := s.WithDetails(details...)
|
||||
if err != nil {
|
||||
t.Fatalf("(%v).WithDetails(%v) = %v, %v; want _, <nil>", s, details, res, err)
|
||||
}
|
||||
return res.Err()
|
||||
}
|
||||
|
||||
func (s) TestErrorIs(t *testing.T) {
|
||||
// Test errors.
|
||||
testErr := status.Error(codes.Internal, "internal server error")
|
||||
testErrWithDetails := errWithDetails(t, status.New(codes.Internal, "internal server error"), &testpb.Empty{})
|
||||
|
||||
// Test cases.
|
||||
testCases := []struct {
|
||||
err1, err2 error
|
||||
want bool
|
||||
}{
|
||||
{err1: testErr, err2: nil, want: false},
|
||||
{err1: testErr, err2: status.Error(codes.Internal, "internal server error"), want: true},
|
||||
{err1: testErr, err2: status.Error(codes.Internal, "internal error"), want: false},
|
||||
{err1: testErr, err2: status.Error(codes.Unknown, "internal server error"), want: false},
|
||||
{err1: testErr, err2: errors.New("non-grpc error"), want: false},
|
||||
{err1: testErrWithDetails, err2: status.Error(codes.Internal, "internal server error"), want: false},
|
||||
{err1: testErrWithDetails, err2: errWithDetails(t, status.New(codes.Internal, "internal server error"), &testpb.Empty{}), want: true},
|
||||
{err1: testErrWithDetails, err2: errWithDetails(t, status.New(codes.Internal, "internal server error"), &testpb.Empty{}, &testpb.Empty{}), want: false},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
isError, ok := tc.err1.(interface{ Is(target error) bool })
|
||||
if !ok {
|
||||
t.Errorf("(%v) does not implement is", tc.err1)
|
||||
continue
|
||||
}
|
||||
|
||||
is := isError.Is(tc.err2)
|
||||
if is != tc.want {
|
||||
t.Errorf("(%v).Is(%v) = %t; want %t", tc.err1, tc.err2, is, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestStatusDetails tests how gRPC handles grpc-status-details-bin, especially
|
||||
// in cases where it doesn't match the grpc-status trailer or contains arbitrary
|
||||
// data.
|
||||
func (s) TestStatusDetails(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
|
||||
defer cancel()
|
||||
|
||||
for _, serverType := range []struct {
|
||||
name string
|
||||
startServerFunc func(*stubserver.StubServer) error
|
||||
}{{
|
||||
name: "normal server",
|
||||
startServerFunc: func(ss *stubserver.StubServer) error {
|
||||
return ss.StartServer()
|
||||
},
|
||||
}, {
|
||||
name: "handler server",
|
||||
startServerFunc: func(ss *stubserver.StubServer) error {
|
||||
return ss.StartHandlerServer()
|
||||
},
|
||||
}} {
|
||||
t.Run(serverType.name, func(t *testing.T) {
|
||||
// Convenience function for making a status including details.
|
||||
detailErr := func(c codes.Code, m string) error {
|
||||
s, err := status.New(c, m).WithDetails(&testpb.SimpleRequest{
|
||||
Payload: &testpb.Payload{Body: []byte("detail msg")},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Error adding details: %v", err)
|
||||
}
|
||||
return s.Err()
|
||||
}
|
||||
|
||||
serialize := func(err error) string {
|
||||
buf, _ := proto.Marshal(status.Convert(err).Proto())
|
||||
return string(buf)
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
trailerSent metadata.MD
|
||||
errSent error
|
||||
trailerWant []string
|
||||
errWant error
|
||||
errContains error
|
||||
}{{
|
||||
name: "basic without details",
|
||||
trailerSent: metadata.MD{},
|
||||
errSent: status.Error(codes.Aborted, "test msg"),
|
||||
errWant: status.Error(codes.Aborted, "test msg"),
|
||||
}, {
|
||||
name: "basic without details passes through trailers",
|
||||
trailerSent: metadata.MD{"grpc-status-details-bin": []string{"random text"}},
|
||||
errSent: status.Error(codes.Aborted, "test msg"),
|
||||
trailerWant: []string{"random text"},
|
||||
errWant: status.Error(codes.Aborted, "test msg"),
|
||||
}, {
|
||||
name: "basic without details conflicts with manual details",
|
||||
trailerSent: metadata.MD{"grpc-status-details-bin": []string{serialize(status.Error(codes.Canceled, "test msg"))}},
|
||||
errSent: status.Error(codes.Aborted, "test msg"),
|
||||
trailerWant: []string{serialize(status.Error(codes.Canceled, "test msg"))},
|
||||
errContains: status.Error(codes.Internal, "mismatch"),
|
||||
}, {
|
||||
name: "basic with details",
|
||||
trailerSent: metadata.MD{},
|
||||
errSent: detailErr(codes.Aborted, "test msg"),
|
||||
trailerWant: []string{serialize(detailErr(codes.Aborted, "test msg"))},
|
||||
errWant: detailErr(codes.Aborted, "test msg"),
|
||||
}, {
|
||||
name: "basic with details discards user's trailers",
|
||||
trailerSent: metadata.MD{"grpc-status-details-bin": []string{"will be ignored"}},
|
||||
errSent: detailErr(codes.Aborted, "test msg"),
|
||||
trailerWant: []string{serialize(detailErr(codes.Aborted, "test msg"))},
|
||||
errWant: detailErr(codes.Aborted, "test msg"),
|
||||
}}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Start a simple server that returns the trailer and error it receives from
|
||||
// channels.
|
||||
ss := &stubserver.StubServer{
|
||||
UnaryCallF: func(ctx context.Context, _ *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
|
||||
grpc.SetTrailer(ctx, tc.trailerSent)
|
||||
return nil, tc.errSent
|
||||
},
|
||||
}
|
||||
if err := serverType.startServerFunc(ss); err != nil {
|
||||
t.Fatalf("Error starting endpoint server: %v", err)
|
||||
}
|
||||
if err := ss.StartClient(); err != nil {
|
||||
t.Fatalf("Error starting endpoint client: %v", err)
|
||||
}
|
||||
defer ss.Stop()
|
||||
|
||||
trailerGot := metadata.MD{}
|
||||
_, errGot := ss.Client.UnaryCall(ctx, &testpb.SimpleRequest{}, grpc.Trailer(&trailerGot))
|
||||
gsdb := trailerGot["grpc-status-details-bin"]
|
||||
if !cmp.Equal(gsdb, tc.trailerWant) {
|
||||
t.Errorf("Trailer got: %v; want: %v", gsdb, tc.trailerWant)
|
||||
}
|
||||
if tc.errWant != nil && !testutils.StatusErrEqual(errGot, tc.errWant) {
|
||||
t.Errorf("Err got: %v; want: %v", errGot, tc.errWant)
|
||||
}
|
||||
if tc.errContains != nil && (status.Code(errGot) != status.Code(tc.errContains) || !strings.Contains(status.Convert(errGot).Message(), status.Convert(tc.errContains).Message())) {
|
||||
t.Errorf("Err got: %v; want: (Contains: %v)", errGot, tc.errWant)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestStatus_ErrorDetailsMessageV1 verifies backward compatibility of the
|
||||
// status.Details() method when using protobuf code generated with only the
|
||||
// MessageV1 API implementation.
|
||||
func (s) TestStatus_ErrorDetailsMessageV1(t *testing.T) {
|
||||
details := []protoadapt.MessageV1{
|
||||
&tpb.SimpleMessage{Data: "abc"},
|
||||
}
|
||||
s, err := status.New(codes.Aborted, "").WithDetails(details...)
|
||||
if err != nil {
|
||||
t.Fatalf("(%v).WithDetails(%+v) failed: %v", s, details, err)
|
||||
}
|
||||
gotDetails := s.Details()
|
||||
for i, msg := range gotDetails {
|
||||
if got, want := reflect.TypeOf(msg), reflect.TypeOf(details[i]); got != want {
|
||||
t.Errorf("reflect.Typeof(%v) = %v, want = %v", msg, got, want)
|
||||
}
|
||||
if _, ok := msg.(protoadapt.MessageV1); !ok {
|
||||
t.Errorf("(%v).Details() returned message that doesn't implement protoadapt.MessageV1: %v", s, msg)
|
||||
}
|
||||
if diff := cmp.Diff(msg, details[i], protocmp.Transform()); diff != "" {
|
||||
t.Errorf("(%v).Details got unexpected output, diff (-got +want):\n%s", s, diff)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestStatus_ErrorDetailsMessageV1AndV2 verifies that status.Details() method
|
||||
// returns the same message types when using protobuf code generated with both the
|
||||
// MessageV1 and MessageV2 API implementations.
|
||||
func (s) TestStatus_ErrorDetailsMessageV1AndV2(t *testing.T) {
|
||||
details := []protoadapt.MessageV1{
|
||||
&testpb.Empty{},
|
||||
}
|
||||
s, err := status.New(codes.Aborted, "").WithDetails(details...)
|
||||
if err != nil {
|
||||
t.Fatalf("(%v).WithDetails(%+v) failed: %v", s, details, err)
|
||||
}
|
||||
gotDetails := s.Details()
|
||||
for i, msg := range gotDetails {
|
||||
if got, want := reflect.TypeOf(msg), reflect.TypeOf(details[i]); got != want {
|
||||
t.Errorf("reflect.Typeof(%v) = %v, want = %v", msg, got, want)
|
||||
}
|
||||
if _, ok := msg.(protoadapt.MessageV1); !ok {
|
||||
t.Errorf("(%v).Details() returned message that doesn't implement protoadapt.MessageV1: %v", s, msg)
|
||||
}
|
||||
if _, ok := msg.(protoadapt.MessageV2); !ok {
|
||||
t.Errorf("(%v).Details() returned message that doesn't implement protoadapt.MessageV2: %v", s, msg)
|
||||
}
|
||||
if diff := cmp.Diff(msg, details[i], protocmp.Transform()); diff != "" {
|
||||
t.Errorf("(%v).Details got unexpected output, diff (-got +want):\n%s", s, diff)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestFromError_Wrapped(t *testing.T) {
|
||||
base := status.New(codes.Canceled, "inner canceled")
|
||||
sWithDetails, err := base.WithDetails(&testpb.Empty{})
|
||||
if err != nil {
|
||||
t.Fatalf("WithDetails failed: %v", err)
|
||||
}
|
||||
innerErr := sWithDetails.Err()
|
||||
mustStatus := func(message string) *status.Status {
|
||||
st, err := status.New(codes.Canceled, message).WithDetails(&testpb.Empty{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
err error
|
||||
wantStatus *status.Status
|
||||
}{
|
||||
{
|
||||
name: "direct_error",
|
||||
err: innerErr,
|
||||
wantStatus: mustStatus("inner canceled"),
|
||||
},
|
||||
{
|
||||
name: "wrapped_error",
|
||||
err: fmt.Errorf("wrapped: %w", innerErr),
|
||||
wantStatus: mustStatus("wrapped: rpc error: code = Canceled desc = inner canceled"),
|
||||
},
|
||||
{
|
||||
name: "double_wrapped_error",
|
||||
err: fmt.Errorf("outer: %w", fmt.Errorf("inner: %w", innerErr)),
|
||||
wantStatus: mustStatus("outer: inner: rpc error: code = Canceled desc = inner canceled"),
|
||||
},
|
||||
{
|
||||
name: "double_wrapped_single_errorf",
|
||||
err: fmt.Errorf("error: %w: %w", errors.New("test error"), innerErr),
|
||||
wantStatus: mustStatus("error: test error: rpc error: code = Canceled desc = inner canceled"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, ok := status.FromError(tc.err)
|
||||
if !ok {
|
||||
t.Fatalf("status.FromError(%v) returned false; want true", tc.err)
|
||||
}
|
||||
if diff := cmp.Diff(tc.wantStatus, got, protocmp.Transform(), cmp.AllowUnexported(status.Status{})); diff != "" {
|
||||
t.Fatalf("status.FromError(%v) got unexpected output, diff (-want +got):\n%s", tc.err, diff)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
482
status/status_test.go
Normal file
482
status/status_test.go
Normal file
@@ -0,0 +1,482 @@
|
||||
/*
|
||||
*
|
||||
* Copyright 2017 gRPC authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package status
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
cpb "google.golang.org/genproto/googleapis/rpc/code"
|
||||
epb "google.golang.org/genproto/googleapis/rpc/errdetails"
|
||||
spb "google.golang.org/genproto/googleapis/rpc/status"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"google.golang.org/protobuf/protoadapt"
|
||||
"google.golang.org/protobuf/reflect/protoreflect"
|
||||
"google.golang.org/protobuf/types/known/anypb"
|
||||
"google.golang.org/protobuf/types/known/durationpb"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/internal/grpctest"
|
||||
"google.golang.org/grpc/internal/status"
|
||||
)
|
||||
|
||||
type s struct {
|
||||
grpctest.Tester
|
||||
}
|
||||
|
||||
func Test(t *testing.T) {
|
||||
grpctest.RunSubTests(t, s{})
|
||||
}
|
||||
|
||||
// errEqual is essentially a copy of testutils.StatusErrEqual(), to avoid a
|
||||
// cyclic dependency.
|
||||
func errEqual(err1, err2 error) bool {
|
||||
status1, ok := FromError(err1)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
status2, ok := FromError(err2)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
return proto.Equal(status1.Proto(), status2.Proto())
|
||||
}
|
||||
|
||||
func (s) TestErrorsWithSameParameters(t *testing.T) {
|
||||
const description = "some description"
|
||||
e1 := Errorf(codes.AlreadyExists, description)
|
||||
e2 := Errorf(codes.AlreadyExists, description)
|
||||
if e1 == e2 || !errEqual(e1, e2) {
|
||||
t.Fatalf("Errors should be equivalent but unique - e1: %v, %v e2: %p, %v", e1.(*status.Error), e1, e2.(*status.Error), e2)
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestFromToProto(t *testing.T) {
|
||||
s := &spb.Status{
|
||||
Code: int32(codes.Internal),
|
||||
Message: "test test test",
|
||||
Details: []*anypb.Any{{TypeUrl: "foo", Value: []byte{3, 2, 1}}},
|
||||
}
|
||||
|
||||
err := FromProto(s)
|
||||
if got := err.Proto(); !proto.Equal(s, got) {
|
||||
t.Fatalf("Expected errors to be identical - s: %v got: %v", s, got)
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestFromNilProto(t *testing.T) {
|
||||
tests := []*Status{nil, FromProto(nil)}
|
||||
for _, s := range tests {
|
||||
if c := s.Code(); c != codes.OK {
|
||||
t.Errorf("s: %v - Expected s.Code() = OK; got %v", s, c)
|
||||
}
|
||||
if m := s.Message(); m != "" {
|
||||
t.Errorf("s: %v - Expected s.Message() = \"\"; got %q", s, m)
|
||||
}
|
||||
if p := s.Proto(); p != nil {
|
||||
t.Errorf("s: %v - Expected s.Proto() = nil; got %q", s, p)
|
||||
}
|
||||
if e := s.Err(); e != nil {
|
||||
t.Errorf("s: %v - Expected s.Err() = nil; got %v", s, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestError(t *testing.T) {
|
||||
err := Error(codes.Internal, "test description")
|
||||
if got, want := err.Error(), "rpc error: code = Internal desc = test description"; got != want {
|
||||
t.Fatalf("err.Error() = %q; want %q", got, want)
|
||||
}
|
||||
s, _ := FromError(err)
|
||||
if got, want := s.Code(), codes.Internal; got != want {
|
||||
t.Fatalf("err.Code() = %s; want %s", got, want)
|
||||
}
|
||||
if got, want := s.Message(), "test description"; got != want {
|
||||
t.Fatalf("err.Message() = %s; want %s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestErrorOK(t *testing.T) {
|
||||
err := Error(codes.OK, "foo")
|
||||
if err != nil {
|
||||
t.Fatalf("Error(codes.OK, _) = %p; want nil", err.(*status.Error))
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestErrorProtoOK(t *testing.T) {
|
||||
s := &spb.Status{Code: int32(codes.OK)}
|
||||
if got := ErrorProto(s); got != nil {
|
||||
t.Fatalf("ErrorProto(%v) = %v; want nil", s, got)
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestFromError(t *testing.T) {
|
||||
code, message := codes.Internal, "test description"
|
||||
err := Error(code, message)
|
||||
s, ok := FromError(err)
|
||||
if !ok || s.Code() != code || s.Message() != message || s.Err() == nil {
|
||||
t.Fatalf("FromError(%v) = %v, %v; want <Code()=%s, Message()=%q, Err()!=nil>, true", err, s, ok, code, message)
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestFromErrorOK(t *testing.T) {
|
||||
code, message := codes.OK, ""
|
||||
s, ok := FromError(nil)
|
||||
if !ok || s.Code() != code || s.Message() != message || s.Err() != nil {
|
||||
t.Fatalf("FromError(nil) = %v, %v; want <Code()=%s, Message()=%q, Err=nil>, true", s, ok, code, message)
|
||||
}
|
||||
}
|
||||
|
||||
type customError struct {
|
||||
Code codes.Code
|
||||
Message string
|
||||
Details []*anypb.Any
|
||||
}
|
||||
|
||||
func (c customError) Error() string {
|
||||
return fmt.Sprintf("rpc error: code = %s desc = %s", c.Code, c.Message)
|
||||
}
|
||||
|
||||
func (c customError) GRPCStatus() *Status {
|
||||
return status.FromProto(&spb.Status{
|
||||
Code: int32(c.Code),
|
||||
Message: c.Message,
|
||||
Details: c.Details,
|
||||
})
|
||||
}
|
||||
|
||||
func (s) TestFromErrorImplementsInterface(t *testing.T) {
|
||||
code, message := codes.Internal, "test description"
|
||||
details := []*anypb.Any{{
|
||||
TypeUrl: "testUrl",
|
||||
Value: []byte("testValue"),
|
||||
}}
|
||||
err := customError{
|
||||
Code: code,
|
||||
Message: message,
|
||||
Details: details,
|
||||
}
|
||||
s, ok := FromError(err)
|
||||
if !ok || s.Code() != code || s.Message() != message || s.Err() == nil {
|
||||
t.Fatalf("FromError(%v) = %v, %v; want <Code()=%s, Message()=%q, Err()!=nil>, true", err, s, ok, code, message)
|
||||
}
|
||||
pd := s.Proto().GetDetails()
|
||||
if len(pd) != 1 || !proto.Equal(pd[0], details[0]) {
|
||||
t.Fatalf("s.Proto.GetDetails() = %v; want <Details()=%s>", pd, details)
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestFromErrorUnknownError(t *testing.T) {
|
||||
code, message := codes.Unknown, "unknown error"
|
||||
err := errors.New("unknown error")
|
||||
s, ok := FromError(err)
|
||||
if ok || s.Code() != code || s.Message() != message {
|
||||
t.Fatalf("FromError(%v) = %v, %v; want <Code()=%s, Message()=%q>, false", err, s, ok, code, message)
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestFromErrorWrapped(t *testing.T) {
|
||||
const code, message = codes.Internal, "test description"
|
||||
err := fmt.Errorf("wrapped error: %w", Error(code, message))
|
||||
s, ok := FromError(err)
|
||||
if !ok || s.Code() != code || s.Message() != err.Error() || s.Err() == nil {
|
||||
t.Fatalf("FromError(%v) = %v, %v; want <Code()=%s, Message()=%q, Err()!=nil>, true", err, s, ok, code, message)
|
||||
}
|
||||
}
|
||||
|
||||
type customErrorNilStatus struct {
|
||||
}
|
||||
|
||||
func (c customErrorNilStatus) Error() string {
|
||||
return "test"
|
||||
}
|
||||
|
||||
func (c customErrorNilStatus) GRPCStatus() *Status {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s) TestFromErrorImplementsInterfaceReturnsOKStatus(t *testing.T) {
|
||||
err := customErrorNilStatus{}
|
||||
s, ok := FromError(err)
|
||||
if ok || s.Code() != codes.Unknown || s.Message() != err.Error() {
|
||||
t.Fatalf("FromError(%v) = %v, %v; want <Code()=%s, Message()=%q, Err()!=nil>, true", err, s, ok, codes.Unknown, err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestFromErrorImplementsInterfaceReturnsOKStatusWrapped(t *testing.T) {
|
||||
err := fmt.Errorf("wrapping: %w", customErrorNilStatus{})
|
||||
s, ok := FromError(err)
|
||||
if ok || s.Code() != codes.Unknown || s.Message() != err.Error() {
|
||||
t.Fatalf("FromError(%v) = %v, %v; want <Code()=%s, Message()=%q, Err()!=nil>, true", err, s, ok, codes.Unknown, err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestFromErrorImplementsInterfaceWrapped(t *testing.T) {
|
||||
const code, message = codes.Internal, "test description"
|
||||
err := fmt.Errorf("wrapped error: %w", customError{Code: code, Message: message})
|
||||
s, ok := FromError(err)
|
||||
if !ok || s.Code() != code || s.Message() != err.Error() || s.Err() == nil {
|
||||
t.Fatalf("FromError(%v) = %v, %v; want <Code()=%s, Message()=%q, Err()!=nil>, true", err, s, ok, code, message)
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestCode(t *testing.T) {
|
||||
const code = codes.Internal
|
||||
err := Error(code, "test description")
|
||||
if s := Code(err); s != code {
|
||||
t.Fatalf("Code(%v) = %v; want <Code()=%s>", err, s, code)
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestCodeOK(t *testing.T) {
|
||||
if s, code := Code(nil), codes.OK; s != code {
|
||||
t.Fatalf("Code(%v) = %v; want <Code()=%s>", nil, s, code)
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestCodeImplementsInterface(t *testing.T) {
|
||||
const code = codes.Internal
|
||||
err := customError{Code: code, Message: "test description"}
|
||||
if s := Code(err); s != code {
|
||||
t.Fatalf("Code(%v) = %v; want <Code()=%s>", err, s, code)
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestCodeUnknownError(t *testing.T) {
|
||||
const code = codes.Unknown
|
||||
err := errors.New("unknown error")
|
||||
if s := Code(err); s != code {
|
||||
t.Fatalf("Code(%v) = %v; want <Code()=%s>", err, s, code)
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestCodeWrapped(t *testing.T) {
|
||||
const code = codes.Internal
|
||||
err := fmt.Errorf("wrapped: %w", Error(code, "test description"))
|
||||
if s := Code(err); s != code {
|
||||
t.Fatalf("Code(%v) = %v; want <Code()=%s>", err, s, code)
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestCodeImplementsInterfaceWrapped(t *testing.T) {
|
||||
const code = codes.Internal
|
||||
err := fmt.Errorf("wrapped: %w", customError{Code: code, Message: "test description"})
|
||||
if s := Code(err); s != code {
|
||||
t.Fatalf("Code(%v) = %v; want <Code()=%s>", err, s, code)
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestConvertKnownError(t *testing.T) {
|
||||
code, message := codes.Internal, "test description"
|
||||
err := Error(code, message)
|
||||
s := Convert(err)
|
||||
if s.Code() != code || s.Message() != message {
|
||||
t.Fatalf("Convert(%v) = %v; want <Code()=%s, Message()=%q>", err, s, code, message)
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestConvertUnknownError(t *testing.T) {
|
||||
code, message := codes.Unknown, "unknown error"
|
||||
err := errors.New("unknown error")
|
||||
s := Convert(err)
|
||||
if s.Code() != code || s.Message() != message {
|
||||
t.Fatalf("Convert(%v) = %v; want <Code()=%s, Message()=%q>", err, s, code, message)
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestStatus_ErrorDetails(t *testing.T) {
|
||||
tests := []struct {
|
||||
code codes.Code
|
||||
details []protoadapt.MessageV1
|
||||
}{
|
||||
{
|
||||
code: codes.NotFound,
|
||||
details: nil,
|
||||
},
|
||||
{
|
||||
code: codes.NotFound,
|
||||
details: []protoadapt.MessageV1{
|
||||
&epb.ResourceInfo{
|
||||
ResourceType: "book",
|
||||
ResourceName: "projects/1234/books/5678",
|
||||
Owner: "User",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
code: codes.Internal,
|
||||
details: []protoadapt.MessageV1{
|
||||
&epb.DebugInfo{
|
||||
StackEntries: []string{
|
||||
"first stack",
|
||||
"second stack",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
code: codes.Unavailable,
|
||||
details: []protoadapt.MessageV1{
|
||||
&epb.RetryInfo{
|
||||
RetryDelay: &durationpb.Duration{Seconds: 60},
|
||||
},
|
||||
&epb.ResourceInfo{
|
||||
ResourceType: "book",
|
||||
ResourceName: "projects/1234/books/5678",
|
||||
Owner: "User",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
s, err := New(tc.code, "").WithDetails(tc.details...)
|
||||
if err != nil {
|
||||
t.Fatalf("(%v).WithDetails(%+v) failed: %v", str(s), tc.details, err)
|
||||
}
|
||||
details := s.Details()
|
||||
if len(details) != len(tc.details) {
|
||||
t.Fatalf("len(s.Details()) = %d, want = %d.", len(details), len(tc.details))
|
||||
}
|
||||
for i := range details {
|
||||
if !proto.Equal(details[i].(protoreflect.ProtoMessage), tc.details[i].(protoreflect.ProtoMessage)) {
|
||||
t.Fatalf("(%v).Details()[%d] = %+v, want %+v", str(s), i, details[i], tc.details[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestStatus_WithDetails_Fail(t *testing.T) {
|
||||
tests := []*Status{
|
||||
nil,
|
||||
FromProto(nil),
|
||||
New(codes.OK, ""),
|
||||
}
|
||||
for _, s := range tests {
|
||||
if s, err := s.WithDetails(); err == nil || s != nil {
|
||||
t.Fatalf("(%v).WithDetails(%+v) = %v, %v; want nil, non-nil", str(s), []proto.Message{}, s, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s) TestStatus_ErrorDetails_Fail(t *testing.T) {
|
||||
tests := []struct {
|
||||
s *Status
|
||||
want []any
|
||||
}{
|
||||
{
|
||||
s: nil,
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
s: FromProto(nil),
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
s: New(codes.OK, ""),
|
||||
want: []any{},
|
||||
},
|
||||
{
|
||||
s: FromProto(&spb.Status{
|
||||
Code: int32(cpb.Code_CANCELLED),
|
||||
Details: []*anypb.Any{
|
||||
{
|
||||
TypeUrl: "",
|
||||
Value: []byte{},
|
||||
},
|
||||
mustMarshalAny(&epb.ResourceInfo{
|
||||
ResourceType: "book",
|
||||
ResourceName: "projects/1234/books/5678",
|
||||
Owner: "User",
|
||||
}),
|
||||
},
|
||||
}),
|
||||
want: []any{
|
||||
errors.New("invalid empty type URL"),
|
||||
&epb.ResourceInfo{
|
||||
ResourceType: "book",
|
||||
ResourceName: "projects/1234/books/5678",
|
||||
Owner: "User",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
details := tc.s.Details()
|
||||
if len(details) != len(tc.want) {
|
||||
t.Fatalf("len(s.Details()) = %d, want = %d.", len(details), len(tc.want))
|
||||
}
|
||||
for i, d := range details {
|
||||
// s.Details can either contain an error or a proto message. We
|
||||
// want to do a compare the proto message for an Equal match, and
|
||||
// for errors only check for presence.
|
||||
if _, ok := d.(error); ok {
|
||||
if (d != nil) != (tc.want[i] != nil) {
|
||||
t.Fatalf("s.Details()[%v] was %v; want %v", i, d, tc.want[i])
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !cmp.Equal(d, tc.want[i], cmp.Comparer(proto.Equal)) {
|
||||
t.Fatalf("s.Details()[%v] was %v; want %v", i, d, tc.want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func str(s *Status) string {
|
||||
if s == nil {
|
||||
return "nil"
|
||||
}
|
||||
if s.Proto() == nil {
|
||||
return "<Code=OK>"
|
||||
}
|
||||
return fmt.Sprintf("<Code=%v, Message=%q, Details=%+v>", s.Code(), s.Message(), s.Details())
|
||||
}
|
||||
|
||||
// mustMarshalAny converts a protobuf message to an any.
|
||||
func mustMarshalAny(msg proto.Message) *anypb.Any {
|
||||
m, err := anypb.New(msg)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("anypb.New(%+v) failed: %v", msg, err))
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (s) TestFromContextError(t *testing.T) {
|
||||
testCases := []struct {
|
||||
in error
|
||||
want *Status
|
||||
}{
|
||||
{in: nil, want: New(codes.OK, "")},
|
||||
{in: context.DeadlineExceeded, want: New(codes.DeadlineExceeded, context.DeadlineExceeded.Error())},
|
||||
{in: context.Canceled, want: New(codes.Canceled, context.Canceled.Error())},
|
||||
{in: errors.New("other"), want: New(codes.Unknown, "other")},
|
||||
{in: fmt.Errorf("wrapped: %w", context.DeadlineExceeded), want: New(codes.DeadlineExceeded, "wrapped: "+context.DeadlineExceeded.Error())},
|
||||
{in: fmt.Errorf("wrapped: %w", context.Canceled), want: New(codes.Canceled, "wrapped: "+context.Canceled.Error())},
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
got := FromContextError(tc.in)
|
||||
if got.Code() != tc.want.Code() || got.Message() != tc.want.Message() {
|
||||
t.Errorf("FromContextError(%v) = %v; want %v", tc.in, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user