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

     1  // Copyright 2023 GoEdge CDN goedge.cdn@gmail.com. All rights reserved. Official site: https://goedge.cn .
     2  
     3  package counters_test
     4  
     5  import (
     6  	"github.com/TeaOSLab/EdgeNode/internal/utils/counters"
     7  	"github.com/TeaOSLab/EdgeNode/internal/utils/testutils"
     8  	"github.com/iwind/TeaGo/assert"
     9  	"github.com/iwind/TeaGo/types"
    10  	timeutil "github.com/iwind/TeaGo/utils/time"
    11  	"runtime"
    12  	"testing"
    13  	"time"
    14  )
    15  
    16  func TestItem_Increase(t *testing.T) {
    17  	if !testutils.IsSingleTesting() {
    18  		return
    19  	}
    20  
    21  	var item = counters.NewItem[uint32](10)
    22  	t.Log(item.Increase(), item.Sum())
    23  	time.Sleep(1 * time.Second)
    24  	t.Log(item.Increase(), item.Sum())
    25  	time.Sleep(2 * time.Second)
    26  	t.Log(item.Increase(), item.Sum())
    27  	time.Sleep(5 * time.Second)
    28  	t.Log(item.Increase(), item.Sum())
    29  	time.Sleep(6 * time.Second)
    30  	t.Log(item.Increase(), item.Sum())
    31  	time.Sleep(5 * time.Second)
    32  	t.Log(item.Increase(), item.Sum())
    33  	time.Sleep(11 * time.Second)
    34  	t.Log(item.Increase(), item.Sum())
    35  }
    36  
    37  func TestItem_Increase2(t *testing.T) {
    38  	// run only under single testing
    39  	if !testutils.IsSingleTesting() {
    40  		return
    41  	}
    42  
    43  	var a = assert.NewAssertion(t)
    44  
    45  	var item = counters.NewItem[uint32](23)
    46  	for i := 0; i < 100; i++ {
    47  		t.Log("round "+types.String(i)+":", item.Increase(), item.Sum(), timeutil.Format("H:i:s"))
    48  		time.Sleep(2 * time.Second)
    49  	}
    50  
    51  	item.Reset()
    52  	a.IsTrue(item.Sum() == 0)
    53  }
    54  
    55  func TestItem_IsExpired(t *testing.T) {
    56  	if !testutils.IsSingleTesting() {
    57  		return
    58  	}
    59  
    60  	var item = counters.NewItem[uint32](10)
    61  	t.Log(item.IsExpired(time.Now().Unix()))
    62  	time.Sleep(10 * time.Second)
    63  	t.Log(item.IsExpired(time.Now().Unix()))
    64  	time.Sleep(2 * time.Second)
    65  	t.Log(item.IsExpired(time.Now().Unix()))
    66  	time.Sleep(2 * time.Second)
    67  	t.Log(item.IsExpired(time.Now().Unix()))
    68  }
    69  
    70  func BenchmarkItem_Increase(b *testing.B) {
    71  	runtime.GOMAXPROCS(1)
    72  
    73  	b.ReportAllocs()
    74  
    75  	b.RunParallel(func(pb *testing.PB) {
    76  		for pb.Next() {
    77  			var item = counters.NewItem[uint32](60)
    78  			item.Increase()
    79  			item.Sum()
    80  		}
    81  	})
    82  }