...

Source file src/github.com/go-kit/kit/sd/lb/random_test.go

Documentation: github.com/go-kit/kit/sd/lb

     1  package lb
     2  
     3  import (
     4  	"context"
     5  	"math"
     6  	"testing"
     7  
     8  	"github.com/go-kit/kit/endpoint"
     9  	"github.com/go-kit/kit/sd"
    10  )
    11  
    12  func TestRandom(t *testing.T) {
    13  	var (
    14  		n          = 7
    15  		endpoints  = make([]endpoint.Endpoint, n)
    16  		counts     = make([]int, n)
    17  		seed       = int64(12345)
    18  		iterations = 1000000
    19  		want       = iterations / n
    20  		tolerance  = want / 100 // 1%
    21  	)
    22  
    23  	for i := 0; i < n; i++ {
    24  		i0 := i
    25  		endpoints[i] = func(context.Context, interface{}) (interface{}, error) { counts[i0]++; return struct{}{}, nil }
    26  	}
    27  
    28  	endpointer := sd.FixedEndpointer(endpoints)
    29  	balancer := NewRandom(endpointer, seed)
    30  
    31  	for i := 0; i < iterations; i++ {
    32  		endpoint, _ := balancer.Endpoint()
    33  		endpoint(context.Background(), struct{}{})
    34  	}
    35  
    36  	for i, have := range counts {
    37  		delta := int(math.Abs(float64(want - have)))
    38  		if delta > tolerance {
    39  			t.Errorf("%d: want %d, have %d, delta %d > %d tolerance", i, want, have, delta, tolerance)
    40  		}
    41  	}
    42  }
    43  
    44  func TestRandomNoEndpoints(t *testing.T) {
    45  	endpointer := sd.FixedEndpointer{}
    46  	balancer := NewRandom(endpointer, 1415926)
    47  	_, err := balancer.Endpoint()
    48  	if want, have := ErrNoEndpoints, err; want != have {
    49  		t.Errorf("want %v, have %v", want, have)
    50  	}
    51  
    52  }
    53  

View as plain text