status_test.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /*
  2. *
  3. * Copyright 2017 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. package status
  19. import (
  20. "context"
  21. "errors"
  22. "fmt"
  23. "testing"
  24. "github.com/golang/protobuf/proto"
  25. "github.com/golang/protobuf/ptypes"
  26. apb "github.com/golang/protobuf/ptypes/any"
  27. dpb "github.com/golang/protobuf/ptypes/duration"
  28. "github.com/google/go-cmp/cmp"
  29. cpb "google.golang.org/genproto/googleapis/rpc/code"
  30. epb "google.golang.org/genproto/googleapis/rpc/errdetails"
  31. spb "google.golang.org/genproto/googleapis/rpc/status"
  32. "google.golang.org/grpc/codes"
  33. "google.golang.org/grpc/internal/grpctest"
  34. )
  35. type s struct {
  36. grpctest.Tester
  37. }
  38. func Test(t *testing.T) {
  39. grpctest.RunSubTests(t, s{})
  40. }
  41. // errEqual is essentially a copy of testutils.StatusErrEqual(), to avoid a
  42. // cyclic dependency.
  43. func errEqual(err1, err2 error) bool {
  44. status1, ok := FromError(err1)
  45. if !ok {
  46. return false
  47. }
  48. status2, ok := FromError(err2)
  49. if !ok {
  50. return false
  51. }
  52. return proto.Equal(status1.Proto(), status2.Proto())
  53. }
  54. func (s) TestErrorsWithSameParameters(t *testing.T) {
  55. const description = "some description"
  56. e1 := Errorf(codes.AlreadyExists, description)
  57. e2 := Errorf(codes.AlreadyExists, description)
  58. if e1 == e2 || !errEqual(e1, e2) {
  59. t.Fatalf("Errors should be equivalent but unique - e1: %v, %v e2: %p, %v", e1.(*statusError), e1, e2.(*statusError), e2)
  60. }
  61. }
  62. func (s) TestFromToProto(t *testing.T) {
  63. s := &spb.Status{
  64. Code: int32(codes.Internal),
  65. Message: "test test test",
  66. Details: []*apb.Any{{TypeUrl: "foo", Value: []byte{3, 2, 1}}},
  67. }
  68. err := FromProto(s)
  69. if got := err.Proto(); !proto.Equal(s, got) {
  70. t.Fatalf("Expected errors to be identical - s: %v got: %v", s, got)
  71. }
  72. }
  73. func (s) TestFromNilProto(t *testing.T) {
  74. tests := []*Status{nil, FromProto(nil)}
  75. for _, s := range tests {
  76. if c := s.Code(); c != codes.OK {
  77. t.Errorf("s: %v - Expected s.Code() = OK; got %v", s, c)
  78. }
  79. if m := s.Message(); m != "" {
  80. t.Errorf("s: %v - Expected s.Message() = \"\"; got %q", s, m)
  81. }
  82. if p := s.Proto(); p != nil {
  83. t.Errorf("s: %v - Expected s.Proto() = nil; got %q", s, p)
  84. }
  85. if e := s.Err(); e != nil {
  86. t.Errorf("s: %v - Expected s.Err() = nil; got %v", s, e)
  87. }
  88. }
  89. }
  90. func (s) TestError(t *testing.T) {
  91. err := Error(codes.Internal, "test description")
  92. if got, want := err.Error(), "rpc error: code = Internal desc = test description"; got != want {
  93. t.Fatalf("err.Error() = %q; want %q", got, want)
  94. }
  95. s, _ := FromError(err)
  96. if got, want := s.Code(), codes.Internal; got != want {
  97. t.Fatalf("err.Code() = %s; want %s", got, want)
  98. }
  99. if got, want := s.Message(), "test description"; got != want {
  100. t.Fatalf("err.Message() = %s; want %s", got, want)
  101. }
  102. }
  103. func (s) TestErrorOK(t *testing.T) {
  104. err := Error(codes.OK, "foo")
  105. if err != nil {
  106. t.Fatalf("Error(codes.OK, _) = %p; want nil", err.(*statusError))
  107. }
  108. }
  109. func (s) TestErrorProtoOK(t *testing.T) {
  110. s := &spb.Status{Code: int32(codes.OK)}
  111. if got := ErrorProto(s); got != nil {
  112. t.Fatalf("ErrorProto(%v) = %v; want nil", s, got)
  113. }
  114. }
  115. func (s) TestFromError(t *testing.T) {
  116. code, message := codes.Internal, "test description"
  117. err := Error(code, message)
  118. s, ok := FromError(err)
  119. if !ok || s.Code() != code || s.Message() != message || s.Err() == nil {
  120. t.Fatalf("FromError(%v) = %v, %v; want <Code()=%s, Message()=%q, Err()!=nil>, true", err, s, ok, code, message)
  121. }
  122. }
  123. func (s) TestFromErrorOK(t *testing.T) {
  124. code, message := codes.OK, ""
  125. s, ok := FromError(nil)
  126. if !ok || s.Code() != code || s.Message() != message || s.Err() != nil {
  127. t.Fatalf("FromError(nil) = %v, %v; want <Code()=%s, Message()=%q, Err=nil>, true", s, ok, code, message)
  128. }
  129. }
  130. type customError struct {
  131. Code codes.Code
  132. Message string
  133. Details []*apb.Any
  134. }
  135. func (c customError) Error() string {
  136. return fmt.Sprintf("rpc error: code = %s desc = %s", c.Code, c.Message)
  137. }
  138. func (c customError) GRPCStatus() *Status {
  139. return &Status{
  140. s: &spb.Status{
  141. Code: int32(c.Code),
  142. Message: c.Message,
  143. Details: c.Details,
  144. },
  145. }
  146. }
  147. func (s) TestFromErrorImplementsInterface(t *testing.T) {
  148. code, message := codes.Internal, "test description"
  149. details := []*apb.Any{{
  150. TypeUrl: "testUrl",
  151. Value: []byte("testValue"),
  152. }}
  153. err := customError{
  154. Code: code,
  155. Message: message,
  156. Details: details,
  157. }
  158. s, ok := FromError(err)
  159. if !ok || s.Code() != code || s.Message() != message || s.Err() == nil {
  160. t.Fatalf("FromError(%v) = %v, %v; want <Code()=%s, Message()=%q, Err()!=nil>, true", err, s, ok, code, message)
  161. }
  162. pd := s.Proto().GetDetails()
  163. if len(pd) != 1 || !proto.Equal(pd[0], details[0]) {
  164. t.Fatalf("s.Proto.GetDetails() = %v; want <Details()=%s>", pd, details)
  165. }
  166. }
  167. func (s) TestFromErrorUnknownError(t *testing.T) {
  168. code, message := codes.Unknown, "unknown error"
  169. err := errors.New("unknown error")
  170. s, ok := FromError(err)
  171. if ok || s.Code() != code || s.Message() != message {
  172. t.Fatalf("FromError(%v) = %v, %v; want <Code()=%s, Message()=%q>, false", err, s, ok, code, message)
  173. }
  174. }
  175. func (s) TestConvertKnownError(t *testing.T) {
  176. code, message := codes.Internal, "test description"
  177. err := Error(code, message)
  178. s := Convert(err)
  179. if s.Code() != code || s.Message() != message {
  180. t.Fatalf("Convert(%v) = %v; want <Code()=%s, Message()=%q>", err, s, code, message)
  181. }
  182. }
  183. func (s) TestConvertUnknownError(t *testing.T) {
  184. code, message := codes.Unknown, "unknown error"
  185. err := errors.New("unknown error")
  186. s := Convert(err)
  187. if s.Code() != code || s.Message() != message {
  188. t.Fatalf("Convert(%v) = %v; want <Code()=%s, Message()=%q>", err, s, code, message)
  189. }
  190. }
  191. func (s) TestStatus_ErrorDetails(t *testing.T) {
  192. tests := []struct {
  193. code codes.Code
  194. details []proto.Message
  195. }{
  196. {
  197. code: codes.NotFound,
  198. details: nil,
  199. },
  200. {
  201. code: codes.NotFound,
  202. details: []proto.Message{
  203. &epb.ResourceInfo{
  204. ResourceType: "book",
  205. ResourceName: "projects/1234/books/5678",
  206. Owner: "User",
  207. },
  208. },
  209. },
  210. {
  211. code: codes.Internal,
  212. details: []proto.Message{
  213. &epb.DebugInfo{
  214. StackEntries: []string{
  215. "first stack",
  216. "second stack",
  217. },
  218. },
  219. },
  220. },
  221. {
  222. code: codes.Unavailable,
  223. details: []proto.Message{
  224. &epb.RetryInfo{
  225. RetryDelay: &dpb.Duration{Seconds: 60},
  226. },
  227. &epb.ResourceInfo{
  228. ResourceType: "book",
  229. ResourceName: "projects/1234/books/5678",
  230. Owner: "User",
  231. },
  232. },
  233. },
  234. }
  235. for _, tc := range tests {
  236. s, err := New(tc.code, "").WithDetails(tc.details...)
  237. if err != nil {
  238. t.Fatalf("(%v).WithDetails(%+v) failed: %v", str(s), tc.details, err)
  239. }
  240. details := s.Details()
  241. for i := range details {
  242. if !proto.Equal(details[i].(proto.Message), tc.details[i]) {
  243. t.Fatalf("(%v).Details()[%d] = %+v, want %+v", str(s), i, details[i], tc.details[i])
  244. }
  245. }
  246. }
  247. }
  248. func (s) TestStatus_WithDetails_Fail(t *testing.T) {
  249. tests := []*Status{
  250. nil,
  251. FromProto(nil),
  252. New(codes.OK, ""),
  253. }
  254. for _, s := range tests {
  255. if s, err := s.WithDetails(); err == nil || s != nil {
  256. t.Fatalf("(%v).WithDetails(%+v) = %v, %v; want nil, non-nil", str(s), []proto.Message{}, s, err)
  257. }
  258. }
  259. }
  260. func (s) TestStatus_ErrorDetails_Fail(t *testing.T) {
  261. tests := []struct {
  262. s *Status
  263. i []interface{}
  264. }{
  265. {
  266. nil,
  267. nil,
  268. },
  269. {
  270. FromProto(nil),
  271. nil,
  272. },
  273. {
  274. New(codes.OK, ""),
  275. []interface{}{},
  276. },
  277. {
  278. FromProto(&spb.Status{
  279. Code: int32(cpb.Code_CANCELLED),
  280. Details: []*apb.Any{
  281. {
  282. TypeUrl: "",
  283. Value: []byte{},
  284. },
  285. mustMarshalAny(&epb.ResourceInfo{
  286. ResourceType: "book",
  287. ResourceName: "projects/1234/books/5678",
  288. Owner: "User",
  289. }),
  290. },
  291. }),
  292. []interface{}{
  293. errors.New(`message type url "" is invalid`),
  294. &epb.ResourceInfo{
  295. ResourceType: "book",
  296. ResourceName: "projects/1234/books/5678",
  297. Owner: "User",
  298. },
  299. },
  300. },
  301. }
  302. for _, tc := range tests {
  303. got := tc.s.Details()
  304. if !cmp.Equal(got, tc.i, cmp.Comparer(proto.Equal), cmp.Comparer(equalError)) {
  305. t.Errorf("(%v).Details() = %+v, want %+v", str(tc.s), got, tc.i)
  306. }
  307. }
  308. }
  309. func equalError(x, y error) bool {
  310. return x == y || (x != nil && y != nil && x.Error() == y.Error())
  311. }
  312. func str(s *Status) string {
  313. if s == nil {
  314. return "nil"
  315. }
  316. if s.s == nil {
  317. return "<Code=OK>"
  318. }
  319. return fmt.Sprintf("<Code=%v, Message=%q, Details=%+v>", codes.Code(s.s.GetCode()), s.s.GetMessage(), s.s.GetDetails())
  320. }
  321. // mustMarshalAny converts a protobuf message to an any.
  322. func mustMarshalAny(msg proto.Message) *apb.Any {
  323. any, err := ptypes.MarshalAny(msg)
  324. if err != nil {
  325. panic(fmt.Sprintf("ptypes.MarshalAny(%+v) failed: %v", msg, err))
  326. }
  327. return any
  328. }
  329. func (s) TestFromContextError(t *testing.T) {
  330. testCases := []struct {
  331. in error
  332. want *Status
  333. }{
  334. {in: nil, want: New(codes.OK, "")},
  335. {in: context.DeadlineExceeded, want: New(codes.DeadlineExceeded, context.DeadlineExceeded.Error())},
  336. {in: context.Canceled, want: New(codes.Canceled, context.Canceled.Error())},
  337. {in: errors.New("other"), want: New(codes.Unknown, "other")},
  338. }
  339. for _, tc := range testCases {
  340. got := FromContextError(tc.in)
  341. if got.Code() != tc.want.Code() || got.Message() != tc.want.Message() {
  342. t.Errorf("FromContextError(%v) = %v; want %v", tc.in, got, tc.want)
  343. }
  344. }
  345. }