HTTP Handler Testing in Go Language
Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /usr/www/phpsites/public/yayprogramming/wp-content/plugins/wp-syntax/wp-syntax.php on line 383
Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /usr/www/phpsites/public/yayprogramming/wp-content/plugins/wp-syntax/wp-syntax.php on line 383
Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /usr/www/phpsites/public/yayprogramming/wp-content/plugins/wp-syntax/wp-syntax.php on line 383
This is a short snippet for your Go Language tests that need the response of a http server handler while POST-ing form value to handler. The function will check if body of response includes the string of your choice.
Hander
1 2 3 | func ShowIndexHandler(w http.ResponseWriter, r *http.Request) { } |
HTTP Test Function
This function will give you everything you need to get a response from your HTTP handler.
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 | // import "net/http/httptest" func DoHTTPTest(handlerName http.HandlerFunc, method string, array map[string]string, expected string) bool { req, err := http.NewRequest(method, "/blank", nil) q := req.URL.Query() for k, v := range array{ q.Add(k, v) } req.URL.RawQuery = q.Encode() if err != nil { panic(err) } rr := httptest.NewRecorder() handler := http.HandlerFunc(handlerName) handler.ServeHTTP(rr, req) fmt.Println("Response: ", rr.Body.String()) if strings.Contains(rr.Body.String(),expected) { return true } else { return false } } |
Actual Test Function
This function would go inside your test for your go language application.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | func TestHandlerTest(t *testing.T) { // insert your form values here output := map[string]string{ "email": "info@domain.com", "password": "password123", } // what do you expect the response to include? (if "success" is in any part of response) expects := "success" // get true/false if string was included in response testResponse := DoHTTPTest(ShowIndexHandler, "POST", output, expects) // fail if response didn't include "success" if !testResponse { t.Fail() } } |
CSS
Next Post
Scale Down an Iframe
Go Language