TestProgressShutdownsWithErrFiller
Vladimir Bauer
3 years ago
| 0 | 0 | package mpb_test |
| 1 | 1 | |
| 2 | 2 | import ( |
| 3 | "bytes" | |
| 3 | 4 | "context" |
| 5 | "errors" | |
| 4 | 6 | "io" |
| 5 | 7 | "math/rand" |
| 8 | "strings" | |
| 6 | 9 | "testing" |
| 7 | 10 | "time" |
| 8 | 11 | |
| 180 | 183 | } |
| 181 | 184 | } |
| 182 | 185 | |
| 186 | func TestProgressShutdownsWithErrFiller(t *testing.T) { | |
| 187 | var debug bytes.Buffer | |
| 188 | shutdown := make(chan struct{}) | |
| 189 | p := mpb.New( | |
| 190 | mpb.WithShutdownNotifier(shutdown), | |
| 191 | mpb.WithOutput(io.Discard), | |
| 192 | mpb.WithDebugOutput(&debug), | |
| 193 | ) | |
| 194 | ||
| 195 | testError := errors.New("test error") | |
| 196 | bar := p.AddBar(100, | |
| 197 | mpb.BarFillerMiddleware(func(base mpb.BarFiller) mpb.BarFiller { | |
| 198 | return mpb.BarFillerFunc(func(w io.Writer, st decor.Statistics) error { | |
| 199 | if st.Current >= 42 { | |
| 200 | return testError | |
| 201 | } | |
| 202 | return base.Fill(w, st) | |
| 203 | }) | |
| 204 | }), | |
| 205 | ) | |
| 206 | ||
| 207 | for bar.IsRunning() { | |
| 208 | time.Sleep(randomDuration(100 * time.Millisecond)) | |
| 209 | bar.Increment() | |
| 210 | } | |
| 211 | ||
| 212 | go p.Wait() | |
| 213 | ||
| 214 | select { | |
| 215 | case <-shutdown: | |
| 216 | if err := strings.TrimSpace(debug.String()); err != testError.Error() { | |
| 217 | t.Errorf("Expected err: %q, got %q\n", testError.Error(), err) | |
| 218 | } | |
| 219 | case <-time.After(timeout): | |
| 220 | t.Errorf("Progress didn't shutdown after %v", timeout) | |
| 221 | } | |
| 222 | } | |
| 223 | ||
| 183 | 224 | func randomDuration(max time.Duration) time.Duration { |
| 184 | 225 | return time.Duration(rand.Intn(10)+1) * max / 10 |
| 185 | 226 | } |