bps/bandwidth_test.go
2014-03-02 23:03:00 -08:00

119 lines
2.6 KiB
Go

package bandwidth
import (
"log"
"testing"
"time"
)
func init() {
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
}
func general(t *testing.T) {
bw, err := NewBandwidth([]int{1, 10, 60}, 100*time.Millisecond)
if err != nil {
t.Error(err)
}
go bw.Run()
bw.AddRx <- 10
bw.AddTx <- 10
time.Sleep(1 * time.Second)
log.Printf("%+v", <-bw.Rx)
log.Printf("%+v", <-bw.Tx)
for i := 0; i < 10; i++ {
bw.AddRx <- (10 * i)
bw.AddRx <- (10 * i)
time.Sleep(500 * time.Millisecond)
log.Printf("%+v", <-bw.Rx)
log.Printf("%+v", <-bw.Tx)
}
log.Printf("%+v", <-bw.Rx)
log.Printf("%+v", <-bw.Tx)
time.Sleep(10 * time.Second)
log.Printf("%+v", <-bw.Rx)
log.Printf("%+v", <-bw.Tx)
close(bw.Quit)
time.Sleep(100 * time.Millisecond)
log.Printf("%+v", <-bw.Rx)
log.Printf("%+v", <-bw.Tx)
}
func validate(t *testing.T, actual, expected []float64) {
if len(actual) != len(expected) {
t.Errorf("len is not same: %d expected %d", len(actual), len(expected))
}
for i, _ := range actual {
if actual[i] != expected[i] {
t.Errorf("%dth: got %f expected %f", i, actual[i], expected[i])
}
}
}
func TestOncePerSecond(t *testing.T) {
bw, err := NewBandwidth([]int{1, 10, 60}, 100*time.Millisecond)
if err != nil {
t.Error(err)
}
bw.rxstream = newStream([]int{1, 10, 60})
var i int64 = 0
for ; i < 1000; i++ {
d := datum{
value: 1.0,
at: time.Unix(1234567890+i, 0),
}
bw.rxstream.add(d)
}
validate(t, bw.rxstream.averages(), []float64{1.0, 1.0, 1.0})
}
func TestOneOverManySeconds(t *testing.T) {
bw, err := NewBandwidth([]int{1, 10, 60}, 100*time.Millisecond)
if err != nil {
t.Error(err)
}
bw.rxstream = newStream([]int{1, 10, 60})
var i int64 = 0
for ; i < 1000; i++ {
d := datum{
value: 1.0,
at: time.Unix(1234567890+i*2, 0),
}
bw.rxstream.add(d)
}
validate(t, bw.rxstream.averages(), []float64{0.0, 0.5, 0.5})
}
func TestManyPerSecond(t *testing.T) {
bw, err := NewBandwidth([]int{1, 10, 60}, 100*time.Millisecond)
if err != nil {
t.Error(err)
}
bw.rxstream = newStream([]int{1, 10, 60})
var i int64 = 0
for ; i < 10000; i++ {
d := datum{
value: 1.0,
at: time.Unix(1234567890, i*10000000),
}
bw.rxstream.add(d)
}
validate(t, bw.rxstream.averages(), []float64{100.0, 100.0, 100.0})
}
func TestEmpty(t *testing.T) {
bw, err := NewBandwidth([]int{1, 10, 60}, 100*time.Millisecond)
if err != nil {
t.Error(err)
}
bw.rxstream = newStream([]int{1, 10, 60})
validate(t, bw.rxstream.averages(), []float64{})
}
func TestEmptySeconds(t *testing.T) {
_, err := NewBandwidth([]int{}, 100*time.Millisecond)
if err == nil {
t.Error(err)
}
}