From 08782b92f787d3e7cd8ee60f2fff462a7872e60b Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Thu, 29 Apr 2021 14:43:02 -0700 Subject: [PATCH] tstest: add WaitFor helper Signed-off-by: Brad Fitzpatrick --- tstest/doc.go | 6 ------ tstest/tstest.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 6 deletions(-) delete mode 100644 tstest/doc.go create mode 100644 tstest/tstest.go diff --git a/tstest/doc.go b/tstest/doc.go deleted file mode 100644 index 72e63b7db..000000000 --- a/tstest/doc.go +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package tstest provides utilities for use in unit tests. -package tstest diff --git a/tstest/tstest.go b/tstest/tstest.go new file mode 100644 index 000000000..0bda2d6cb --- /dev/null +++ b/tstest/tstest.go @@ -0,0 +1,31 @@ +// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package tstest provides utilities for use in unit tests. +package tstest + +import ( + "context" + "time" + + "tailscale.com/logtail/backoff" + "tailscale.com/types/logger" +) + +// WaitFor retries try for up to maxWait. +// It returns nil once try returns nil the first time. +// If maxWait passes without success, it returns try's last error. +func WaitFor(maxWait time.Duration, try func() error) error { + bo := backoff.NewBackoff("wait-for", logger.Discard, maxWait/4) + deadline := time.Now().Add(maxWait) + var err error + for time.Now().Before(deadline) { + err = try() + if err == nil { + break + } + bo.BackOff(context.Background(), err) + } + return err +}