Codebase list golang-github-vbauerster-mpb / be9d736
Refactor: TestWithContext Vladimir Bauer 8 years ago
2 changed file(s) with 20 addition(s) and 32 deletion(s). Raw diff Collapse all Expand all
33
44 import (
55 "context"
6 "fmt"
76 "io/ioutil"
8 "math/rand"
9 "sync"
107 "testing"
118 "time"
129
1310 "github.com/vbauerster/mpb"
14 "github.com/vbauerster/mpb/decor"
1511 )
1612
1713 func TestWithContext(t *testing.T) {
2319 mpb.WithShutdownNotifier(shutdown),
2420 )
2521
26 var wg sync.WaitGroup
27 total := 100
2822 numBars := 3
29 wg.Add(numBars)
30
23 bars := make([]*mpb.Bar, 0, numBars)
3124 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)
3627 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))
4530 bar.Increment()
4631 }
4732 }()
4833 }
4934
50 time.AfterFunc(300*time.Millisecond, cancel)
35 time.AfterFunc(100*time.Millisecond, cancel)
5136
52 wg.Wait()
5337 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 }
5543 select {
5644 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")
5947 }
6048 }
7676
7777 func TestWithCancel(t *testing.T) {
7878 cancel := make(chan struct{})
79 shutdown := make(chan struct{})
7980 p := mpb.New(
8081 mpb.Output(ioutil.Discard),
8182 mpb.WithCancel(cancel),
83 mpb.WithShutdownNotifier(shutdown),
8284 )
8385
8486 numBars := 3
85
86 type sample struct {
87 id int
88 total int64
89 current int64
90 }
91
9287 bars := make([]*mpb.Bar, 0, numBars)
9388 for i := 0; i < numBars; i++ {
9489 bar := p.AddBar(int64(1000), mpb.BarID(i))
110105 if bar.Current() >= bar.Total() {
111106 t.Errorf("bar %d: total = %d, current = %d\n", bar.ID(), bar.Total(), bar.Current())
112107 }
108 }
109 select {
110 case <-shutdown:
111 case <-time.After(100 * time.Millisecond):
112 t.Error("Progress didn't stop")
113113 }
114114 }
115115