|
| 1 | +package collectors |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "testing" |
| 8 | + |
| 9 | + "google.golang.org/grpc/codes" |
| 10 | + "google.golang.org/grpc/status" |
| 11 | +) |
| 12 | + |
| 13 | +// TestIsDeadlineExceeded verifies that IsDeadlineExceeded recognizes the |
| 14 | +// various shapes a deadline error can take, most importantly a server-side |
| 15 | +// gRPC status error whose code is DeadlineExceeded but whose description does |
| 16 | +// not mention "context deadline exceeded". |
| 17 | +func TestIsDeadlineExceeded(t *testing.T) { |
| 18 | + tests := []struct { |
| 19 | + name string |
| 20 | + err error |
| 21 | + want bool |
| 22 | + }{ |
| 23 | + { |
| 24 | + name: "nil error", |
| 25 | + err: nil, |
| 26 | + want: false, |
| 27 | + }, |
| 28 | + { |
| 29 | + name: "bare context deadline", |
| 30 | + err: context.DeadlineExceeded, |
| 31 | + want: true, |
| 32 | + }, |
| 33 | + { |
| 34 | + name: "grpc status with context deadline desc", |
| 35 | + err: status.Error( |
| 36 | + codes.DeadlineExceeded, |
| 37 | + context.DeadlineExceeded.Error(), |
| 38 | + ), |
| 39 | + want: true, |
| 40 | + }, |
| 41 | + { |
| 42 | + name: "grpc RST_STREAM deadline", |
| 43 | + err: status.Error( |
| 44 | + codes.DeadlineExceeded, |
| 45 | + "stream terminated by RST_STREAM with error "+ |
| 46 | + "code: CANCEL", |
| 47 | + ), |
| 48 | + want: true, |
| 49 | + }, |
| 50 | + { |
| 51 | + name: "wrapped grpc RST_STREAM deadline", |
| 52 | + err: fmt.Errorf("WalletCollector WalletBalance failed "+ |
| 53 | + "with: %w", status.Error( |
| 54 | + codes.DeadlineExceeded, |
| 55 | + "stream terminated by RST_STREAM with error "+ |
| 56 | + "code: CANCEL", |
| 57 | + )), |
| 58 | + want: true, |
| 59 | + }, |
| 60 | + { |
| 61 | + name: "unrelated grpc error", |
| 62 | + err: status.Error( |
| 63 | + codes.Unavailable, "connection refused", |
| 64 | + ), |
| 65 | + want: false, |
| 66 | + }, |
| 67 | + { |
| 68 | + name: "unrelated plain error", |
| 69 | + err: errors.New("something else failed"), |
| 70 | + want: false, |
| 71 | + }, |
| 72 | + } |
| 73 | + |
| 74 | + for _, tc := range tests { |
| 75 | + t.Run(tc.name, func(t *testing.T) { |
| 76 | + if got := IsDeadlineExceeded(tc.err); got != tc.want { |
| 77 | + t.Fatalf("IsDeadlineExceeded(%v) = %v, want %v", |
| 78 | + tc.err, got, tc.want) |
| 79 | + } |
| 80 | + }) |
| 81 | + } |
| 82 | +} |
0 commit comments