How to check sleep function in golang

I wrote my own sleep function and want to test it. Below 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 does not work. I try to get the start and end times, and then compare it with the expected time. The expected time will be in seconds. I tried end.Sub(start) , but that returns me something like 1m30.0909 , instead I need 90 . It would be great if someone could help me. Thanks:)

+5
source share
2 answers

Elapsed Time:

The easiest way to get the elapsed time from a specific time ( start ) is to use the time.Since() function, which returns the time.Duration , which has the Duration.Seconds() method, which returns the duration in seconds as float64 .

So, in your case, the elapsed seconds:

 sec := time.Since(start).Seconds() 

Now for testing ...

When testing sleeping functions, you should consider that after sleep it is not guaranteed that the code will continue to be executed immediately. For example, quoting from the document time.Sleep() :

Sleep pauses the current goroutine for at least duration d.

So, when writing test code for functions like sleep, I would test the following:

  • Elapsed time must be at least indicated
  • and suppose some error field.

So, for example, check this as follows:

 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") } } 
+10
source

If you use time.Unix (), which gives you the number of seconds since the era (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") } } 

Your code is currently subtracting time.Now (), which does not return the result you plan to use. The test requires simple int values ​​representing seconds.

+1
source

All Articles