| 3 | 3 |
|
| 4 | 4 |
import (
|
| 5 | 5 |
"context"
|
| 6 | |
"fmt"
|
| 7 | 6 |
"io/ioutil"
|
| 8 | |
"math/rand"
|
| 9 | |
"sync"
|
| 10 | 7 |
"testing"
|
| 11 | 8 |
"time"
|
| 12 | 9 |
|
| 13 | 10 |
"github.com/vbauerster/mpb"
|
| 14 | |
"github.com/vbauerster/mpb/decor"
|
| 15 | 11 |
)
|
| 16 | 12 |
|
| 17 | 13 |
func TestWithContext(t *testing.T) {
|
|
| 23 | 19 |
mpb.WithShutdownNotifier(shutdown),
|
| 24 | 20 |
)
|
| 25 | 21 |
|
| 26 | |
var wg sync.WaitGroup
|
| 27 | |
total := 100
|
| 28 | 22 |
numBars := 3
|
| 29 | |
wg.Add(numBars)
|
| 30 | |
|
|
23 |
bars := make([]*mpb.Bar, 0, numBars)
|
| 31 | 24 |
for i := 0; i < numBars; i++ {
|
| 32 | |
name := fmt.Sprintf("Bar#%d:", i)
|
| 33 | |
bar := p.AddBar(int64(total), mpb.BarID(i),
|
| 34 | |
mpb.PrependDecorators(decor.StaticName(name, len(name), 0)))
|
| 35 | |
|
|
25 |
bar := p.AddBar(int64(1000), mpb.BarID(i))
|
|
26 |
bars = append(bars, bar)
|
| 36 | 27 |
go func() {
|
| 37 | |
defer wg.Done()
|
| 38 | |
for i := 0; i < total; i++ {
|
| 39 | |
select {
|
| 40 | |
case <-ctx.Done():
|
| 41 | |
return
|
| 42 | |
default:
|
| 43 | |
}
|
| 44 | |
time.Sleep(time.Duration(rand.Intn(10)+1) * time.Second / 100)
|
|
28 |
for !bar.Completed() {
|
|
29 |
time.Sleep(randomDuration(40 * time.Millisecond))
|
| 45 | 30 |
bar.Increment()
|
| 46 | 31 |
}
|
| 47 | 32 |
}()
|
| 48 | 33 |
}
|
| 49 | 34 |
|
| 50 | |
time.AfterFunc(300*time.Millisecond, cancel)
|
|
35 |
time.AfterFunc(100*time.Millisecond, cancel)
|
| 51 | 36 |
|
| 52 | |
wg.Wait()
|
| 53 | 37 |
p.Stop()
|
| 54 | |
|
|
38 |
for _, bar := range bars {
|
|
39 |
if bar.Current() >= bar.Total() {
|
|
40 |
t.Errorf("bar %d: total = %d, current = %d\n", bar.ID(), bar.Total(), bar.Current())
|
|
41 |
}
|
|
42 |
}
|
| 55 | 43 |
select {
|
| 56 | 44 |
case <-shutdown:
|
| 57 | |
case <-time.After(500 * time.Millisecond):
|
| 58 | |
t.Error("ProgressBar didn't stop")
|
|
45 |
case <-time.After(100 * time.Millisecond):
|
|
46 |
t.Error("Progress didn't stop")
|
| 59 | 47 |
}
|
| 60 | 48 |
}
|