-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbot_manager_test.go
More file actions
357 lines (315 loc) · 10.1 KB
/
bot_manager_test.go
File metadata and controls
357 lines (315 loc) · 10.1 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
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
package main
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"sync"
"testing"
"time"
"quantmesh/config"
"quantmesh/event"
"quantmesh/storage"
)
func TestBotManagerResolveLatestStartConfigUsesRefreshedBotSnapshot(t *testing.T) {
botID := "bot-start-refresh"
stale := config.BotConfig{
ID: botID,
Exchange: "binance",
Symbol: "BTCUSDT",
MarketType: "futures",
OrderQuantity: 100,
PositionSafetyCheck: 5,
}
fresh := stale
fresh.OrderQuantity = 250
bm := &BotManager{
cfg: &config.Config{
Bots: []config.BotConfig{fresh},
},
}
got := bm.resolveLatestStartConfig(stale)
if got.OrderQuantity != 250 {
t.Fatalf("expected refreshed order quantity 250, got %.2f", got.OrderQuantity)
}
}
func TestBotManagerResolveLatestStartConfigPrefersBotConfigSnapshot(t *testing.T) {
tmp := t.TempDir()
dbPath := filepath.Join(tmp, "quantmesh.db")
cfg := &config.Config{}
cfg.Storage.Enabled = true
cfg.Storage.Type = "sqlite"
cfg.Storage.Path = dbPath
cfg.Storage.BufferSize = 1
cfg.Storage.BatchSize = 1
storageService, err := storage.NewStorageService(cfg, context.Background())
if err != nil {
t.Fatalf("NewStorageService: %v", err)
}
defer storageService.Stop()
botID := "bot-config-ssot"
stale := config.BotConfig{
ID: botID,
Exchange: "binance",
Symbol: "BTCUSDT",
MarketType: "futures",
OrderQuantity: 100,
}
if _, err := storage.SaveBotConfigSnapshot(
context.Background(),
storageService.GetStorage(),
&config.BotConfigFile{
BotID: botID,
Name: "Test Bot",
Exchange: "binance",
Symbol: "BTCUSDT",
MarketType: "futures",
Grid: config.GridConfig{
OrderQuantity: 250,
},
},
"test",
"unit",
); err != nil {
t.Fatalf("SaveBotConfigSnapshot: %v", err)
}
bm := &BotManager{
cfg: &config.Config{
Bots: []config.BotConfig{stale},
},
storageService: storageService,
}
got := bm.resolveLatestStartConfig(stale)
if got.OrderQuantity != 250 {
t.Fatalf("expected bot_configs order quantity 250, got %.2f", got.OrderQuantity)
}
}
// TestBotManagerConcurrentAccessNoPanic 驗證並發讀寫 runtimes 不會觸發 map 競態崩潰
func TestBotManagerConcurrentAccessNoPanic(t *testing.T) {
bm := &BotManager{
runtimes: make(map[string]*BotRuntime),
}
var wg sync.WaitGroup
for i := 0; i < 20; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
for j := 0; j < 200; j++ {
botID := fmt.Sprintf("bot-%d-%d", i, j)
bm.AddRuntime(&BotRuntime{
BotID: botID,
Config: config.BotConfig{ID: botID, Exchange: "binance", Symbol: "BTCUSDT", MarketType: "futures"},
})
}
}(i)
}
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < 600; j++ {
_ = bm.List()
}
}()
}
wg.Wait()
}
func TestBotManagerWarnsOnSingleLegRunning(t *testing.T) {
eb := event.NewEventBus(64)
sub := eb.Subscribe()
defer eb.Unsubscribe(sub)
cfg := &config.Config{
BotGroups: []config.BotGroup{
{ID: "g1", Name: "hedge-btc", BotIDs: []string{"fut-bot", "spot-bot"}},
},
}
bm := &BotManager{
cfg: cfg,
runtimes: make(map[string]*BotRuntime),
eventBus: eb,
groupLegAlerted: make(map[string]bool),
groupLegTimers: make(map[string]*time.Timer),
}
bm.AddRuntime(&BotRuntime{BotID: "fut-bot", Config: config.BotConfig{ID: "fut-bot", Exchange: "binance", Symbol: "BTCUSDT", MarketType: "futures"}})
bm.AddRuntime(&BotRuntime{BotID: "spot-bot", Config: config.BotConfig{ID: "spot-bot", Exchange: "binance", Symbol: "BTCUSDT", MarketType: "spot"}})
// 从双腿运行切到单腿运行,应触发告警
if err := bm.StopBot("spot-bot"); err != nil {
t.Fatalf("StopBot failed: %v", err)
}
gotAlert := false
timeout := time.After(2 * time.Second)
for !gotAlert {
select {
case evt := <-sub:
if evt != nil && evt.Type == event.EventTypeError {
if groupID, ok := evt.Data["group_id"].(string); ok && groupID == "g1" {
gotAlert = true
}
}
case <-timeout:
t.Fatalf("expected single-leg warning event, but not received")
}
}
// 恢复双腿运行,应触发恢复提示
bm.AddRuntime(&BotRuntime{BotID: "spot-bot", Config: config.BotConfig{ID: "spot-bot", Exchange: "binance", Symbol: "BTCUSDT", MarketType: "spot"}})
bm.checkGroupLegConsistencyForBot("spot-bot")
gotRecovered := false
timeout2 := time.After(2 * time.Second)
for !gotRecovered {
select {
case evt := <-sub:
if evt != nil && evt.Type == event.EventTypeRiskRecovered {
if groupID, ok := evt.Data["group_id"].(string); ok && groupID == "g1" {
gotRecovered = true
}
}
case <-timeout2:
t.Fatalf("expected hedge group recovered event, but not received")
}
}
}
func TestBotManagerAutoPausesSingleLegAfterGrace(t *testing.T) {
eb := event.NewEventBus(64)
sub := eb.Subscribe()
defer eb.Unsubscribe(sub)
cfg := &config.Config{
BotGroups: []config.BotGroup{
{ID: "g2", Name: "hedge-eth", BotIDs: []string{"fut-bot2", "spot-bot2"}},
},
}
bm := &BotManager{
cfg: cfg,
runtimes: make(map[string]*BotRuntime),
eventBus: eb,
groupLegAlerted: make(map[string]bool),
groupLegTimers: make(map[string]*time.Timer),
singleLegGraceSec: 1,
}
fut := &BotRuntime{BotID: "fut-bot2", Config: config.BotConfig{ID: "fut-bot2", Exchange: "binance", Symbol: "ETHUSDT", MarketType: "futures"}}
spot := &BotRuntime{BotID: "spot-bot2", Config: config.BotConfig{ID: "spot-bot2", Exchange: "binance", Symbol: "ETHUSDT", MarketType: "spot"}}
bm.AddRuntime(fut)
bm.AddRuntime(spot)
// 触发单腿运行
if err := bm.StopBot("spot-bot2"); err != nil {
t.Fatalf("StopBot failed: %v", err)
}
gotTriggered := false
timeout := time.After(3 * time.Second)
for !gotTriggered {
select {
case evt := <-sub:
if evt != nil && evt.Type == event.EventTypeRiskTriggered {
if groupID, ok := evt.Data["group_id"].(string); ok && groupID == "g2" {
gotTriggered = true
}
}
case <-timeout:
t.Fatalf("expected risk_triggered event for single leg auto-pause")
}
}
fut.configMu.RLock()
paused := fut.Config.OpenPositionControl.PauseOpening
fut.configMu.RUnlock()
if !paused {
t.Fatalf("expected running leg to be paused after single-leg grace timeout")
}
}
// TestBotManagerIsBotEnabledInDB_StorageUnavailable 驗證存儲不可用時:無文件記錄則保守返回禁用
func TestBotManagerIsBotEnabledInDB_StorageUnavailable(t *testing.T) {
bm := &BotManager{storageService: nil}
enabled, reason := bm.IsBotEnabledInDB("test-bot")
if enabled {
t.Fatalf("storage 不可用且無文件記錄時應保守返回 enabled=false,got enabled=true")
}
if reason != "storage_unavailable" {
t.Fatalf("expected reason=storage_unavailable, got %q", reason)
}
}
// TestBotManagerIsBotEnabledInDB_StorageNil_FileFallback 驗證存儲為 nil 時從文件讀取(修復 EnableBot 寫文件後 StartBot 仍拒絕啟動)
func TestBotManagerIsBotEnabledInDB_StorageNil_FileFallback(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "bot_states.json")
data := `{"enabled-bot":{"enabled":true,"reason":"用戶通過 Web UI 啟用"}}`
if err := os.WriteFile(path, []byte(data), 0644); err != nil {
t.Fatalf("write file: %v", err)
}
bm := &BotManager{storageService: nil, botStatesFileOverride: path}
enabled, reason := bm.IsBotEnabledInDB("enabled-bot")
if !enabled {
t.Fatalf("文件中有 enabled=true 時應返回 enabled=true,got enabled=false")
}
if reason != "from_file" {
t.Fatalf("expected reason=from_file, got %q", reason)
}
}
// TestBotManagerBotStateFileFallback 驗證存儲不可用時從文件讀取已停止狀態
func TestBotManagerBotStateFileFallback(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "bot_states.json")
// 寫入已停止的 bot 狀態
data := `{"stopped-bot":{"enabled":false,"reason":"用戶停止"}}`
if err := os.WriteFile(path, []byte(data), 0644); err != nil {
t.Fatalf("write file: %v", err)
}
bm := &BotManager{storageService: nil, botStatesFileOverride: path}
enabled, found := bm.isBotEnabledFromFile("stopped-bot")
if !found {
t.Fatalf("應從文件讀取到 stopped-bot 的狀態")
}
if enabled {
t.Fatalf("stopped-bot 應為 enabled=false")
}
// 不存在的 bot 應返回 found=false
_, found2 := bm.isBotEnabledFromFile("nonexistent")
if found2 {
t.Fatalf("不存在的 bot 應返回 found=false")
}
}
// TestBotManagerGetStoppedAtFromFile 驗證從文件讀取停止時間
func TestBotManagerGetStoppedAtFromFile(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "bot_states.json")
stoppedAt := "2026-03-21T10:30:00+08:00"
data := fmt.Sprintf(`{"stopped-bot":{"enabled":false,"updated_at":"%s","reason":"用戶停止"}}`, stoppedAt)
if err := os.WriteFile(path, []byte(data), 0644); err != nil {
t.Fatalf("write file: %v", err)
}
bm := &BotManager{storageService: nil, botStatesFileOverride: path}
got, ok := bm.GetStoppedAt("stopped-bot")
if !ok {
t.Fatalf("應從文件讀取到 stopped-bot 的停止時間")
}
if got != stoppedAt {
t.Fatalf("expected stopped_at=%q, got %q", stoppedAt, got)
}
// 不存在的 bot 應返回 ok=false
_, ok2 := bm.GetStoppedAt("nonexistent")
if ok2 {
t.Fatalf("不存在的 bot 應返回 ok=false")
}
// enabled=true 的 bot 不應返回停止時間(視為從未停止過,或已重新啟用)
data2 := `{"running-bot":{"enabled":true,"updated_at":"2026-03-21T10:00:00+08:00","reason":""}}`
if err := os.WriteFile(path, []byte(data2), 0644); err != nil {
t.Fatalf("write file: %v", err)
}
_, ok3 := bm.GetStoppedAt("running-bot")
if ok3 {
t.Fatalf("enabled=true 的 bot 不應返回停止時間")
}
}
func TestBotManager_LastStartFailureRoundTrip(t *testing.T) {
eb := event.NewEventBus(16)
bm := NewBotManager(&config.Config{}, eb, nil, nil, "")
bid := "test-bot-fail"
bm.recordStartFailure(bid, errors.New("账戶餘額不足"))
msg, _, ok := bm.GetLastStartFailure(bid)
if !ok || msg != "账戶餘額不足" {
t.Fatalf("GetLastStartFailure: ok=%v msg=%q", ok, msg)
}
bm.clearStartFailure(bid)
_, _, ok2 := bm.GetLastStartFailure(bid)
if ok2 {
t.Fatalf("clear 後應無記錄")
}
}