TestHeapBasic tests Heap invariant and synchronization.
(t *testing.T)
| 43 | |
| 44 | // TestHeapBasic tests Heap invariant and synchronization. |
| 45 | func TestHeapBasic(t *testing.T) { |
| 46 | h := NewHeap(testHeapObjectKeyFunc, compareInts) |
| 47 | var wg sync.WaitGroup |
| 48 | wg.Add(2) |
| 49 | const amount = 500 |
| 50 | var i, u int |
| 51 | // Insert items in the heap in opposite orders in two go routines. |
| 52 | go func() { |
| 53 | for i = amount; i > 0; i-- { |
| 54 | h.Add(mkHeapObj(string([]rune{'a', rune(i)}), i)) |
| 55 | } |
| 56 | wg.Done() |
| 57 | }() |
| 58 | go func() { |
| 59 | for u = 0; u < amount; u++ { |
| 60 | h.Add(mkHeapObj(string([]rune{'b', rune(u)}), u+1)) |
| 61 | } |
| 62 | wg.Done() |
| 63 | }() |
| 64 | // Wait for the two go routines to finish. |
| 65 | wg.Wait() |
| 66 | // Make sure that the numbers are popped in ascending order. |
| 67 | prevNum := 0 |
| 68 | for i := 0; i < amount*2; i++ { |
| 69 | obj, err := h.Pop() |
| 70 | num := obj.(testHeapObject).val.(int) |
| 71 | // All the items must be sorted. |
| 72 | if err != nil || prevNum > num { |
| 73 | t.Errorf("got %v out of order, last was %v", obj, prevNum) |
| 74 | } |
| 75 | prevNum = num |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | // Tests Heap.Add and ensures that heap invariant is preserved after adding items. |
| 80 | func TestHeap_Add(t *testing.T) { |