@@ -3,8 +3,11 @@ package kod
3
3
import (
4
4
"context"
5
5
"testing"
6
+ "time"
6
7
8
+ "github.com/knadh/koanf/v2"
7
9
"github.com/stretchr/testify/assert"
10
+ "github.com/stretchr/testify/require"
8
11
"go.uber.org/goleak"
9
12
)
10
13
@@ -51,3 +54,100 @@ func TestConfigEnv(t *testing.T) {
51
54
assert .Equal (t , k .config .Version , "1.0.0" )
52
55
assert .Equal (t , k .config .Env , "dev" )
53
56
}
57
+
58
+ type testComponent struct {
59
+ Implements [testInterface ]
60
+ WithConfig [testConfig ]
61
+ initialized bool
62
+ initErr error
63
+ shutdown bool
64
+ shutdownErr error
65
+ }
66
+
67
+ type testConfig struct {
68
+ Value string `default:"default"`
69
+ }
70
+
71
+ type testInterface interface {
72
+ IsInitialized () bool
73
+ }
74
+
75
+ func (c * testComponent ) Init (context.Context ) error {
76
+ c .initialized = true
77
+ return c .initErr
78
+ }
79
+
80
+ func (c * testComponent ) Shutdown (context.Context ) error {
81
+ c .shutdown = true
82
+ return c .shutdownErr
83
+ }
84
+
85
+ func (c * testComponent ) IsInitialized () bool {
86
+ return c .initialized
87
+ }
88
+
89
+ func (c * testComponent ) implements (testInterface ) {}
90
+
91
+ func TestConfigurationLoading (t * testing.T ) {
92
+ tests := []struct {
93
+ name string
94
+ koanf * koanf.Koanf
95
+ filename string
96
+ wantErr bool
97
+ }{
98
+ {
99
+ name : "custom koanf" ,
100
+ koanf : koanf .New ("." ), // 使用 koanf.New() 替代空实例
101
+ },
102
+ {
103
+ name : "invalid file extension" ,
104
+ filename : "config.invalid" ,
105
+ wantErr : true ,
106
+ },
107
+ {
108
+ name : "missing file" ,
109
+ filename : "notexist.yaml" ,
110
+ wantErr : true , // Should use defaults
111
+ },
112
+ }
113
+
114
+ for _ , tt := range tests {
115
+ t .Run (tt .name , func (t * testing.T ) {
116
+ opts := []func (* options ){
117
+ WithConfigFile (tt .filename ),
118
+ }
119
+ if tt .koanf != nil {
120
+ opts = append (opts , WithKoanf (tt .koanf ))
121
+ }
122
+
123
+ k , err := newKod (context .Background (), opts ... )
124
+ if tt .wantErr {
125
+ assert .Error (t , err )
126
+ return
127
+ }
128
+ require .NoError (t , err )
129
+
130
+ cfg := k .Config ()
131
+ assert .NotEmpty (t , cfg .Name )
132
+ assert .NotEmpty (t , cfg .Env )
133
+ assert .Equal (t , 5 * time .Second , cfg .ShutdownTimeout )
134
+ })
135
+ }
136
+ }
137
+
138
+ func TestDeferHooks (t * testing.T ) {
139
+ k , err := newKod (context .Background ())
140
+ require .NoError (t , err )
141
+
142
+ executed := false
143
+ k .Defer ("test" , func (context.Context ) error {
144
+ executed = true
145
+ return nil
146
+ })
147
+
148
+ ctx , cancel := context .WithCancel (context .Background ())
149
+ defer cancel ()
150
+
151
+ k .hooker .Do (ctx )
152
+ assert .True (t , executed )
153
+ }
0 commit comments