Skip to content

Commit

Permalink
add example test
Browse files Browse the repository at this point in the history
  • Loading branch information
sysulq committed Dec 25, 2024
1 parent 85409e8 commit 8b14727
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
17 changes: 17 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/go-kod/kod/interceptor/kmetric"
"github.com/go-kod/kod/interceptor/krecovery"
"github.com/go-kod/kod/interceptor/ktrace"
"github.com/knadh/koanf/v2"
"go.uber.org/mock/gomock"
)

Expand Down Expand Up @@ -268,3 +269,19 @@ func Example_testWithLogObserver() {
// 1
// 0
}

// This example demonstrates how to use [kod.RunTest], [kod.WithKoanf] to run a test function with a custom koanf instance.
func Example_testWithKoanf() {
c := koanf.New("_")
c.Set("name", "testName")

kod.RunTest(&testing.T{}, func(ctx context.Context, app *helloworld.App) {
fmt.Println(app.Config().Name)
app.HelloWorld.Get().SayHello(ctx)
}, kod.WithKoanf(c))
// Output:
// helloWorld init
// testName
// Hello, World!
// helloWorld shutdown
}
14 changes: 12 additions & 2 deletions kod.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,13 @@ func WithInterceptors(interceptors ...interceptor.Interceptor) func(*options) {
}
}

// WithKoanf is an option setter for specifying a custom Koanf instance.
func WithKoanf(cfg *koanf.Koanf) func(*options) {
return func(opts *options) {
opts.koanf = cfg
}
}

// MustRun is a helper function to run the application with the provided main component and options.
// It panics if an error occurs during the execution.
func MustRun[T any, P PointerToMain[T]](ctx context.Context, run func(context.Context, *T) error, opts ...func(*options)) {
Expand Down Expand Up @@ -330,11 +337,14 @@ type options struct {
fakes map[reflect.Type]any
registrations []*Registration
interceptors []interceptor.Interceptor
koanf *koanf.Koanf
}

// newKod creates a new instance of Kod with the provided registrations and options.
func newKod(_ context.Context, opts ...func(*options)) (*Kod, error) {
opt := &options{}
opt := &options{
koanf: koanf.New("."),
}
for _, o := range opts {
o(opt)
}
Expand Down Expand Up @@ -413,7 +423,7 @@ func (k *Kod) parseConfig(filename string) error {
}
}

c := koanf.New(".")
c := k.opts.koanf
err := c.Load(env.Provider("KOD_", ".", func(s string) string {
return strings.Replace(strings.ToLower(s), "_", ".", -1)
}), nil)
Expand Down

0 comments on commit 8b14727

Please sign in to comment.