summaryrefslogtreecommitdiffhomepage
path: root/util/ringbuffer/ringbuffer_test.go
blob: fae3f5328d7c7d20fe4dbfedc34e86fc4667f263 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause

package ringbuffer

import (
	"reflect"
	"testing"
)

func TestRingBuffer(t *testing.T) {
	const numItems = 10
	rb := New[int](numItems)

	for i := 0; i < numItems-1; i++ {
		rb.Add(i)
	}

	t.Run("NotFull", func(t *testing.T) {
		if ll := rb.Len(); ll != numItems-1 {
			t.Fatalf("got len %d; want %d", ll, numItems-1)
		}
		all := rb.GetAll()
		want := []int{0, 1, 2, 3, 4, 5, 6, 7, 8}
		if !reflect.DeepEqual(all, want) {
			t.Fatalf("items mismatch\ngot: %v\nwant %v", all, want)
		}
	})

	t.Run("Full", func(t *testing.T) {
		// Append items to evict something
		rb.Add(98)
		rb.Add(99)

		if ll := rb.Len(); ll != numItems {
			t.Fatalf("got len %d; want %d", ll, numItems)
		}
		all := rb.GetAll()
		want := []int{1, 2, 3, 4, 5, 6, 7, 8, 98, 99}
		if !reflect.DeepEqual(all, want) {
			t.Fatalf("items mismatch\ngot: %v\nwant %v", all, want)
		}
	})

	t.Run("Clear", func(t *testing.T) {
		rb.Clear()
		if ll := rb.Len(); ll != 0 {
			t.Fatalf("got len %d; want 0", ll)
		}
		all := rb.GetAll()
		if len(all) != 0 {
			t.Fatalf("got non-empty list; want empty")
		}
	})
}