github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/ticker_test.go (about)

     1  package utils
     2  
     3  import (
     4  	"github.com/TeaOSLab/EdgeNode/internal/utils/testutils"
     5  	"sync"
     6  	"testing"
     7  	"time"
     8  )
     9  
    10  func TestRawTicker(t *testing.T) {
    11  	if !testutils.IsSingleTesting() {
    12  		return
    13  	}
    14  
    15  	var ticker = time.NewTicker(2 * time.Second)
    16  	go func() {
    17  		for range ticker.C {
    18  			t.Log("tick")
    19  		}
    20  		t.Log("stop")
    21  	}()
    22  
    23  	time.Sleep(6 * time.Second)
    24  	ticker.Stop()
    25  	time.Sleep(1 * time.Second)
    26  }
    27  
    28  func TestTicker(t *testing.T) {
    29  	if !testutils.IsSingleTesting() {
    30  		return
    31  	}
    32  
    33  	ticker := NewTicker(3 * time.Second)
    34  	go func() {
    35  		time.Sleep(10 * time.Second)
    36  		ticker.Stop()
    37  	}()
    38  	for ticker.Next() {
    39  		t.Log("tick")
    40  	}
    41  	t.Log("finished")
    42  }
    43  
    44  func TestTicker2(t *testing.T) {
    45  	if !testutils.IsSingleTesting() {
    46  		return
    47  	}
    48  
    49  	ticker := NewTicker(1 * time.Second)
    50  	go func() {
    51  		time.Sleep(5 * time.Second)
    52  		ticker.Stop()
    53  	}()
    54  	for {
    55  		t.Log("loop")
    56  		select {
    57  		case <-ticker.raw.C:
    58  			t.Log("tick")
    59  		case <-ticker.done:
    60  			return
    61  		}
    62  	}
    63  }
    64  
    65  func TestTickerEvery(t *testing.T) {
    66  	if !testutils.IsSingleTesting() {
    67  		return
    68  	}
    69  
    70  	i := 0
    71  	wg := &sync.WaitGroup{}
    72  	wg.Add(1)
    73  	Every(2*time.Second, func(ticker *Ticker) {
    74  		i++
    75  		t.Log("TestTickerEvery i:", i)
    76  		if i >= 4 {
    77  			ticker.Stop()
    78  			wg.Done()
    79  		}
    80  	})
    81  	wg.Wait()
    82  }
    83  
    84  func TestTicker_StopTwice(t *testing.T) {
    85  	if !testutils.IsSingleTesting() {
    86  		return
    87  	}
    88  
    89  	ticker := NewTicker(3 * time.Second)
    90  	go func() {
    91  		time.Sleep(10 * time.Second)
    92  		ticker.Stop()
    93  		ticker.Stop()
    94  	}()
    95  	for ticker.Next() {
    96  		t.Log("tick")
    97  	}
    98  	t.Log("finished")
    99  }