forgejo-runner-optimiser/internal/summary/writer_test.go
Waldemar Kindler 7201a527d8
All checks were successful
ci / build (push) Successful in 1m39s
feat(collector): Summaries metrics at the end of the process
2026-02-04 16:21:17 +01:00

93 lines
2.8 KiB
Go

// ABOUTME: Tests for the summary writer that emits run summaries via slog.
// ABOUTME: Validates JSON output, text output, and nil summary handling.
package summary
import (
"bytes"
"strings"
"testing"
"time"
)
func TestSummaryWriter_JSON(t *testing.T) {
var buf bytes.Buffer
w := NewSummaryWriter(&buf, "json")
s := &RunSummary{
StartTime: time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC),
EndTime: time.Date(2025, 1, 1, 0, 1, 0, 0, time.UTC),
DurationSeconds: 60,
SampleCount: 12,
CPUTotal: StatSummary{Peak: 95.5, Avg: 42.0, P95: 88.0},
MemUsedBytes: StatSummary{Peak: 8000000, Avg: 4000000, P95: 7500000},
MemUsedPercent: StatSummary{Peak: 80.0, Avg: 40.0, P95: 75.0},
TopCPUProcesses: []ProcessPeak{
{PID: 1, Name: "busy", PeakCPU: 95.5, PeakMem: 1000},
},
TopMemProcesses: []ProcessPeak{
{PID: 2, Name: "hungry", PeakCPU: 10.0, PeakMem: 8000000},
},
}
w.Write(s)
output := buf.String()
if !strings.Contains(output, "run_summary") {
t.Errorf("output should contain 'run_summary', got: %s", output)
}
if !strings.Contains(output, "duration_seconds") {
t.Errorf("output should contain 'duration_seconds', got: %s", output)
}
if !strings.Contains(output, "sample_count") {
t.Errorf("output should contain 'sample_count', got: %s", output)
}
if !strings.Contains(output, "cpu_total_percent") {
t.Errorf("output should contain 'cpu_total_percent', got: %s", output)
}
if !strings.Contains(output, "mem_used_bytes") {
t.Errorf("output should contain 'mem_used_bytes', got: %s", output)
}
if !strings.Contains(output, "top_cpu_processes") {
t.Errorf("output should contain 'top_cpu_processes', got: %s", output)
}
if !strings.Contains(output, "top_mem_processes") {
t.Errorf("output should contain 'top_mem_processes', got: %s", output)
}
}
func TestSummaryWriter_Text(t *testing.T) {
var buf bytes.Buffer
w := NewSummaryWriter(&buf, "text")
s := &RunSummary{
StartTime: time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC),
EndTime: time.Date(2025, 1, 1, 0, 1, 0, 0, time.UTC),
DurationSeconds: 60,
SampleCount: 12,
CPUTotal: StatSummary{Peak: 95.5, Avg: 42.0, P95: 88.0},
MemUsedBytes: StatSummary{Peak: 8000000, Avg: 4000000, P95: 7500000},
MemUsedPercent: StatSummary{Peak: 80.0, Avg: 40.0, P95: 75.0},
}
w.Write(s)
output := buf.String()
if !strings.Contains(output, "run_summary") {
t.Errorf("output should contain 'run_summary', got: %s", output)
}
if !strings.Contains(output, "duration_seconds") {
t.Errorf("output should contain 'duration_seconds', got: %s", output)
}
}
func TestSummaryWriter_NilSummary(t *testing.T) {
var buf bytes.Buffer
w := NewSummaryWriter(&buf, "json")
// Should not panic and should not write anything
w.Write(nil)
if buf.Len() != 0 {
t.Errorf("expected no output for nil summary, got: %s", buf.String())
}
}