Skip to content

Commit

Permalink
Test for empty set of provided uris
Browse files Browse the repository at this point in the history
  • Loading branch information
dtrejod committed Aug 26, 2022
1 parent a7a5f5f commit 8ac8585
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 18 deletions.
5 changes: 5 additions & 0 deletions conjure-go-client/httpclient/internal/rr_selector.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import (
"math/rand"
"net/http"
"sync"

werror "github.com/palantir/witchcraft-go-error"
)

type roundRobinSelector struct {
Expand All @@ -42,6 +44,9 @@ func NewRoundRobinURISelector(nanoClock func() int64) URISelector {
func (s *roundRobinSelector) Select(uris []string, _ http.Header) ([]string, error) {
s.Lock()
defer s.Unlock()
if len(uris) == 0 {
return nil, werror.Error("no valid uris provided to round robin uri-selector")
}

s.updateURIs(uris)
s.offset = (s.offset + 1) % len(uris)
Expand Down
44 changes: 26 additions & 18 deletions conjure-go-client/httpclient/internal/rr_selector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,27 +19,35 @@ import (
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestRoundRobinSelector_Select(t *testing.T) {
uris := []string{"uri1", "uri2", "uri3", "uri4", "uri5"}
scorer := NewRoundRobinURISelector(func() int64 { return time.Now().UnixNano() })

const iterations = 100
observed := make(map[string]int, iterations)
for i := 0; i < iterations; i++ {
uri, err := scorer.Select(uris, nil)
assert.NoError(t, err)
assert.Len(t, uri, 1)
observed[uri[0]] = observed[uri[0]] + 1
}

occurences := make([]int, 0, len(observed))
for _, count := range observed {
occurences = append(occurences, count)
}

for _, v := range occurences {
assert.Equal(t, occurences[0], v)
}
t.Run("round robins across valid connections", func(t *testing.T) {
uris := []string{"uri1", "uri2", "uri3", "uri4", "uri5"}
const iterations = 100
observed := make(map[string]int, iterations)
for i := 0; i < iterations; i++ {
uri, err := scorer.Select(uris, nil)
assert.NoError(t, err)
assert.Len(t, uri, 1)
observed[uri[0]] = observed[uri[0]] + 1
}

occurences := make([]int, 0, len(observed))
for _, count := range observed {
occurences = append(occurences, count)
}

for _, v := range occurences {
assert.Equal(t, occurences[0], v)
}
})

t.Run("erorrs with empty set of provided uris", func(t *testing.T) {
_, err := scorer.Select([]string{}, nil)
require.Error(t, err)
})
}

0 comments on commit 8ac8585

Please sign in to comment.