hybridgroup.gobot/utils_test.go

94 lines
1.7 KiB
Go
Raw Normal View History

2014-04-16 12:10:32 +08:00
package gobot
import (
2014-06-13 05:38:03 +08:00
"testing"
2014-06-07 05:44:16 +08:00
"time"
2014-11-30 16:19:53 +08:00
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
2014-11-30 16:19:53 +08:00
2014-06-13 05:38:03 +08:00
func TestEvery(t *testing.T) {
i := 0
begin := time.Now()
sem := make(chan time.Time, 1)
2014-06-13 05:38:03 +08:00
Every(2*time.Millisecond, func() {
i++
2014-10-29 06:50:32 +08:00
if i == 2 {
sem <- time.Now()
2014-10-29 06:50:32 +08:00
}
2014-06-13 05:38:03 +08:00
})
<-sem
if time.Since(begin) < 4*time.Millisecond {
2014-10-29 06:50:32 +08:00
t.Error("Test should have taken at least 4 milliseconds")
}
2014-06-13 05:38:03 +08:00
}
func TestEveryWhenStopped(t *testing.T) {
sem := make(chan bool)
done := Every(100*time.Millisecond, func() {
sem <- true
})
select {
case <-sem:
done.Stop()
2022-10-23 21:17:48 +08:00
case <-time.After(190 * time.Millisecond):
done.Stop()
require.Fail(t, "Every was not called")
}
select {
2022-10-23 21:17:48 +08:00
case <-time.After(190 * time.Millisecond):
case <-sem:
t.Error("Every should have stopped")
}
}
2014-06-13 05:38:03 +08:00
func TestAfter(t *testing.T) {
i := 0
sem := make(chan bool)
2022-10-23 21:17:48 +08:00
After(100*time.Millisecond, func() {
2014-06-13 05:38:03 +08:00
i++
sem <- true
2014-06-13 05:38:03 +08:00
})
select {
case <-sem:
2022-10-23 21:17:48 +08:00
case <-time.After(190 * time.Millisecond):
require.Fail(t, "After was not called")
}
assert.Equal(t, 1, i)
2014-06-13 05:38:03 +08:00
}
2014-04-16 12:10:32 +08:00
2014-06-13 05:38:03 +08:00
func TestFromScale(t *testing.T) {
assert.InDelta(t, 0.5, FromScale(5, 0, 10), 0.0)
2014-06-13 05:38:03 +08:00
}
func TestToScale(t *testing.T) {
assert.InDelta(t, 10.0, ToScale(500, 0, 10), 0.0)
assert.InDelta(t, 0.0, ToScale(-1, 0, 10), 0.0)
assert.InDelta(t, 5.0, ToScale(0.5, 0, 10), 0.0)
2014-06-13 05:38:03 +08:00
}
func TestRescale(t *testing.T) {
assert.InDelta(t, 5.0, Rescale(500, 0, 1000, 0, 10), 0.0)
assert.InDelta(t, 490.0, Rescale(-1.0, -1, 0, 490, 350), 0.0)
}
2014-06-13 05:38:03 +08:00
func TestRand(t *testing.T) {
a := Rand(10000)
b := Rand(10000)
2014-06-13 05:38:03 +08:00
if a == b {
require.Fail(t, "%v should not equal %v", a, b)
2014-06-13 05:38:03 +08:00
}
}
func TestDefaultName(t *testing.T) {
name := DefaultName("tester")
assert.Contains(t, name, "tester")
}