Skip to content

Commit

Permalink
test: avoid leaking goroutines
Browse files Browse the repository at this point in the history
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
```
  • Loading branch information
trym-b committed Apr 2, 2024
1 parent 6786312 commit 4063436
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 0 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
7 changes: 7 additions & 0 deletions internal/workerpool/workerpool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {})
Expand Down

0 comments on commit 4063436

Please sign in to comment.