github.com/mongodb/grip@v0.0.0-20240213223901-f906268d82b9/send/error_handler_test.go (about) 1 package send 2 3 import ( 4 "errors" 5 "io" 6 "net/http" 7 "strings" 8 "testing" 9 10 "github.com/stretchr/testify/assert" 11 "github.com/stretchr/testify/require" 12 ) 13 14 func TestHandleHTTPResponseError(t *testing.T) { 15 for _, test := range []struct { 16 name string 17 resp *http.Response 18 hasErr bool 19 contains string 20 }{ 21 { 22 name: "NilResponse", 23 }, 24 { 25 name: "100StatusCode", 26 resp: &http.Response{ 27 StatusCode: http.StatusContinue, 28 Body: io.NopCloser(strings.NewReader("continue")), 29 }, 30 hasErr: true, 31 contains: "continue", 32 }, 33 { 34 name: "103StatusCode", 35 resp: &http.Response{ 36 StatusCode: http.StatusEarlyHints, 37 Body: io.NopCloser(strings.NewReader("hints")), 38 }, 39 hasErr: true, 40 contains: "hints", 41 }, 42 { 43 name: "200StatusCode", 44 resp: &http.Response{ 45 StatusCode: http.StatusOK, 46 Body: io.NopCloser(strings.NewReader("body")), 47 }, 48 }, 49 { 50 name: "226StatusCode", 51 resp: &http.Response{ 52 StatusCode: http.StatusIMUsed, 53 Body: io.NopCloser(strings.NewReader("body")), 54 }, 55 }, 56 { 57 name: "300StatusCode", 58 resp: &http.Response{ 59 StatusCode: http.StatusMultipleChoices, 60 Body: io.NopCloser(strings.NewReader("lot's of choices")), 61 }, 62 hasErr: true, 63 contains: "lot's of choices", 64 }, 65 { 66 name: "400StatusCode", 67 resp: &http.Response{ 68 StatusCode: http.StatusBadRequest, 69 Body: io.NopCloser(strings.NewReader("invalid request")), 70 }, 71 hasErr: true, 72 contains: "invalid request", 73 }, 74 { 75 name: "511StatusCode", 76 resp: &http.Response{ 77 StatusCode: http.StatusNetworkAuthenticationRequired, 78 Body: io.NopCloser(strings.NewReader("auth required")), 79 }, 80 hasErr: true, 81 contains: "auth required", 82 }, 83 { 84 name: "ReaderError", 85 resp: &http.Response{ 86 StatusCode: http.StatusInternalServerError, 87 Body: io.NopCloser(&errorReader{}), 88 }, 89 hasErr: true, 90 contains: "failed to read response body", 91 }, 92 } { 93 t.Run(test.name, func(t *testing.T) { 94 err := handleHTTPResponseError(test.resp) 95 if test.hasErr { 96 require.Error(t, err) 97 assert.Contains(t, err.Error(), test.contains) 98 } else { 99 assert.NoError(t, err) 100 } 101 }) 102 } 103 } 104 105 type errorReader struct{} 106 107 func (r *errorReader) Read(_ []byte) (int, error) { 108 return 0, errors.New("read error") 109 }