package main // End-to-end smoke test against SQLite + local-disk storage — the // DB_DRIVER=sqlite / STORAGE_DRIVER=local combination that lets this app be // tested with no external services at all. Exercises the real mux/handlers; // only OIDC login/callback are skipped (they need a real provider), so the // session cookie is minted directly the same way Callback would. import ( "bytes" "encoding/json" "fmt" "mime/multipart" "net/http" "net/http/httptest" "path/filepath" "testing" "github.com/google/uuid" "vlog/internal/auth" "vlog/internal/db" "vlog/internal/handlers" "vlog/internal/storage" ) // a minimal valid 1x1 PNG. var testPNG = []byte{ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0d, 0x0a, 0x2d, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, } func newTestApp(t *testing.T) (*http.ServeMux, string) { t.Helper() dir := t.TempDir() database, err := db.Connect("sqlite", filepath.Join(dir, "test.db")) if err != nil { t.Fatalf("db.Connect: %v", err) } t.Cleanup(func() { database.Close() }) store, err := storage.NewLocal(filepath.Join(dir, "uploads")) if err != nil { t.Fatalf("storage.NewLocal: %v", err) } // Authenticator is nil — fine as long as the test never hits // /api/auth/login or /api/auth/callback (OIDC needs a real provider). h := handlers.New(database, store, nil, "test-jwt-secret", false) mux := http.NewServeMux() registerRoutes(mux, h) // Simulate what Callback does on first login: JIT-provision a user row // and mint the same session JWT. userID := uuid.New().String() if _, err := database.Exec(`INSERT INTO users (id, oidc_sub, email, name) VALUES (?, ?, ?, ?)`, userID, "test-sub", "test@example.com", "Test User"); err != nil { t.Fatalf("seed user: %v", err) } token, err := auth.MintSessionJWT("test-jwt-secret", userID, "test@example.com") if err != nil { t.Fatalf("mint session: %v", err) } return mux, token } func doJSON(t *testing.T, mux *http.ServeMux, token, method, path string, body interface{}) *httptest.ResponseRecorder { t.Helper() var buf bytes.Buffer if body != nil { if err := json.NewEncoder(&buf).Encode(body); err != nil { t.Fatalf("encode body: %v", err) } } req := httptest.NewRequest(method, path, &buf) req.Header.Set("Content-Type", "application/json") req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token}) rec := httptest.NewRecorder() mux.ServeHTTP(rec, req) return rec } func doUpload(t *testing.T, mux *http.ServeMux, token, path, fieldFile string, content []byte) *httptest.ResponseRecorder { t.Helper() var buf bytes.Buffer w := multipart.NewWriter(&buf) part, err := w.CreateFormFile("file", fieldFile) if err != nil { t.Fatalf("create form file: %v", err) } if _, err := part.Write(content); err != nil { t.Fatalf("write form file: %v", err) } w.Close() req := httptest.NewRequest(http.MethodPost, path, &buf) req.Header.Set("Content-Type", w.FormDataContentType()) req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token}) rec := httptest.NewRecorder() mux.ServeHTTP(rec, req) return rec } func TestFullFlow_SQLiteAndLocalStorage(t *testing.T) { mux, token := newTestApp(t) // Me rec := doJSON(t, mux, token, http.MethodGet, "/api/me", nil) if rec.Code != http.StatusOK { t.Fatalf("GET /api/me: got %d, body %s", rec.Code, rec.Body.String()) } // Create car rec = doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{ "rego": "ABC123", "make": "Toyota", "model": "Corolla", "year": 2018, "regoExpiry": "2026-09-01", "wofExpiry": "2026-08-20", }) if rec.Code != http.StatusCreated { t.Fatalf("POST /api/cars: got %d, body %s", rec.Code, rec.Body.String()) } var car struct { ID string `json:"id"` Rego string `json:"rego"` } if err := json.Unmarshal(rec.Body.Bytes(), &car); err != nil { t.Fatalf("decode car: %v", err) } if car.Rego != "ABC123" { t.Fatalf("expected rego ABC123, got %q", car.Rego) } // List cars rec = doJSON(t, mux, token, http.MethodGet, "/api/cars", nil) if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("ABC123")) { t.Fatalf("GET /api/cars: got %d, body %s", rec.Code, rec.Body.String()) } // Upload photo (local storage) rec = doUpload(t, mux, token, fmt.Sprintf("/api/cars/%s/photo", car.ID), "photo.png", testPNG) if rec.Code != http.StatusOK { t.Fatalf("POST photo: got %d, body %s", rec.Code, rec.Body.String()) } // Stream photo back req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/cars/%s/photo", car.ID), nil) req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token}) rec2 := httptest.NewRecorder() mux.ServeHTTP(rec2, req) if rec2.Code != http.StatusOK { t.Fatalf("GET photo: got %d", rec2.Code) } if got := rec2.Body.Bytes(); !bytes.Equal(got, testPNG) { t.Fatalf("photo bytes round-trip mismatch: got %d bytes, want %d", len(got), len(testPNG)) } if ct := rec2.Header().Get("Content-Type"); ct != "image/png" { t.Fatalf("expected image/png content-type, got %q", ct) } // A renamed non-image file must be rejected (content-sniffing, not extension) rec = doUpload(t, mux, token, fmt.Sprintf("/api/cars/%s/photo", car.ID), "fake.png", []byte("not actually a png")) if rec.Code != http.StatusUnsupportedMediaType { t.Fatalf("expected 415 for fake png, got %d, body %s", rec.Code, rec.Body.String()) } // Add a service entry rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/service-entries", car.ID), map[string]interface{}{ "entryDate": "2026-07-01", "entryType": "Oil change", "performedAt": "Bob's Garage", "odometer": 45000, }) if rec.Code != http.StatusCreated { t.Fatalf("POST service-entries: got %d, body %s", rec.Code, rec.Body.String()) } var entry struct { ID string `json:"id"` } json.Unmarshal(rec.Body.Bytes(), &entry) // Attach a PNG to it rec = doUpload(t, mux, token, fmt.Sprintf("/api/service-entries/%s/files", entry.ID), "invoice.png", testPNG) if rec.Code != http.StatusCreated { t.Fatalf("POST service-entry file: got %d, body %s", rec.Code, rec.Body.String()) } var file struct { ID string `json:"id"` } json.Unmarshal(rec.Body.Bytes(), &file) // Timeline shows the entry with its file rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/service-entries", car.ID), nil) if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("invoice.png")) { t.Fatalf("GET service-entries: got %d, body %s", rec.Code, rec.Body.String()) } // Stream the attachment back req = httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/files/%s", file.ID), nil) req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token}) rec2 = httptest.NewRecorder() mux.ServeHTTP(rec2, req) if rec2.Code != http.StatusOK || !bytes.Equal(rec2.Body.Bytes(), testPNG) { t.Fatalf("GET file: got %d, %d bytes", rec2.Code, rec2.Body.Len()) } // Add a custom reminder due soon, and one far in the future rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/reminders", car.ID), map[string]interface{}{ "reminderType": "custom", "label": "Spark plugs", "dueDate": "2026-08-20", }) if rec.Code != http.StatusCreated { t.Fatalf("POST reminders: got %d, body %s", rec.Code, rec.Body.String()) } rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/reminders", car.ID), map[string]interface{}{ "reminderType": "service", "dueDate": "2030-01-01", }) if rec.Code != http.StatusCreated { t.Fatalf("POST reminders (far future): got %d, body %s", rec.Code, rec.Body.String()) } // Dashboard should surface: the near-due custom reminder, rego expiry, // and WoF expiry (all within 30 days) — but not the 2030 reminder. rec = doJSON(t, mux, token, http.MethodGet, "/api/dashboard", nil) if rec.Code != http.StatusOK { t.Fatalf("GET dashboard: got %d, body %s", rec.Code, rec.Body.String()) } var items []map[string]interface{} if err := json.Unmarshal(rec.Body.Bytes(), &items); err != nil { t.Fatalf("decode dashboard: %v", err) } kinds := map[string]bool{} for _, it := range items { kinds[it["reminderType"].(string)] = true } for _, want := range []string{"custom", "rego", "wof"} { if !kinds[want] { t.Errorf("expected dashboard to include kind %q, items: %+v", want, items) } } if len(items) != 3 { t.Errorf("expected exactly 3 dashboard items (not the 2030 reminder), got %d: %+v", len(items), items) } // Delete the car — must cascade to entries/files/reminders. rec = doJSON(t, mux, token, http.MethodDelete, fmt.Sprintf("/api/cars/%s", car.ID), nil) if rec.Code != http.StatusOK { t.Fatalf("DELETE car: got %d, body %s", rec.Code, rec.Body.String()) } rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s", car.ID), nil) if rec.Code != http.StatusNotFound { t.Fatalf("GET deleted car: expected 404, got %d", rec.Code) } // The attached file should also be gone from local disk (best-effort // delete on cascade) — GET should now 404. req = httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/files/%s", file.ID), nil) req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token}) rec2 = httptest.NewRecorder() mux.ServeHTTP(rec2, req) if rec2.Code != http.StatusNotFound { t.Fatalf("GET file after car delete: expected 404, got %d", rec2.Code) } } func TestKnowledgeBase(t *testing.T) { mux, token := newTestApp(t) rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "KB001"}) if rec.Code != http.StatusCreated { t.Fatalf("POST /api/cars: got %d, body %s", rec.Code, rec.Body.String()) } var car struct { ID string `json:"id"` } json.Unmarshal(rec.Body.Bytes(), &car) // Create rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/knowledge", car.ID), map[string]interface{}{ "title": "Coolant type", "body": "Use Toyota Super Long Life Coolant, pink, diluted 50/50.", }) if rec.Code != http.StatusCreated { t.Fatalf("POST knowledge: got %d, body %s", rec.Code, rec.Body.String()) } var entry struct { ID string `json:"id"` Title string `json:"title"` } json.Unmarshal(rec.Body.Bytes(), &entry) if entry.Title != "Coolant type" { t.Fatalf("expected title Coolant type, got %q", entry.Title) } // List rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/knowledge", car.ID), nil) if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("Coolant type")) { t.Fatalf("GET knowledge: got %d, body %s", rec.Code, rec.Body.String()) } // Update rec = doJSON(t, mux, token, http.MethodPut, fmt.Sprintf("/api/knowledge/%s", entry.ID), map[string]interface{}{ "title": "Coolant type (updated)", "body": "Use Toyota Super Long Life Coolant, pink, diluted 50/50. Bleed via the top-left nipple.", }) if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("Bleed via")) { t.Fatalf("PUT knowledge: got %d, body %s", rec.Code, rec.Body.String()) } // Delete rec = doJSON(t, mux, token, http.MethodDelete, fmt.Sprintf("/api/knowledge/%s", entry.ID), nil) if rec.Code != http.StatusOK { t.Fatalf("DELETE knowledge: got %d, body %s", rec.Code, rec.Body.String()) } rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/knowledge", car.ID), nil) if rec.Code != http.StatusOK || string(rec.Body.Bytes()) != `{"items":[],"hasMore":false}`+"\n" { t.Fatalf("expected empty knowledge list after delete, got %d: %s", rec.Code, rec.Body.String()) } } // TestListPagination covers both paginated list endpoints (service entries // and knowledge entries) — the thing that matters for a car with a very // long history: a page at a time, never the whole thing in one response. func TestListPagination(t *testing.T) { mux, token := newTestApp(t) rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "PAGE001"}) if rec.Code != http.StatusCreated { t.Fatalf("POST /api/cars: got %d, body %s", rec.Code, rec.Body.String()) } var car struct { ID string `json:"id"` } json.Unmarshal(rec.Body.Bytes(), &car) const total = 25 for i := 0; i < total; i++ { rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/service-entries", car.ID), map[string]interface{}{ "entryDate": fmt.Sprintf("2020-01-%02d", (i%28)+1), "entryType": fmt.Sprintf("Entry %d", i), }) if rec.Code != http.StatusCreated { t.Fatalf("seed service entry %d: got %d, body %s", i, rec.Code, rec.Body.String()) } rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/knowledge", car.ID), map[string]interface{}{ "title": fmt.Sprintf("KB %d", i), "body": "body", }) if rec.Code != http.StatusCreated { t.Fatalf("seed knowledge entry %d: got %d, body %s", i, rec.Code, rec.Body.String()) } } for _, endpoint := range []string{"service-entries", "knowledge"} { // Default page (no ?limit=) should cap at 20 and report more available. rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/%s", car.ID, endpoint), nil) var firstPage struct { Items []json.RawMessage `json:"items"` HasMore bool `json:"hasMore"` } if err := json.Unmarshal(rec.Body.Bytes(), &firstPage); err != nil { t.Fatalf("%s first page: decode failed: %v, body %s", endpoint, err, rec.Body.String()) } if len(firstPage.Items) != 20 || !firstPage.HasMore { t.Fatalf("%s first page: expected 20 items + hasMore=true, got %d items, hasMore=%v", endpoint, len(firstPage.Items), firstPage.HasMore) } // Second page (offset=20) should return the remaining 5, hasMore=false. rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/%s?limit=20&offset=20", car.ID, endpoint), nil) var secondPage struct { Items []json.RawMessage `json:"items"` HasMore bool `json:"hasMore"` } if err := json.Unmarshal(rec.Body.Bytes(), &secondPage); err != nil { t.Fatalf("%s second page: decode failed: %v, body %s", endpoint, err, rec.Body.String()) } if len(secondPage.Items) != total-20 || secondPage.HasMore { t.Fatalf("%s second page: expected %d items + hasMore=false, got %d items, hasMore=%v", endpoint, total-20, len(secondPage.Items), secondPage.HasMore) } // A tiny explicit page size still respects hasMore correctly. rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/%s?limit=3&offset=0", car.ID, endpoint), nil) var smallPage struct { Items []json.RawMessage `json:"items"` HasMore bool `json:"hasMore"` } json.Unmarshal(rec.Body.Bytes(), &smallPage) if len(smallPage.Items) != 3 || !smallPage.HasMore { t.Fatalf("%s small page: expected 3 items + hasMore=true, got %d items, hasMore=%v", endpoint, len(smallPage.Items), smallPage.HasMore) } } } func TestSecondUserCannotSeeFirstUsersCar(t *testing.T) { mux, token1 := newTestApp(t) rec := doJSON(t, mux, token1, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "PRIVATE1"}) if rec.Code != http.StatusCreated { t.Fatalf("POST /api/cars: got %d, body %s", rec.Code, rec.Body.String()) } var car struct { ID string `json:"id"` } json.Unmarshal(rec.Body.Bytes(), &car) // Mint a second user's session against the SAME app/db (simulating a // second OIDC-authenticated user). // newTestApp already seeded one user in its own fresh DB, so instead we // reuse the mux but mint a token for a brand-new, never-provisioned user. req := httptest.NewRequest(http.MethodGet, "/api/cars", nil) badToken, err := auth.MintSessionJWT("test-jwt-secret", "00000000-0000-0000-0000-000000000000", "other@example.com") if err != nil { t.Fatalf("mint: %v", err) } req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: badToken}) rec2 := httptest.NewRecorder() mux.ServeHTTP(rec2, req) if rec2.Code != http.StatusOK || string(rec2.Body.Bytes()) != "[]\n" { // (also guards against regressing to encoding an empty list as // JSON null, which would crash the frontend's cars.length checks) t.Fatalf("second user's garage should be empty, got %d: %s", rec2.Code, rec2.Body.String()) } // And can't reach the first user's car by ID either. rec3 := doJSON(t, mux, badToken, http.MethodGet, fmt.Sprintf("/api/cars/%s", car.ID), nil) if rec3.Code != http.StatusNotFound { t.Fatalf("expected 404 for other user's car, got %d", rec3.Code) } } func TestSharingPublicEndpoints(t *testing.T) { mux, token := newTestApp(t) rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "SHARE1", "make": "Honda"}) if rec.Code != http.StatusCreated { t.Fatalf("POST /api/cars: got %d, body %s", rec.Code, rec.Body.String()) } var car struct { ID string `json:"id"` } json.Unmarshal(rec.Body.Bytes(), &car) // Not shared yet — public endpoint 404s. req := httptest.NewRequest(http.MethodGet, "/api/public/cars/nonexistent-token", nil) rec2 := httptest.NewRecorder() mux.ServeHTTP(rec2, req) if rec2.Code != http.StatusNotFound { t.Fatalf("expected 404 for unknown share token, got %d", rec2.Code) } // Turn sharing on. rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/share", car.ID), nil) if rec.Code != http.StatusOK { t.Fatalf("POST share: got %d, body %s", rec.Code, rec.Body.String()) } var shared struct { ShareToken string `json:"shareToken"` } json.Unmarshal(rec.Body.Bytes(), &shared) if shared.ShareToken == "" { t.Fatal("expected a non-empty shareToken") } // Add a service entry with an attachment, to confirm docs are included // in the public view (the whole point of sharing when selling a car). rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/service-entries", car.ID), map[string]interface{}{ "entryDate": "2026-01-01", "entryType": "Oil change", }) var entry struct { ID string `json:"id"` } json.Unmarshal(rec.Body.Bytes(), &entry) rec = doUpload(t, mux, token, fmt.Sprintf("/api/service-entries/%s/files", entry.ID), "invoice.png", testPNG) var file struct { ID string `json:"id"` } json.Unmarshal(rec.Body.Bytes(), &file) // Public car info — no auth cookie needed at all. req = httptest.NewRequest(http.MethodGet, "/api/public/cars/"+shared.ShareToken, nil) rec2 = httptest.NewRecorder() mux.ServeHTTP(rec2, req) if rec2.Code != http.StatusOK || !bytes.Contains(rec2.Body.Bytes(), []byte("SHARE1")) { t.Fatalf("public car: got %d, body %s", rec2.Code, rec2.Body.String()) } // Public service history — should include the attachment. req = httptest.NewRequest(http.MethodGet, "/api/public/cars/"+shared.ShareToken+"/service-entries", nil) rec2 = httptest.NewRecorder() mux.ServeHTTP(rec2, req) if rec2.Code != http.StatusOK || !bytes.Contains(rec2.Body.Bytes(), []byte("invoice.png")) { t.Fatalf("public service-entries: got %d, body %s", rec2.Code, rec2.Body.String()) } // Public file download. req = httptest.NewRequest(http.MethodGet, "/api/public/cars/"+shared.ShareToken+"/files/"+file.ID, nil) rec2 = httptest.NewRecorder() mux.ServeHTTP(rec2, req) if rec2.Code != http.StatusOK || !bytes.Equal(rec2.Body.Bytes(), testPNG) { t.Fatalf("public file: got %d, %d bytes", rec2.Code, rec2.Body.Len()) } // Revoke — public endpoint 404s again. rec = doJSON(t, mux, token, http.MethodDelete, fmt.Sprintf("/api/cars/%s/share", car.ID), nil) if rec.Code != http.StatusOK { t.Fatalf("DELETE share: got %d, body %s", rec.Code, rec.Body.String()) } req = httptest.NewRequest(http.MethodGet, "/api/public/cars/"+shared.ShareToken, nil) rec2 = httptest.NewRecorder() mux.ServeHTTP(rec2, req) if rec2.Code != http.StatusNotFound { t.Fatalf("expected 404 after revoke, got %d", rec2.Code) } } func TestFuelEntries(t *testing.T) { mux, token := newTestApp(t) rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "FUEL1"}) var car struct { ID string `json:"id"` } json.Unmarshal(rec.Body.Bytes(), &car) rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/fuel-entries", car.ID), map[string]interface{}{ "entryDate": "2026-07-01", "litres": 45.5, "cost": 98.20, "odometer": 50000, "location": "BP", }) if rec.Code != http.StatusCreated { t.Fatalf("POST fuel-entries: got %d, body %s", rec.Code, rec.Body.String()) } var entry struct { ID string `json:"id"` Litres float64 `json:"litres"` } json.Unmarshal(rec.Body.Bytes(), &entry) if entry.Litres != 45.5 { t.Fatalf("expected litres 45.5, got %v", entry.Litres) } rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/fuel-entries", car.ID), nil) if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("BP")) { t.Fatalf("GET fuel-entries: got %d, body %s", rec.Code, rec.Body.String()) } rec = doJSON(t, mux, token, http.MethodPut, fmt.Sprintf("/api/fuel-entries/%s", entry.ID), map[string]interface{}{ "entryDate": "2026-07-01", "litres": 46, "cost": 100, "location": "Z Energy", }) if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("Z Energy")) { t.Fatalf("PUT fuel-entries: got %d, body %s", rec.Code, rec.Body.String()) } rec = doJSON(t, mux, token, http.MethodDelete, fmt.Sprintf("/api/fuel-entries/%s", entry.ID), nil) if rec.Code != http.StatusOK { t.Fatalf("DELETE fuel-entries: got %d, body %s", rec.Code, rec.Body.String()) } } func TestMileageAndMilestone(t *testing.T) { mux, token := newTestApp(t) rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "MILE1", "odometer": 68420}) var car struct { ID string `json:"id"` } json.Unmarshal(rec.Body.Bytes(), &car) // With no history points yet, still reports current reading, just no // rate/throughput estimate. rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/mileage", car.ID), nil) var m struct { CurrentOdometer int `json:"currentOdometer"` KmPerYear *float64 `json:"kmPerYear"` YearsPer100k *float64 `json:"yearsPer100k"` Next100kEta *string `json:"next100kEta"` } json.Unmarshal(rec.Body.Bytes(), &m) if m.KmPerYear != nil || m.YearsPer100k != nil { t.Fatalf("expected no rate/throughput with <2 data points, got kmPerYear=%v yearsPer100k=%v", m.KmPerYear, m.YearsPer100k) } // Add a historical fuel entry a year ago at a lower reading — now there // are two points and a rate/throughput estimate should compute. yearAgo := "2025-08-06" doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/fuel-entries", car.ID), map[string]interface{}{ "entryDate": yearAgo, "litres": 40, "cost": 80, "odometer": 50000, }) rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/mileage", car.ID), nil) json.Unmarshal(rec.Body.Bytes(), &m) if m.KmPerYear == nil || *m.KmPerYear < 17000 || *m.KmPerYear > 19500 { t.Fatalf("expected ~18,420 km/year, got %v", m.KmPerYear) } // 100,000km / ~18,420km per year is ~5.4 years — a throughput figure // from today, unrelated to the odometer's current position (68,420km // is nowhere near a "100,000km" round number, and that's the point). if m.YearsPer100k == nil || *m.YearsPer100k < 5.0 || *m.YearsPer100k > 6.0 { t.Fatalf("expected ~5.4 years per 100,000km, got %v", m.YearsPer100k) } if m.Next100kEta == nil { t.Fatal("expected a next100kEta date once a rate is known") } } func TestSynthesizedReminders(t *testing.T) { mux, token := newTestApp(t) rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{ "rego": "REM001", "regoExpiry": "2026-08-20", "wofExpiry": "2026-08-15", }) var car struct { ID string `json:"id"` } json.Unmarshal(rec.Body.Bytes(), &car) // Even with zero real reminders, rego/WoF show up automatically. rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/reminders", car.ID), nil) var views []map[string]interface{} json.Unmarshal(rec.Body.Bytes(), &views) types := map[string]bool{} for _, v := range views { types[v["reminderType"].(string)] = true if v["id"] != nil && v["reminderType"] == "rego" { t.Fatalf("synthesized rego reminder should have a nil id, got %v", v["id"]) } } if !types["rego"] || !types["wof"] { t.Fatalf("expected synthesized rego+wof reminders, got %+v", views) } // Configure a service interval and log a qualifying service entry — // a synthesized "service" reminder should now also appear. doJSON(t, mux, token, http.MethodPut, fmt.Sprintf("/api/cars/%s", car.ID), map[string]interface{}{ "rego": "REM001", "serviceIntervalKm": 10000, "serviceIntervalMonths": 6, }) doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/service-entries", car.ID), map[string]interface{}{ "entryDate": "2026-01-01", "entryType": "Full service", "odometer": 40000, "isService": true, }) rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/reminders", car.ID), nil) json.Unmarshal(rec.Body.Bytes(), &views) types = map[string]bool{} for _, v := range views { types[v["reminderType"].(string)] = true } if !types["service"] { t.Fatalf("expected synthesized service reminder after logging a qualifying entry, got %+v", views) } // A completed real reminder is hidden by default, shown with ?completed=1. rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/reminders", car.ID), map[string]interface{}{ "reminderType": "custom", "label": "Test reminder", "dueDate": "2026-09-01", }) var reminder struct { ID string `json:"id"` } json.Unmarshal(rec.Body.Bytes(), &reminder) doJSON(t, mux, token, http.MethodPut, fmt.Sprintf("/api/reminders/%s", reminder.ID), map[string]interface{}{"completed": true}) rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/reminders", car.ID), nil) if bytes.Contains(rec.Body.Bytes(), []byte("Test reminder")) { t.Fatalf("completed reminder should be hidden by default, got %s", rec.Body.String()) } rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/reminders?completed=1", car.ID), nil) if !bytes.Contains(rec.Body.Bytes(), []byte("Test reminder")) { t.Fatalf("completed reminder should show with ?completed=1, got %s", rec.Body.String()) } }