TestWithWidth
Vladimir Bauer
8 years ago
| 12 | 12 | "github.com/vbauerster/mpb/decor" |
| 13 | 13 | ) |
| 14 | 14 | |
| 15 | func TestBarSetWidth(t *testing.T) { | |
| 16 | var buf bytes.Buffer | |
| 17 | // overwrite default width 80 | |
| 18 | customWidth := 60 | |
| 19 | p := mpb.New(mpb.Output(&buf), mpb.WithWidth(customWidth)) | |
| 20 | bar := p.AddBar(100, mpb.BarTrim()) | |
| 21 | ||
| 22 | for i := 0; i < 100; i++ { | |
| 23 | bar.Incr(1) | |
| 24 | } | |
| 25 | ||
| 26 | p.Stop() | |
| 27 | ||
| 28 | gotWidth := len(buf.Bytes()) | |
| 29 | if gotWidth != customWidth+1 { // +1 for new line | |
| 30 | t.Errorf("Expected width: %d, got: %d\n", customWidth, gotWidth) | |
| 31 | } | |
| 32 | } | |
| 33 | ||
| 34 | func TestBarSetInvalidWidth(t *testing.T) { | |
| 35 | var buf bytes.Buffer | |
| 36 | p := mpb.New(mpb.Output(&buf), mpb.WithWidth(1)) | |
| 37 | bar := p.AddBar(100, mpb.BarTrim()) | |
| 38 | ||
| 39 | for i := 0; i < 100; i++ { | |
| 40 | bar.Incr(1) | |
| 41 | } | |
| 42 | ||
| 43 | p.Stop() | |
| 44 | ||
| 45 | wantWidth := 80 | |
| 46 | gotWidth := len(buf.Bytes()) | |
| 47 | if gotWidth != wantWidth+1 { // +1 for new line | |
| 48 | t.Errorf("Expected width: %d, got: %d\n", wantWidth, gotWidth) | |
| 15 | func TestWithWidth(t *testing.T) { | |
| 16 | cases := map[string]struct{ w, expected int }{ | |
| 17 | "WithWidth-1": {-1, 81}, | |
| 18 | "WithWidth0": {0, 3}, | |
| 19 | "WithWidth1": {1, 3}, | |
| 20 | "WithWidth2": {2, 3}, | |
| 21 | "WithWidth3": {3, 4}, | |
| 22 | "WithWidth60": {60, 61}, | |
| 23 | } | |
| 24 | ||
| 25 | var buf bytes.Buffer | |
| 26 | for k, tc := range cases { | |
| 27 | buf.Reset() | |
| 28 | p := mpb.New( | |
| 29 | mpb.Output(&buf), | |
| 30 | mpb.WithWidth(tc.w), | |
| 31 | ) | |
| 32 | bar := p.AddBar(10, mpb.BarTrim()) | |
| 33 | ||
| 34 | for i := 0; i < 10; i++ { | |
| 35 | bar.Increment() | |
| 36 | } | |
| 37 | ||
| 38 | p.Stop() | |
| 39 | ||
| 40 | gotWidth := len(buf.Bytes()) | |
| 41 | if gotWidth != tc.expected { | |
| 42 | t.Errorf("%s: Expected width: %d, got: %d\n", k, tc.expected, gotWidth) | |
| 43 | } | |
| 49 | 44 | } |
| 50 | 45 | } |
| 51 | 46 | |
| 63 | 58 | go func() { |
| 64 | 59 | for i := 0; i < 100; i++ { |
| 65 | 60 | time.Sleep(10 * time.Millisecond) |
| 66 | bar.Incr(1) | |
| 61 | bar.Increment() | |
| 67 | 62 | } |
| 68 | 63 | }() |
| 69 | 64 | |