Added test classes for the scheduler

This commit is contained in:
🐙PiperYxzzy
2022-05-29 20:55:28 +02:00
parent 2d65f565ec
commit f373165790

View File

@@ -0,0 +1,76 @@
package scheduled
import (
"testing"
"time"
)
func TestImmediateScheduler(t *testing.T) {
now := time.Now().UnixNano()
c := make(chan bool)
go ExecuteImmediatelyAndSchedule(func() (string, time.Duration) {
c <- true
return "", time.Second
})
<-c
firstDuration := time.Duration.Nanoseconds(time.Millisecond)
elapsed := time.Now().UnixNano() - now
if elapsed > firstDuration {
t.Errorf("did not immediately execute within %v, took %v", firstDuration, elapsed)
}
<-c
secondDuration := elapsed + time.Duration.Nanoseconds(time.Second) + firstDuration
elapsed = time.Now().UnixNano() - now
if elapsed > secondDuration {
t.Errorf("did not schedule second execute within %v nanoseconds, took %v", secondDuration, elapsed)
}
<-c
thirdDuration := elapsed + time.Duration.Nanoseconds(time.Second) + firstDuration
elapsed = time.Now().UnixNano() - now
if elapsed > thirdDuration {
t.Errorf("did not schedule third execute within %v nanoseconds, took %v", thirdDuration, elapsed)
}
}
func TestDelayedScheduler(t *testing.T) {
now := time.Now().UnixNano()
c := make(chan bool)
go ExecuteWithDelayAndSchedule(func() (string, time.Duration) {
c <- true
return "", time.Second
}, time.Millisecond*500)
<-c
firstDuration := time.Duration.Nanoseconds(time.Millisecond * 502)
elapsed := time.Now().UnixNano() - now
if elapsed > firstDuration {
t.Errorf("did not immediately execute within %v, took %v", firstDuration, elapsed)
}
<-c
secondDuration := elapsed + time.Duration.Nanoseconds(time.Second) + firstDuration
elapsed = time.Now().UnixNano() - now
if elapsed > secondDuration {
t.Errorf("did not schedule second execute within %v nanoseconds, took %v", secondDuration, elapsed)
}
<-c
thirdDuration := elapsed + time.Duration.Nanoseconds(time.Second) + firstDuration
elapsed = time.Now().UnixNano() - now
if elapsed > thirdDuration {
t.Errorf("did not schedule third execute within %v nanoseconds, took %v", thirdDuration, elapsed)
}
}