Files
powerwatts/main_test.go
T
2026-04-20 11:07:30 +02:00

162 lines
4.9 KiB
Go

package main
import (
"bytes"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
)
func TestHandleIndexRendersWatts(t *testing.T) {
srv := &server{secret: "secret", store: &store{value: 123, updatedAt: time.Date(2026, 4, 20, 12, 34, 56, 0, time.UTC)}}
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
srv.handleIndex(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
}
if !strings.Contains(rec.Body.String(), "123") {
t.Fatalf("response did not contain watt value: %s", rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "Last updated:") {
t.Fatalf("response did not contain last updated label: %s", rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "20.04.2026 12:34:56") {
t.Fatalf("response did not contain german datetime: %s", rec.Body.String())
}
}
func TestFormatGermanNumber(t *testing.T) {
tests := map[int]string{
0: "0",
12: "12",
999: "999",
1000: "1.000",
10000: "10.000",
1234567: "1.234.567",
-1000: "-1.000",
}
for input, want := range tests {
if got := formatGermanNumber(input); got != want {
t.Fatalf("formatGermanNumber(%d) = %q, want %q", input, got, want)
}
}
}
func TestHandleWriteRequiresSecret(t *testing.T) {
srv := &server{secret: "secret", store: &store{}}
req := httptest.NewRequest(http.MethodPost, "/write", bytes.NewBufferString(`{"watts":456}`))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
srv.handleWrite(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusUnauthorized)
}
}
func TestHandleWriteStoresValue(t *testing.T) {
srv := &server{secret: "secret", store: &store{}}
req := httptest.NewRequest(http.MethodPost, "/write", bytes.NewBufferString(`{"watts":456}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Secret", "secret")
rec := httptest.NewRecorder()
srv.handleWrite(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
}
if got := srv.store.get(); got != 456 {
t.Fatalf("stored watts = %d, want %d", got, 456)
}
if srv.store.updatedAt.IsZero() {
t.Fatal("updatedAt was not set")
}
}
func TestLoadConfig(t *testing.T) {
path := t.TempDir() + "/config.json"
if err := os.WriteFile(path, []byte(`{"write_secret":"secret","addr":":9090","chart_max_watts":750}`), 0o600); err != nil {
t.Fatalf("write config: %v", err)
}
cfg, err := loadConfig(path)
if err != nil {
t.Fatalf("loadConfig returned error: %v", err)
}
if cfg.WriteSecret != "secret" {
t.Fatalf("write_secret = %q, want %q", cfg.WriteSecret, "secret")
}
if cfg.Addr != ":9090" {
t.Fatalf("addr = %q, want %q", cfg.Addr, ":9090")
}
if cfg.ChartMaxWatts != 750 {
t.Fatalf("chart_max_watts = %d, want %d", cfg.ChartMaxWatts, 750)
}
}
func TestBuildHistoryChartEmpty(t *testing.T) {
chart := buildHistoryChart(nil, 0)
if !strings.Contains(string(chart), "No power history yet") {
t.Fatalf("empty chart did not contain fallback text: %s", string(chart))
}
}
func TestBuildHistoryChartRendersPolyline(t *testing.T) {
history := []sample{
{at: time.Date(2026, 4, 20, 0, 0, 0, 0, time.UTC), value: 100},
{at: time.Date(2026, 4, 20, 6, 0, 0, 0, time.UTC), value: 200},
{at: time.Date(2026, 4, 20, 12, 0, 0, 0, time.UTC), value: 150},
}
chart := buildHistoryChart(history, 0)
if !strings.Contains(string(chart), "<polyline") {
t.Fatalf("chart did not contain polyline: %s", string(chart))
}
for _, want := range []string{"W", "00:00", "06:00", "12:00"} {
if !strings.Contains(string(chart), want) {
t.Fatalf("chart did not include %q: %s", want, string(chart))
}
}
if !strings.Contains(string(chart), "0 W") {
t.Fatalf("chart did not include zero baseline: %s", string(chart))
}
}
func TestBuildHistoryChartUsesConfiguredMax(t *testing.T) {
history := []sample{{at: time.Date(2026, 4, 20, 12, 0, 0, 0, time.UTC), value: 250}}
chart := buildHistoryChart(history, 1000)
if !strings.Contains(string(chart), "1.000 W") {
t.Fatalf("chart did not include configured max: %s", string(chart))
}
if strings.Contains(string(chart), "250 W") {
t.Fatalf("chart unexpectedly used sample max instead of configured max: %s", string(chart))
}
}
func TestStoreTrimsHistoryToMaxPoints(t *testing.T) {
s := &store{}
base := time.Date(2026, 4, 20, 0, 0, 0, 0, time.UTC)
s.mu.Lock()
for i := 0; i < maxHistoryPoints+25; i++ {
s.history = append(s.history, sample{at: base.Add(time.Duration(i) * time.Second), value: i})
}
s.trimHistoryLocked(base.Add(time.Duration(maxHistoryPoints+25) * time.Second))
got := len(s.history)
s.mu.Unlock()
if got != maxHistoryPoints {
t.Fatalf("history length = %d, want %d", got, maxHistoryPoints)
}
if s.history[0].value != 25 {
t.Fatalf("oldest retained value = %d, want %d", s.history[0].value, 25)
}
}