pqueue_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package pqueue
  2. import (
  3. "container/heap"
  4. "math/rand"
  5. "path/filepath"
  6. "reflect"
  7. "runtime"
  8. "sort"
  9. "testing"
  10. )
  11. func equal(t *testing.T, act, exp interface{}) {
  12. if !reflect.DeepEqual(exp, act) {
  13. _, file, line, _ := runtime.Caller(1)
  14. t.Logf("\033[31m%s:%d:\n\n\texp: %#v\n\n\tgot: %#v\033[39m\n\n",
  15. filepath.Base(file), line, exp, act)
  16. t.FailNow()
  17. }
  18. }
  19. func TestPriorityQueue(t *testing.T) {
  20. c := 100
  21. pq := New(c)
  22. for i := 0; i < c+1; i++ {
  23. heap.Push(&pq, &Item{Value: i, Priority: int64(i)})
  24. }
  25. equal(t, pq.Len(), c+1)
  26. equal(t, cap(pq), c*2)
  27. for i := 0; i < c+1; i++ {
  28. item := heap.Pop(&pq)
  29. equal(t, item.(*Item).Value.(int), i)
  30. }
  31. equal(t, cap(pq), c/4)
  32. }
  33. func TestUnsortedInsert(t *testing.T) {
  34. c := 100
  35. pq := New(c)
  36. ints := make([]int, 0, c)
  37. for i := 0; i < c; i++ {
  38. v := rand.Int()
  39. ints = append(ints, v)
  40. heap.Push(&pq, &Item{Value: i, Priority: int64(v)})
  41. }
  42. equal(t, pq.Len(), c)
  43. equal(t, cap(pq), c)
  44. sort.Ints(ints)
  45. for i := 0; i < c; i++ {
  46. item, _ := pq.PeekAndShift(int64(ints[len(ints)-1]))
  47. equal(t, item.Priority, int64(ints[i]))
  48. }
  49. }
  50. func TestRemove(t *testing.T) {
  51. c := 100
  52. pq := New(c)
  53. for i := 0; i < c; i++ {
  54. v := rand.Int()
  55. heap.Push(&pq, &Item{Value: "test", Priority: int64(v)})
  56. }
  57. for i := 0; i < 10; i++ {
  58. heap.Remove(&pq, rand.Intn((c-1)-i))
  59. }
  60. lastPriority := heap.Pop(&pq).(*Item).Priority
  61. for i := 0; i < (c - 10 - 1); i++ {
  62. item := heap.Pop(&pq)
  63. equal(t, lastPriority < item.(*Item).Priority, true)
  64. lastPriority = item.(*Item).Priority
  65. }
  66. }