Skip to content
This repository was archived by the owner on Aug 30, 2024. It is now read-only.

Commit 79b7089

Browse files
committed
chore: add tests for clog.ErrGroup
1 parent 1198810 commit 79b7089

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed

internal/x/xsync/doc.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
// Package xsync provides utilities for concurrency.
2+
package xsync

internal/x/xsync/syncwriter.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package xsync
2+
3+
import (
4+
"io"
5+
"sync"
6+
)
7+
8+
// Writer synchronizes concurrent writes to an underlying writer.
9+
func Writer(w io.Writer) io.Writer {
10+
return &writer{
11+
w: w,
12+
}
13+
}
14+
15+
type writer struct {
16+
mu sync.Mutex
17+
w io.Writer
18+
}
19+
20+
func (sw *writer) Write(b []byte) (int, error) {
21+
sw.mu.Lock()
22+
defer sw.mu.Unlock()
23+
return sw.w.Write(b)
24+
}

pkg/clog/errgroup_test.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package clog
2+
3+
import (
4+
"bytes"
5+
"errors"
6+
"strings"
7+
"testing"
8+
9+
"cdr.dev/slog/sloggers/slogtest/assert"
10+
11+
"cdr.dev/coder-cli/internal/x/xsync"
12+
)
13+
14+
func TestErrGroup(t *testing.T) {
15+
t.Run("success", func(t *testing.T) {
16+
egroup := LoggedErrGroup()
17+
18+
var buf bytes.Buffer
19+
SetOutput(xsync.Writer(&buf))
20+
21+
egroup.Go(func() error { return nil })
22+
egroup.Go(func() error { return nil })
23+
egroup.Go(func() error { return nil })
24+
25+
err := egroup.Wait()
26+
assert.Success(t, "error group wait", err)
27+
assert.Equal(t, "empty log buffer", "", buf.String())
28+
})
29+
t.Run("failure_count", func(t *testing.T) {
30+
egroup := LoggedErrGroup()
31+
32+
var buf bytes.Buffer
33+
SetOutput(xsync.Writer(&buf))
34+
35+
egroup.Go(func() error { return errors.New("whoops") })
36+
egroup.Go(func() error { return Error("rich error", "second line") })
37+
38+
err := egroup.Wait()
39+
assert.ErrorContains(t, "error group wait", err, "2 failures emitted")
40+
assert.True(t, "log buf contains", strings.Contains(buf.String(), "fatal: whoops\n\n"))
41+
assert.True(t, "log buf contains", strings.Contains(buf.String(), "error: rich error\n | second line\n\n"))
42+
})
43+
}

0 commit comments

Comments
 (0)