github.com/akamai/AkamaiOPEN-edgegrid-golang/v2@v2.17.0/pkg/edgeworkers/errors_test.go (about) 1 package edgeworkers 2 3 import ( 4 "io/ioutil" 5 "net/http" 6 "strings" 7 "testing" 8 9 "github.com/akamai/AkamaiOPEN-edgegrid-golang/v2/pkg/session" 10 "github.com/stretchr/testify/require" 11 "github.com/tj/assert" 12 ) 13 14 func TestNewError(t *testing.T) { 15 sess, err := session.New() 16 require.NoError(t, err) 17 18 req, err := http.NewRequest( 19 http.MethodHead, 20 "/", 21 nil) 22 require.NoError(t, err) 23 24 tests := map[string]struct { 25 response *http.Response 26 expected *Error 27 }{ 28 "valid response, status code 500": { 29 response: &http.Response{ 30 Status: "Internal Server Error", 31 StatusCode: http.StatusInternalServerError, 32 Body: ioutil.NopCloser(strings.NewReader( 33 `{"type":"a","title":"b","detail":"c","status":500}`), 34 ), 35 Request: req, 36 }, 37 expected: &Error{ 38 Type: "a", 39 Title: "b", 40 Detail: "c", 41 Status: http.StatusInternalServerError, 42 }, 43 }, 44 "invalid response body, assign status code": { 45 response: &http.Response{ 46 Status: "Internal Server Error", 47 StatusCode: http.StatusInternalServerError, 48 Body: ioutil.NopCloser(strings.NewReader( 49 `test`), 50 ), 51 Request: req, 52 }, 53 expected: &Error{ 54 Title: "test", 55 Detail: "", 56 Status: http.StatusInternalServerError, 57 }, 58 }, 59 } 60 for name, test := range tests { 61 t.Run(name, func(t *testing.T) { 62 res := Client(sess).(*edgeworkers).Error(test.response) 63 assert.Equal(t, test.expected, res) 64 }) 65 } 66 } 67 68 func TestIs(t *testing.T) { 69 tests := map[string]struct { 70 err Error 71 target Error 72 expected bool 73 }{ 74 "different error code": { 75 err: Error{Status: 404}, 76 target: Error{Status: 401}, 77 expected: false, 78 }, 79 "same error code": { 80 err: Error{Status: 404}, 81 target: Error{Status: 404}, 82 expected: true, 83 }, 84 "same error code and title": { 85 err: Error{Status: 404, Title: "some error"}, 86 target: Error{Status: 404, Title: "some error"}, 87 expected: true, 88 }, 89 "same error code and different error message": { 90 err: Error{Status: 404, Title: "some error"}, 91 target: Error{Status: 404, Title: "other error"}, 92 expected: false, 93 }, 94 } 95 96 for name, test := range tests { 97 t.Run(name, func(t *testing.T) { 98 assert.Equal(t, test.err.Is(&test.target), test.expected) 99 }) 100 } 101 }