github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/util/selector/roundrobin/roundrobin_test.go (about)

     1  // Licensed under the Apache License, Version 2.0 (the "License");
     2  // you may not use this file except in compliance with the License.
     3  // You may obtain a copy of the License at
     4  //
     5  //     https://www.apache.org/licenses/LICENSE-2.0
     6  //
     7  // Unless required by applicable law or agreed to in writing, software
     8  // distributed under the License is distributed on an "AS IS" BASIS,
     9  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    10  // See the License for the specific language governing permissions and
    11  // limitations under the License.
    12  //
    13  // Original source: github.com/micro/go-micro/v3/selector/roundrobin/roundrobin_test.go
    14  
    15  package roundrobin
    16  
    17  import (
    18  	"testing"
    19  
    20  	"github.com/tickoalcantara12/micro/v3/util/selector"
    21  	"github.com/stretchr/testify/assert"
    22  )
    23  
    24  func TestRoundRobin(t *testing.T) {
    25  	selector.Tests(t, NewSelector())
    26  
    27  	r1 := "127.0.0.1:8000"
    28  	r2 := "127.0.0.1:8001"
    29  	r3 := "127.0.0.1:8002"
    30  
    31  	sel := NewSelector()
    32  
    33  	// By passing r1 and r2 first, it forces a set sequence of (r1 => r2 => r3 => r1)
    34  
    35  	next, err := sel.Select([]string{r1})
    36  	r := next()
    37  	assert.Nil(t, err, "Error should be nil")
    38  	assert.Equal(t, r1, r, "Expected route to be r1")
    39  
    40  	next, err = sel.Select([]string{r2})
    41  	r = next()
    42  	assert.Nil(t, err, "Error should be nil")
    43  	assert.Equal(t, r2, r, "Expected route to be r2")
    44  
    45  	routes := []string{r1, r2, r3}
    46  	next, err = sel.Select(routes)
    47  	assert.Nil(t, err, "Error should be nil")
    48  	n1, n2, n3, n4 := next(), next(), next(), next()
    49  
    50  	// start element is random but then it should loop through in order
    51  	start := -1
    52  	for i := 0; i < 3; i++ {
    53  		if n1 == routes[i] {
    54  			start = i
    55  			break
    56  		}
    57  	}
    58  	assert.NotEqual(t, start, -1)
    59  	assert.Equal(t, routes[start], n1, "Unexpected route")
    60  	assert.Equal(t, routes[(start+1)%3], n2, "Unexpected route")
    61  	assert.Equal(t, routes[(start+2)%3], n3, "Unexpected route")
    62  	assert.Equal(t, routes[(start+3)%3], n4, "Unexpected route")
    63  }