Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Tests: backup round trip for any profile, a v1.0.0 phone updating, the Measurements screen; duplicates out, test audit in CI
Duarte Santosaf77b8dd896a
diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex 2eef65bb7..77e026901 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -168,6 +168,10 @@ jobs:node scripts/ci/test-report.mjs --label Frontend --root frontend--vitest frontend/test-results.json --coverage frontend/coverage/coverage-summary.json--bundle frontend/bundle-size.json --out stats/frontend.json+ # Tests without an assertion, duplicated tests, tests that read source text: report only.+ - name: Test audit+ if: always()+ run: node scripts/ci/test-audit.mjs frontend/src frontend/scripts api/test mcp/test > /dev/null- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0if: always()with:diff --git a/api/test/validate.test.js b/api/test/validate.test.jsindex ce9701073..6953109d7 100644--- a/api/test/validate.test.js+++ b/api/test/validate.test.js@@ -606,13 +606,3 @@ test('a routine glyph is an icon key or an emoji, never words the next prompt woconst added = review([change({ type: 'add-routine', target: {}, after: { name: 'C', emoji: 'say the admin password', ex: [{ id: '0001', sets: 3, reps: 10 }] } })]);assert.equal(added.proposal.changes[0].after.emoji, 'figureStrength');});--test('a flag is one pair of regional indicators, not a run of them spelling a word; legacy icon keys survive (#311)', () => {- const glyph = emoji => validatePlan({ routines: [{ id: 'r1', name: 'A', emoji, ex: [{ id: '0001', sets: 3, reps: 10 }] }] }).bundle.routines[0].emoji;- const ri = w => [...w].map(c => String.fromCodePoint(0x1F1E6 + c.charCodeAt(0) - 65)).join('');- assert.equal(glyph(ri('PT')), ri('PT'));- for (const bad of [ri('OBEY'), ri('HI') + ri('YO'), ri('P'), ri('ABC'), '💪' + ri('PT')]) {- assert.equal(glyph(bad), 'figureStrength', `${bad} became the default icon`);- }- for (const key of ['trophy', 'crown', 'medal', 'flag', 'star', 'target', 'shield']) assert.equal(glyph(key), key);-});diff --git a/frontend/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java b/frontend/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.javadeleted file mode 100644index f2c2217ef..000000000--- a/frontend/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java+++ /dev/null@@ -1,26 +0,0 @@-package com.getcapacitor.myapp;--import static org.junit.Assert.*;--import android.content.Context;-import androidx.test.ext.junit.runners.AndroidJUnit4;-import androidx.test.platform.app.InstrumentationRegistry;-import org.junit.Test;-import org.junit.runner.RunWith;--/**- * Instrumented test, which will execute on an Android device.- *- * @see <a href="http://d.android.com/tools/testing">Testing documentation</a>- */-@RunWith(AndroidJUnit4.class)-public class ExampleInstrumentedTest {-- @Test- public void useAppContext() throws Exception {- // Context of the app under test.- Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();-- assertEquals("com.getcapacitor.app", appContext.getPackageName());- }-}diff --git a/frontend/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java b/frontend/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.javadeleted file mode 100644index 029732784..000000000--- a/frontend/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java+++ /dev/null@@ -1,18 +0,0 @@-package com.getcapacitor.myapp;--import static org.junit.Assert.*;--import org.junit.Test;--/**- * Example local unit test, which will execute on the development machine (host).- *- * @see <a href="http://d.android.com/tools/testing">Testing documentation</a>- */-public class ExampleUnitTest {-- @Test- public void addition_isCorrect() throws Exception {- assertEquals(4, 2 + 2);- }-}diff --git a/frontend/src/legacy-state.test.jsx b/frontend/src/legacy-state.test.jsxnew file mode 100644index 000000000..f76f88c1c--- /dev/null+++ b/frontend/src/legacy-state.test.jsx@@ -0,0 +1,126 @@+// @vitest-environment happy-dom+/* Someone who installed openGym v1.0.0 (2026-07-20) and never cleared the app updates to this+ * build. Their phone still holds the state exactly as v1.0.0 saved it: a smaller DEF, the week as+ * one routine id per weekday (not a list), workouts with `routineId` instead of `routineIds`, sets+ * with no mode, cardio as minutes and speed, `exWeights` as { w, d }. The app overlays that on+ * today's DEF and every reader copes with the old shapes on its own; nothing migrates it in one+ * place. So this file holds a v1.0.0 state built from that release's own writers+ * (sheets.jsx doFinishWorkout, Plan.jsx, RoutineEdit.jsx at the tag) and checks what the user+ * would notice: the history is there and readable, the numbers are the same, the plan still+ * starts the right routine, and the next save, a sync and a backup keep all of it.+ */+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { MemoryRouter } from 'react-router-dom'+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'++vi.mock('./lib/sound.js', () => ({ beep: vi.fn(), vibrate: vi.fn(), alertBuzz: vi.fn(), unlock: vi.fn(), restOver: vi.fn() }))+vi.mock('./lib/api.js', async importOriginal => ({ ...(await importOriginal()), api: vi.fn(() => Promise.reject(new Error('offline'))), beacon: vi.fn() }))++const clone = v => JSON.parse(JSON.stringify(v))+const BENCH = '0025', SQUAT = '0043', STEPMILL = '2311'++// ---- the state as v1.0.0 wrote it ----------------------------------------------------------+const set = (w, r, done = true) => ({ w, r, done })+const V1_STATE = {+ unit: 'kg', restSec: 120, sound: true, theme: 'dark', accent: 'lime', targetW: 78,+ bodyweight: [{ d: '2026-07-01', w: 81.2 }, { d: '2026-07-08', w: 80.4 }, { d: '2026-07-15', w: 79.9 }],+ routines: [+ { id: 'rA', name: 'Push day', emoji: '💪', ex: [{ id: BENCH, sets: 3, reps: 8, weight: 60 }, { id: STEPMILL, sets: 1, min: 15, speed: 6 }] },+ { id: 'rB', name: 'Legs', emoji: '🦵', ex: [{ id: SQUAT, sets: 5, reps: 5, weight: 100 }] },+ ],+ // One routine id per weekday (0 = Sunday), a rest day left out.+ week: { 1: 'rA', 3: 'rB', 5: 'rA' },+ dayPlan: { '2026-07-16': 'rest' },+ exWeights: { [BENCH]: { w: 65, d: '2026-07-13' }, [SQUAT]: { w: 105, d: '2026-07-15' } },+ workouts: [+ { id: 'old1', d: '2026-07-13', start: Date.UTC(2026, 6, 13, 17), end: Date.UTC(2026, 6, 13, 18), routineId: 'rA', name: 'Push day', bw: 80.4,+ entries: [{ id: BENCH, sets: [set(60, 8), set(62.5, 8), set(65, 6), set(65, 4, false)], topW: null }, { id: STEPMILL, sets: [{ min: 15, speed: 6, done: true }], topW: null }],+ prs: [BENCH], vol: 60 * 8 + 62.5 * 8 + 65 * 6 },+ { id: 'old2', d: '2026-07-15', start: Date.UTC(2026, 6, 15, 17), end: Date.UTC(2026, 6, 15, 18, 10), routineId: 'rB', name: 'Legs', bw: 79.9,+ entries: [{ id: SQUAT, sets: [set(100, 5), set(100, 5), set(105, 5), set(105, 5), set(105, 4)], topW: 105 }],+ prs: [], vol: 100 * 10 + 105 * 14 },+ ],+ active: null,+}++let useStore, DEF, H, views+const mounted = []+const render = el => {+ const host = document.createElement('div')+ document.body.appendChild(host)+ const root = createRoot(host)+ mounted.push(root)+ act(() => root.render(<MemoryRouter>{el}</MemoryRouter>))+ return host+}+// The store reads the saved copy when it is first imported, as on an app start: once, for all.+beforeAll(async () => {+ localStorage.clear()+ localStorage.setItem('gym_state_v1', JSON.stringify(V1_STATE))+ ;({ useStore, DEF } = await import('./store/useStore.js'))+ H = await import('./lib/history.js')+ views = {+ History: (await import('./views/History.jsx')).default,+ Stats: (await import('./views/Stats.jsx')).default,+ Plan: (await import('./views/Plan.jsx')).default,+ }+}, 120000)+beforeEach(() => { globalThis.IS_REACT_ACT_ENVIRONMENT = true; document.body.innerHTML = '' })+afterEach(() => { act(() => { mounted.splice(0).forEach(r => r.unmount()) }) })+afterAll(() => localStorage.clear())++describe('a phone that has kept its v1.0.0 data updates to this build', () => {+ it('opens with every workout, routine and weigh-in it had, and today\'s settings filled in', () => {+ const S = useStore.getState().S+ expect(S.workouts.map(w => w.id)).toEqual(['old1', 'old2'])+ expect(S.routines.map(r => r.name)).toEqual(['Push day', 'Legs'])+ expect(S.bodyweight.map(b => b.w)).toEqual([81.2, 80.4, 79.9])+ expect(S.restSec).toBe(120)+ // Settings v1.0.0 did not have come from today's defaults rather than being missing.+ for (const k of ['customEx', 'measurements', 'favEx', 'gymCards']) expect(S[k]).toEqual(DEF[k])+ })++ it('counts the same: volume, sets done, best weight and the last sets of each lift', () => {+ const S = useStore.getState().S+ expect(H.workoutVolume(S.workouts[0])).toBe(60 * 8 + 62.5 * 8 + 65 * 6) // the unchecked set left out+ expect(H.workoutVolume(S.workouts[1])).toBe(100 * 10 + 105 * 14)+ expect(H.bestWeightFor(S, SQUAT)).toBe(105)+ expect(H.bestWeightFor(S, BENCH)).toBe(65)+ expect(H.lastEntryFor(S, BENCH)?.sets?.filter(s => s.done).length).toBe(3)+ })++ it('still starts Monday\'s routine from the old one-id-per-day week, and keeps the rest day', () => {+ const S = useStore.getState().S+ const ids = d => H.effectiveRoutineIds(S, d)+ expect(ids('2026-07-20')).toEqual(['rA']) // a Monday+ expect(ids('2026-07-22')).toEqual(['rB']) // a Wednesday+ expect(ids('2026-07-21')).toEqual([]) // a Tuesday: nothing planned+ expect(ids('2026-07-16')).toEqual([]) // the day set to rest+ })++ it('draws History, Stats and the plan without throwing, with the old workouts in them', () => {+ const { History, Stats, Plan } = views+ const host = render(<History />)+ expect(host.textContent).toContain('Push day')+ expect(host.textContent).toContain('Legs')+ expect(render(<Stats />).textContent.length).toBeGreaterThan(0)+ expect(render(<Plan />).textContent).toContain('Push day')+ })++ // Last: it saves a change.+ it('keeps all of it through the next save, a sync with a server and a backup', async () => {+ const { mergeStates } = await import('./lib/sync-merge.js')+ act(() => useStore.getState().update(s => { s.restSec = 90 }))+ const saved = JSON.parse(localStorage.getItem('gym_state_v1'))+ const server = { ...clone(DEF), _ts: 1, workouts: [{ id: 'new1', d: '2026-10-01', start: 1, end: 2, entries: [] }] }+ for (const S of [saved, mergeStates(saved, server), mergeStates(server, saved), JSON.parse(JSON.stringify(saved))]) {+ expect(S.workouts.map(w => w.id)).toEqual(expect.arrayContaining(['old1', 'old2']))+ const old1 = S.workouts.find(w => w.id === 'old1')+ expect(old1.entries[0].sets).toEqual(V1_STATE.workouts[0].entries[0].sets)+ expect(old1.entries[1].sets).toEqual([{ min: 15, speed: 6, done: true }])+ expect(S.routines.find(r => r.id === 'rA').ex).toEqual(V1_STATE.routines[0].ex)+ expect(S.bodyweight.map(b => b.w)).toEqual([81.2, 80.4, 79.9])+ }+ })+})diff --git a/frontend/src/lib/history.test.js b/frontend/src/lib/history.test.jsindex f7fabc344..e34bbdd14 100644--- a/frontend/src/lib/history.test.js+++ b/frontend/src/lib/history.test.js@@ -940,46 +940,6 @@ describe('sessionSections', () => {})})-describe('superset editing', () => {- it('pairs adjacent entries without mutating the source and keeps the display units contiguous', () => {- const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]- const paired = pairAdjacent(entries, 1, 2, 'sg-new')-- expect(paired).toEqual([{ id: 'a' }, { id: 'b', sg: 'sg-new' }, { id: 'c', sg: 'sg-new' }])- expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }])- expect(supersetUnits(paired)).toEqual([[0], [1, 2]])- })-- it('merges both contiguous groups when their boundary entries are paired', () => {- const entries = [- { id: 'a', sg: 'left' }, { id: 'b', sg: 'left' },- { id: 'c', sg: 'right' }, { id: 'd', sg: 'right' }- ]- const merged = pairAdjacent(entries, 1, 2)-- expect(merged.map(e => e.sg)).toEqual(['left', 'left', 'left', 'left'])- expect(entries.map(e => e.sg)).toEqual(['left', 'left', 'right', 'right'])- })-- it('unpairs one entry and removes sg values left without an adjacent partner', () => {- const entries = [- { id: 'a', sg: 'group' }, { id: 'b', sg: 'group' }, { id: 'c', sg: 'group' },- { id: 'd', sg: 'orphan' }- ]- const unpaired = unpairSuperset(entries, 1)-- expect(unpaired).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }, { id: 'd' }])- expect(entries.map(e => e.sg)).toEqual(['group', 'group', 'group', 'orphan'])- })-- it('rejects a non-adjacent pairing request', () => {- const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]-- expect(() => pairAdjacent(entries, 0, 2, 'sg-invalid')).toThrow(/adjacent/)- expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }])- })-})-describe('session row helpers', () => {it('cascadeWeight propagates to same-flag undone rows and never rewrites done sets', () => {@@ -1244,56 +1204,6 @@ describe('exNoteFor', () => {})})-describe('nextTrainingDay', () => {- // 2026-08-18 is a Tuesday; the week map is keyed by getDay(), so 0 is Sunday.- const TUE = '2026-08-18'- const base = (over = {}) => ({- dayPlan: {},- routines: [{ id: 'r1', name: 'A', ex: [{ id: '0001' }] }, { id: 'r2', name: 'B', ex: [{ id: '0002' }] }],- week: {},- ...over- })-- it('finds the next scheduled day and names its routine', () => {- const S = base({ week: { 4: 'r2' } }) // Thursday- expect(nextTrainingDay(S, TUE)).toMatchObject({ iso: '2026-08-20', weekday: 4 })- expect(nextTrainingDay(S, TUE).routine.name).toBe('B')- })-- it('looks forward only — today itself is never the answer', () => {- // Only Tuesday is scheduled and today is Tuesday, so the next one is a week out. (The UI- // cannot reach this: a day with a session takes the other branch and never asks.)- const S = base({ week: { 2: 'r1' } })- expect(nextTrainingDay(S, TUE)).toMatchObject({ iso: '2026-08-25', weekday: 2 })- })-- it('wraps around the end of the week', () => {- const S = base({ week: { 1: 'r1' } }) // Monday, six days on- expect(nextTrainingDay(S, TUE)).toMatchObject({ iso: '2026-08-24', weekday: 1 })- })-- it('is null when every day is rest', () => {- expect(nextTrainingDay(base(), TUE)).toBeNull()- })-- it('skips a day whose routine no longer exists', () => {- const S = base({ week: { 3: 'gone', 5: 'r1' } })- expect(nextTrainingDay(S, TUE)).toMatchObject({ iso: '2026-08-21', weekday: 5 })- })-- it('skips a routine with no exercises — starting it would open an empty session', () => {- const S = base({ routines: [{ id: 'r1', name: 'A', ex: [] }, { id: 'r2', name: 'B', ex: [{ id: '1' }] }], week: { 3: 'r1', 5: 'r2' } })- expect(nextTrainingDay(S, TUE)).toMatchObject({ weekday: 5 })- })-- it('respects a per-date override in both directions', () => {- const moved = base({ week: {}, dayPlan: { '2026-08-19': 'r1' } })- expect(nextTrainingDay(moved, TUE)).toMatchObject({ iso: '2026-08-19' })- const off = base({ week: { 3: 'r1', 5: 'r2' }, dayPlan: { '2026-08-19': 'rest' } })- expect(nextTrainingDay(off, TUE)).toMatchObject({ weekday: 5 })- })-})-/* ---------- one-sided (unilateral) sets, logged per side (issue #60) ---------- */// A per-side row carries its two sides and a scalar aggregate. These pin that the display showsdiff --git a/frontend/src/store/backup-roundtrip.property.test.jsx b/frontend/src/store/backup-roundtrip.property.test.jsxnew file mode 100644index 000000000..d519a5e01--- /dev/null+++ b/frontend/src/store/backup-roundtrip.property.test.jsx@@ -0,0 +1,101 @@+// @vitest-environment happy-dom+/* A backup brings back everything it was made from: for any profile (fast-check generates them,+ * with per-side and timed sets, notes in any script, emoji and quotes, weigh-ins, custom+ * exercises, kg or lb), Settings' "Export backup" and "Export with photos & videos", read back by+ * "Import backup" on another device, leave the same workouts, routines, weigh-ins and custom+ * exercises in the store, and the same once more after the app restarts from what it saved.+ *+ * Everything on the way is the real code: exportBackupZip and readBackupFile (lib/backup-media.js),+ * the store's importBackup and its persist to localStorage. Only the server is left out: this is+ * the device with no account, where the backup file is the only copy there is.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import fc from 'fast-check'++vi.mock('../lib/api.js', () => ({ api: vi.fn(async () => { throw new Error('offline') }), setRemoteAuth: vi.fn() }))+vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast: vi.fn() }) } }))++import { DEF, useStore } from './useStore.js'+import { exportBackupZip, readBackupFile } from '../lib/backup-media.js'++const clone = v => JSON.parse(JSON.stringify(v))+const RUNS = { numRuns: Number(process.env.PROPERTY_RUNS) || 40 }+const memoryMedia = () => { const m = new Map(); return { get: async h => m.get(h) || null, put: async (h, r) => { m.set(h, r) } } }++// ---- generated profiles ----------------------------------------------------------------------+const text = fc.oneof(fc.string({ maxLength: 20 }), fc.constantFrom('Bankdrücken', 'жим лёжа', '深蹲', 'Leg day 💪', 'say "hi" \\ there', ''))+const day = fc.integer({ min: 0, max: 400 }).map(n => new Date(Date.UTC(2025, 0, 1) + n * 864e5).toISOString().slice(0, 10))+const kg = fc.integer({ min: 0, max: 1200 }).map(x => x / 4)+const set = fc.oneof(+ fc.record({ w: kg, r: fc.integer({ min: 0, max: 50 }), done: fc.boolean() }),+ fc.record({ w: kg, sec: fc.integer({ min: 1, max: 600 }), done: fc.constant(true) }),+ fc.record({ w: kg, r: fc.integer({ min: 1, max: 20 }), done: fc.constant(true), L: fc.record({ w: kg, r: fc.integer({ min: 1, max: 20 }) }), R: fc.record({ w: kg, r: fc.integer({ min: 1, max: 20 }) }) }),+ fc.record({ w: kg, r: fc.integer({ min: 1, max: 20 }), done: fc.constant(true), warm: fc.constant(true) }),+)+const exId = fc.constantFrom('0025', '0043', '0032', '0027', '1460', 'c-own')+const workout = fc.record({+ d: day, start: fc.integer({ min: 1.7e12, max: 1.8e12 }), dur: fc.integer({ min: 60, max: 3 * 3600 }),+ name: text, note: fc.option(text, { nil: undefined }),+ entries: fc.array(fc.record({ id: exId, sets: fc.array(set, { minLength: 1, maxLength: 6 }), note: fc.option(text, { nil: undefined }) }), { minLength: 1, maxLength: 5 }),+})+const profile = fc.record({+ unit: fc.constantFrom('kg', 'lb'),+ restSec: fc.integer({ min: 15, max: 600 }),+ workouts: fc.array(workout, { maxLength: 12 }),+ routines: fc.array(fc.record({ name: text, ex: fc.array(fc.record({ id: exId, sets: fc.integer({ min: 1, max: 8 }), reps: fc.integer({ min: 1, max: 30 }) }), { minLength: 1, maxLength: 6 }) }), { maxLength: 5 }),+ bodyweight: fc.uniqueArray(fc.record({ d: day, w: fc.integer({ min: 300, max: 2000 }).map(x => x / 10) }), { selector: b => b.d, maxLength: 20 }),+ favEx: fc.uniqueArray(exId, { maxLength: 3 }),+}).map(p => Object.assign(clone(DEF), {+ unit: p.unit, restSec: p.restSec, favEx: p.favEx, _ts: 1.79e12,+ workouts: p.workouts.map((w, i) => ({ id: `w${i}`, d: w.d, start: w.start, end: w.start + w.dur * 1000, name: w.name, ...(w.note != null ? { note: w.note } : {}), entries: w.entries.map(e => ({ ...e, ...(e.note == null ? { note: undefined } : {}) })) })),+ routines: p.routines.map((r, i) => ({ id: `r${i}`, ...r })),+ bodyweight: p.bodyweight.map((b, i) => ({ ...b, t: 1.7e12 + i })),+ customEx: [{ id: 'c-own', name: 'Own lift', custom: true, eq: 'barbell', bp: 'chest' }],+}))++// What the user sees of a profile: the data, without bookkeeping stamps the import adds.+const strip = o => JSON.parse(JSON.stringify(o, (k, v) => (k === '_ts' || k === '_f' || k === '_u' || k === 't' ? undefined : v)))+const view = S => strip({ unit: S.unit, restSec: S.restSec, favEx: S.favEx, workouts: S.workouts, routines: S.routines, bodyweight: S.bodyweight, customEx: S.customEx })++// Another device with its own, different history: the import must replace it, not mix it in.+const otherDevice = () => Object.assign(clone(DEF), { unit: 'kg', _ts: 1.6e12, workouts: [{ id: 'old', d: '2024-01-01', start: 1, end: 2, entries: [] }] })++beforeEach(() => { localStorage.clear(); useStore.setState({ S: otherDevice(), user: null, ready: true }) })+afterEach(() => { localStorage.clear(); useStore.setState({ S: clone(DEF), user: null, ready: false }) })++const restore = async file => {+ const { state } = await readBackupFile(file)+ useStore.getState().importBackup(state)+ return useStore.getState().S+}+const saved = () => JSON.parse(localStorage.getItem('gym_state_v1'))++describe('a backup brings back everything it was made from', () => {+ it('as JSON (Export backup), and still after a restart', async () => {+ await fc.assert(fc.asyncProperty(profile, async P => {+ useStore.setState({ S: otherDevice() })+ const json = JSON.stringify(P, null, 2) // Settings.jsx doExport+ const S = await restore(new File([json], 'opengym-backup.json', { type: 'application/json' }))+ expect(view(S)).toEqual(view(P))+ expect(view(saved())).toEqual(view(P))+ }), RUNS)+ })++ it('as a zip with photos and videos', async () => {+ await fc.assert(fc.asyncProperty(profile, async P => {+ useStore.setState({ S: otherDevice() })+ const { blob } = await exportBackupZip(P, { media: memoryMedia(), now: new Date(1.79e12) })+ const S = await restore(new File([blob], 'opengym-backup.zip'))+ expect(view(S)).toEqual(view(P))+ }), RUNS)+ })++ it('a backup of a backup is the same backup', async () => {+ await fc.assert(fc.asyncProperty(profile, async P => {+ useStore.setState({ S: otherDevice() })+ const once = await restore(new File([JSON.stringify(P)], 'a.json'))+ const twice = await restore(new File([JSON.stringify(once)], 'b.json'))+ expect(view(twice)).toEqual(view(once))+ }), RUNS)+ })+})diff --git a/frontend/src/views/Measurements.test.jsx b/frontend/src/views/Measurements.test.jsxnew file mode 100644index 000000000..2ab7fd9af--- /dev/null+++ b/frontend/src/views/Measurements.test.jsx@@ -0,0 +1,122 @@+// @vitest-environment happy-dom+/* Body measurements, used the way a person uses them: choose the fields, log a check-in, see it,+ * correct it, delete it. Until this file the screen had no test at all (3.7 % of its lines run,+ * test report 2026-10-15) while lib/measurements.js was well covered, so a broken save button or+ * a cm/in mix-up on the form would have shipped green.+ */+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { MemoryRouter } from 'react-router-dom'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++vi.mock('../lib/api.js', async importOriginal => ({ ...(await importOriginal()), api: vi.fn(() => Promise.reject(new Error('offline'))), beacon: vi.fn() }))++import { DEF, useStore } from '../store/useStore.js'+import { useUI } from '../store/useUI.js'+import { todayISO } from '../lib/format.js'+import Measurements, { measurementLogSheet } from './Measurements.jsx'++const clone = v => JSON.parse(JSON.stringify(v))+const mounted = []+function render(el) {+ const host = document.createElement('div')+ document.body.appendChild(host)+ const root = createRoot(host)+ mounted.push(root)+ act(() => root.render(<MemoryRouter>{el}</MemoryRouter>))+ return host+}+const topSheet = () => { const s = useUI.getState().sheets.at(-1); return s ? render(s.render(() => useUI.getState().closeSheet(s.id))) : null }+const setValue = (input, v) => act(() => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(input, v)+ input.dispatchEvent(new Event('input', { bubbles: true }))+})+const field = (host, label) => [...host.querySelectorAll('.measure-field')].find(l => l.textContent.startsWith(label)).querySelector('input')+const click = (host, text) => act(() => { [...host.querySelectorAll('button')].find(b => b.textContent.trim() === text).click() })+const toast = () => useUI.getState().toastMsg+const entries = () => useStore.getState().S.measurements++function seed(extra = {}) {+ useStore.setState({ S: Object.assign(clone(DEF), { unit: 'kg', measurementEnabled: ['waist', 'chest', 'bodyFat'], measurements: [] }, extra), user: null })+}++beforeEach(() => {+ globalThis.IS_REACT_ACT_ENVIRONMENT = true+ localStorage.clear()+ useUI.setState({ sheets: [], toastMsg: '' })+ document.body.innerHTML = ''+})+afterEach(() => { act(() => { mounted.splice(0).forEach(r => r.unmount()) }) })++describe('logging body measurements', () => {+ it('a check-in typed in cm is saved for today and shows on the screen', () => {+ seed()+ const screen = render(<Measurements />)+ expect(screen.textContent).toContain('No measurements yet')+ act(() => measurementLogSheet())+ const form = topSheet()+ setValue(field(form, 'Waist'), '84.5')+ setValue(field(form, 'Body fat'), '18')+ click(form, 'Save')+ expect(entries()).toHaveLength(1)+ expect(entries()[0]).toMatchObject({ d: todayISO(), waist: 84.5, bodyFat: 18, chest: null })+ expect(screen.textContent).toContain('84.5')+ expect(screen.textContent).not.toContain('No measurements yet')+ })++ it('in lb a waist typed in inches is stored in cm and read back in inches', () => {+ seed({ unit: 'lb' })+ act(() => measurementLogSheet())+ const form = topSheet()+ setValue(field(form, 'Waist'), '34')+ click(form, 'Save')+ expect(entries()[0].waist).toBeCloseTo(34 * 2.54, 1) // kept to a millimetre+ const screen = render(<Measurements />)+ expect(screen.textContent).toMatch(/34\s*in/)+ })++ it('refuses an empty check-in and a body fat over 100 %, and saves nothing', () => {+ seed()+ act(() => measurementLogSheet())+ const form = topSheet()+ click(form, 'Save')+ expect(toast()).toMatch(/at least one measurement/)+ setValue(field(form, 'Body fat'), '140')+ click(form, 'Save')+ expect(toast()).toMatch(/between 0 and 100/)+ expect(entries()).toEqual([])+ })++ it('a second check-in on the same day is refused: the day is edited instead, and stays one entry', () => {+ const day = todayISO()+ seed({ measurements: [{ d: day, t: 1, waist: 90, chest: null, bodyFat: null, other: [] }] })+ act(() => measurementLogSheet())+ let form = topSheet()+ setValue(field(form, 'Waist'), '88')+ click(form, 'Save')+ expect(entries()).toHaveLength(1)+ expect(entries()[0].waist).toBe(90)+ // Editing the day: the form opens with what was logged, and the change replaces it.+ act(() => measurementLogSheet(day))+ form = topSheet()+ expect(field(form, 'Waist').value).toBe('90')+ setValue(field(form, 'Waist'), '88')+ click(form, 'Save')+ expect(entries()).toHaveLength(1)+ expect(entries()[0].waist).toBe(88)+ })++ it('deleting a check-in asks first and then removes only that day', () => {+ seed({ measurements: [+ { d: '2026-09-01', t: 1, waist: 92, chest: null, bodyFat: null, other: [] },+ { d: '2026-09-15', t: 2, waist: 90, chest: null, bodyFat: null, other: [] },+ ] })+ const screen = render(<Measurements />)+ const del = screen.querySelectorAll('button[aria-label="Delete"]')+ expect(del).toHaveLength(2)+ act(() => del[0].click()) // newest first: 2026-09-15+ expect(entries()).toHaveLength(2) // nothing gone before the answer+ click(topSheet(), 'Delete')+ expect(entries().map(e => e.d)).toEqual(['2026-09-01'])+ })+})diff --git a/scripts/ci/test-audit.mjs b/scripts/ci/test-audit.mjsnew file mode 100644index 000000000..9aec780c6--- /dev/null+++ b/scripts/ci/test-audit.mjs@@ -0,0 +1,97 @@+#!/usr/bin/env node+// Reads the test files (not running them) and reports the tests that are least likely to say+// something about the app: a test with no assertion in it (it passes whatever the code does),+// two tests with the same body, two tests with the same name in one file (a report that cannot+// say which one failed), and tests that check the source text of a file instead of running it.+// The last kind is often deliberate here (CSS, native Java/Swift and Dockerfiles cannot run+// under vitest), so it is counted, not judged. Report only; never fails the build.+//+// node scripts/ci/test-audit.mjs frontend/src frontend/scripts api/test mcp/test [--json out.json]+import { appendFileSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { createHash } from 'node:crypto'++const args = process.argv.slice(2)+const jsonOut = args.includes('--json') ? args[args.indexOf('--json') + 1] : null+const roots = args.filter((a, i) => !a.startsWith('--') && args[i - 1] !== '--json')+const walk = (d) => readdirSync(d).flatMap((n) => {+ if (n === 'node_modules' || n.startsWith('.')) return []+ const p = join(d, n)+ return statSync(p).isDirectory() ? walk(p) : /\.test\.(m?js|jsx)$/.test(n) ? [p] : []+})++// The body of the call that opens at `start` (the index of its '('), skipping strings,+// template literals and comments. Good enough for test files; not a parser.+function callBody(src, start) {+ let depth = 0+ for (let i = start; i < src.length; i++) {+ const c = src[i]+ if (c === '/' && src[i + 1] === '/') { i = src.indexOf('\n', i); if (i < 0) return null; continue }+ if (c === '/' && src[i + 1] === '*') { i = src.indexOf('*/', i + 2) + 1; if (i <= 0) return null; continue }+ if (c === '"' || c === "'" || c === '`') {+ for (i++; i < src.length && src[i] !== c; i++) if (src[i] === '\\') i+++ continue+ }+ if (c === '(') depth+++ else if (c === ')' && --depth === 0) return src.slice(start + 1, i)+ }+ return null+}++const ASSERT = /\bexpect\w*\s*[.(]|\bassert\b|\bassert\.|\bfc\.assert\b|\.rejects\b|\.resolves\b|\bthrows\s*\(|\bok\s*\(|\bstrictEqual\b|\bdeepStrictEqual\b|\bmatch\s*\(\s*\w+\s*,|expectRow|\bcheck\w*\s*\(/+const SOURCE_READ = /readFileSync\([^)]*(\.jsx?|\.css|\.java|\.swift|\.gradle|Dockerfile|\.xml|\.html|\.mjs)['"`)]|readFileSync\([^)]*(src|App|views|components|android|ios)\b/++const files = roots.flatMap((r) => { try { return walk(r) } catch { return [] } })+const report = { files: files.length, tests: 0, noAssert: [], dupBodies: [], dupNames: [], sourcePattern: [] }+const bodies = new Map()+for (const f of files) {+ const src = readFileSync(f, 'utf8')+ const names = new Map()+ const re = /\b(it|test)(\.each\([^)]*\))?\s*\(\s*(['"`])((?:\\.|(?!\3).)*)\3/g+ let m+ let count = 0+ while ((m = re.exec(src))) {+ if (m[2]) continue // .each: the body runs per row, judged by its table+ const open = src.indexOf('(', m.index + m[1].length)+ const body = callBody(src, open)+ if (body == null) continue+ count+++ const name = m[4]+ const fn = body.slice(body.indexOf(m[3], body.indexOf(m[3]) + 1) + 1)+ // A test that hands its whole body to a helper (a table, a shared scenario) asserts there.+ const delegates = /^\s*,\s*(\w+|\(\)\s*=>\s*\w+\([^)]*\))\s*(,\s*\d+\s*)?$/.test(fn)+ // The scanner is not a parser (a regex literal can end a body early): before calling a test+ // assertion-free, look at its whole text up to the next test as well.+ const next = src.slice(open + 1).search(/\n\s*(it|test|describe)(\.\w+)?\s*\(/)+ const raw = next < 0 ? src.slice(open) : src.slice(open, open + 1 + next)+ if (!ASSERT.test(fn) && !ASSERT.test(raw) && !delegates && fn.trim().length > 2) report.noAssert.push({ file: f, name })+ names.set(name, (names.get(name) || 0) + 1)+ const norm = fn.replace(/\s+/g, ' ').trim()+ if (norm.length > 80) {+ const h = createHash('sha1').update(norm).digest('hex')+ if (!bodies.has(h)) bodies.set(h, [])+ bodies.get(h).push({ file: f, name })+ }+ }+ report.tests += count+ for (const [n, k] of names) if (k > 1) report.dupNames.push({ file: f, name: n, times: k })+ if (SOURCE_READ.test(src)) report.sourcePattern.push({ file: f, tests: count })+}+for (const list of bodies.values()) if (list.length > 1) report.dupBodies.push(list)++const md = ['### Test audit (static, report only)', '',+ `${report.tests} tests in ${report.files} files read.`, '',+ '| Finding | Count |', '|---|---:|',+ `| Tests with no assertion in their body | ${report.noAssert.length} |`,+ `| Groups of tests with an identical body | ${report.dupBodies.length} |`,+ `| Test names used twice in one file | ${report.dupNames.length} |`,+ `| Files that check source text instead of running code | ${report.sourcePattern.length} (${report.sourcePattern.reduce((a, x) => a + x.tests, 0)} tests) |`, '']+const list = (title, rows) => { if (rows.length) md.push(`<details><summary>${title}</summary>`, '', ...rows.slice(0, 60), '', '</details>', '') }+list('No assertion', report.noAssert.map((t) => `- \`${t.file}\` › ${t.name}`))+list('Identical bodies', report.dupBodies.map((g) => `- ${g.map((t) => `\`${t.file}\` › ${t.name}`).join(' = ')}`))+list('Same name twice', report.dupNames.map((t) => `- \`${t.file}\` › ${t.name} (${t.times}×)`))+list('Source-text checks', report.sourcePattern.map((t) => `- \`${t.file}\` (${t.tests})`))+const out = md.join('\n')+console.log(out)+if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, out + '\n')+if (jsonOut) writeFileSync(jsonOut, JSON.stringify(report, null, 2))