github.com/xmplusdev/xmcore@v1.8.11-0.20240412132628-5518b55526af/app/router/weight_test.go (about)

     1  package router_test
     2  
     3  import (
     4  	"reflect"
     5  	"testing"
     6  
     7  	"github.com/xmplusdev/xmcore/app/router"
     8  )
     9  
    10  func TestWeight(t *testing.T) {
    11  	manager := router.NewWeightManager(
    12  		[]*router.StrategyWeight{
    13  			{
    14  				Match: "x5",
    15  				Value: 100,
    16  			},
    17  			{
    18  				Match: "x8",
    19  			},
    20  			{
    21  				Regexp: true,
    22  				Match:  `\bx0+(\.\d+)?\b`,
    23  				Value:  1,
    24  			},
    25  			{
    26  				Regexp: true,
    27  				Match:  `\bx\d+(\.\d+)?\b`,
    28  			},
    29  		},
    30  		1, func(v, w float64) float64 {
    31  			return v * w
    32  		},
    33  	)
    34  	tags := []string{
    35  		"node name, x5, and more",
    36  		"node name, x8",
    37  		"node name, x15",
    38  		"node name, x0100, and more",
    39  		"node name, x10.1",
    40  		"node name, x00.1, and more",
    41  	}
    42  	// test weight
    43  	expected := []float64{100, 8, 15, 100, 10.1, 1}
    44  	actual := make([]float64, 0)
    45  	for _, tag := range tags {
    46  		actual = append(actual, manager.Get(tag))
    47  	}
    48  	if !reflect.DeepEqual(expected, actual) {
    49  		t.Errorf("expected: %v, actual: %v", expected, actual)
    50  	}
    51  	// test scale
    52  	expected2 := []float64{1000, 80, 150, 1000, 101, 10}
    53  	actual2 := make([]float64, 0)
    54  	for _, tag := range tags {
    55  		actual2 = append(actual2, manager.Apply(tag, 10))
    56  	}
    57  	if !reflect.DeepEqual(expected2, actual2) {
    58  		t.Errorf("expected2: %v, actual2: %v", expected2, actual2)
    59  	}
    60  }