Merge branch 'master' into add-tests

This commit is contained in:
Mohammed Al Sahaf
2026-06-09 02:30:37 +03:00
committed by GitHub
4 changed files with 124 additions and 6 deletions

View File

@@ -127,6 +127,19 @@ func (r *WeightedRoundRobinSelection) Provision(ctx caddy.Context) error {
return nil
}
// Validate ensures that r's configuration is valid
func (r *WeightedRoundRobinSelection) Validate() error {
if r.totalWeight <= 0 {
return fmt.Errorf("weighted_round_robin requires at least one upstream with a positive weight")
}
for _, weight := range r.Weights {
if weight < 0 {
return fmt.Errorf("weight of an upstream cannot be negative")
}
}
return nil
}
// Select returns an available host, if any.
func (r *WeightedRoundRobinSelection) Select(pool UpstreamPool, _ *http.Request, _ http.ResponseWriter) *Upstream {
if len(pool) == 0 {
@@ -891,6 +904,7 @@ var (
_ Selector = (*CookieHashSelection)(nil)
_ caddy.Validator = (*RandomChoiceSelection)(nil)
_ caddy.Validator = (*WeightedRoundRobinSelection)(nil)
_ caddy.Provisioner = (*RandomChoiceSelection)(nil)
_ caddy.Provisioner = (*WeightedRoundRobinSelection)(nil)

View File

@@ -131,6 +131,48 @@ func TestWeightedRoundRobinPolicy(t *testing.T) {
}
}
func TestWeightedRoundRobinSelection_Validate(t *testing.T) {
tests := []struct {
name string
weights []int
wantErr bool
}{
{
name: "Valid 0 2 1 case",
weights: []int{0, 2, 1},
wantErr: false,
},
{
name: "Invalid 0 case (single)",
weights: []int{0},
wantErr: true,
},
{
name: "Invalid 0 0 case (multiple)",
weights: []int{0, 0},
wantErr: true,
},
{
name: "Valid weights",
weights: []int{1, 1, 1},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := &WeightedRoundRobinSelection{
Weights: tt.weights,
}
_ = s.Provision(caddy.Context{})
err := s.Validate()
if (err != nil) != tt.wantErr {
t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestWeightedRoundRobinPolicyWithZeroWeight(t *testing.T) {
pool := testPool()
wrrPolicy := WeightedRoundRobinSelection{