github.com/netdata/go.d.plugin@v0.58.1/agent/ticker/ticket_test.go (about)

     1  // SPDX-License-Identifier: GPL-3.0-or-later
     2  
     3  package ticker
     4  
     5  import (
     6  	"testing"
     7  	"time"
     8  )
     9  
    10  // TODO: often fails Circle CI (~200-240)
    11  var allowedDelta = 500 * time.Millisecond
    12  
    13  func TestTickerParallel(t *testing.T) {
    14  	for i := 0; i < 100; i++ {
    15  		i := i
    16  		go func() {
    17  			time.Sleep(time.Second / 100 * time.Duration(i))
    18  			TestTicker(t)
    19  		}()
    20  	}
    21  	time.Sleep(4 * time.Second)
    22  }
    23  
    24  func TestTicker(t *testing.T) {
    25  	tk := New(time.Second)
    26  	defer tk.Stop()
    27  	prev := time.Now()
    28  	for i := 0; i < 3; i++ {
    29  		<-tk.C
    30  		now := time.Now()
    31  		diff := abs(now.Round(time.Second).Sub(now))
    32  		if diff >= allowedDelta {
    33  			t.Errorf("Ticker is not aligned: expect delta < %v but was: %v (%s)", allowedDelta, diff, now.Format(time.RFC3339Nano))
    34  		}
    35  		if i > 0 {
    36  			dt := now.Sub(prev)
    37  			if abs(dt-time.Second) >= allowedDelta {
    38  				t.Errorf("Ticker interval: expect delta < %v ns but was: %v", allowedDelta, abs(dt-time.Second))
    39  			}
    40  		}
    41  		prev = now
    42  	}
    43  }
    44  
    45  func abs(a time.Duration) time.Duration {
    46  	if a < 0 {
    47  		return -a
    48  	}
    49  	return a
    50  }