github.com/ethersphere/bee/v2@v2.2.0/pkg/rate/rate_test.go (about)

     1  // Copyright 2022 The Swarm Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package rate_test
     6  
     7  import (
     8  	"testing"
     9  	"time"
    10  
    11  	"github.com/ethersphere/bee/v2/pkg/rate"
    12  )
    13  
    14  func TestRateFirstBucket(t *testing.T) {
    15  	t.Parallel()
    16  
    17  	windowSize := 1000 * time.Millisecond
    18  	var r = 15
    19  
    20  	rate := rate.New(windowSize)
    21  	rate.SetTimeFunc(func() time.Time { return setTime(windowSize) })
    22  	rate.Add(r)
    23  
    24  	got := rate.Rate()
    25  	if got != float64(r) {
    26  		t.Fatalf("got %v, want %v", got, r)
    27  	}
    28  }
    29  
    30  // // TestIgnoreOldBuckets tests that the buckets older than the most recent two buckets are ignored in rate calculation.
    31  func TestIgnoreOldBuckets(t *testing.T) {
    32  	t.Parallel()
    33  
    34  	windowSize := 1000 * time.Millisecond
    35  	var r = 100
    36  
    37  	rate := rate.New(windowSize)
    38  
    39  	rate.SetTimeFunc(func() time.Time { return setTime(windowSize) })
    40  	rate.Add(10)
    41  
    42  	// windowSize * 3 ensures that the previous bucket is ignored
    43  	rate.SetTimeFunc(func() time.Time { return setTime(windowSize * 3) })
    44  	rate.Add(r)
    45  
    46  	got := rate.Rate()
    47  	if got != float64(r) {
    48  		t.Fatalf("got %v, want %v", got, r)
    49  	}
    50  }
    51  
    52  func TestRate(t *testing.T) {
    53  	t.Parallel()
    54  
    55  	// windowSizeMs := 1000
    56  	windowSize := 1000 * time.Millisecond
    57  	const r = 100
    58  
    59  	// tc represents the different ratios that will applied to the previous bucket in the Rate calculation
    60  	// eg: the ratio is x, so (1 - 1/x) will be applied to the previous bucket
    61  	for _, tc := range []struct {
    62  		ratio int
    63  		rate  float64
    64  	}{
    65  		{ratio: 2, rate: 150},
    66  		{ratio: 4, rate: 175},
    67  		{ratio: 5, rate: 180},
    68  		{ratio: 10, rate: 190},
    69  		{ratio: 100, rate: 199},
    70  	} {
    71  
    72  		rate := rate.New(windowSize)
    73  
    74  		rate.SetTimeFunc(func() time.Time { return setTime(windowSize) })
    75  		rate.Add(r)
    76  
    77  		rate.SetTimeFunc(func() time.Time { return setTime(windowSize*2 + windowSize/time.Duration(tc.ratio)) })
    78  		rate.Add(r)
    79  
    80  		got := rate.Rate()
    81  		if got != tc.rate {
    82  			t.Fatalf("ratio %v, got %v, want %v", tc.ratio, got, tc.rate)
    83  		}
    84  	}
    85  }
    86  
    87  func setTime(ms time.Duration) time.Time {
    88  	return time.UnixMilli(ms.Milliseconds())
    89  }