Skip to content

Commit

Permalink
refactor: example and log
Browse files Browse the repository at this point in the history
  • Loading branch information
sysulq committed Sep 6, 2024
1 parent a676dee commit 80d1102
Show file tree
Hide file tree
Showing 7 changed files with 56 additions and 21 deletions.
45 changes: 38 additions & 7 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ import (
"github.com/go-kod/kod/interceptor/kmetric"
"github.com/go-kod/kod/interceptor/krecovery"
"github.com/go-kod/kod/interceptor/ktrace"
"github.com/go-kod/kod/internal/kslog"
"go.uber.org/mock/gomock"
)

// This example demonstrates how to use [kod.Run] and [kod.Implements] to run a simple application.
func Example_mainComponent() {
kod.Run(context.Background(), func(ctx context.Context, app *helloworld.App) error {
fmt.Println("Hello, World!")
Expand All @@ -26,6 +26,7 @@ func Example_mainComponent() {
// helloWorld shutdown
}

// This example demonstrates how to use [kod.Ref] to reference a component and call a method on it.
func Example_componentRefAndCall() {
kod.Run(context.Background(), func(ctx context.Context, app *helloworld.App) error {
app.HelloWorld.Get().SayHello(ctx)
Expand All @@ -37,6 +38,7 @@ func Example_componentRefAndCall() {
// helloWorld shutdown
}

// This example demonstrates how to use [kod.LazyInit] to defer component initialization until it is needed.
func Example_componentLazyInit() {
kod.Run(context.Background(), func(ctx context.Context, app *helloworld.App) error {
app.HelloLazy.Get().SayHello(ctx)
Expand All @@ -52,6 +54,7 @@ func Example_componentLazyInit() {
// helloWorld shutdown
}

// This example demonstrates how to use [kod.WithFakes] and [kod.Fake] to provide a mock implementation of a component.
func Example_componentMock() {
mock := helloworld.NewMockHelloWorld(gomock.NewController(nil))
mock.EXPECT().SayHello(gomock.Any()).Return()
Expand All @@ -65,21 +68,33 @@ func Example_componentMock() {
// Nothing printed from mock
}

// This example demonstrates how to use [kod.WithConfig] to provide a configuration to the application.
func Example_config() {
kod.Run(context.Background(), func(ctx context.Context, app *helloworld.App) error {
fmt.Println(app.Config().Name)
app.HelloWorld.Get().SayHello(ctx)
return nil
}, kod.WithConfigFile("./examples/helloworld/config.toml"))
// Output:
// helloWorld init
// globalConfig
// Hello, World!config
// helloWorld shutdown
}

// This example demonstrates how to use [kod.WithGlobalConfig] to provide a global configuration to the application.
func Example_configGlobal() {
kod.Run(context.Background(), func(ctx context.Context, app *helloworld.App) error {
fmt.Println(app.Config().Name)
return nil
}, kod.WithConfigFile("./examples/helloworld/config.toml"))
// Output:
// helloWorld init
// globalConfig
// helloWorld shutdown
}

// This example demonstrates how to use [kod.WithLogger] to provide a custom logger to the application.
func Example_log() {
logger, observer := kslog.NewTestLogger()
logger, observer := kod.NewTestLogger()

kod.RunTest(&testing.T{}, func(ctx context.Context, app *helloworld.App) {
app.L(ctx).Debug("Hello, World!")
Expand All @@ -100,6 +115,7 @@ func Example_log() {
// {"level":"INFO","msg":"Hello, World!","component":"github.com/go-kod/kod/examples/helloworld/HelloWorld"}
}

// This example demonstrates how to use [kod.WithInterceptors] to provide a custom interceptor to the application.
func Example_interceptor() {
interceptor := interceptor.Interceptor(func(ctx context.Context, info interceptor.CallInfo, req, res []interface{}, next interceptor.HandleFunc) error {
fmt.Println("Before call")
Expand All @@ -120,6 +136,8 @@ func Example_interceptor() {
// helloWorld shutdown
}

// This example demonstrates how to use built-in interceptors
// Such as [krecovery.Interceptor], [ktrace.Interceptor], and [kmetric.Interceptor] ...
func Example_interceptorBuiltin() {
kod.Run(context.Background(), func(ctx context.Context, app *helloworld.App) error {
app.HelloWorld.Get().SayHello(ctx)
Expand All @@ -131,6 +149,7 @@ func Example_interceptorBuiltin() {
// helloWorld shutdown
}

// This example demonstrates how to use [kod.RunTest] to run a test function.
func Example_test() {
kod.RunTest(&testing.T{}, func(ctx context.Context, app *helloworld.App) {
app.HelloWorld.Get().SayHello(ctx)
Expand All @@ -141,6 +160,7 @@ func Example_test() {
// helloWorld shutdown
}

// This example demonstrates how to use [kod.RunTest], [kod.Fake] and [kod.WithFakes] to run a test function with a mock component.
func Example_testWithMockComponent() {
mock := helloworld.NewMockHelloWorld(gomock.NewController(nil))
mock.EXPECT().SayHello(gomock.Any()).Return()
Expand All @@ -153,6 +173,7 @@ func Example_testWithMockComponent() {
// Nothing printed from mock
}

// This example demonstrates how to use [kod.RunTest] and [kod.WithConfigFile] to run a test function with a configuration.
func Example_testWithConfig() {
kod.RunTest(&testing.T{}, func(ctx context.Context, app *helloworld.App) {
fmt.Println(app.Config().Name)
Expand All @@ -165,16 +186,26 @@ func Example_testWithConfig() {
// helloWorld shutdown
}

// Example_testWithLogObserver demonstrates how to test log output.
// This example demonstrates how to use [kod.RunTest], [kod.NewTestLogger] and [kod.WithLogger] to run a test function with a custom logger.
func Example_testWithLogObserver() {
kod.RunTest(&testing.T{}, func(ctx context.Context, app *helloworld.App) {
logger, observer := kod.NewTestLogger()

t := &testing.T{}
kod.RunTest(t, func(ctx context.Context, app *helloworld.App) {
app.L(ctx).Debug("Hello, World!")
app.L(ctx).Info("Hello, World!")
app.L(ctx).Warn("Hello, World!")
app.L(ctx).Error("Hello, World!")
})
}, kod.WithLogger(logger))

fmt.Println(observer.Len())
fmt.Println(observer.ErrorCount())
fmt.Println(observer.Clean().Len())

// Output:
// helloWorld init
// helloWorld shutdown
// 3
// 1
// 0
}
10 changes: 4 additions & 6 deletions internal/kslog/log_observer.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"encoding/json"
"log/slog"
"strings"

"github.com/samber/lo"
)

// removeTime removes the top-level time attribute.
Expand All @@ -31,9 +33,7 @@ func (b *observer) parse() []map[string]any {
}

var m map[string]any
if err := json.Unmarshal([]byte(line), &m); err != nil {
panic(err)
}
lo.Must0(json.Unmarshal([]byte(line), &m))

data = append(data, m)
}
Expand Down Expand Up @@ -69,9 +69,7 @@ func (b *observer) Filter(filter func(map[string]any) bool) *observer {

buf := new(bytes.Buffer)
for _, line := range filtered {
if err := json.NewEncoder(buf).Encode(line); err != nil {
panic(err)
}
lo.Must0(json.NewEncoder(buf).Encode(line))
}

return &observer{
Expand Down
8 changes: 7 additions & 1 deletion testing.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,16 @@ import (
"github.com/go-kod/kod/internal/kslog"
)

var NewTestObserver = kslog.NewTestLogger
// NewTestLogger returns a new test logger.
var NewTestLogger = kslog.NewTestLogger

// fakeComponent is a fake component.
type fakeComponent struct {
intf reflect.Type
impl any
}

// Fake returns a fake component.
func Fake[T any](impl any) fakeComponent {
t := reflect.TypeFor[T]()
if _, ok := impl.(T); !ok {
Expand All @@ -26,6 +29,7 @@ func Fake[T any](impl any) fakeComponent {
return fakeComponent{intf: t, impl: impl}
}

// options contains options for the runner.
type runner struct {
options []func(*options)
}
Expand All @@ -51,6 +55,7 @@ func RunTest3[T1, T2, T3 any](tb testing.TB, body func(context.Context, T1, T2,
runTest(tb, body, opts...)
}

// runTest runs a test function.
func runTest(tb testing.TB, testBody any, opts ...func(*options)) {
tb.Helper()

Expand All @@ -61,6 +66,7 @@ func runTest(tb testing.TB, testBody any, opts ...func(*options)) {
}
}

// sub runs a test function.
func (r runner) sub(tb testing.TB, testBody any) error {
tb.Helper()

Expand Down
8 changes: 4 additions & 4 deletions tests/case1/case_lazy_init_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
)

func TestLazyInit(t *testing.T) {
log, observer := kod.NewTestObserver()
log, observer := kod.NewTestLogger()

kod.RunTest(t, func(ctx context.Context, k *lazyInitImpl) {
require.Equal(t, 1, observer.Len(), observer.String())
Expand All @@ -28,7 +28,7 @@ func TestLazyInit(t *testing.T) {
}

func TestLazyInitTest(t *testing.T) {
log, observer := kod.NewTestObserver()
log, observer := kod.NewTestLogger()

kod.RunTest2(t, func(ctx context.Context, k *lazyInitImpl, comp *lazyInitComponent) {
k.Try(ctx)
Expand All @@ -42,7 +42,7 @@ func TestLazyInitTest(t *testing.T) {
}

func TestLazyInitTest2(t *testing.T) {
log, observer := kod.NewTestObserver()
log, observer := kod.NewTestLogger()

kod.RunTest2(t, func(ctx context.Context, k LazyInitImpl, comp LazyInitComponent) {
require.Equal(t, 2, observer.Len(), observer.String())
Expand All @@ -54,7 +54,7 @@ func TestLazyInitTest2(t *testing.T) {
}

func TestLazyInitTest3(t *testing.T) {
log, observer := kod.NewTestObserver()
log, observer := kod.NewTestLogger()

kod.RunTest2(t, func(ctx context.Context, k *lazyInitImpl, comp LazyInitComponent) {
k.Try(ctx)
Expand Down
2 changes: 1 addition & 1 deletion tests/case1/case_log_file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
)

func TestLogFile(t *testing.T) {
log, observer := kod.NewTestObserver()
log, observer := kod.NewTestLogger()

kod.RunTest(t, func(ctx context.Context, k Test1Component) {
_, err := k.Foo(ctx, &FooReq{Id: 1})
Expand Down
2 changes: 1 addition & 1 deletion tests/case1/case_log_level_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
)

func TestLogLevel(t *testing.T) {
log, observer := kod.NewTestObserver()
log, observer := kod.NewTestLogger()

kod.RunTest(t, func(ctx context.Context, k *test1Component) {
observer.Clean()
Expand Down
2 changes: 1 addition & 1 deletion tests/case1/case_log_mock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
)

func TestMockLog(t *testing.T) {
log, observer := kod.NewTestObserver()
log, observer := kod.NewTestLogger()
t.Setenv("KOD_LOG_LEVEL", "error")

kod.RunTest(t, func(ctx context.Context, k Test1Component) {
Expand Down

0 comments on commit 80d1102

Please sign in to comment.