1/*
2 *
3 * Copyright 2019 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19package status_test
20
21import (
22	"errors"
23	"testing"
24
25	"github.com/golang/protobuf/proto"
26	"google.golang.org/grpc/codes"
27	"google.golang.org/grpc/status"
28	"google.golang.org/grpc/test/grpc_testing"
29)
30
31func errWithDetails(t *testing.T, s *status.Status, details ...proto.Message) error {
32	t.Helper()
33	res, err := s.WithDetails(details...)
34	if err != nil {
35		t.Fatalf("(%v).WithDetails(%v) = %v, %v; want _, <nil>", s, details, res, err)
36	}
37	return res.Err()
38}
39
40func TestErrorIs(t *testing.T) {
41	// Test errors.
42	testErr := status.Error(codes.Internal, "internal server error")
43	testErrWithDetails := errWithDetails(t, status.New(codes.Internal, "internal server error"), &grpc_testing.Empty{})
44
45	// Test cases.
46	testCases := []struct {
47		err1, err2 error
48		want       bool
49	}{
50		{err1: testErr, err2: nil, want: false},
51		{err1: testErr, err2: status.Error(codes.Internal, "internal server error"), want: true},
52		{err1: testErr, err2: status.Error(codes.Internal, "internal error"), want: false},
53		{err1: testErr, err2: status.Error(codes.Unknown, "internal server error"), want: false},
54		{err1: testErr, err2: errors.New("non-grpc error"), want: false},
55		{err1: testErrWithDetails, err2: status.Error(codes.Internal, "internal server error"), want: false},
56		{err1: testErrWithDetails, err2: errWithDetails(t, status.New(codes.Internal, "internal server error"), &grpc_testing.Empty{}), want: true},
57		{err1: testErrWithDetails, err2: errWithDetails(t, status.New(codes.Internal, "internal server error"), &grpc_testing.Empty{}, &grpc_testing.Empty{}), want: false},
58	}
59
60	for _, tc := range testCases {
61		isError, ok := tc.err1.(interface{ Is(target error) bool })
62		if !ok {
63			t.Errorf("(%v) does not implement is", tc.err1)
64			continue
65		}
66
67		is := isError.Is(tc.err2)
68		if is != tc.want {
69			t.Errorf("(%v).Is(%v) = %t; want %t", tc.err1, tc.err2, is, tc.want)
70		}
71	}
72}
73