1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| package main
import ( "errors" "io/ioutil" "net/http" "net/http/httptest" "os" "strings" "testing" "time" )
func panicError(writer http.ResponseWriter, request *http.Request) error { return errors.New("Internal Server Error") } func errUserError(writer http.ResponseWriter, request *http.Request) error { return custom_error{"user error", time.Now(), "position"} }
func notExistError(writer http.ResponseWriter, request *http.Request) error { return os.ErrNotExist }
func forbidError(writer http.ResponseWriter, request *http.Request) error { return os.ErrPermission }
func noError(writer http.ResponseWriter, request *http.Request) error { return nil }
var tests = []struct { h appHandler code int message string }{ {panicError, 500, "Internal Server Error"}, {errUserError, 400, "position: user error"}, {notExistError, 404, "Not Found"}, {forbidError, 403, "Forbidden"}, {noError, 200, ""}, }
func TestErrWrapper(t *testing.T) { for _, tt := range tests { f := errWraper(tt.h) response := httptest.NewRecorder() request := httptest.NewRequest( http.MethodGet, "http://www.baidu.com", nil, ) f(response, request) verifyResponse(response.Result(), tt.code, tt.message, t) } }
func TestErrWraperInServer(t *testing.T) { for _, tt := range tests { f := errWraper(tt.h) server := httptest.NewServer(http.HandlerFunc(f)) resp, _ := http.Get(server.URL) verifyResponse(resp, tt.code, tt.message, t) } }
func verifyResponse(resp *http.Response, expectedCode int, expectedMsg string, t *testing.T) { b, _ := ioutil.ReadAll(resp.Body) body := strings.Trim(string(b), "\n") if resp.StatusCode != expectedCode || body != expectedMsg { t.Errorf("expect (%d, %s);"+ "got (%d, %s)", expectedCode, expectedMsg, resp.StatusCode, body) } }
|