github.com/richardwilkes/toolbox@v1.121.0/rate/limiter_test.go (about)

     1  // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the Mozilla Public
     4  // License, version 2.0. If a copy of the MPL was not distributed with
     5  // this file, You can obtain one at http://mozilla.org/MPL/2.0/.
     6  //
     7  // This Source Code Form is "Incompatible With Secondary Licenses", as
     8  // defined by the Mozilla Public License, version 2.0.
     9  
    10  package rate_test
    11  
    12  import (
    13  	"testing"
    14  	"time"
    15  
    16  	"github.com/richardwilkes/toolbox/check"
    17  	"github.com/richardwilkes/toolbox/rate"
    18  )
    19  
    20  func TestCap(t *testing.T) {
    21  	rl := rate.New(50*1024, time.Second)
    22  	check.Equal(t, 50*1024, rl.Cap(true))
    23  	sub := rl.New(100 * 1024)
    24  	check.Equal(t, 100*1024, sub.Cap(false))
    25  	check.Equal(t, 50*1024, sub.Cap(true))
    26  	sub.SetCap(1024)
    27  	check.Equal(t, 1024, sub.Cap(true))
    28  	rl.Close()
    29  	check.True(t, sub.Closed())
    30  	check.True(t, rl.Closed())
    31  }
    32  
    33  func TestUse(t *testing.T) {
    34  	rl := rate.New(100, 100*time.Millisecond)
    35  	endAfter := time.Now().Add(250 * time.Millisecond)
    36  	for endAfter.After(time.Now()) {
    37  		err := <-rl.Use(1)
    38  		check.NoError(t, err)
    39  	}
    40  	check.Equal(t, 100, rl.LastUsed())
    41  	rl.Close()
    42  	check.True(t, rl.Closed())
    43  }