-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathexample_test.go
364 lines (321 loc) · 11.3 KB
/
example_test.go
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package kod_test
import (
"context"
"fmt"
"log/slog"
"testing"
"github.com/go-kod/kod"
"github.com/go-kod/kod/examples/helloworld"
"github.com/go-kod/kod/interceptor"
"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.opentelemetry.io/otel"
"go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/sdk/trace/tracetest"
"go.uber.org/mock/gomock"
)
// This example demonstrates how to use [kod.Run] and [kod.Implements] to run a simple application.
func Example_componentRun() {
kod.Run(context.Background(), func(ctx context.Context, app *helloworld.App) error {
fmt.Println("Hello, World!")
return nil
})
// Output:
// helloWorld init
// Hello, World!
// helloWorld shutdown
}
// This example demonstrates how to use [kod.MustRun] and [kod.Implements] to run a simple application.
func Example_componentRunMust() {
kod.MustRun(context.Background(), func(ctx context.Context, app *helloworld.App) error {
fmt.Println("Hello, World!")
return nil
})
// Output:
// helloWorld init
// Hello, World!
// 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)
return nil
})
// Output:
// helloWorld init
// Hello, World!
// 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.HelloWorldLazy.Get().SayHello(ctx)
app.HelloWorld.Get().SayHello(ctx)
return nil
})
// Output:
// helloWorld init
// lazyHelloWorld init
// Hello, Lazy!
// Hello, World!
// lazyHelloWorld shutdown
// 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()).DoAndReturn(func(ctx context.Context) {
fmt.Println("Hello, Mock!")
})
kod.Run(context.Background(), func(ctx context.Context, app *helloworld.App) error {
app.HelloWorld.Get().SayHello(ctx)
return nil
}, kod.WithFakes(kod.Fake[helloworld.HelloWorld](mock)))
// Output:
// Hello, Mock!
}
// This example demonstrates how to use [kod.WithConfig] to provide a configuration to the application.
func Example_configInComponent() {
kod.Run(context.Background(), func(ctx context.Context, app *helloworld.App) error {
app.HelloWorld.Get().SayHello(ctx)
return nil
}, kod.WithConfigFile("./examples/helloworld/config.toml"))
// Output:
// helloWorld init
// 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 logging with OpenTelemetry.
func Example_openTelemetryLog() {
logger, observer := kod.NewTestLogger()
slog.SetDefault(logger)
kod.RunTest(&testing.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!")
app.HelloWorld.Get().SayHello(ctx)
})
fmt.Println(observer.RemoveKeys("trace_id", "span_id", "time"))
// Output:
// helloWorld init
// Hello, World!
// helloWorld shutdown
// {"component":"github.com/go-kod/kod/Main","level":"INFO","msg":"Hello, World!"}
// {"component":"github.com/go-kod/kod/Main","level":"WARN","msg":"Hello, World!"}
// {"component":"github.com/go-kod/kod/Main","level":"ERROR","msg":"Hello, World!"}
// {"component":"github.com/go-kod/kod/examples/helloworld/HelloWorld","level":"INFO","msg":"Hello, World!"}
}
// This example demonstrates how to use tracing with OpenTelemetry.
func Example_openTelemetryTrace() {
logger, observer := kod.NewTestLogger()
slog.SetDefault(logger)
// create otel test exporter
spanRecorder := tracetest.NewSpanRecorder()
tracerProvider := trace.NewTracerProvider(trace.WithSpanProcessor(spanRecorder))
otel.SetTracerProvider(tracerProvider)
kod.Run(context.Background(), func(ctx context.Context, app *helloworld.App) error {
ctx, span := app.Tracer().Start(ctx, "example")
defer span.End()
app.L(ctx).Info("Hello, World!")
app.L(ctx).WarnContext(ctx, "Hello, World!")
app.HelloWorld.Get().SayHello(ctx)
return nil
}, kod.WithInterceptors(ktrace.Interceptor()))
fmt.Println(observer.Filter(func(m map[string]any) bool {
return m["trace_id"] != nil && m["span_id"] != nil
}).RemoveKeys("trace_id", "span_id", "time"))
// Output:
// helloWorld init
// Hello, World!
// helloWorld shutdown
// {"component":"github.com/go-kod/kod/Main","level":"INFO","msg":"Hello, World!"}
// {"component":"github.com/go-kod/kod/Main","level":"WARN","msg":"Hello, World!"}
// {"component":"github.com/go-kod/kod/examples/helloworld/HelloWorld","level":"INFO","msg":"Hello, World!"}
}
// This example demonstrates how to use metrics with OpenTelemetry.
func Example_openTelemetryMetric() {
kod.Run(context.Background(), func(ctx context.Context, app *helloworld.App) error {
metric, _ := app.Meter().Int64Counter("example")
metric.Add(ctx, 1)
return nil
})
// Output:
// helloWorld init
// helloWorld shutdown
}
// This example demonstrates how to use [kod.WithInterceptors] to provide global interceptors to the application.
func Example_interceptorGlobal() {
itcpt := interceptor.Interceptor(func(ctx context.Context, info interceptor.CallInfo, req, res []interface{}, next interceptor.HandleFunc) error {
fmt.Println("Before call")
err := next(ctx, info, req, res)
fmt.Println("After call")
return err
})
kod.Run(context.Background(), func(ctx context.Context, app *helloworld.App) error {
app.HelloWorld.Get().SayHello(ctx)
return nil
}, kod.WithInterceptors(itcpt))
// Output:
// helloWorld init
// Before call
// Hello, World!
// After call
// helloWorld shutdown
}
// This example demonstrates how to use built-in interceptors with [kod.WithInterceptors].
// 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)
return nil
}, kod.WithInterceptors(krecovery.Interceptor(), ktrace.Interceptor(), kmetric.Interceptor()))
// Output:
// helloWorld init
// Hello, World!
// helloWorld shutdown
}
// This example demonstrates how to use [kod.RunTest] to run a test function.
func Example_testRun() {
kod.RunTest(&testing.T{}, func(ctx context.Context, app *helloworld.App) {
app.HelloWorld.Get().SayHello(ctx)
})
// Output:
// helloWorld init
// Hello, World!
// 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()).DoAndReturn(func(ctx context.Context) {
fmt.Println("Hello, Mock!")
})
kod.RunTest(&testing.T{}, func(ctx context.Context, app *helloworld.App) {
app.HelloWorld.Get().SayHello(ctx)
}, kod.WithFakes(kod.Fake[helloworld.HelloWorld](mock)))
// Output:
// Hello, 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)
app.HelloWorld.Get().SayHello(ctx)
}, kod.WithConfigFile("./examples/helloworld/config.toml"))
// Output:
// helloWorld init
// globalConfig
// Hello, World!config
// helloWorld shutdown
}
// This example demonstrates how to use kod.WithGlobalConfig with default configuration.
func Example_testWithDefaultConfig() {
kod.RunTest(&testing.T{}, func(ctx context.Context, app *helloworld.App) {
fmt.Println(app.Config().Name)
app.HelloWorld.Get().SayHello(ctx)
})
// Output:
// helloWorld init
// kod
// Hello, World!
// helloWorld shutdown
}
// This example demonstrates how to use [kod.RunTest], [kod.NewTestLogger] to run a test function with a custom logger.
func Example_testWithLogObserver() {
logger, observer := kod.NewTestLogger()
slog.SetDefault(logger)
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!")
})
fmt.Println(observer.Len())
fmt.Println(observer.ErrorCount())
fmt.Println(observer.Clean().Len())
// Output:
// helloWorld init
// helloWorld shutdown
// 3
// 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
}
// This example demonstrates how to use [kod.RunTest] to run a test function with a defer function.
func Example_testWithDefer() {
kod.RunTest(&testing.T{}, func(ctx context.Context, app *helloworld.App) {
k := kod.FromContext(ctx)
k.Defer("test", func(ctx context.Context) error {
fmt.Println("Defer called")
return nil
})
fmt.Println(app.Config().Name)
app.HelloWorld.Get().SayHello(ctx)
})
// Output:
// helloWorld init
// kod
// Hello, World!
// Defer called
// helloWorld shutdown
}
// This example demonstrates how to use [in
// Example_testDynamicInterceptor demonstrates how to use dynamic interceptors in kod.
// It shows:
// 1. How to create a custom interceptor function that executes before and after method calls
// 2. How to set a default interceptor using interceptor.SetDefault
// 3. The difference between intercepted and non-intercepted method calls
//
// The example makes two calls to SayHello:
// - First call executes normally without interception
// - Second call is wrapped by the interceptor which prints "Before call" and "After call"
func Example_testDynamicInterceptor() {
kod.Run(context.Background(), func(ctx context.Context, app *helloworld.App) error {
itcpt := func(ctx context.Context, info interceptor.CallInfo, req, res []interface{}, next interceptor.HandleFunc) error {
fmt.Println("Before call")
err := next(ctx, info, req, res)
fmt.Println("After call")
return err
}
app.HelloWorld.Get().SayHello(ctx)
kod.FromContext(ctx).SetInterceptors(itcpt)
app.HelloWorld.Get().SayHello(ctx)
return nil
})
// Output:
// helloWorld init
// Hello, World!
// Before call
// Hello, World!
// After call
// helloWorld shutdown
}