gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/grpc/balancer/rls/internal/adaptive/lookback_test.go (about)

     1  /*
     2   *
     3   * Copyright 2020 gRPC authors.
     4   *
     5   * Licensed under the Apache License, Version 2.0 (the "License");
     6   * you may not use this file except in compliance with the License.
     7   * You may obtain a copy of the License at
     8   *
     9   *     http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   *
    17   */
    18  
    19  package adaptive
    20  
    21  import (
    22  	"testing"
    23  	"time"
    24  )
    25  
    26  func TestLookback(t *testing.T) {
    27  	makeTicks := func(offsets []int64) []time.Time {
    28  		var ticks []time.Time
    29  		now := time.Now()
    30  		for _, offset := range offsets {
    31  			ticks = append(ticks, now.Add(time.Duration(offset)))
    32  		}
    33  		return ticks
    34  	}
    35  
    36  	// lookback.add and lookback.sum behave correctly.
    37  	testcases := []struct {
    38  		desc   string
    39  		bins   int64
    40  		ticks  []time.Time
    41  		values []int64
    42  		want   []int64
    43  	}{
    44  		{
    45  			"Accumulate",
    46  			3,
    47  			makeTicks([]int64{0, 1, 2}), // Ticks
    48  			[]int64{1, 2, 3},            // Values
    49  			[]int64{1, 3, 6},            // Want
    50  		},
    51  		{
    52  			"LightTimeTravel",
    53  			3,
    54  			makeTicks([]int64{1, 0, 2}), // Ticks
    55  			[]int64{1, 2, 3},            // Values
    56  			[]int64{1, 3, 6},            // Want
    57  		},
    58  		{
    59  			"HeavyTimeTravel",
    60  			3,
    61  			makeTicks([]int64{8, 0, 9}), // Ticks
    62  			[]int64{1, 2, 3},            // Values
    63  			[]int64{1, 1, 4},            // Want
    64  		},
    65  		{
    66  			"Rollover",
    67  			1,
    68  			makeTicks([]int64{0, 1, 2}), // Ticks
    69  			[]int64{1, 2, 3},            // Values
    70  			[]int64{1, 2, 3},            // Want
    71  		},
    72  	}
    73  
    74  	for _, test := range testcases {
    75  		t.Run(test.desc, func(t *testing.T) {
    76  			lb := newLookback(test.bins, time.Duration(test.bins))
    77  			for i, tick := range test.ticks {
    78  				lb.add(tick, test.values[i])
    79  				if got := lb.sum(tick); got != test.want[i] {
    80  					t.Errorf("sum for index %d got %d, want %d", i, got, test.want[i])
    81  				}
    82  			}
    83  		})
    84  	}
    85  }