|
| 1 | +package lfu |
| 2 | + |
| 3 | +import ( |
| 4 | + "container/heap" |
| 5 | + "testing" |
| 6 | + "time" |
| 7 | +) |
| 8 | + |
| 9 | +func TestPriorityQueue(t *testing.T) { |
| 10 | + // perl -MList::Util -e 'print join ",", List::Util::shuffle(1..10)' |
| 11 | + nums := []int{2, 1, 4, 5, 6, 9, 7, 10, 8, 3} |
| 12 | + queue := newPriorityQueue[int, int](len(nums)) |
| 13 | + entries := make([]*entry[int, int], 0, len(nums)) |
| 14 | + |
| 15 | + for _, v := range nums { |
| 16 | + entry := newEntry(v, v) |
| 17 | + entries = append(entries, entry) |
| 18 | + heap.Push(queue, entry) |
| 19 | + } |
| 20 | + |
| 21 | + if got := queue.Len(); len(nums) != got { |
| 22 | + t.Errorf("want %d, but got %d", len(nums), got) |
| 23 | + } |
| 24 | + |
| 25 | + // check the initial state |
| 26 | + for idx, entry := range *queue { |
| 27 | + if entry.index != idx { |
| 28 | + t.Errorf("want index %d, but got %d", entry.index, idx) |
| 29 | + } |
| 30 | + if entry.item.ReferenceCount != 1 { |
| 31 | + t.Errorf("want count 1") |
| 32 | + } |
| 33 | + if got := entry.item.Value; nums[idx] != got { |
| 34 | + t.Errorf("want value %d but got %d", nums[idx], got) |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + // updates len - 1 entries (updated all reference count and referenced_at) |
| 39 | + // so the lowest priority will be the last element. |
| 40 | + // |
| 41 | + // this loop creates |
| 42 | + // - Reference counters other than the last element are 2. |
| 43 | + // - The first element is the oldest referenced_at in reference counter is 2 |
| 44 | + for i := 0; i < len(nums)-1; i++ { |
| 45 | + entry := entries[i] |
| 46 | + queue.update(entry, nums[i]) |
| 47 | + time.Sleep(time.Millisecond) |
| 48 | + } |
| 49 | + |
| 50 | + // check the priority by reference counter |
| 51 | + wantValue := nums[len(nums)-1] |
| 52 | + got := heap.Pop(queue).(*entry[int, int]) |
| 53 | + if got.index != -1 { |
| 54 | + t.Errorf("want index -1, but got %d", got.index) |
| 55 | + } |
| 56 | + if wantValue != got.item.Value { |
| 57 | + t.Errorf("want the lowest priority value is %d, but got %d", wantValue, got.item.Value) |
| 58 | + } |
| 59 | + if want, got := len(nums)-1, queue.Len(); want != got { |
| 60 | + t.Errorf("want %d, but got %d", want, got) |
| 61 | + } |
| 62 | + |
| 63 | + // check the priority by referenced_at |
| 64 | + wantValue2 := nums[0] |
| 65 | + got2 := heap.Pop(queue).(*entry[int, int]) |
| 66 | + if got.index != -1 { |
| 67 | + t.Errorf("want index -1, but got %d", got.index) |
| 68 | + } |
| 69 | + if wantValue2 != got2.item.Value { |
| 70 | + t.Errorf("want the lowest priority value is %d, but got %d", wantValue2, got2.item.Value) |
| 71 | + } |
| 72 | + if want, got := len(nums)-2, queue.Len(); want != got { |
| 73 | + t.Errorf("want %d, but got %d", want, got) |
| 74 | + } |
| 75 | +} |
0 commit comments