github.com/go-kivik/kivik/v4@v4.3.2/kiviktest/kt/errors.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 package kt 14 15 import ( 16 "net/http" 17 18 kivik "github.com/go-kivik/kivik/v4" 19 ) 20 21 // CheckError compares the error's status code with that expected. 22 func (c *Context) CheckError(err error) (match bool, success bool) { 23 c.T.Helper() 24 status := c.Int("status") 25 if status == 0 && err == nil { 26 return true, true 27 } 28 switch actualStatus := kivik.HTTPStatus(err); actualStatus { 29 case status: 30 // This is expected 31 return true, status == 0 32 case 0: 33 c.Errorf("Expected failure %d/%s, got success", status, http.StatusText(status)) 34 return false, true 35 default: 36 if status == 0 { 37 c.Errorf("Unexpected failure: %d/%s", kivik.HTTPStatus(err), err) 38 return false, false 39 } 40 c.Errorf("Unexpected failure state.\nExpected: %d/%s\n Actual: %d/%s", status, http.StatusText(status), actualStatus, err) 41 return false, false 42 } 43 } 44 45 // IsExpected checks the error against the expected status, and returns true 46 // if they match. 47 func (c *Context) IsExpected(err error) bool { 48 c.T.Helper() 49 m, _ := c.CheckError(err) 50 return m 51 } 52 53 // IsSuccess is similar to IsExpected, except for its return value. This method 54 // returns true if the expected status == 0, regardless of the error. 55 func (c *Context) IsSuccess(err error) bool { 56 c.T.Helper() 57 _, s := c.CheckError(err) 58 return s 59 } 60 61 // IsExpectedSuccess combines IsExpected() and IsSuccess(), returning true only 62 // if there is no error, and no error was expected. 63 func (c *Context) IsExpectedSuccess(err error) bool { 64 c.T.Helper() 65 m, s := c.CheckError(err) 66 return m && s 67 }