package my_select import ( "net/http" "net/http/httptest" "testing" "time" ) func TestRacer(t *testing.T) { t.Run("compares speeds of servers, returning url of the fastest one", func(t *testing.T) { slowServer := makeDelayedServer(20 * time.Microsecond) defer slowServer.Close() fastServer := makeDelayedServer(0 * time.Microsecond) 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 server doesn't respond within 10s", func(t *testing.T) { serverA := makeDelayedServer(50 * time.Millisecond) serverB := makeDelayedServer(60 * time.Millisecond) defer serverA.Close() defer serverB.Close() _, err := ConfigurableRacer(serverA.URL, serverB.URL, 10*time.Millisecond) if err == nil { t.Error("expected an error but didn't get 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) })) }