105 lines
2.6 KiB
Go

package agent
import (
"context"
"errors"
"testing"
"time"
"git.opencomputing.cn/yumoqing/host-metrics-collector/internal/model"
)
func TestCollectWithTimeoutReturnsResult(t *testing.T) {
ctx := context.Background()
samples, err := collectWithTimeout(ctx, 2*time.Second, func() ([]model.Sample, error) {
return []model.Sample{{Name: "cpu.usage", Value: 1.0}}, nil
})
if err != nil {
t.Fatalf("collectWithTimeout returned error: %v", err)
}
if len(samples) != 1 || samples[0].Name != "cpu.usage" {
t.Fatalf("samples = %+v", samples)
}
}
func TestCollectWithTimeoutReturnsError(t *testing.T) {
ctx := context.Background()
wantErr := errors.New("collect failed")
_, err := collectWithTimeout(ctx, 2*time.Second, func() ([]model.Sample, error) {
return nil, wantErr
})
if !errors.Is(err, wantErr) {
t.Fatalf("err = %v, want %v", err, wantErr)
}
}
func TestCollectWithTimeoutTimesOut(t *testing.T) {
ctx := context.Background()
_, err := collectWithTimeout(ctx, 20*time.Millisecond, func() ([]model.Sample, error) {
time.Sleep(200 * time.Millisecond)
return nil, nil
})
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err = %v, want context.DeadlineExceeded", err)
}
}
func TestCollectWithTimeoutRespectsContextCancel(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := collectWithTimeout(ctx, 2*time.Second, func() ([]model.Sample, error) {
return nil, nil
})
if !errors.Is(err, context.Canceled) {
t.Fatalf("err = %v, want context.Canceled", err)
}
}
func TestRunGroupEmitsSamplesAndStops(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
out := make(chan model.Sample, 16)
errc := make(chan error, 16)
fn := func() ([]model.Sample, error) {
return []model.Sample{{Name: "mem.used_percent", Value: 50}}, nil
}
go runGroup(ctx, 20*time.Millisecond, time.Second, "core", fn, out, errc)
select {
case s := <-out:
if s.Name != "mem.used_percent" {
t.Fatalf("sample = %+v", s)
}
case <-time.After(2 * time.Second):
t.Fatalf("timed out waiting for sample")
}
cancel()
}
func TestRunGroupReportsCollectError(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
out := make(chan model.Sample, 1)
errc := make(chan error, 1)
fn := func() ([]model.Sample, error) {
return nil, errors.New("boom")
}
go runGroup(ctx, 20*time.Millisecond, time.Second, "core", fn, out, errc)
select {
case err := <-errc:
if err == nil {
t.Fatalf("expected non-nil error")
}
case <-time.After(2 * time.Second):
t.Fatalf("timed out waiting for error")
}
cancel()
}