Testing POST request with http.Redirect gives "stopped after 10 redirects" error

917 views
Skip to first unread message

Mirco Zeiss

unread,
Nov 3, 2015, 8:11:23 AM11/3/15
to golang-nuts
I'm trying to test my http handler where I redirect after a successful post request (i.e. user logs in). Check out


The first test is fine. The second test fails.

If I change

http.Redirect(w, r, "/", http.StatusSeeOther)

to

http.Redirect(w, r, "/", http.StatusTemporaryRedirect)

it works. However 307 redirects a POST request with a POST method. I'd like to have POST -> Redirect -> GET.

I have successfully tested POST redirect using the following code

server := httptest.NewServer(handler)
defer server
.Close()
data := url.Values{
 
"login": {"john"},
 
"password": {"secret"},
}

req, err := http.NewRequest("POST", server.URL, strings.NewReader(data.Encode()))
if err != nil {
  panic
(err)
}
req
.Header.Set("Content-Type", "application/x-www-form-urlencoded")
transport
:= http.Transport{}
res
, err := transport.RoundTrip(req)
if err != nil {
  panic
(err)
}

 That's a lot of boilerplate so is there any other way for testing POST redirect?

Giulio Iotti

unread,
Nov 4, 2015, 5:47:39 AM11/4/15
to golang-nuts
On Tuesday, November 3, 2015 at 3:11:23 PM UTC+2, Mirco Zeiss wrote:
I'm trying to test my http handler where I redirect after a successful post request (i.e. user logs in). Check out


The first test is fine. The second test fails.

Isn't the second test setting up an HTTP server that for every URL serves the login function? Then the login function redirects to root, which is again handled by the login function...

In short: you are not testing anything. My advice is not to test the routing (the Gorilla folks test it for you) but test the logic independently from HTTP.

If you want to use httptest, be careful to set up the routing (calling main() in your case).

-- 
Giulio Iotti

Mirco Zeiss

unread,
Nov 4, 2015, 7:23:19 AM11/4/15
to golang-nuts
Do you have an example test? Independently from HTTP as you wrote.

Giulio Iotti

unread,
Nov 4, 2015, 7:29:36 AM11/4/15
to golang-nuts
On Wednesday, November 4, 2015 at 2:23:19 PM UTC+2, Mirco Zeiss wrote
Do you have an example test? Independently from HTTP as you wrote.

I'm sorry, I don't understand. The example in github doesn't have any logic.

I meant to say, if you have a login function that actually does something, when you test it, call it directly, bypassing the routing.

In the example in GitHub the test fails because you setup a httptest.Server that handles any request with "func login(...)" and this handler always redirects (in the end, to itself).

-- 
Giulio Iotti

Mirco Zeiss

unread,
Nov 4, 2015, 8:07:07 AM11/4/15
to golang-nuts
You brought me onto the right track.

I've made the router an extra package that I can require in my tests as a whole. Not just individual http.HandlerFuncs. Now redirecting works as expected.
Reply all
Reply to author
Forward
0 new messages