k8s.io/apiserver@v0.31.1/pkg/util/flowcontrol/fairqueuing/eventclock/real_event_clock_test.go (about)

     1  /*
     2  Copyright 2021 The Kubernetes 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 eventclock
    18  
    19  import (
    20  	"math/rand"
    21  	"sync/atomic"
    22  	"testing"
    23  	"time"
    24  )
    25  
    26  func TestRealEventClock(t *testing.T) {
    27  	ec := Real{}
    28  	var numDone int32
    29  	now := ec.Now()
    30  	const batchSize = 100
    31  	times := make(chan time.Time, batchSize+1)
    32  	try := func(abs bool, d time.Duration) {
    33  		f := func(u time.Time) {
    34  			realD := ec.Since(now)
    35  			atomic.AddInt32(&numDone, 1)
    36  			times <- u
    37  			if realD < d {
    38  				t.Errorf("Asked for %v, got %v", d, realD)
    39  			}
    40  		}
    41  		if abs {
    42  			ec.EventAfterTime(f, now.Add(d))
    43  		} else {
    44  			ec.EventAfterDuration(f, d)
    45  		}
    46  	}
    47  	try(true, time.Millisecond*3300)
    48  	for i := 0; i < batchSize; i++ {
    49  		d := time.Duration(rand.Intn(30)-3) * time.Millisecond * 100
    50  		try(i%2 == 0, d)
    51  	}
    52  	time.Sleep(time.Second * 4)
    53  	if atomic.LoadInt32(&numDone) != batchSize+1 {
    54  		t.Errorf("Got only %v events", numDone)
    55  	}
    56  	lastTime := now
    57  	for i := 0; i <= batchSize; i++ {
    58  		nextTime := <-times
    59  		if nextTime.Before(now) {
    60  			continue
    61  		}
    62  		dt := nextTime.Sub(lastTime) / (50 * time.Millisecond)
    63  		if dt < 0 {
    64  			t.Errorf("Got %s after %s", nextTime, lastTime)
    65  		}
    66  		lastTime = nextTime
    67  	}
    68  }