File: tinyqueue_test.go

package info (click to toggle)
golang-github-tidwall-tinyqueue 0.0~git20180302.1e39f55-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 60 kB
  • sloc: makefile: 2
file content (65 lines) | stat: -rw-r--r-- 1,325 bytes parent folder | download
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
package tinyqueue

import (
	"math/rand"
	"sort"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

type floatValue float64

func (a floatValue) Less(b Item) bool {
	return a < b.(floatValue)
}

var data, sorted = func() ([]Item, []Item) {
	rand.Seed(time.Now().UnixNano())
	var data []Item
	for i := 0; i < 100; i++ {
		data = append(data, floatValue(rand.Float64()*100))
	}
	sorted := make([]Item, len(data))
	copy(sorted, data)
	sort.Slice(sorted, func(i, j int) bool {
		return sorted[i].Less(sorted[j])
	})
	return data, sorted
}()

func TestMaintainsPriorityQueue(t *testing.T) {
	q := New(nil)
	for i := 0; i < len(data); i++ {
		q.Push(data[i])
	}
	assert.Equal(t, q.Peek(), sorted[0])
	var result []Item
	for q.length > 0 {
		result = append(result, q.Pop())
	}
	assert.Equal(t, result, sorted)
}

func TestAcceptsDataInConstructor(t *testing.T) {
	q := New(data)
	var result []Item
	for q.length > 0 {
		result = append(result, q.Pop())
	}
	assert.Equal(t, result, sorted)
}
func TestHandlesEdgeCasesWithFewElements(t *testing.T) {
	q := New(nil)
	q.Push(floatValue(2))
	q.Push(floatValue(1))
	q.Pop()
	q.Pop()
	q.Pop()
	q.Push(floatValue(2))
	q.Push(floatValue(1))
	assert.Equal(t, float64(q.Pop().(floatValue)), 1.0)
	assert.Equal(t, float64(q.Pop().(floatValue)), 2.0)
	assert.Equal(t, q.Pop(), nil)
}