File: ringbuffer_test.go

package info (click to toggle)
golang-github-tideland-golib 4.24.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,144 kB
  • sloc: makefile: 4
file content (104 lines) | stat: -rw-r--r-- 2,215 bytes parent folder | download | duplicates (3)
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Tideland Go Library - Collections - Ring Buffer - Unit Tests
//
// Copyright (C) 2015 Frank Mueller / Tideland / Oldenburg / Germany
//
// All rights reserved. Use of this source code is governed
// by the new BSD license.

package collections_test

//--------------------
// IMPORTS
//--------------------

import (
	"testing"

	"github.com/tideland/golib/audit"
	"github.com/tideland/golib/collections"
)

//--------------------
// TESTS
//--------------------

// TestRingBufferPush tests the pushing of values.
func TestRingBufferPush(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)

	rb := collections.NewRingBuffer(0)
	assert.Equal(rb.Cap(), 2)
	assert.Length(rb, 0)

	rb = collections.NewRingBuffer(10)
	assert.Equal(rb.Cap(), 10)
	assert.Length(rb, 0)

	rb.Push(1, "alpha", nil, true)
	assert.Length(rb, 4)
	assert.Equal(rb.String(), "[1]->[alpha]->[<nil>]->[true]")
}

// TestRingBufferPeekPop tests the peeking and popping of values.
func TestRingBufferPop(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)

	rb := collections.NewRingBuffer(10)
	assert.Equal(rb.Cap(), 10)
	assert.Length(rb, 0)
	v, ok := rb.Peek()
	assert.False(ok)
	assert.Nil(v)
	v, ok = rb.Pop()
	assert.False(ok)
	assert.Nil(v)

	rb.Push(1, "alpha", nil, true)
	assert.Length(rb, 4)
	assert.Equal(rb.String(), "[1]->[alpha]->[<nil>]->[true]")

	tests := []struct {
		value  interface{}
		ok     bool
		length int
	}{
		{1, true, 3},
		{"alpha", true, 2},
		{nil, true, 1},
		{true, true, 0},
		{nil, false, 0},
	}
	for _, test := range tests {
		v, ok := rb.Peek()
		assert.Equal(v, test.value)
		assert.Equal(ok, test.ok)
		v, ok = rb.Pop()
		assert.Equal(v, test.value)
		assert.Equal(ok, test.ok)
		assert.Length(rb, test.length)
	}
	rb.Push(2, "beta")
	assert.Equal(rb.Cap(), 10)
	assert.Length(rb, 2)
}

// TestRingBufferGrow tests the growing of the ring buffer.
func TestRingBufferGrow(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)

	rb := collections.NewRingBuffer(4)
	assert.Equal(rb.Cap(), 4)
	assert.Length(rb, 0)

	rb.Push(1, 2, 3, 4, 5, 6, 7, 8)
	assert.Equal(rb.Cap(), 8)
	assert.Length(rb, 8)

	rb.Pop()
	rb.Pop()

	assert.Equal(rb.Cap(), 8)
	assert.Length(rb, 6)
}

// EOF