github.com/TeaOSLab/EdgeNode@v1.3.8/internal/ttlcache/piece_test.go (about)

     1  package ttlcache
     2  
     3  import (
     4  	"github.com/iwind/TeaGo/rands"
     5  	"testing"
     6  	"time"
     7  )
     8  
     9  func TestPiece_Add(t *testing.T) {
    10  	piece := NewPiece[int](10)
    11  	piece.Add(1, &Item[int]{expiredAt: time.Now().Unix() + 3600})
    12  	piece.Add(2, &Item[int]{})
    13  	piece.Add(3, &Item[int]{})
    14  	piece.Delete(3)
    15  	for key, item := range piece.m {
    16  		t.Log(key, item.Value)
    17  	}
    18  	t.Log(piece.Read(1))
    19  }
    20  
    21  func TestPiece_Add_Same(t *testing.T) {
    22  	piece := NewPiece[int](10)
    23  	piece.Add(1, &Item[int]{expiredAt: time.Now().Unix() + 3600})
    24  	piece.Add(1, &Item[int]{expiredAt: time.Now().Unix() + 3600})
    25  	for key, item := range piece.m {
    26  		t.Log(key, item.Value)
    27  	}
    28  	t.Log(piece.Read(1))
    29  }
    30  
    31  func TestPiece_MaxItems(t *testing.T) {
    32  	piece := NewPiece[int](10)
    33  	for i := 0; i < 1000; i++ {
    34  		piece.Add(uint64(i), &Item[int]{expiredAt: time.Now().Unix() + 3600})
    35  	}
    36  	t.Log(len(piece.m))
    37  }
    38  
    39  func TestPiece_GC(t *testing.T) {
    40  	piece := NewPiece[int](10)
    41  	piece.Add(1, &Item[int]{Value: 1, expiredAt: time.Now().Unix() + 1})
    42  	piece.Add(2, &Item[int]{Value: 2, expiredAt: time.Now().Unix() + 1})
    43  	piece.Add(3, &Item[int]{Value: 3, expiredAt: time.Now().Unix() + 1})
    44  	t.Log("before gc ===")
    45  	for key, item := range piece.m {
    46  		t.Log(key, item.Value)
    47  	}
    48  
    49  	time.Sleep(1 * time.Second)
    50  	piece.GC()
    51  
    52  	t.Log("after gc ===")
    53  	for key, item := range piece.m {
    54  		t.Log(key, item.Value)
    55  	}
    56  }
    57  
    58  func TestPiece_GC2(t *testing.T) {
    59  	piece := NewPiece[int](10)
    60  	for i := 0; i < 10_000; i++ {
    61  		piece.Add(uint64(i), &Item[int]{Value: 1, expiredAt: time.Now().Unix() + int64(rands.Int(1, 10))})
    62  	}
    63  
    64  	time.Sleep(1 * time.Second)
    65  
    66  	before := time.Now()
    67  	piece.GC()
    68  	t.Log(time.Since(before).Seconds()*1000, "ms")
    69  	t.Log(piece.Count())
    70  }