racer: add timeout test

This commit is contained in:
vinchent 2024-09-18 13:08:31 +02:00
parent 2dc7275f15
commit 3cc29f8383
2 changed files with 40 additions and 23 deletions

View File

@ -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
// }

View File

@ -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 {