refactor TestDecorStatisticsAvailableWidth
Vladimir Bauer
4 years ago
| 1 | 1 | |
| 2 | 2 | import ( |
| 3 | 3 | "bytes" |
| 4 | "context" | |
| 4 | 5 | "fmt" |
| 5 | 6 | "io/ioutil" |
| 6 | 7 | "strings" |
| 222 | 223 | } |
| 223 | 224 | |
| 224 | 225 | func TestDecorStatisticsAvailableWidth(t *testing.T) { |
| 225 | total := 100 | |
| 226 | down := make(chan struct{}) | |
| 227 | checkDone := make(chan struct{}) | |
| 226 | var called [2]bool | |
| 228 | 227 | td1 := func(s decor.Statistics) string { |
| 229 | 228 | if s.AvailableWidth != 80 { |
| 230 | 229 | t.Errorf("expected AvailableWidth %d got %d\n", 80, s.AvailableWidth) |
| 231 | 230 | } |
| 231 | called[0] = true | |
| 232 | 232 | return fmt.Sprintf("\x1b[31;1;4m%s\x1b[0m", strings.Repeat("0", 20)) |
| 233 | 233 | } |
| 234 | 234 | td2 := func(s decor.Statistics) string { |
| 235 | defer func() { | |
| 236 | select { | |
| 237 | case checkDone <- struct{}{}: | |
| 238 | default: | |
| 239 | } | |
| 240 | }() | |
| 241 | 235 | if s.AvailableWidth != 40 { |
| 242 | 236 | t.Errorf("expected AvailableWidth %d got %d\n", 40, s.AvailableWidth) |
| 243 | 237 | } |
| 238 | called[1] = true | |
| 244 | 239 | return "" |
| 245 | 240 | } |
| 246 | p := mpb.New( | |
| 247 | mpb.WithWidth(100), | |
| 248 | mpb.WithShutdownNotifier(down), | |
| 241 | ctx, cancel := context.WithCancel(context.Background()) | |
| 242 | refresh := make(chan interface{}) | |
| 243 | p := mpb.NewWithContext(ctx, mpb.WithWidth(100), | |
| 244 | mpb.WithManualRefresh(refresh), | |
| 249 | 245 | mpb.WithOutput(ioutil.Discard), |
| 250 | 246 | ) |
| 251 | bar := p.AddBar(int64(total), | |
| 247 | _ = p.AddBar(0, | |
| 252 | 248 | mpb.BarFillerTrim(), |
| 253 | 249 | mpb.PrependDecorators( |
| 254 | 250 | decor.Name(strings.Repeat("0", 20)), |
| 259 | 255 | decor.Any(td2), |
| 260 | 256 | ), |
| 261 | 257 | ) |
| 262 | go func() { | |
| 263 | for { | |
| 264 | select { | |
| 265 | case <-checkDone: | |
| 266 | bar.Abort(true) | |
| 267 | case <-down: | |
| 268 | return | |
| 269 | } | |
| 270 | } | |
| 271 | }() | |
| 272 | for !bar.Completed() { | |
| 273 | bar.Increment() | |
| 274 | } | |
| 275 | p.Wait() | |
| 258 | refresh <- time.Now() | |
| 259 | cancel() | |
| 260 | p.Wait() | |
| 261 | for i, ok := range called { | |
| 262 | if !ok { | |
| 263 | t.Errorf("Decorator %d isn't called", i+1) | |
| 264 | } | |
| 265 | } | |
| 276 | 266 | } |
| 277 | 267 | |
| 278 | 268 | func panicDecorator(panicMsg string, cond func(decor.Statistics) bool) decor.Decorator { |