github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/swarmkit/manager/dispatcher/heartbeat/heartbeat_test.go (about)

     1  package heartbeat
     2  
     3  import (
     4  	"testing"
     5  	"time"
     6  )
     7  
     8  func TestHeartbeatBeat(t *testing.T) {
     9  	ch := make(chan struct{})
    10  	hb := New(200*time.Millisecond, func() {
    11  		close(ch)
    12  	})
    13  	for i := 0; i < 4; i++ {
    14  		time.Sleep(100 * time.Millisecond)
    15  		hb.Beat()
    16  	}
    17  	hb.Stop()
    18  	select {
    19  	case <-ch:
    20  		t.Fatal("Heartbeat was expired")
    21  	case <-time.After(100 * time.Millisecond):
    22  	}
    23  }
    24  
    25  func TestHeartbeatTimeout(t *testing.T) {
    26  	ch := make(chan struct{})
    27  	hb := New(100*time.Millisecond, func() {
    28  		close(ch)
    29  	})
    30  	defer hb.Stop()
    31  	select {
    32  	case <-ch:
    33  	case <-time.After(500 * time.Millisecond):
    34  		t.Fatal("timeoutFunc wasn't called in timely fashion")
    35  	}
    36  }
    37  
    38  func TestHeartbeatReactivate(t *testing.T) {
    39  	ch := make(chan struct{}, 2)
    40  	hb := New(100*time.Millisecond, func() {
    41  		ch <- struct{}{}
    42  	})
    43  	defer hb.Stop()
    44  	time.Sleep(200 * time.Millisecond)
    45  	hb.Beat()
    46  	time.Sleep(200 * time.Millisecond)
    47  	for i := 0; i < 2; i++ {
    48  		select {
    49  		case <-ch:
    50  		case <-time.After(500 * time.Millisecond):
    51  			t.Fatal("timeoutFunc wasn't called in timely fashion")
    52  		}
    53  	}
    54  }
    55  
    56  func TestHeartbeatUpdate(t *testing.T) {
    57  	ch := make(chan struct{})
    58  	hb := New(1*time.Second, func() {
    59  		close(ch)
    60  	})
    61  	defer hb.Stop()
    62  	hb.Update(100 * time.Millisecond)
    63  	hb.Beat()
    64  	time.Sleep(200 * time.Millisecond)
    65  	select {
    66  	case <-ch:
    67  	case <-time.After(500 * time.Millisecond):
    68  		t.Fatal("timeoutFunc wasn't called in timely fashion")
    69  	}
    70  }