github.com/treeverse/lakefs@v1.24.1-0.20240520134607-95648127bfb0/pkg/api/helpers/errors_test.go (about) 1 package helpers_test 2 3 import ( 4 "fmt" 5 "net/http" 6 "testing" 7 8 "github.com/treeverse/lakefs/pkg/api/helpers" 9 ) 10 11 type Response struct { 12 HTTPResponse *http.Response 13 } 14 15 type Body struct { 16 Response 17 Body []byte 18 } 19 20 func TestResponseAsError(t *testing.T) { 21 expectedClean418 := fmt.Sprintf("[%s]: %s", http.StatusText(http.StatusTeapot), "request failed") 22 23 cases := []struct { 24 name string 25 response interface{} 26 message string // non-empty to match return error; empty to signal no error 27 }{ 28 {"no_HTTPResponse_field", &struct{ A int }{17}, "[no HTTPResponse]: request failed"}, 29 {"OK", &Response{&http.Response{StatusCode: 234}}, ""}, 30 {"status_code", &Response{&http.Response{StatusCode: http.StatusTeapot}}, expectedClean418}, 31 { 32 "status message", 33 &Response{&http.Response{StatusCode: http.StatusTeapot, Status: "espresso"}}, 34 "[espresso]: request failed", 35 }, 36 { 37 "non-JSON body", 38 &Body{Response{&http.Response{StatusCode: http.StatusTeapot}}, []byte("it's not JSON")}, 39 expectedClean418, 40 }, 41 { 42 "JSON body with no message", 43 &Body{Response{&http.Response{StatusCode: http.StatusTeapot}}, []byte("{\"yes\": true}")}, 44 expectedClean418, 45 }, 46 { 47 "JSON body", 48 &Body{Response{&http.Response{StatusCode: http.StatusTeapot}}, []byte("{\"message\": \"lemonade\"}")}, 49 "[I'm a teapot]: lemonade request failed", 50 }, 51 } 52 53 for _, tt := range cases { 54 t.Run(tt.name, func(t *testing.T) { 55 err := helpers.ResponseAsError(tt.response) 56 if tt.message == "" { 57 if err != nil { 58 t.Errorf("unexpected error %s", err) 59 } 60 } else { 61 if err == nil || err.Error() != tt.message { 62 t.Errorf("got error \"%s\" but wanted \"%s\"", err, tt.message) 63 } 64 } 65 }) 66 } 67 }