github.com/web-platform-tests/wpt.fyi@v0.0.0-20240530210107-70cf978996f1/api/query/cache/lru/lru_test.go (about)

     1  //go:build small
     2  // +build small
     3  
     4  // Copyright 2018 The WPT Dashboard Project. All rights reserved.
     5  // Use of this source code is governed by a BSD-style license that can be
     6  // found in the LICENSE file.
     7  
     8  package lru
     9  
    10  import (
    11  	"math/rand"
    12  	"sync"
    13  	"testing"
    14  	"time"
    15  
    16  	"github.com/stretchr/testify/assert"
    17  )
    18  
    19  func TestLRUEmpty(t *testing.T) {
    20  	l := NewLRU()
    21  	removed := l.EvictLRU(1.0)
    22  	assert.Nil(t, removed)
    23  }
    24  
    25  func TestSimple(t *testing.T) {
    26  	l := NewLRU()
    27  	l.Access(1)
    28  	l.Access(2)
    29  	removed := l.EvictLRU(0.5)
    30  	assert.Equal(t, []int64{int64(1)}, removed)
    31  }
    32  
    33  func TestRoundUpToOne(t *testing.T) {
    34  	l := NewLRU()
    35  	l.Access(1)
    36  	l.Access(2)
    37  	removed := l.EvictLRU(-1000.0)
    38  	assert.Equal(t, []int64{int64(1)}, removed)
    39  }
    40  
    41  func TestRoundDown(t *testing.T) {
    42  	l := NewLRU()
    43  	l.Access(1)
    44  	l.Access(2)
    45  	removed := l.EvictLRU(0.99999)
    46  	assert.Equal(t, []int64{int64(1)}, removed)
    47  }
    48  
    49  func TestRoundWayDown(t *testing.T) {
    50  	l := NewLRU()
    51  	l.Access(1)
    52  	l.Access(2)
    53  	removed := l.EvictLRU(1000.0)
    54  	assert.Equal(t, []int64{int64(1), int64(2)}, removed)
    55  }
    56  
    57  func TestRepeatAccess(t *testing.T) {
    58  	l := NewLRU()
    59  	l.Access(1)
    60  	l.Access(2)
    61  	l.Access(1)
    62  	// Remove slightly over half of the items to avoid floating point
    63  	// errors in the case that 0.5 * 2 is < 1.
    64  	removed := l.EvictLRU(0.51)
    65  	assert.Equal(t, []int64{int64(2)}, removed)
    66  }
    67  
    68  func TestConcurrency(t *testing.T) {
    69  	l := NewLRU()
    70  	var wg sync.WaitGroup
    71  	for i := 1; i <= 100; i++ {
    72  		wg.Add(1)
    73  		go func(id int64) {
    74  			defer wg.Done()
    75  			l.Access(id)
    76  			wait := rand.Int() % 1000
    77  			time.Sleep(time.Nanosecond * time.Duration(wait))
    78  			removed := l.EvictLRU(0.0)
    79  			assert.Equal(t, 1, len(removed))
    80  		}(int64(i))
    81  	}
    82  	wg.Wait()
    83  
    84  	removed := l.EvictLRU(0.0)
    85  	assert.Nil(t, removed)
    86  }