test(x): 添加 x 目录下 inspector/metrics/monitor 的生命周期测试;修复 inspector 测试导入及 sqlite3 驱动注册,确保:
- 在本地有 Redis 时能运行完整集成测试 - 在无 Redis 环境下会自动跳过,避免破坏单元测试套件 同时补充了 metrics/monitor 的基本单元测试,改善测试的稳定性和可维护性
This commit is contained in:
68
x/metrics/metrics_test.go
Normal file
68
x/metrics/metrics_test.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"code.tczkiot.com/wlw/taskq"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func TestNewDefaultsAndName(t *testing.T) {
|
||||
m := New(Options{})
|
||||
if m == nil {
|
||||
t.Fatalf("New returned nil")
|
||||
}
|
||||
if m.opts.Namespace == "" {
|
||||
t.Fatalf("expected default Namespace")
|
||||
}
|
||||
if m.Name() != "metrics" {
|
||||
t.Fatalf("unexpected Name: %s", m.Name())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollectNoInspectorNoQueues(t *testing.T) {
|
||||
m := New(Options{Interval: time.Millisecond})
|
||||
// ensure collect() is safe to call when inspector or queues are nil
|
||||
m.collect()
|
||||
}
|
||||
|
||||
func makeTestRedis(t *testing.T) redis.UniversalClient {
|
||||
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379", DB: 15})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := rdb.Ping(ctx).Err(); err != nil {
|
||||
t.Skipf("redis not available: %v", err)
|
||||
}
|
||||
if err := rdb.FlushDB(context.Background()).Err(); err != nil {
|
||||
t.Fatalf("failed to flush redis: %v", err)
|
||||
}
|
||||
return rdb
|
||||
}
|
||||
|
||||
func TestMetricsLifecycleWithServlet(t *testing.T) {
|
||||
rdb := makeTestRedis(t)
|
||||
m := New(Options{Interval: time.Second})
|
||||
|
||||
// register plugin via default servlet
|
||||
s := taskq.NewServlet()
|
||||
taskq.SetDefault(s)
|
||||
|
||||
cfg := taskq.Config{Redis: rdb, Tasks: []*taskq.Task{}, Plugins: []taskq.Plugin{m}}
|
||||
if err := taskq.Configure(cfg); err != nil {
|
||||
t.Fatalf("Configure failed: %v", err)
|
||||
}
|
||||
|
||||
if err := taskq.Init(context.Background()); err != nil {
|
||||
t.Fatalf("Init failed: %v", err)
|
||||
}
|
||||
|
||||
if err := taskq.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start failed: %v", err)
|
||||
}
|
||||
|
||||
taskq.Stop()
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
rdb.Close()
|
||||
}
|
||||
Reference in New Issue
Block a user