package racer import ( "net/http" "net/http/httptest" "testing" "time" ) type SpyRacerTimeout struct{} func (s *SpyRacerTimeout) Timeout() <-chan time.Time { return time.After(1 * time.Millisecond) } func TestRacer(t *testing.T) { t.Run("compares speeds of servers, returning the url of the fasted one", func(t *testing.T) { slowServer := makeDelayedServer(20 * time.Millisecond) defer slowServer.Close() fastServer := makeDelayedServer(0 * time.Millisecond) defer fastServer.Close() slowURL := slowServer.URL fastURL := fastServer.URL want := fastURL got, _ := Racer(slowURL, fastURL) if got != want { t.Errorf("got %q, want %q", got, want) } }) t.Run("returns an error if a server doesn't respond within 10s", func(t *testing.T) { serverA := makeDelayedServer(25 * time.Millisecond) defer serverA.Close() serverB := makeDelayedServer(25 * time.Millisecond) defer serverB.Close() _, err := ConfigurableRacer(serverA.URL, serverB.URL, 20*time.Millisecond) if err == nil { t.Error("expected an error but didn't got one") } }) } func makeDelayedServer(delay time.Duration) *httptest.Server { return httptest.NewServer(http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { time.Sleep(delay) w.WriteHeader(http.StatusOK) })) }