Skip to content

Commit

Permalink
Add test cases for bg
Browse files Browse the repository at this point in the history
  • Loading branch information
swift1337 committed Jul 12, 2024
1 parent 4bdf50f commit d7ccb9c
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pkg/bg/bg.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func logError(err error, cfg config) {

name := cfg.name
if name == "" {
name = "no task name specified"
name = "unknown"
}

cfg.logger.Error().Err(err).Str("worker.name", name).Msgf("Background task failed")
Expand Down
81 changes: 81 additions & 0 deletions pkg/bg/bg_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package bg

import (
"bytes"
"context"
"fmt"
"testing"
"time"

"github.com/rs/zerolog"
"github.com/stretchr/testify/assert"
)

func TestWork(t *testing.T) {
ctx := context.Background()

t.Run("basic case", func(t *testing.T) {
// ARRANGE
signal := make(chan struct{})

// ACT
Work(ctx, func(ctx context.Context) error {
// simulate some work
time.Sleep(100 * time.Millisecond)
close(signal)
return nil
})

// ASSERT
<-signal
assertChanClosed(t, signal)
})

t.Run("with name and logger", func(t *testing.T) {
// ARRANGE
// Given a logger
out := &bytes.Buffer{}
logger := zerolog.New(out)

// And a that returns an error
call := func(ctx context.Context) error {
time.Sleep(100 * time.Millisecond)
return fmt.Errorf("oopsie")
}

// ACT
Work(ctx, call, WithName("hello"), WithLogger(logger))
time.Sleep(200 * time.Millisecond)

// Check the log output
const expected = `{"level":"error","error":"oopsie","worker.name":"hello","message":"Background task failed"}`
assert.JSONEq(t, expected, out.String())
})

t.Run("panic recovery", func(t *testing.T) {
// ARRANGE
// Given a logger
out := &bytes.Buffer{}
logger := zerolog.New(out)

// And a that returns an error
call := func(ctx context.Context) error {
panic("press F")
return nil
}

// ACT
Work(ctx, call, WithLogger(logger))
time.Sleep(100 * time.Millisecond)

// Check the log output
const expected = `{"level":"error","error":"recovered from PANIC in background task: press F",` +
`"worker.name":"unknown","message":"Background task failed"}`
assert.JSONEq(t, expected, out.String())
})
}

func assertChanClosed(t *testing.T, ch <-chan struct{}) {
_, ok := <-ch
assert.False(t, ok, "channel is not closed")
}

0 comments on commit d7ccb9c

Please sign in to comment.