Files
mg4/server/api_test.go
T
nilsandClaude Opus 5.5 51e6f6fd48 Server: rewrite in Go as an API-only service
Same endpoints, request formats, validation rules and InfluxDB layout as
the Next.js server, so the car needs no change: POST /v1/telemetry,
PUT /v1/consumption/daily, PUT /v1/charging-sessions/{id}, GET
/v1/consumption/history/{id}, GET /v1/health. The dashboard, login and
the /v1/history reads are gone; Grafana takes over the dashboards.

- Go 1.26 standard library (net/http routing, log/slog) plus the
  official InfluxDB 2 client. Fails closed at startup on a missing
  InfluxDB setting or an ingest token under 24 characters.
- ABRP forwarder ported: newest fresh sample, rate limited, never
  queued, credentials only in the form body.
- 22 tests: validation, aggregation, forwarding, config, and the
  handlers through a fake store. govulncheck clean (x/net 0.60.0,
  toolchain go1.26.9).
- Image: static binary on distroless, about 11 MB, UID 65532, port
  8080; the build runs vet and the tests.
- Dev shell: Go, gopls and govulncheck instead of Node.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QLJfZQZeAKAwSqViTmLzki
2026-10-17 15:17:42 +02:00

171 lines
5.2 KiB
Go

package main
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
)
type fakeStore struct {
mu sync.Mutex
telemetry []TelemetrySample
chunks []ConsumptionChunk
sessions []ChargingSession
fail error
}
func (f *fakeStore) WriteTelemetry(_ context.Context, _ string, s []TelemetrySample) error {
f.mu.Lock()
defer f.mu.Unlock()
if f.fail != nil {
return f.fail
}
f.telemetry = append(f.telemetry, s...)
return nil
}
func (f *fakeStore) WriteConsumptionChunk(_ context.Context, c ConsumptionChunk) error {
f.mu.Lock()
defer f.mu.Unlock()
if f.fail != nil {
return f.fail
}
f.chunks = append(f.chunks, c)
return nil
}
func (f *fakeStore) WriteChargingSession(_ context.Context, s ChargingSession) error {
f.mu.Lock()
defer f.mu.Unlock()
f.sessions = append(f.sessions, s)
return f.fail
}
func (f *fakeStore) ReadConsumptionChunks(context.Context, string) ([]ConsumptionChunk, error) {
f.mu.Lock()
defer f.mu.Unlock()
return f.chunks, f.fail
}
const testToken = "ingest-test-token-0123456789abcdef"
func newTestAPI() (*API, *fakeStore) {
store := &fakeStore{}
return &API{Store: store, IngestToken: testToken, Forwarder: &Forwarder{}}, store
}
func do(t *testing.T, h http.Handler, method, path, token, body string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, path, strings.NewReader(body))
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
func TestHealthNeedsNoToken(t *testing.T) {
api, _ := newTestAPI()
rec := do(t, api.Routes(), "GET", "/v1/health", "", "")
if rec.Code != 200 || strings.TrimSpace(rec.Body.String()) != `{"status":"ok"}` {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
}
func TestEveryOtherEndpointNeedsTheIngestToken(t *testing.T) {
api, _ := newTestAPI()
h := api.Routes()
for _, c := range []struct{ method, path string }{
{"POST", "/v1/telemetry"},
{"PUT", "/v1/consumption/daily"},
{"PUT", "/v1/charging-sessions/" + testSession},
{"GET", "/v1/consumption/history/" + testInstallation},
} {
for _, token := range []string{"", "wrong-token-0123456789abcdef", testToken + "x"} {
if rec := do(t, h, c.method, c.path, token, "{}"); rec.Code != 401 {
t.Errorf("%s %s with %q: want 401, got %d", c.method, c.path, token, rec.Code)
}
}
}
}
func TestTelemetryIsStoredAndBadInputIsA400(t *testing.T) {
api, store := newTestAPI()
h := api.Routes()
rec := do(t, h, "POST", "/v1/telemetry", testToken, string(telemetryBody(`{"utc":1790000000,"soc":80}`)))
if rec.Code != 204 || len(store.telemetry) != 1 {
t.Fatalf("%d, stored %d", rec.Code, len(store.telemetry))
}
rec = do(t, h, "POST", "/v1/telemetry", testToken, string(telemetryBody(`{"utc":1790000000,"soc":120}`)))
if rec.Code != 400 || !strings.Contains(rec.Body.String(), "samples[0].soc is invalid") {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
if rec := do(t, h, "GET", "/v1/telemetry", testToken, ""); rec.Code != 405 {
t.Fatalf("GET on a POST route: want 405, got %d", rec.Code)
}
}
func TestAFailedWriteIsA500WithoutDetail(t *testing.T) {
api, store := newTestAPI()
store.fail = errors.New("influx says: token xyz rejected")
rec := do(t, api.Routes(), "POST", "/v1/telemetry", testToken, string(telemetryBody(`{"utc":1790000000,"soc":80}`)))
if rec.Code != 500 || strings.Contains(rec.Body.String(), "xyz") {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
}
func TestOversizedBodiesAreRejected(t *testing.T) {
api, _ := newTestAPI()
big := `{"x":"` + strings.Repeat("a", maxBodyBytes) + `"}`
if rec := do(t, api.Routes(), "PUT", "/v1/consumption/daily", testToken, big); rec.Code != 400 {
t.Fatalf("want 400, got %d", rec.Code)
}
}
func TestHistoryReturnsDaysNewestFirstAndTheLifetime(t *testing.T) {
api, _ := newTestAPI()
h := api.Routes()
day := func(date string, at int64) string {
return `{"installationId":"` + testInstallation + `","date":"` + date + `","recordedAt":` +
jsonInt(at) + `,"day":{"km":2.5,"kwh":0.4,"hours":0.03,"socDrop":0.6}}`
}
// Two chunks on one day and one on the next. Retry dedupe is InfluxDB's overwrite and is
// covered by the end-to-end check, not this fake.
for _, body := range []string{day("2026-10-16", 1000), day("2026-10-16", 2000), day("2026-10-17", 3000)} {
if rec := do(t, h, "PUT", "/v1/consumption/daily", testToken, body); rec.Code != 204 {
t.Fatalf("chunk: %d %s", rec.Code, rec.Body)
}
}
rec := do(t, h, "GET", "/v1/consumption/history/"+testInstallation, testToken, "")
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
var got struct {
Records []struct {
Date string `json:"date"`
Day Totals `json:"day"`
} `json:"records"`
Lifetime Totals `json:"lifetime"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
if len(got.Records) != 2 || got.Records[0].Date != "2026-10-17" || got.Records[1].Day.Km != 5 || got.Lifetime.Km != 7.5 {
t.Fatalf("%s", rec.Body)
}
if rec := do(t, h, "GET", "/v1/consumption/history/not-a-uuid", testToken, ""); rec.Code != 400 {
t.Fatalf("bad id: want 400, got %d", rec.Code)
}
}
func jsonInt(v int64) string {
b, _ := json.Marshal(v)
return string(b)
}