From f37316579020654a306d71f2489175bb1be09e68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=F0=9F=90=99PiperYxzzy?= Date: Sun, 29 May 2022 20:55:28 +0200 Subject: [PATCH] Added test classes for the scheduler --- scheduled/scheduled_test.go | 76 +++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 scheduled/scheduled_test.go diff --git a/scheduled/scheduled_test.go b/scheduled/scheduled_test.go new file mode 100644 index 0000000..9a8a84f --- /dev/null +++ b/scheduled/scheduled_test.go @@ -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) + } +}