diff options
| -rw-r--r-- | timeoutat/timeoutat.go | 24 | ||||
| -rw-r--r-- | timeoutat/timeoutat_test.go | 27 |
2 files changed, 38 insertions, 13 deletions
diff --git a/timeoutat/timeoutat.go b/timeoutat/timeoutat.go index bf8227e..d61dba2 100644 --- a/timeoutat/timeoutat.go +++ b/timeoutat/timeoutat.go @@ -29,19 +29,17 @@ func TimeoutAt( ) (response chan interface{}) { response = make(chan interface{}) go func(ctx context.Context) { - go func() { - if debug.IsDebug(debugLevel) { - fmt.Printf("Timeout expected to end at %v\n", when) - } - select { - case <-time.After(when.Sub(time.Now())): - case <-ctx.Done(): - } - response <- struct{}{} - if debug.IsDebug(debugLevel) { - fmt.Printf("Timeout ended at %v\n", time.Now()) - } - }() + if debug.IsDebug(debugLevel) { + fmt.Printf("Timeout expected to end at %v\n", when) + } + select { + case <-time.After(when.Sub(time.Now())): + case <-ctx.Done(): + } + response <- struct{}{} + if debug.IsDebug(debugLevel) { + fmt.Printf("Timeout ended at %v\n", time.Now()) + } }(ctx) return } diff --git a/timeoutat/timeoutat_test.go b/timeoutat/timeoutat_test.go new file mode 100644 index 0000000..b0c91fe --- /dev/null +++ b/timeoutat/timeoutat_test.go @@ -0,0 +1,27 @@ +package timeoutat + +import ( + "context" + "testing" + "time" + + "github.com/network-quality/goresponsiveness/debug" +) + +func TestTimeoutAt(t *testing.T) { + testTime := 5 * time.Second + testTimeLimit := 6 * time.Second + + now := time.Now() + select { + case <-TimeoutAt(context.Background(), time.Now().Add(testTime), debug.NoDebug): + + } + then := time.Now() + + actualTime := then.Sub(now) + + if actualTime >= testTimeLimit { + t.Fatalf("Should have taken 5 seconds but it really took %v!", actualTime) + } +} |
