simplify TestWithContext
Vladimir Bauer
4 years ago
| 76 | 76 | } |
| 77 | 77 | |
| 78 | 78 | func TestWithContext(t *testing.T) { |
| 79 | shutdown := make(chan struct{}) | |
| 79 | 80 | ctx, cancel := context.WithCancel(context.Background()) |
| 80 | shutdown := make(chan struct{}) | |
| 81 | p := mpb.NewWithContext(ctx, | |
| 82 | mpb.WithOutput(ioutil.Discard), | |
| 83 | mpb.WithRefreshRate(50*time.Millisecond), | |
| 84 | mpb.WithShutdownNotifier(shutdown), | |
| 85 | ) | |
| 81 | p := mpb.NewWithContext(ctx, mpb.WithShutdownNotifier(shutdown), mpb.WithOutput(ioutil.Discard)) | |
| 86 | 82 | |
| 87 | total := 10000 | |
| 88 | numBars := 3 | |
| 89 | bars := make([]*mpb.Bar, 0, numBars) | |
| 90 | for i := 0; i < numBars; i++ { | |
| 91 | bar := p.AddBar(int64(total)) | |
| 92 | bars = append(bars, bar) | |
| 93 | go func() { | |
| 94 | for !bar.Completed() { | |
| 95 | bar.Increment() | |
| 96 | time.Sleep(randomDuration(100 * time.Millisecond)) | |
| 97 | } | |
| 98 | }() | |
| 99 | } | |
| 83 | start := make(chan struct{}) | |
| 84 | done := make(chan struct{}) | |
| 85 | bar := p.AddBar(0) // never complete bar | |
| 86 | go func() { | |
| 87 | close(start) | |
| 88 | for !bar.Completed() { | |
| 89 | bar.Increment() | |
| 90 | time.Sleep(randomDuration(100 * time.Millisecond)) | |
| 91 | } | |
| 92 | close(done) | |
| 93 | }() | |
| 100 | 94 | |
| 101 | time.Sleep(50 * time.Millisecond) | |
| 95 | go func() { | |
| 96 | select { | |
| 97 | case <-done: | |
| 98 | p.Wait() | |
| 99 | case <-time.After(100 * time.Millisecond): | |
| 100 | t.Error("Progress didn't stop") | |
| 101 | } | |
| 102 | }() | |
| 103 | ||
| 104 | <-start | |
| 102 | 105 | cancel() |
| 103 | ||
| 104 | p.Wait() | |
| 105 | select { | |
| 106 | case <-shutdown: | |
| 107 | case <-time.After(100 * time.Millisecond): | |
| 108 | t.Error("Progress didn't stop") | |
| 109 | } | |
| 106 | <-shutdown | |
| 110 | 107 | } |
| 111 | 108 | |
| 112 | 109 | // MaxWidthDistributor shouldn't stuck in the middle while removing or aborting a bar |