errors_test.go41 lines, 1.5 KB
| 1 | package gateway |
| 2 | |
| 3 | import ( |
| 4 | "net/http/httptest" |
| 5 | "strings" |
| 6 | "testing" |
| 7 | |
| 8 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 9 | "google.golang.org/genproto/googleapis/rpc/errdetails" |
| 10 | "google.golang.org/grpc/codes" |
| 11 | "google.golang.org/grpc/status" |
| 12 | ) |
| 13 | |
| 14 | func TestFromRPC(t *testing.T) { |
| 15 | invalid, _ := status.New(codes.InvalidArgument, "invalid input: amount").WithDetails( |
| 16 | &errdetails.BadRequest{FieldViolations: []*errdetails.BadRequest_FieldViolation{ |
| 17 | {Field: "amount", Description: "must be positive"}, |
| 18 | }}) |
| 19 | broke, _ := status.New(codes.FailedPrecondition, "insufficient funds").WithDetails( |
| 20 | &errdetails.ErrorInfo{Reason: "insufficient_funds", Domain: "payments"}) |
| 21 | |
| 22 | tests := []struct { |
| 23 | err error |
| 24 | status int |
| 25 | body string // a part of the JSON the client gets |
| 26 | }{ |
| 27 | {invalid.Err(), 422, `"fields":{"amount":"must be positive"}`}, |
| 28 | {broke.Err(), 422, `"code":"insufficient_funds"`}, |
| 29 | {status.Error(codes.NotFound, "wallet not found"), 404, `"code":"not_found"`}, |
| 30 | {status.Error(codes.DeadlineExceeded, "too slow"), 504, `"code":"upstream_timeout"`}, |
| 31 | {status.Error(codes.Unavailable, "connection refused"), 502, `"code":"upstream_unavailable"`}, |
| 32 | {status.Error(codes.Internal, "boom"), 500, `"code":"internal"`}, |
| 33 | } |
| 34 | for _, tt := range tests { |
| 35 | rr := httptest.NewRecorder() |
| 36 | httpx.Error(rr, httptest.NewRequest("GET", "/", nil), fromRPC(tt.err)) |
| 37 | if rr.Code != tt.status || !strings.Contains(rr.Body.String(), tt.body) { |
| 38 | t.Errorf("%v: got %d %s, want %d with %s", tt.err, rr.Code, rr.Body, tt.status, tt.body) |
| 39 | } |
| 40 | } |
| 41 | } |