github.com/ulule/limiter/v3@v3.11.3-0.20230613131926-4cb9c1da4633/rate_test.go (about)

     1  package limiter_test
     2  
     3  import (
     4  	"reflect"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/stretchr/testify/require"
     9  
    10  	"github.com/ulule/limiter/v3"
    11  )
    12  
    13  // TestRate tests Rate methods.
    14  func TestRate(t *testing.T) {
    15  	is := require.New(t)
    16  
    17  	expected := map[string]limiter.Rate{
    18  		"10-S": {
    19  			Formatted: "10-S",
    20  			Period:    1 * time.Second,
    21  			Limit:     int64(10),
    22  		},
    23  		"356-M": {
    24  			Formatted: "356-M",
    25  			Period:    1 * time.Minute,
    26  			Limit:     int64(356),
    27  		},
    28  		"3-H": {
    29  			Formatted: "3-H",
    30  			Period:    1 * time.Hour,
    31  			Limit:     int64(3),
    32  		},
    33  		"2000-D": {
    34  			Formatted: "2000-D",
    35  			Period:    24 * time.Hour,
    36  			Limit:     int64(2000),
    37  		},
    38  	}
    39  
    40  	for k, v := range expected {
    41  		r, err := limiter.NewRateFromFormatted(k)
    42  		is.NoError(err)
    43  		is.True(reflect.DeepEqual(v, r))
    44  	}
    45  
    46  	wrongs := []string{
    47  		"10 S",
    48  		"10:S",
    49  		"AZERTY",
    50  		"na wak",
    51  		"H-10",
    52  	}
    53  
    54  	for _, w := range wrongs {
    55  		_, err := limiter.NewRateFromFormatted(w)
    56  		is.Error(err)
    57  	}
    58  
    59  }