From c2165c4ede8812c3a844b93452e58920cfc58a3d Mon Sep 17 00:00:00 2001 From: Elle Mouton Date: Fri, 13 Dec 2024 10:30:37 +0200 Subject: [PATCH] fn: add Guard test helper Copied from lightninglabs/loop --- fn/tests.go | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 fn/tests.go diff --git a/fn/tests.go b/fn/tests.go new file mode 100644 index 000000000..e492e5330 --- /dev/null +++ b/fn/tests.go @@ -0,0 +1,51 @@ +package fn + +import ( + "os" + "runtime/pprof" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// GuardConfig stores options for Guard function. +type GuardConfig struct { + timeout time.Duration +} + +// GuardOption is an option for Guard function. +type GuardOption func(*GuardConfig) + +// WithGuardTimeout sets timeout for the guard. Default is 5s. +func WithGuardTimeout(timeout time.Duration) GuardOption { + return func(c *GuardConfig) { + c.timeout = timeout + } +} + +// GuardTest implements a test level timeout. +func GuardTest(t *testing.T, opts ...GuardOption) func() { + cfg := GuardConfig{ + timeout: 5 * time.Second, + } + for _, opt := range opts { + opt(&cfg) + } + + done := make(chan struct{}) + go func() { + select { + case <-time.After(cfg.timeout): + err := pprof.Lookup("goroutine").WriteTo(os.Stdout, 1) + require.NoError(t, err) + panic("test timeout") + + case <-done: + } + }() + + return func() { + close(done) + } +}