github.com/codingfuture/orig-energi3@v0.8.4/swarm/network/priorityqueue/priorityqueue_test.go (about) 1 // Copyright 2018 The Energi Core Authors 2 // Copyright 2018 The go-ethereum Authors 3 // This file is part of the Energi Core library. 4 // 5 // The Energi Core library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The Energi Core library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the Energi Core library. If not, see <http://www.gnu.org/licenses/>. 17 18 package priorityqueue 19 20 import ( 21 "context" 22 "sync" 23 "testing" 24 ) 25 26 func TestPriorityQueue(t *testing.T) { 27 var results []string 28 wg := sync.WaitGroup{} 29 pq := New(3, 2) 30 wg.Add(1) 31 go pq.Run(context.Background(), func(v interface{}) { 32 results = append(results, v.(string)) 33 wg.Done() 34 }) 35 pq.Push("2.0", 2) 36 wg.Wait() 37 if results[0] != "2.0" { 38 t.Errorf("expected first result %q, got %q", "2.0", results[0]) 39 } 40 41 Loop: 42 for i, tc := range []struct { 43 priorities []int 44 values []string 45 results []string 46 errors []error 47 }{ 48 { 49 priorities: []int{0}, 50 values: []string{""}, 51 results: []string{""}, 52 }, 53 { 54 priorities: []int{0, 1}, 55 values: []string{"0.0", "1.0"}, 56 results: []string{"1.0", "0.0"}, 57 }, 58 { 59 priorities: []int{1, 0}, 60 values: []string{"1.0", "0.0"}, 61 results: []string{"1.0", "0.0"}, 62 }, 63 { 64 priorities: []int{0, 1, 1}, 65 values: []string{"0.0", "1.0", "1.1"}, 66 results: []string{"1.0", "1.1", "0.0"}, 67 }, 68 { 69 priorities: []int{0, 0, 0}, 70 values: []string{"0.0", "0.0", "0.1"}, 71 errors: []error{nil, nil, ErrContention}, 72 }, 73 } { 74 var results []string 75 wg := sync.WaitGroup{} 76 pq := New(3, 2) 77 wg.Add(len(tc.values)) 78 for j, value := range tc.values { 79 err := pq.Push(value, tc.priorities[j]) 80 if tc.errors != nil && err != tc.errors[j] { 81 t.Errorf("expected push error %v, got %v", tc.errors[j], err) 82 continue Loop 83 } 84 if err != nil { 85 continue Loop 86 } 87 } 88 go pq.Run(context.Background(), func(v interface{}) { 89 results = append(results, v.(string)) 90 wg.Done() 91 }) 92 wg.Wait() 93 for k, result := range tc.results { 94 if results[k] != result { 95 t.Errorf("test case %v: expected %v element %q, got %q", i, k, result, results[k]) 96 } 97 } 98 } 99 }