go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/rate/checker_test.go (about)

     1  /*
     2  
     3  Copyright (c) 2024 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package rate
     9  
    10  import (
    11  	"testing"
    12  	"time"
    13  
    14  	"go.charczuk.com/sdk/assert"
    15  )
    16  
    17  type timeProvider struct {
    18  	index int
    19  	times []time.Time
    20  }
    21  
    22  func (tp *timeProvider) Now() (output time.Time) {
    23  	output = tp.times[tp.index]
    24  	tp.index++
    25  	return
    26  }
    27  
    28  func Test_RateChecker(t *testing.T) {
    29  	tp := timeProvider{times: []time.Time{
    30  		time.Date(2023, 10, 23, 22, 10, 00, 00, time.UTC),
    31  		time.Date(2023, 10, 23, 22, 10, 00, 500, time.UTC),
    32  		time.Date(2023, 10, 23, 22, 10, 00, 1000, time.UTC),
    33  		time.Date(2023, 10, 23, 22, 10, 00, 1500, time.UTC),
    34  		time.Date(2023, 10, 23, 22, 10, 02, 00, time.UTC),
    35  		time.Date(2023, 10, 23, 22, 10, 02, 500, time.UTC),
    36  		time.Date(2023, 10, 23, 22, 10, 02, 1000, time.UTC),
    37  		time.Date(2023, 10, 23, 22, 10, 02, 1500, time.UTC),
    38  	}}
    39  	rc := NewRateChecker(3, time.Second)
    40  	rc.nowProvider = tp.Now
    41  
    42  	assert.ItsNil(t, rc.Check())
    43  	assert.ItsNil(t, rc.Check())
    44  	assert.ItsEqual(t, ErrRateCheckFailure, rc.Check())
    45  	assert.ItsEqual(t, ErrRateCheckFailure, rc.Check())
    46  
    47  	assert.ItsNil(t, rc.Check())
    48  	assert.ItsNil(t, rc.Check())
    49  	assert.ItsEqual(t, ErrRateCheckFailure, rc.Check())
    50  	assert.ItsEqual(t, ErrRateCheckFailure, rc.Check())
    51  }