I have written my own sleep function and want to test it. Following is my code:
func TestSleep(t *testing.T) {
start := time.Now()
mySleepFunction(65)
end := time.Now()
if (end - start) != 65 {
t.Error("Incorrect sleep function")
}
}
This is not working. I am trying to get start time and end time and then compare it with expected time. The expected time will be in seconds. I tried end.Sub(start)
but this returns me something like 1m30.0909
, instead I need 90
as a result. It would be great if someone could help me.
Thanks :)
Elapsed time:
The easiest to get the elapsed time since a specific time (start
) is to use the time.Since()
function which returns a time.Duration
which has a Duration.Seconds()
method which returns the duration in seconds as float64
.
So in your case the elapsed seconds:
sec := time.Since(start).Seconds()
Now on to testing...
When testing sleep-like functions you should take into consideration that after the sleep it is not guaranteed that the code will continue to execute immediately. For example quoting from the doc of time.Sleep()
:
Sleep pauses the current goroutine for at least the duration d.
So when writing test code for sleep-like functions, I would test like this:
So for example test it like this:
func TestSleep(t *testing.T) {
const secSleep = 65.0
start := time.Now()
mySleepFunction(int(secSleep))
sec := time.Since(start).Seconds()
if sec < secSleep || sec > secSleep*1.05 {
t.Error("Incorrect sleep function")
}
}
If you use time.Unix() which gives you the amount of seconds since the epoch (January 1, 1970 UTC.) then your test should work.
func TestSleep(t *testing.T) {
start := time.Now().Unix()
mySleepFunction(65)
end := time.Now().Unix()
if (end - start) != 65{
t.Error("Incorrect sleep function")
}
}
Currently, your code is subtracting a time.Now() which doesn't return the result you intend. Your test wants simple int values that represent seconds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With