From 406343668b1b7933daebe0248bd881d64aa6690c Mon Sep 17 00:00:00 2001 From: Trym bremnes Date: Tue, 2 Apr 2024 07:44:49 +0200 Subject: [PATCH] test: avoid leaking goroutines This commit adds a test that checks for goroutine leaks in the `workerpool` package, and also fixes two goroutine leaks. There is unfortunately no easy way of running `goleak` before every test without either a lot of copy-paste, or additional code to ensure every test file has a `TestMain` function. A leaked goroutine will produce the following error with `goleak`: ``` goleak: Errors on successful test run: found unexpected goroutines: [Goroutine 7 in state chan receive, with github.com/nlnwa/warchaeology/internal/workerpool .New.func1 on top of the stack: goroutine 7 [chan receive]: github.com/nlnwa/warchaeology/internal/workerpool. New.func1(0xc00008a1e0) ./warchaeology/internal/workerpool/workerpool.go: 23 +0x66 created by github.com/nlnwa/warchaeology/internal/workerpool.New in goroutine 6 ./warchaeology/internal/workerpool/workerpool.go: 22 +0x85 ] FAIL github.com/nlnwa/warchaeology/internal/workerpool 0.450s FAIL ``` --- go.mod | 1 + internal/workerpool/workerpool_test.go | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/go.mod b/go.mod index 51cf4f27..bf856d49 100644 --- a/go.mod +++ b/go.mod @@ -20,6 +20,7 @@ require ( github.com/spf13/pflag v1.0.5 github.com/spf13/viper v1.18.2 github.com/stretchr/testify v1.9.0 + go.uber.org/goleak v1.2.0 ) require ( diff --git a/internal/workerpool/workerpool_test.go b/internal/workerpool/workerpool_test.go index cc33ce70..905a85f9 100644 --- a/internal/workerpool/workerpool_test.go +++ b/internal/workerpool/workerpool_test.go @@ -5,17 +5,24 @@ import ( "testing" "github.com/stretchr/testify/assert" + "go.uber.org/goleak" ) +func TestMain(m *testing.M) { + goleak.VerifyTestMain(m) +} + func TestCreatePool(t *testing.T) { ctx := context.Background() pool := New(ctx, 1) + defer pool.CloseWait() assert.NotNil(t, pool) } func TestSubmitJob(t *testing.T) { ctx := context.Background() pool := New(ctx, 1) + defer pool.CloseWait() assert.NotNil(t, pool) pool.Submit(func() {})