Files
mfd-monitor-agent/internal/snapshot/snapshot_test.go
codex 877e4cf41d docs(agent): 统一中文注释并补充部署文档
将代码与测试注释改为中文以符合仓库规范;新增中文部署指南、
示例配置,并完善构建脚本对 VERSION 注入的说明。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-19 02:30:49 +00:00

104 lines
2.7 KiB
Go

package snapshot
import (
"context"
"errors"
"testing"
"time"
"mfd-monitor-agent/internal/status"
)
// TestCollectorFailuresReturnPartialSnapshot 验证采集器失败不会导致整份快照失败。
func TestCollectorFailuresReturnPartialSnapshot(t *testing.T) {
cache := NewCache([]Collector{
CollectorFunc(func(context.Context, *status.HostStatus) error {
return nil
}),
CollectorFunc(func(context.Context, *status.HostStatus) error {
return errors.New("permission denied")
}),
}, "test", time.Now())
got := cache.Collect(context.Background())
if got.Agent.SnapshotStatus != "partial" {
t.Fatalf("snapshot status = %q", got.Agent.SnapshotStatus)
}
if len(got.Errors) != 1 || got.Errors[0].Message != "permission denied" {
t.Fatalf("errors = %+v", got.Errors)
}
}
// TestCacheStoresLastSnapshot 验证成功采集结果被缓存。
func TestCacheStoresLastSnapshot(t *testing.T) {
cache := NewCache([]Collector{
CollectorFunc(func(_ context.Context, out *status.HostStatus) error {
out.Host.Hostname = "host-a"
return nil
}),
}, "test", time.Now())
cache.Collect(context.Background())
got, ok := cache.Get()
if !ok {
t.Fatal("expected cached snapshot")
}
if got.Host.Hostname != "host-a" {
t.Fatalf("hostname = %q", got.Host.Hostname)
}
}
// TestRunCollectsImmediately 验证 Run 在首个间隔 tick 之前立即采集。
func TestRunCollectsImmediately(t *testing.T) {
collected := make(chan struct{})
cache := NewCache([]Collector{
CollectorFunc(func(_ context.Context, out *status.HostStatus) error {
out.Host.Hostname = "host-a"
close(collected)
return nil
}),
}, "test", time.Now())
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go cache.Run(ctx, time.Hour, time.Second)
select {
case <-collected:
case <-time.After(time.Second):
t.Fatal("initial collection did not run")
}
got, ok := cache.Get()
if !ok {
t.Fatal("expected cached snapshot")
}
if got.Host.Hostname != "host-a" {
t.Fatalf("hostname = %q", got.Host.Hostname)
}
}
// TestCollectWithTimeoutMarksCanceledCollectorPartial 验证超时被记为 partial。
func TestCollectWithTimeoutMarksCanceledCollectorPartial(t *testing.T) {
cache := NewCache([]Collector{
CollectorFunc(func(ctx context.Context, _ *status.HostStatus) error {
<-ctx.Done()
return ctx.Err()
}),
}, "test", time.Now())
cache.collectWithTimeout(context.Background(), time.Millisecond)
got, ok := cache.Get()
if !ok {
t.Fatal("expected cached snapshot")
}
if got.Agent.SnapshotStatus != "partial" {
t.Fatalf("snapshot status = %q", got.Agent.SnapshotStatus)
}
if len(got.Errors) != 1 || got.Errors[0].Message != context.DeadlineExceeded.Error() {
t.Fatalf("errors = %+v", got.Errors)
}
}