Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
test(e2e): move API-contract + validation tests down a layer (refs #44) (#46)
Carter1d4dc53d679b
diff --git a/backend/controllers/programs_test.go b/backend/controllers/programs_test.goindex fc406e9..cf41675 100644--- a/backend/controllers/programs_test.go+++ b/backend/controllers/programs_test.go@@ -218,3 +218,29 @@ func TestCreateProgram_setNumberNormalized(t *testing.T) {t.Errorf("expected set_number 1 after normalization, got %v", setNum)}}++func TestListPrograms_filtersBySearchQuery(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ other := otherUser(t)++ db.DB.Exec(`INSERT INTO programs (user_id, name) VALUES (?, ?)`, uid, "Push Day")+ db.DB.Exec(`INSERT INTO programs (user_id, name) VALUES (?, ?)`, uid, "Leg Day")+ // Same matching name under another user — must NOT leak across users.+ db.DB.Exec(`INSERT INTO programs (user_id, name) VALUES (?, ?)`, other, "Push Day (theirs)")++ c, w := newContext(uid, http.MethodGet, "/api/v1/programs?q=push", nil)+ c.Request.URL.RawQuery = "q=push" // case-insensitive LIKE on name, scoped by user+ ListPrograms(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ data := decodeResponse(t, w)["data"].([]any)+ if len(data) != 1 {+ t.Fatalf("expected 1 match for q=push (case-insensitive, excludes 'Leg Day' and the other user's), got %d", len(data))+ }+ if name := data[0].(map[string]any)["name"]; name != "Push Day" {+ t.Errorf("expected 'Push Day', got %v", name)+ }+}diff --git a/backend/controllers/workouts_test.go b/backend/controllers/workouts_test.goindex 9b8a8c9..cc773d9 100644--- a/backend/controllers/workouts_test.go+++ b/backend/controllers/workouts_test.go@@ -230,3 +230,29 @@ func TestListWorkouts_limitCap(t *testing.T) {t.Errorf("expected 5 workouts, got %d", len(data))}}++func TestListWorkouts_filtersBySearchQuery(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ other := otherUser(t)++ db.DB.Exec(`INSERT INTO workouts (user_id, name, started_at) VALUES (?, ?, CURRENT_TIMESTAMP)`, uid, "Morning Push")+ db.DB.Exec(`INSERT INTO workouts (user_id, name, started_at) VALUES (?, ?, CURRENT_TIMESTAMP)`, uid, "Leg Session")+ // Same matching name under another user — must NOT leak across users.+ db.DB.Exec(`INSERT INTO workouts (user_id, name, started_at) VALUES (?, ?, CURRENT_TIMESTAMP)`, other, "Morning Push (theirs)")++ c, w := newContext(uid, http.MethodGet, "/api/v1/workouts?q=push", nil)+ c.Request.URL.RawQuery = "q=push" // case-insensitive LIKE on name, scoped by user+ ListWorkouts(c)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ data := decodeResponse(t, w)["data"].([]any)+ if len(data) != 1 {+ t.Fatalf("expected 1 match for q=push (case-insensitive, excludes 'Leg Session' and the other user's), got %d", len(data))+ }+ if name := data[0].(map[string]any)["name"]; name != "Morning Push" {+ t.Errorf("expected 'Morning Push', got %v", name)+ }+}diff --git a/web/e2e/auth.spec.ts b/web/e2e/auth.spec.tsindex e6e653e..0c7c6ea 100644--- a/web/e2e/auth.spec.ts+++ b/web/e2e/auth.spec.ts@@ -63,13 +63,8 @@ test('server settings Save stays enabled when the field equals the current serveawait expect(save).toBeEnabled()})-test('server settings rejects a scheme-less host instead of guessing the scheme', async ({ page }) => {- // A bare host like "127.0.0.1:9" must be rejected with an error — we no longer- // silently prepend a scheme. The user has to type http:// or https:// explicitly.- await page.goto('/login')- await page.getByRole('button', { name: /server settings/i }).click()- await page.getByPlaceholder('Leave blank to use this site').fill('127.0.0.1:9')- await page.getByRole('button', { name: /test & save/i }).click()- await expect(page.getByText(/include http:\/\/ or https:\/\//i)).toBeVisible()- expect(await page.evaluate(() => localStorage.getItem('server_url'))).toBeNull()-})+// NOTE: the scheme-less-host rejection case was removed — normalizeServerUrl's+// validation (scheme-less, whitespace, unparseable, path-stripping) is covered+// exhaustively in web/src/stores/server.test.ts. The "rejects an invalid URL"+// test above is kept as the single E2E proof that the panel surfaces a+// validation error to the user.diff --git a/web/e2e/exercises.spec.ts b/web/e2e/exercises.spec.tsindex 7ebd8a7..e29388c 100644--- a/web/e2e/exercises.spec.ts+++ b/web/e2e/exercises.spec.ts@@ -56,29 +56,10 @@ test.describe('Exercise Detail', () => {await expect(page.getByRole('heading')).toBeVisible()})- test('PR API returns data after seeded workout', async ({ request }) => {- const res = await request.get(`${API}/exercises/${exerciseId}/prs`, {- headers: { Authorization: `Bearer ${authToken}` }- })- expect(res.status()).toBe(200)- const body = await res.json()- expect(body.data).not.toBeNull()- expect(body.data.weight).toBeGreaterThan(0)- expect(body.data.estimated_1rm).toBeGreaterThan(0)- })-- test('history API returns sessions', async ({ request }) => {- const res = await request.get(`${API}/exercises/${exerciseId}/history`, {- headers: { Authorization: `Bearer ${authToken}` }- })- expect(res.status()).toBe(200)- const body = await res.json()- expect(Array.isArray(body.data)).toBe(true)- expect(body.data.length).toBeGreaterThan(0)- const point = body.data[0]- expect(point.max_weight).toBeGreaterThan(0)- expect(point.sets_count).toBeGreaterThan(0)- })+ // NOTE: the GET /exercises/:id/prs and /history API-contract tests were moved to+ // Go integration tests (controllers/exercises_test.go: TestGetExercisePRs_*,+ // TestGetExerciseHistory_*), which assert exact values deterministically. The+ // beforeAll seeding stays — the UI tests below depend on it.test('exercise detail shows PR card when history exists', async ({ page }) => {await page.goto(`/exercises/${exerciseId}`)diff --git a/web/e2e/food.spec.ts b/web/e2e/food.spec.tsindex 50ef940..45ace95 100644--- a/web/e2e/food.spec.ts+++ b/web/e2e/food.spec.ts@@ -406,88 +406,9 @@ test.describe('Food', () => {await expect(page.locator('input[placeholder="Search food…"]')).toBeVisible()})- test('barcode API returns 404 for unknown barcode', async ({ page }) => {- const h = { Authorization: `Bearer ${authToken}` }- const r = await page.request.get(`${API}/food/barcode/000000000000`, { headers: h })- expect([404, 429, 503]).toContain(r.status())- })-- test('barcode API returns product data for known barcode', async ({ page }) => {- // 051500255186 is Jif Creamy Peanut Butter — seeded via seed script- const h = { Authorization: `Bearer ${authToken}` }- const r = await page.request.get(`${API}/food/barcode/051500255186`, { headers: h })- // May be 200 (product in OFF), 503 (OFF unreachable), 404 or 429 (rate-limited)- expect([200, 503, 404, 429]).toContain(r.status())- })-- // ─── Backend endpoints ─────────────────────────────────────────────────────-- test('GET /food/search returns results for a common query', async ({ page }) => {- const h = { Authorization: `Bearer ${authToken}` }- const r = await page.request.get(`${API}/food/search?q=apple`, { headers: h })- // May be 200 (OFF reachable) or 503 (unreachable) — not 4xx- expect([200, 503]).toContain(r.status())- })-- test('GET /food/history returns array of date-grouped entries', async ({ page }) => {- const h = { Authorization: `Bearer ${authToken}` }- const r = await page.request.get(`${API}/food/history?days=7`, { headers: h })- expect(r.status()).toBe(200)- const body = await r.json()- expect(Array.isArray(body.data)).toBe(true)- if (body.data.length > 0) {- expect(body.data[0]).toHaveProperty('date')- expect(body.data[0]).toHaveProperty('calories')- }- })-- test('GET /food/saved returns user saved foods', async ({ page }) => {- const h = { Authorization: `Bearer ${authToken}` }- const r = await page.request.get(`${API}/food/saved`, { headers: h })- expect(r.status()).toBe(200)- const body = await r.json()- expect(Array.isArray(body.data)).toBe(true)- const found = body.data.find((s: any) => s.name === `${SEED_PREFIX}-saved`)- expect(found).toBeTruthy()- })-- test('PATCH /food/:id updates food log', async ({ page }) => {- const h = { Authorization: `Bearer ${authToken}` }- const [firstId] = seedFoodIds- const r = await page.request.patch(`${API}/food/${firstId}`, {- headers: h,- data: { name: `${SEED_PREFIX}-breakfast`, meal: 'breakfast', calories: 350, protein: 22, carbs: 44, fat: 11, servings: 1, logged_at: todayNoon },- })- expect(r.status()).toBe(200)- const body = await r.json()- expect(body.data.calories).toBe(350)- })-- test('GET /food/:id returns ownership-scoped entry', async ({ page }) => {- const h = { Authorization: `Bearer ${authToken}` }- const [firstId] = seedFoodIds- const r = await page.request.get(`${API}/food/${firstId}`, { headers: h })- expect(r.status()).toBe(200)- const body = await r.json()- expect(body.data.name).toBe(`${SEED_PREFIX}-breakfast`)- })-- test('GET /food?date= returns entries for the specified date', async ({ page }) => {- const h = { Authorization: `Bearer ${authToken}` }- const r = await page.request.get(`${API}/food?date=${today}`, { headers: h })- expect(r.status()).toBe(200)- const body = await r.json()- const seeded = body.data.filter((e: any) => e.name.startsWith(SEED_PREFIX))- expect(seeded.length).toBeGreaterThanOrEqual(3)- })-- test('GET /food/stats returns calorie and macro totals', async ({ page }) => {- const h = { Authorization: `Bearer ${authToken}` }- const r = await page.request.get(`${API}/food/stats?date=${today}`, { headers: h })- expect(r.status()).toBe(200)- const body = await r.json()- expect(body.data).toHaveProperty('total_calories')- expect(body.data).toHaveProperty('total_protein')- expect(body.data.total_calories).toBeGreaterThan(0)- })+ // NOTE: the food API-contract tests (GET/PATCH /food, /food/search, /food/history,+ // /food/saved, /food/stats, /food/barcode) were moved to Go integration tests+ // (controllers/food_test.go), which mock OpenFoodFacts and assert exact values+ // deterministically — no real-network flakiness. The beforeAll seeding stays for+ // the UI tests above.})