github.com/minio/minio@v0.0.0-20240328213742-3f72439b8a27/internal/cachevalue/cache_test.go (about)

     1  // Copyright (c) 2015-2024 MinIO, Inc.
     2  //
     3  // This file is part of MinIO Object Storage stack
     4  //
     5  // This program is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Affero General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // This program is distributed in the hope that it will be useful
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13  // GNU Affero General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Affero General Public License
    16  // along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package cachevalue
    19  
    20  import (
    21  	"testing"
    22  	"time"
    23  )
    24  
    25  func TestCache(t *testing.T) {
    26  	cache := New[time.Time]()
    27  	t.Parallel()
    28  	cache.InitOnce(2*time.Second, Opts{},
    29  		func() (time.Time, error) {
    30  			return time.Now(), nil
    31  		},
    32  	)
    33  
    34  	t1, _ := cache.Get()
    35  
    36  	t2, _ := cache.Get()
    37  
    38  	if !t1.Equal(t2) {
    39  		t.Fatalf("expected time to be equal: %s != %s", t1, t2)
    40  	}
    41  
    42  	time.Sleep(3 * time.Second)
    43  	t3, _ := cache.Get()
    44  
    45  	if t1.Equal(t3) {
    46  		t.Fatalf("expected time to be un-equal: %s == %s", t1, t3)
    47  	}
    48  }
    49  
    50  func BenchmarkCache(b *testing.B) {
    51  	cache := New[time.Time]()
    52  	cache.InitOnce(1*time.Millisecond, Opts{},
    53  		func() (time.Time, error) {
    54  			return time.Now(), nil
    55  		},
    56  	)
    57  
    58  	b.ReportAllocs()
    59  	b.ResetTimer()
    60  
    61  	b.RunParallel(func(pb *testing.PB) {
    62  		for pb.Next() {
    63  			cache.Get()
    64  		}
    65  	})
    66  }