From 8ac86702181cb9af9be6ae82213023574df0e2a3 Mon Sep 17 00:00:00 2001 From: jebbs Date: Tue, 11 Oct 2022 14:51:15 +0800 Subject: [PATCH] add test for selectNodes() --- balancer/balancer_select.go | 4 ++-- balancer/balancer_select_test.go | 39 ++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 balancer/balancer_select_test.go diff --git a/balancer/balancer_select.go b/balancer/balancer_select.go index 9ae8bd40..fc516f5a 100644 --- a/balancer/balancer_select.go +++ b/balancer/balancer_select.go @@ -45,8 +45,8 @@ func selectNodes(nodes []*Node, logger log.Logger, expected int, baselines []opt // go through all base line until find expected selects for _, b := range baselines { baseline := time.Duration(b) - for i := 0; i < availableCount; i++ { - if nodes[i].Weighted > baseline { + for i := count; i < availableCount; i++ { + if nodes[i].Weighted >= baseline { break } count = i + 1 diff --git a/balancer/balancer_select_test.go b/balancer/balancer_select_test.go new file mode 100644 index 00000000..fd905f11 --- /dev/null +++ b/balancer/balancer_select_test.go @@ -0,0 +1,39 @@ +package balancer + +import ( + "testing" + + "github.com/sagernet/sing-box/option" +) + +func TestSelectNodes(t *testing.T) { + nodes := []*Node{ + {HealthCheckStats: HealthCheckStats{Weighted: 50}}, + {HealthCheckStats: HealthCheckStats{Weighted: 70}}, + {HealthCheckStats: HealthCheckStats{Weighted: 100}}, + {HealthCheckStats: HealthCheckStats{Weighted: 110}}, + {HealthCheckStats: HealthCheckStats{Weighted: 120}}, + {HealthCheckStats: HealthCheckStats{Weighted: 150}}, + } + tests := []struct { + expected int + baselines []option.Duration + want int + }{ + {expected: -1, baselines: nil, want: 1}, + {expected: 0, baselines: nil, want: 1}, + {expected: 1, baselines: nil, want: 1}, + {expected: 9999, baselines: nil, want: len(nodes)}, + {expected: 0, baselines: []option.Duration{80, 100}, want: 2}, + {expected: 2, baselines: []option.Duration{50, 100}, want: 2}, + {expected: 3, baselines: []option.Duration{50, 100, 150}, want: 5}, + {expected: 9999, baselines: []option.Duration{50, 100, 150}, want: len(nodes)}, + } + for _, tt := range tests { + t.Run("", func(t *testing.T) { + if got := selectNodes(nodes, nil, tt.expected, tt.baselines); len(got) != tt.want { + t.Errorf("selectNodes() = %v, want %v", len(got), tt.want) + } + }) + } +}