go-by-test/racer/racer_test.go

50 lines
1.1 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
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
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) {
serverA := makeDelayedServer(11 * time.Second)
defer serverA.Close()
serverB := makeDelayedServer(11 * time.Second)
defer serverB.Close()
_, err := Racer(serverA.URL, serverB.URL)
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)
}))
}