From 3cc29f8383334f2c8c4afa424131bd18a0a5ca5f Mon Sep 17 00:00:00 2001 From: vinchent Date: Wed, 18 Sep 2024 13:08:31 +0200 Subject: [PATCH] racer: add timeout test --- racer/racer.go | 26 ++++++++++++++------------ racer/racer_test.go | 37 ++++++++++++++++++++++++++----------- 2 files changed, 40 insertions(+), 23 deletions(-) diff --git a/racer/racer.go b/racer/racer.go index e97ddc3..4949940 100644 --- a/racer/racer.go +++ b/racer/racer.go @@ -1,29 +1,23 @@ package racer import ( - "fmt" + "errors" "net/http" "time" ) -func Racer(a, b string) string { +func Racer(a, b string) (string, error) { select { // wait until channel closed case <-ping(a): - return a + return a, nil case <-ping(b): - return b + return b, nil + case <-time.After(10 * time.Second): + return "", errors.New("timeout") } } -func measureResponseTime(url string) time.Duration { - start := time.Now() - http.Get(url) - duration := time.Since(start) - fmt.Println(duration) - return duration -} - func ping(url string) chan struct{} { ch := make(chan struct{}) go func() { @@ -33,3 +27,11 @@ func ping(url string) chan struct{} { }() return ch } + +// func measureResponseTime(url string) time.Duration { +// start := time.Now() +// http.Get(url) +// duration := time.Since(start) +// fmt.Println(duration) +// return duration +// } diff --git a/racer/racer_test.go b/racer/racer_test.go index 1815334..4c271a0 100644 --- a/racer/racer_test.go +++ b/racer/racer_test.go @@ -8,21 +8,36 @@ import ( ) func TestRacer(t *testing.T) { - slowServer := makeDelayedServer(20 * time.Millisecond) - defer slowServer.Close() + 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() + fastServer := makeDelayedServer(0 * time.Millisecond) + defer fastServer.Close() - slowURL := slowServer.URL - fastURL := fastServer.URL + slowURL := slowServer.URL + fastURL := fastServer.URL - want := fastURL - got := Racer(slowURL, fastURL) + want := fastURL + got, _ := Racer(slowURL, fastURL) - if got != want { - t.Errorf("got %q, want %q", got, want) - } + 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") + } + }) } func makeDelayedServer(delay time.Duration) *httptest.Server {