forked from trpc-group/trpc-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandom_test.go
99 lines (81 loc) · 2.28 KB
/
random_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//
//
// Tencent is pleased to support the open source community by making tRPC available.
//
// Copyright (C) 2023 THL A29 Limited, a Tencent company.
// All rights reserved.
//
// If you have downloaded a copy of the tRPC source code from Tencent,
// please note that tRPC source code is licensed under the Apache 2.0 License,
// A copy of the Apache 2.0 License is included in this file.
//
//
package loadbalance
import (
"context"
"testing"
"trpc.group/trpc-go/trpc-go/naming/bannednodes"
"trpc.group/trpc-go/trpc-go/naming/registry"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestRandomEmptyList(t *testing.T) {
b := NewRandom()
_, err := b.Select("", nil)
assert.Equal(t, err, ErrNoServerAvailable)
}
func TestRandomGet(t *testing.T) {
b := NewRandom()
node, err := b.Select("", []*registry.Node{testNode})
assert.Nil(t, err)
assert.Equal(t, node, testNode)
}
func TestRandom_SelectMandatoryBanned(t *testing.T) {
candidates := []*registry.Node{
{ServiceName: "1", Address: "1"},
{ServiceName: "2", Address: "2"},
}
ctx := context.Background()
ctx = bannednodes.NewCtx(ctx, true)
b := NewRandom()
_, err := b.Select("", candidates, WithContext(ctx))
require.Nil(t, err)
_, err = b.Select("", candidates, WithContext(ctx))
require.Nil(t, err)
_, err = b.Select("", candidates, WithContext(ctx))
require.NotNil(t, err)
nodes, mandatory, ok := bannednodes.FromCtx(ctx)
require.True(t, ok)
require.True(t, mandatory)
var n int
nodes.Range(func(*registry.Node) bool {
n++
return true
})
require.Equal(t, 2, n)
}
func TestRandom_SelectOptionalBanned(t *testing.T) {
candidates := []*registry.Node{
{ServiceName: "1", Address: "1"},
{ServiceName: "2", Address: "2"},
}
ctx := context.Background()
ctx = bannednodes.NewCtx(ctx, false)
b := NewRandom()
n1, err := b.Select("", candidates, WithContext(ctx))
require.Nil(t, err)
n2, err := b.Select("", candidates, WithContext(ctx))
require.Nil(t, err)
require.NotEqual(t, n1.Address, n2.Address)
_, err = b.Select("", candidates, WithContext(ctx))
require.Nil(t, err)
nodes, mandatory, ok := bannednodes.FromCtx(ctx)
require.True(t, ok)
require.False(t, mandatory)
var n int
nodes.Range(func(*registry.Node) bool {
n++
return true
})
require.Equal(t, 3, n)
}