Files
workouts/WorkoutsTests/SyncEngineTests.swift
rzen 6e440317c4 Restructure into a three-tab app with Progress, goals, and Meditation
The UX redesign's first landing (spec in UX-REDESIGN.md): ContentView
becomes a Today / Progress / Settings TabView, "Routine" replaces
"Split" in every user-facing string and view name (code-level types
keep their names), and workout starting moves to shared
WorkoutStarter / StartedWorkoutNavigator plumbing.

- New Progress tab: weekly goal streaks, workout trends, per-exercise
  weight progression, achievements, and the full history list
  (WorkoutLogsView -> WorkoutHistoryView).
- Goals: stable categories workouts roll up to, managed from Settings.
- New Meditation exercise + starter routine; timed sits record to
  Apple Health as Mind & Body sessions.

Claude-Session: https://claude.ai/code/session_012qw2itfzKyEJ1HpsFt8Ex4
2026-07-11 07:53:01 -04:00

100 lines
5.1 KiB
Swift

import Foundation
import IndieSync
import SwiftData
import Testing
@testable import Workouts
/// Coverage for the parts of `SyncEngine` reachable without a live iCloud container.
///
/// SCOPE NOTE: `SyncEngine`'s orchestration (`save`/`delete`/`reconcile`/`reconcileSeeds`)
/// resolves its `DocumentFileStore` *inside* `connect()` from the real ubiquity
/// container — there is no seam to inject a fake store, and the task deliberately rules
/// out building a heavyweight `NSMetadataQuery` mock. So the file-touching paths (incl.
/// FIX-1's rebucketing removal and FIX-2's `.upgrade` stub re-check) are not unit-testable
/// here without refactoring `SyncEngine` to accept an injected store — out of scope.
/// Their *pure* decision logic is already locked elsewhere: `SeedReconcilePlannerTests`
/// (the seed skip/upgrade/write table, incl. the veto that FIX-2 re-checks),
/// `DuplicateCleanupPlannerTests`, `WorkoutPathBucketingTests` (FIX-1's path divergence),
/// and `WorkoutStatusMachineTests`. What remains directly testable is the pure
/// in-memory redirect helper below.
struct SyncEngineTests {
@MainActor
private func makeEngine() throws -> SyncEngine {
let schema = Schema([Routine.self, Exercise.self, Workout.self, WorkoutLog.self])
let config = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)
let backlogURL = FileManager.default.temporaryDirectory
.appending(path: "SyncEngineTests-\(UUID().uuidString).json")
return SyncEngine(container: try ModelContainer(for: schema, configurations: [config]),
backlogURL: backlogURL)
}
/// A minimal workout document with one log, both carrying the given statuses.
private func makeWorkout(id: String, status: WorkoutStatus, logStatus: WorkoutStatus) -> WorkoutDocument {
let now = Date()
var log = WorkoutLogDocument(planFrom: ExerciseDocument(
id: ULID.make(), name: "Seated Row", order: 0, sets: 3, reps: 10,
weight: 90, loadType: LoadType.weight.rawValue, durationSeconds: 0), order: 0, date: now)
log.status = logStatus.rawValue
return WorkoutDocument(
schemaVersion: WorkoutDocument.currentSchemaVersion, id: id,
routineID: nil, routineName: "Upper Body", start: now, end: nil,
status: status.rawValue, createdAt: now, updatedAt: now, logs: [log])
}
/// Locks `onWorkoutBecameActive`'s trigger table: it fires exactly once, on a
/// phone-side `.notStarted` → `.inProgress` transition — not on draft creation,
/// not on a repeat in-progress save, not for a watch-originated update, and not
/// when an old workout is edited from `.completed` back to `.inProgress`.
@MainActor
@Test func becameActiveFiresOnlyOnLocalNotStartedToInProgress() async throws {
let engine = try makeEngine()
var fired: [String] = []
engine.onWorkoutBecameActive = { fired.append($0.id) }
// Draft creation: notStarted → no fire.
let id = ULID.make()
await engine.save(workout: makeWorkout(id: id, status: .notStarted, logStatus: .notStarted))
#expect(fired.isEmpty)
// First exercise starts: notStarted → inProgress fires once.
await engine.save(workout: makeWorkout(id: id, status: .inProgress, logStatus: .inProgress))
#expect(fired == [id])
// Re-saving an already-active run doesn't re-fire.
await engine.save(workout: makeWorkout(id: id, status: .inProgress, logStatus: .inProgress))
#expect(fired == [id])
// A watch-originated start never fires — the watch already owns a session.
let watchID = ULID.make()
await engine.ingestFromWatch(makeWorkout(id: watchID, status: .inProgress, logStatus: .inProgress))
#expect(fired == [id])
// Editing a finished workout back to in-progress isn't a fresh start.
let oldID = ULID.make()
await engine.save(workout: makeWorkout(id: oldID, status: .completed, logStatus: .completed))
await engine.save(workout: makeWorkout(id: oldID, status: .inProgress, logStatus: .inProgress))
#expect(fired == [id])
}
/// With no clone-on-edit fork recorded, `currentRoutineID` is the identity — a view
/// holding a routine id resolves to that same id. This pins the redirect-follow loop's
/// base case and its termination (no redirect → return input, no infinite loop).
@MainActor
@Test func currentRoutineIDIsIdentityWithoutRedirects() throws {
let engine = try makeEngine()
#expect(engine.currentRoutineID(for: "01SEEDABCDEFGHJKMNPQRSTVWX") == "01SEEDABCDEFGHJKMNPQRSTVWX")
#expect(engine.currentRoutineID(for: "") == "")
}
/// A freshly constructed engine is in the `.checking` state until `connect()` runs,
/// and exposes no sync error.
@MainActor
@Test func freshEngineIsCheckingWithNoError() throws {
let engine = try makeEngine()
#expect(engine.iCloudStatus == .checking)
#expect(engine.lastSyncError == nil)
#expect(!engine.isSyncing)
}
}