package bps import ( "bytes" "io" "log" "testing" "time" ) func init() { log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile) } func TestSimple(t *testing.T) { bw, err := New(1*time.Second, 100) if err != nil { t.Fatalf("failure to make reasonable BPS: %v", err) } bw.Close() } func TestBadResolution(t *testing.T) { _, err := New(1*time.Hour, 1) if err == nil { t.Fatal("expected an error, got nil") } } func TestWriter(t *testing.T) { t.Parallel() bw, err := New(1*time.Second, 100) if err != nil { t.Fatalf("failure to make reasonable BPS: %v", err) } b := &bytes.Buffer{} b.Write([]byte("helloooooooooooooooooooooooooooooooooooooooooooooo")) for i := 0; i < 90; i++ { io.Copy(bw, b) last := bw.Rate() time.Sleep(10 * time.Millisecond) if last > bw.Rate() { t.Errorf("rate should be increasing, it isn't: last: %f > current: %f", last, bw.Rate()) } } time.Sleep(2 * time.Second) for i := 0; i < 100; i++ { if bw.Rate() > 0 { t.Errorf("got high rate: got, want 0.0000", bw.Rate()) } time.Sleep(9 * time.Millisecond) } bw.Close() } func TestAdd(t *testing.T) { t.Parallel() bw, err := New(1*time.Second, 100) if err != nil { t.Fatalf("failure to make reasonable BPS: %v", err) } for i := 0; i < 90; i++ { bw.Add(1024) last := bw.Rate() time.Sleep(10 * time.Millisecond) if last > bw.Rate() { t.Errorf("rate should be increasing, it isn't: last: %f > current: %f", last, bw.Rate()) } } time.Sleep(2 * time.Second) for i := 0; i < 100; i++ { if bw.Rate() > 0 { t.Errorf("got high rate: got, want 0.0000", bw.Rate()) } time.Sleep(9 * time.Millisecond) } bw.Close() } func TestHumanBytes(t *testing.T) { t.Parallel() bw, err := New(100*time.Second, 10) if err != nil { t.Fatalf("failure to make reasonable BPS: %v", err) } bw.Add(1000) got := bw.HumanRate() want := "10B/s" if got != want { t.Fatalf("did not get right human rate; got %v, want %v", got, want) } }