Reputation: 125
I'm currently working on an image handler in Go which is intended to reject the upload of unsupported files. My intentions are for the Go program to return an error back via the servers http.ResponceWritter detailing which case for rejection has been met, as json, for the upload service to use.
How errors are set up in the server code:
type Error struct {
ImgHandlerError `json:"error"`
}
type ImgHandlerError struct {
Message string `json:"message"`
Code string `json:"code"`
}
func MakeError(message, code string) *Error {
errorMessage := &Error{
ImgHandlerError: ImgHandlerError{
Message: message,
Code: code,
},
}
return errorMessage
}
func ThrowErr(errorMessage Error, writer http.ResponseWriter) {
jData, err := json.Marshal(errorMessage)
if err != nil {
}
writer.Header().Set("Content-Type", "application/json")
writer.WriteHeader(http.StatusForbidden)
writer.Write(jData)
return
}
How an error is generated and written as a HTTP response:
errorMes := *MakeError("PSD files are not supported", "DEF-IMG-0006")
ThrowErr(errorMes, res)
Currently this works as expected, for example when a .psd is uploaded the current HTTP response comes back as JSON.
{"error":{"message":"PSD files are not supported","code":"DEF-IMG-0006"}}
My problem is now testing this as I'm out of my depth, as this is my first Go program. I'm using the Ginko test suite. I've tried setting up the http.ResponseRecorder
(as I think thats where the solution lies) in the test suite but I'm having no luck. Also of my current tests in the test suite only test functions which don't require the writer http.ResponseWriter
as a param so I'm not sure if I need to start a server in the test suite to have a response writer to read from.
Any help is greatly appreciated
Upvotes: 0
Views: 2121
Reputation: 111
My problem is now testing this as I'm out of my depth, as this is my first Go program.
So you want to do some end-to-end testing. In your test files you could do something like this.
req := httptest.NewRequest("POST", "my/v1/endpoint", bytes.NewBuffer(payload))
responseRecorder = httptest.NewRecorder()
router.ServeHTTP(responseRecorder, request)
Take a look at httptest.NewRequest and httptest.ResponseRecorder.
Essentially you need to set up your router, personally I use mux and make requests to it just as you would if you were a real consumer of your API. Your responseRecorder after the request will have fields like Code for reading the response code and things like Body for reading the response body among other fields.
e.g.
if responseRecorder.Code != 200{
t.FailNow()
}
Upvotes: 2