Created
February 26, 2019 02:10
-
-
Save otiai10/d7b84bbca3f4b223a51d0753ee73fdb9 to your computer and use it in GitHub Desktop.
Go言語のHTTP ClientのTimeoutのテストサンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package httpclienttimeouttest | |
import ( | |
"net/http" | |
"net/http/httptest" | |
"testing" | |
"time" | |
"github.com/otiai10/marmoset" | |
. "github.com/otiai10/mint" | |
) | |
func testrouter() http.Handler { | |
r := marmoset.NewRouter() | |
r.GET("/control", func(rw http.ResponseWriter, req *http.Request) { | |
rw.WriteHeader(http.StatusOK) | |
}) | |
r.GET("/super-slow", func(rw http.ResponseWriter, req *http.Request) { | |
time.Sleep(5 * time.Minute) | |
rw.WriteHeader(http.StatusOK) | |
}) | |
return r | |
} | |
func TestAll(t *testing.T) { | |
s := httptest.NewServer(testrouter()) | |
When(t, "without timeout (control)", func(t *testing.T) { | |
client := new(http.Client) | |
req, _ := http.NewRequest("GET", s.URL+"/control", nil) | |
res, err := client.Do(req) | |
Expect(t, err).ToBe(nil) | |
Expect(t, res.StatusCode).ToBe(200) | |
}) | |
When(t, "with timeout and no any problem", func(t *testing.T) { | |
client := &http.Client{Timeout: 5 * time.Second} | |
req, _ := http.NewRequest("GET", s.URL+"/control", nil) | |
res, err := client.Do(req) | |
Expect(t, err).ToBe(nil) | |
Expect(t, res.StatusCode).ToBe(200) | |
}) | |
When(t, "with timeout and too slow", func(t *testing.T) { | |
client := &http.Client{Timeout: 2 * time.Second} | |
req, _ := http.NewRequest("GET", s.URL+"/super-slow", nil) | |
_, err := client.Do(req) | |
Expect(t, err).Not().ToBe(nil) | |
Expect(t, err.Error()).Match("Timeout exceeded") | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment