-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
88 lines (68 loc) · 1.89 KB
/
example_test.go
File metadata and controls
88 lines (68 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package example
import (
"context"
"fmt"
"log/slog"
"testing"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/fx"
"go.uber.org/fx/fxevent"
)
type TestService struct{}
func NewTestService(
lc fx.Lifecycle,
) *TestService {
lc.Append(fx.Hook{
OnStart: func(context.Context) error {
return errors.WithStack(assert.AnError)
},
})
return &TestService{}
}
var _ slog.Handler = (*CustomLogger)(nil)
type CustomLogger struct {
SeenError bool
Text string
}
func (c *CustomLogger) Enabled(context.Context, slog.Level) bool { return true }
func (c *CustomLogger) Handle(_ context.Context, rec slog.Record) error {
rec.Attrs(func(attr slog.Attr) bool {
if err, ok := attr.Value.Any().(error); ok && err != nil {
c.SeenError = true
}
if attr.Key == "error" {
c.Text = attr.Value.String()
}
return true
})
return nil
}
func (c *CustomLogger) WithAttrs([]slog.Attr) slog.Handler { return c }
func (c *CustomLogger) WithGroup(string) slog.Handler { return c }
func TestExample(t *testing.T) {
slogHandler := CustomLogger{}
app := fx.New(
fx.WithLogger(func() fxevent.Logger {
return &fxevent.SlogLogger{
Logger: slog.New(&slogHandler),
}
}),
fx.Provide(NewTestService),
fx.Invoke(func(_ *TestService, sd fx.Shutdowner) {
sd.Shutdown()
}),
)
err := app.Start(context.Background())
require.Error(t, err, "test error")
<-app.Done()
assert.False(t, slogHandler.SeenError)
assert.Equal(t, "assert.AnError general error for testing", slogHandler.Text)
// here partial checks as path is not stable from machine to machine
fullErrorText := fmt.Sprintf("%+v", err)
t.Log(fullErrorText)
assert.Contains(t, fullErrorText, "assert.AnError")
assert.Contains(t, fullErrorText, "example_test.go:23")
assert.Contains(t, fullErrorText, "go.uber.org/fx@v1.23.0/internal/lifecycle/lifecycle.go:265")
}