vitess.io/vitess@v0.16.2/go/vt/throttler/thread_throttler_test.go (about)

     1  /*
     2  Copyright 2019 The Vitess Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package throttler
    18  
    19  import (
    20  	"testing"
    21  	"time"
    22  )
    23  
    24  func TestThrottle_NoBurst(t *testing.T) {
    25  	tt := newThreadThrottler(0, newAggregatedIntervalHistory(1, 1*time.Second, 1))
    26  	tt.setMaxRate(2)
    27  	// We set the rate to 2 requests per second, and internally the throttler uses a burst value of
    28  	// 1. This means that in any time interval of length t seconds, the throttler should
    29  	// not allow more than floor(2*t+1) requests. For example, in the interval [1500ms, 1501ms], of
    30  	// length 1ms, we shouldn't be able to send more than floor(2*10^-3+1)=1 requests.
    31  	if gotBackoff := tt.throttle(sinceZero(1500 * time.Millisecond)); gotBackoff != NotThrottled {
    32  		t.Fatalf("throttler should not have throttled us: backoff = %v", gotBackoff)
    33  	}
    34  	wantBackoff := 499 * time.Millisecond
    35  	if gotBackoff := tt.throttle(sinceZero(1501 * time.Millisecond)); gotBackoff != wantBackoff {
    36  		t.Fatalf("throttler should have throttled us. got = %v, want = %v", gotBackoff, wantBackoff)
    37  	}
    38  }