Skip to content

Instantly share code, notes, and snippets.

@otiai10
Created February 26, 2019 02:10
Show Gist options
  • Save otiai10/d7b84bbca3f4b223a51d0753ee73fdb9 to your computer and use it in GitHub Desktop.
Save otiai10/d7b84bbca3f4b223a51d0753ee73fdb9 to your computer and use it in GitHub Desktop.
Go言語のHTTP ClientのTimeoutのテストサンプル
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