go-by-test/racer/racer_test.go

56 lines
1.3 KiB
Go
Raw Normal View History

2024-09-18 08:15:53 +00:00
package racer
2024-09-18 10:45:58 +00:00
import (
"net/http"
"net/http/httptest"
"testing"
"time"
)
2024-09-18 08:15:53 +00:00
2024-09-18 11:41:55 +00:00
type SpyRacerTimeout struct{}
func (s *SpyRacerTimeout) Timeout() <-chan time.Time {
return time.After(1 * time.Millisecond)
}
2024-09-18 08:15:53 +00:00
func TestRacer(t *testing.T) {
2024-09-18 11:08:31 +00:00
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()
2024-09-18 10:45:58 +00:00
2024-09-18 11:08:31 +00:00
fastServer := makeDelayedServer(0 * time.Millisecond)
defer fastServer.Close()
2024-09-18 10:45:58 +00:00
2024-09-18 11:08:31 +00:00
slowURL := slowServer.URL
fastURL := fastServer.URL
2024-09-18 08:15:53 +00:00
2024-09-18 11:08:31 +00:00
want := fastURL
2024-09-18 11:41:55 +00:00
got, _ := Racer(slowURL, fastURL)
2024-09-18 08:15:53 +00:00
2024-09-18 11:08:31 +00:00
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) {
2024-09-18 11:41:55 +00:00
serverA := makeDelayedServer(25 * time.Millisecond)
2024-09-18 11:08:31 +00:00
defer serverA.Close()
2024-09-18 11:41:55 +00:00
serverB := makeDelayedServer(25 * time.Millisecond)
2024-09-18 11:08:31 +00:00
defer serverB.Close()
2024-09-18 11:41:55 +00:00
_, err := ConfigurableRacer(serverA.URL, serverB.URL, 20*time.Millisecond)
2024-09-18 11:08:31 +00:00
if err == nil {
t.Error("expected an error but didn't got one")
}
})
2024-09-18 08:15:53 +00:00
}
2024-09-18 10:54:47 +00:00
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)
}))
}