Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a sleep function in golang

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 :)

like image 617
Vrushank Doshi Avatar asked Sep 16 '15 03:09

Vrushank Doshi


2 Answers

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:

  • elapsed time should be at least the specified,
  • and allow some error margin.

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")
    }
}
like image 143
icza Avatar answered Oct 28 '22 08:10

icza


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.

like image 37
jabgibson Avatar answered Oct 28 '22 08:10

jabgibson