From 0eafb34d7e2c9971c9341878a7c1d3ffa034418b Mon Sep 17 00:00:00 2001 From: Will Hawkins Date: Fri, 10 Feb 2023 18:13:03 -0500 Subject: [Cleanup] Update timeoutat.TimeoutAt to remove extraneous go func Also, add a test for timeoutat.TimeoutAt. --- timeoutat/timeoutat.go | 24 +++++++++++------------- timeoutat/timeoutat_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 13 deletions(-) create mode 100644 timeoutat/timeoutat_test.go 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) + } +} -- cgit v1.2.3