github.com/go-kivik/kivik/v4@v4.3.2/x/kivikd/couchserver/errors_test.go (about) 1 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 2 // use this file except in compliance with the License. You may obtain a copy of 3 // the License at 4 // 5 // http://www.apache.org/licenses/LICENSE-2.0 6 // 7 // Unless required by applicable law or agreed to in writing, software 8 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 9 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 // License for the specific language governing permissions and limitations under 11 // the License. 12 13 //go:build !js 14 15 package couchserver 16 17 import ( 18 "bytes" 19 "errors" 20 "log" 21 "net/http" 22 "net/http/httptest" 23 "testing" 24 25 "gitlab.com/flimzy/testy" 26 27 internal "github.com/go-kivik/kivik/v4/int/errors" 28 ) 29 30 func TestHandleError(t *testing.T) { 31 h := Handler{} 32 type eTest struct { 33 Name string 34 Err error 35 Expected interface{} 36 } 37 tests := []eTest{ 38 { 39 Name: "NilError", 40 Expected: nil, 41 }, 42 { 43 Name: "SimpleError", 44 Err: errors.New("test error"), 45 Expected: map[string]string{ 46 "error": "internal_server_error", 47 "reason": "test error", 48 }, 49 }, 50 { 51 Name: "kivik error", 52 Err: &internal.Error{Status: http.StatusNotFound, Message: "it ain't there"}, 53 Expected: map[string]string{ 54 "error": "not_found", 55 "reason": "it ain't there", 56 }, 57 }, 58 } 59 for _, test := range tests { 60 func(test eTest) { 61 t.Run(test.Name, func(t *testing.T) { 62 w := httptest.NewRecorder() 63 h.HandleError(w, test.Err) 64 resp := w.Result() 65 defer resp.Body.Close() 66 if d := testy.DiffAsJSON(test.Expected, resp.Body); d != nil { 67 t.Error(d) 68 } 69 }) 70 }(test) 71 } 72 } 73 74 type errorResponseWriter struct { 75 http.ResponseWriter 76 } 77 78 func (w *errorResponseWriter) Write(_ []byte) (int, error) { 79 return 0, errors.New("unusual write error") 80 } 81 82 func TestHandleErrorFailure(t *testing.T) { 83 logBuf := &bytes.Buffer{} 84 h := &Handler{ 85 Logger: log.New(logBuf, "", 0), 86 } 87 w := httptest.NewRecorder() 88 h.HandleError(&errorResponseWriter{w}, errors.New("test error")) 89 90 expected := "Failed to send send error: unusual write error\n" 91 if expected != logBuf.String() { 92 t.Errorf("Expected: %s\n Actual: %s", expected, logBuf.String()) 93 } 94 }