1package pb 2 3import ( 4 "bytes" 5 "strings" 6 "sync" 7 "testing" 8 "time" 9 10 "github.com/fatih/color" 11 "github.com/mattn/go-colorable" 12) 13 14func Test_IncrementAddsOne(t *testing.T) { 15 count := 5000 16 bar := New(count) 17 expected := 1 18 actual := bar.Increment() 19 20 if actual != expected { 21 t.Errorf("Expected {%d} was {%d}", expected, actual) 22 } 23} 24 25func Test_Width(t *testing.T) { 26 count := 5000 27 bar := New(count) 28 width := 100 29 bar.SetWidth(100).Callback = func(out string) { 30 if len(out) != width { 31 t.Errorf("Bar width expected {%d} was {%d}", len(out), width) 32 } 33 } 34 bar.Start() 35 bar.Increment() 36 bar.Finish() 37} 38 39func Test_MultipleFinish(t *testing.T) { 40 bar := New(5000) 41 bar.Add(2000) 42 bar.Finish() 43 bar.Finish() 44} 45 46func TestWriteRace(t *testing.T) { 47 outBuffer := &bytes.Buffer{} 48 totalCount := 20 49 bar := New(totalCount) 50 bar.Output = outBuffer 51 bar.Start() 52 var wg sync.WaitGroup 53 for i := 0; i < totalCount; i++ { 54 wg.Add(1) 55 go func() { 56 bar.Increment() 57 time.Sleep(250 * time.Millisecond) 58 wg.Done() 59 }() 60 } 61 wg.Wait() 62 bar.Finish() 63} 64 65func Test_Format(t *testing.T) { 66 bar := New(5000).Format(strings.Join([]string{ 67 color.GreenString("["), 68 color.New(color.BgGreen).SprintFunc()("o"), 69 color.New(color.BgHiGreen).SprintFunc()("o"), 70 color.New(color.BgRed).SprintFunc()("o"), 71 color.GreenString("]"), 72 }, "\x00")) 73 w := colorable.NewColorableStdout() 74 bar.Callback = func(out string) { 75 w.Write([]byte(out)) 76 } 77 bar.Add(2000) 78 bar.Finish() 79 bar.Finish() 80} 81 82func Test_MultiCharacter(t *testing.T) { 83 bar := New(5).Format(strings.Join([]string{"[[[", "---", ">>", "....", "]]"}, "\x00")) 84 bar.Start() 85 for i := 0; i < 5; i++ { 86 time.Sleep(500 * time.Millisecond) 87 bar.Increment() 88 } 89 90 time.Sleep(500 * time.Millisecond) 91 bar.Finish() 92} 93 94func Test_AutoStat(t *testing.T) { 95 bar := New(5) 96 bar.AutoStat = true 97 bar.Start() 98 time.Sleep(2 * time.Second) 99 //real start work 100 for i := 0; i < 5; i++ { 101 time.Sleep(500 * time.Millisecond) 102 bar.Increment() 103 } 104 //real finish work 105 time.Sleep(2 * time.Second) 106 bar.Finish() 107} 108 109func Test_Finish_PrintNewline(t *testing.T) { 110 bar := New(5) 111 buf := &bytes.Buffer{} 112 bar.Output = buf 113 bar.Finish() 114 115 expected := "\n" 116 actual := buf.String() 117 //Finish should write newline to bar.Output 118 if !strings.HasSuffix(actual, expected) { 119 t.Errorf("Expected %q to have suffix %q", expected, actual) 120 } 121} 122 123func Test_FinishPrint(t *testing.T) { 124 bar := New(5) 125 buf := &bytes.Buffer{} 126 bar.Output = buf 127 bar.FinishPrint("foo") 128 129 expected := "foo\n" 130 actual := buf.String() 131 //FinishPrint should write to bar.Output 132 if !strings.HasSuffix(actual, expected) { 133 t.Errorf("Expected %q to have suffix %q", expected, actual) 134 } 135} 136