345 lines
12 KiB
Markdown
345 lines
12 KiB
Markdown
# VitFit V2 — Test Structure
|
|
|
|
---
|
|
|
|
## Directory Layout
|
|
|
|
```
|
|
/home/ubuntu/site/
|
|
└── tests/
|
|
├── helpers/
|
|
│ ├── db.js In-memory SQLite setup/teardown for unit + integration tests
|
|
│ ├── auth.js Generate test JWTs for any role
|
|
│ ├── factories.js Seeders: makeOrg(), makeUser(role), makeVideo(), makeTimer(), etc.
|
|
│ └── socket.js Create test Socket.io server + client pairs
|
|
├── unit/
|
|
│ ├── timer-engine.test.js
|
|
│ ├── validate-mime.test.js
|
|
│ ├── storage.test.js
|
|
│ ├── contrast.test.js
|
|
│ └── respond.test.js
|
|
├── integration/
|
|
│ ├── auth.test.js
|
|
│ ├── users.test.js
|
|
│ ├── videos.test.js
|
|
│ ├── workouts.test.js
|
|
│ ├── timers.test.js
|
|
│ ├── crossfit.test.js
|
|
│ ├── clients.test.js
|
|
│ ├── audit.test.js
|
|
│ ├── org.test.js
|
|
│ └── migrations.test.js
|
|
├── socket/
|
|
│ └── timer-engine.socket.test.js
|
|
└── e2e/
|
|
└── display-burn-in.test.js
|
|
```
|
|
|
|
Test runner: **Jest** with `--forceExit` flag (cleans up open DB handles).
|
|
|
|
---
|
|
|
|
## helpers/db.js
|
|
|
|
```js
|
|
createTestDb(): Promise<{ sequelize, models }>
|
|
```
|
|
Creates an in-memory SQLite DB (`:memory:`), runs all migrations, returns sequelize instance.
|
|
Each test file calls this in `beforeAll` and calls `sequelize.close()` in `afterAll`.
|
|
Migrations run against in-memory DB, validating that the migration chain is complete and idempotent.
|
|
|
|
```js
|
|
seedOrg(sequelize): Promise<{ org, branding }>
|
|
seedUser(sequelize, orgId, role, overrides?): Promise<User>
|
|
seedVideo(sequelize, orgId, overrides?): Promise<Video>
|
|
```
|
|
Minimal seed helpers. `factories.js` builds on these with realistic defaults.
|
|
|
|
---
|
|
|
|
## helpers/auth.js
|
|
|
|
```js
|
|
makeJwt(user: Partial<User>): string
|
|
```
|
|
Signs a short-lived (5-minute) test JWT. Does not hit the DB.
|
|
Usage: `const token = makeJwt({ id: 1, role: 'Coach', organizationId: 1 });`
|
|
|
|
```js
|
|
authHeader(token: string): { Authorization: string }
|
|
```
|
|
Returns `{ Authorization: 'Bearer <token>' }` for use in supertest requests.
|
|
|
|
---
|
|
|
|
## Unit Tests
|
|
|
|
### tests/unit/timer-engine.test.js
|
|
|
|
Tests the `TimerEngine` state machine in isolation (no real Socket.io).
|
|
|
|
```
|
|
✓ starts in 'idle' status
|
|
✓ transitions to 'running' on start()
|
|
✓ phase advances set → rest after setTime elapses
|
|
✓ phase advances rest → move after restTime elapses
|
|
✓ phase advances move → set, increments currentSet
|
|
✓ increments currentExercise after all sets complete
|
|
✓ increments currentLap after all exercises complete
|
|
✓ emits timer:complete (not timer:stopped) on natural completion
|
|
✓ emits timer:stopped (not timer:complete) on manual stop()
|
|
✓ complete() does NOT call stop() — no double-event emission
|
|
✓ getState() returns correct snapshot mid-run
|
|
✓ skips rest phase when restTime = 0
|
|
✓ skips move phase when moveTime = 0
|
|
✓ phaseEndTime is an absolute timestamp (not a delta)
|
|
```
|
|
|
|
Uses a mock `io` object that records emitted events.
|
|
|
|
### tests/unit/validate-mime.test.js
|
|
|
|
```
|
|
✓ accepts first 12 bytes of a real MP4 file (ftyp magic bytes)
|
|
✓ accepts first 12 bytes of a MOV file
|
|
✓ accepts first 12 bytes of an M4V file
|
|
✓ rejects a WebM file
|
|
✓ rejects a text file renamed to .mp4
|
|
✓ rejects an empty buffer
|
|
✓ throws UPLOAD_TYPE_INVALID (not a generic error)
|
|
✓ reads only from file path, does NOT load whole file into memory
|
|
```
|
|
|
|
Uses real minimal binary fixtures (12-byte magic byte sequences only).
|
|
|
|
### tests/unit/storage.test.js
|
|
|
|
```
|
|
✓ returns warning: false when free > STORAGE_WARN_BYTES
|
|
✓ returns warning: true when free < STORAGE_WARN_BYTES
|
|
✓ caches result for 60 seconds (second call within 60s returns cached value)
|
|
✓ returns fresh result after 60 second cache expiry
|
|
✓ checkUploadAllowed middleware returns 507 when warning: true
|
|
✓ checkUploadAllowed middleware calls next() when warning: false
|
|
```
|
|
|
|
Mocks `check-disk-space` to return controlled values.
|
|
|
|
### tests/unit/contrast.test.js
|
|
|
|
Tests `validateContrastRatio()` in org service.
|
|
|
|
```
|
|
✓ #00FF88 on #1a1a1a passes (>= 4.5:1)
|
|
✓ #000000 on #1a1a1a fails (ratio too low)
|
|
✓ #FFFFFF on #1a1a1a passes
|
|
✓ #777777 on #1a1a1a fails
|
|
✓ invalid hex throws VALIDATION_FAILED
|
|
✓ empty string throws VALIDATION_FAILED
|
|
```
|
|
|
|
### tests/unit/respond.test.js
|
|
|
|
```
|
|
✓ ok() sends 200 with { data }
|
|
✓ created() sends 201 with { data }
|
|
✓ collection() sends 200 with { data, meta } including correct totalPages
|
|
✓ noContent() sends 204 with no body
|
|
✓ err() sends correct status with { error: { code, message, field } }
|
|
```
|
|
|
|
---
|
|
|
|
## Integration Tests
|
|
|
|
All integration tests use `supertest` against a real Express app with an in-memory SQLite DB.
|
|
No network calls. No real files written to disk (multer storage overridden to use `/tmp`).
|
|
|
|
### tests/integration/migrations.test.js
|
|
|
|
**Critical test — run before all others.**
|
|
|
|
```
|
|
✓ migration 001 (baseline) is idempotent — runs twice without error
|
|
✓ migration 002+ run in order without error
|
|
✓ all expected tables exist after full migration
|
|
✓ all expected columns exist on each table
|
|
✓ running db:migrate on already-migrated DB makes no changes
|
|
✓ V1-compatible data inserted before migrations is preserved after
|
|
```
|
|
|
|
### tests/integration/auth.test.js
|
|
|
|
```
|
|
✓ POST /auth/login returns jwt on valid credentials
|
|
✓ POST /auth/login returns LOGIN_FAILED on bad password
|
|
✓ POST /auth/login returns LOGIN_FAILED on inactive user
|
|
✓ POST /auth/login rate-limits after 10 attempts
|
|
✓ POST /auth/login with rememberDevice returns deviceToken
|
|
✓ POST /auth/device-login returns new jwt + rotated token
|
|
✓ POST /auth/device-login returns AUTH_DEVICE_TOKEN_INVALID on revoked token
|
|
✓ POST /auth/device-login returns AUTH_DEVICE_TOKEN_INVALID on expired token
|
|
✓ POST /auth/refresh-token returns new jwt
|
|
✓ POST /auth/logout returns 204 and logs audit event
|
|
✓ Authenticated request with valid jwt returns 200
|
|
✓ Authenticated request with no jwt returns 401
|
|
✓ Authenticated request with expired jwt returns 401
|
|
```
|
|
|
|
### tests/integration/users.test.js
|
|
|
|
```
|
|
✓ GET /users returns paginated list for Owner
|
|
✓ GET /users returns 403 for Coach
|
|
✓ POST /users creates user with hashed password
|
|
✓ POST /users returns 409 on duplicate username
|
|
✓ DELETE /users/:id deactivates user (does not hard delete)
|
|
✓ DELETE /users/:id returns LAST_OWNER_PROTECTED if last Owner
|
|
✓ DELETE /users/:id revokes all device tokens for the user
|
|
✓ PUT /users/:id/role returns LAST_OWNER_PROTECTED when demoting last Owner
|
|
✓ PUT /users/:id/role returns AUTH_FORBIDDEN when Owner tries to change own role
|
|
✓ PUT /users/:id/password re-hashes password
|
|
✓ PUT /api/v1/my/password succeeds with correct currentPassword
|
|
✓ PUT /api/v1/my/password returns 401 with wrong currentPassword
|
|
✓ Cross-org: user from org B cannot be found by org A
|
|
```
|
|
|
|
### tests/integration/videos.test.js
|
|
|
|
```
|
|
✓ GET /videos returns only videos for requesting org
|
|
✓ GET /videos filters by category
|
|
✓ POST /videos accepts valid MP4 (multer disk + magic-byte check)
|
|
✓ POST /videos rejects non-video file (UPLOAD_TYPE_INVALID)
|
|
✓ POST /videos returns 507 when disk below threshold
|
|
✓ DELETE /videos/:id removes DB record and file
|
|
✓ DELETE /videos/:id returns 404 for wrong org
|
|
✓ GET /videos/stream/:filename returns 206 with Range header
|
|
✓ GET /videos/stream/:filename returns 200 without Range header
|
|
✓ GET /videos/stream/../secret.txt returns 400 (path traversal blocked)
|
|
✓ GET /videos/stream/:filename returns 404 for filename not in org's DB
|
|
```
|
|
|
|
### tests/integration/workouts.test.js
|
|
|
|
```
|
|
✓ GET /workouts/today uses org timezone, not server local time
|
|
✓ GET /workouts/today returns workouts for org's "today" across DST boundary
|
|
✓ POST /workouts returns VALIDATION_FAILED if video ID belongs to different org
|
|
✓ DELETE /workouts/:id blocks Coach from deleting another Coach's workout
|
|
✓ DELETE /workouts/:id allows Owner to delete any workout
|
|
✓ GET /workouts includes null for deleted video slots (LEFT JOIN)
|
|
```
|
|
|
|
### tests/integration/timers.test.js
|
|
|
|
```
|
|
✓ POST /timers/:id/launch creates session and returns sessionId
|
|
✓ POST /timers/:id/launch returns 409 if a session already active for org
|
|
✓ DELETE /timers/session stops active session
|
|
✓ Timer session not found after server restart (in-memory, expected)
|
|
```
|
|
|
|
### tests/integration/clients.test.js
|
|
|
|
```
|
|
✓ Coach only sees own clients
|
|
✓ Owner sees all clients in org
|
|
✓ Client cannot access /clients route
|
|
✓ POST /clients/:id/workouts validates videoId belongs to org
|
|
✓ DELETE /clients/:id/workouts/:id soft-deletes (row remains, deletedAt set)
|
|
✓ GET /clients/:id/workouts excludes coachNotes when requester is client
|
|
✓ POST /clients/:id/sessions/cancel returns 400 if < 24h until session (client)
|
|
✓ POST /clients/:id/sessions/cancel succeeds for coach regardless of time
|
|
✓ Feature flag client-management: returns 403 when flag absent
|
|
```
|
|
|
|
### tests/integration/audit.test.js
|
|
|
|
```
|
|
✓ video.upload event recorded after successful upload
|
|
✓ auth.login.failed recorded on bad password
|
|
✓ user.create recorded when Owner creates user
|
|
✓ Audit log failures do not break the parent request
|
|
✓ GET /audit-logs returns 403 for Coach
|
|
✓ GET /audit-logs/export returns CSV with correct headers
|
|
✓ Audit records survive even if the referenced user is deactivated
|
|
```
|
|
|
|
---
|
|
|
|
## Socket Tests
|
|
|
|
### tests/socket/timer-engine.socket.test.js
|
|
|
|
Uses a real Socket.io server bound to a random port + a test client.
|
|
|
|
```
|
|
✓ Client receives timer:state on timer:join
|
|
✓ Client receives timer:tick events after start
|
|
✓ tick events arrive at most once per second
|
|
✓ Client receives timer:phase-change on phase transition
|
|
✓ Client receives timer:complete on natural completion, NOT timer:stopped
|
|
✓ Client receives timer:stopped on manual stop(), NOT timer:complete
|
|
✓ Reconnected client receives timer:state after timer:join re-emit
|
|
✓ timer:error SESSION_NOT_FOUND emitted for unknown sessionId
|
|
✓ unauthenticated socket is disconnected immediately
|
|
✓ socket from different org cannot join another org's timer room
|
|
```
|
|
|
|
---
|
|
|
|
## E2E / Burn-In Test
|
|
|
|
### tests/e2e/display-burn-in.test.js
|
|
|
|
Long-running test. Only run manually (`npm run test:burnin`). Not in CI.
|
|
|
|
Uses Playwright (headless Safari via WebKit engine) to simulate the iPad kiosk scenario.
|
|
|
|
```
|
|
✓ App loads and authenticates via device token
|
|
✓ Timer display page opens and joins socket room
|
|
✓ Timer runs for its full configured duration (uses a 60-second test timer)
|
|
✓ phase:change events fire on schedule
|
|
✓ timer:complete fires at end, NOT timer:stopped
|
|
✓ DOM is not rebuilt during timer run (MutationObserver counts mutations < threshold)
|
|
✓ Memory does not grow > 20 MB over 60-second run (page.metrics())
|
|
✓ After simulated disconnect and reconnect, timer re-syncs correctly
|
|
✓ AirPlay keep-alive animation is present in the DOM (CSS animation detected)
|
|
```
|
|
|
|
---
|
|
|
|
## Test Scripts (package.json)
|
|
|
|
```json
|
|
{
|
|
"scripts": {
|
|
"test": "jest tests/unit tests/integration tests/socket --forceExit",
|
|
"test:unit": "jest tests/unit --forceExit",
|
|
"test:int": "jest tests/integration --forceExit",
|
|
"test:socket": "jest tests/socket --forceExit",
|
|
"test:burnin": "jest tests/e2e/display-burn-in.test.js --forceExit --testTimeout=300000",
|
|
"test:ci": "jest tests/unit tests/integration tests/socket --forceExit --ci --coverage"
|
|
}
|
|
}
|
|
```
|
|
|
|
`test:burnin` is excluded from `test` and `test:ci` — it's a manual check, not a gate.
|
|
|
|
---
|
|
|
|
## Test Dependencies (devDependencies only)
|
|
|
|
```json
|
|
{
|
|
"jest": "^29",
|
|
"supertest": "^6",
|
|
"playwright": "^1"
|
|
}
|
|
```
|
|
|
|
No test framework is added to `dependencies` — tests only run in the dev environment.
|
|
Playwright is installed separately for the burn-in test: `npx playwright install webkit`.
|