Add a watchOS test target

New Workouts Watch AppTests bundle wired into the watch scheme. Extracts
the phone-to-watch cache apply/prune into a pure, session-free
WatchCacheApplier seam and makes the HR-zone bucketing a nonisolated
static, so both can be unit-tested off the main actor without a live
WatchConnectivity session.

Claude-Session: https://claude.ai/code/session_01HJDQQDA9QdP8zByg43H5v3
This commit is contained in:
2026-07-08 07:57:24 -04:00
parent a4ed4df756
commit 1b399ee7ba
6 changed files with 387 additions and 14 deletions
@@ -0,0 +1,163 @@
import Foundation
import SwiftData
import Testing
@testable import Workouts_Watch_App
/// Locks the phonewatch state apply/prune contract the pure `WatchCacheApplier` seam the
/// `WatchConnectivityBridge` delegates its cache mutation to. The bridge wraps `WCSession`, so
/// this session-free seam is the testable surface for the three behaviors that matter:
/// 1. An authoritative push upserts the splits/workouts the phone sent.
/// 2. An authoritative **empty** push prunes stale rows the phone no longer has (the
/// recently-fixed case otherwise a deleted split / aged-out run is orphaned forever).
/// 3. A `nil` set (the phone's payload failed to decode a build/schema mismatch) is a
/// decode failure, not an empty set: it must skip entirely and NOT prune real rows.
///
/// These are all membership/presence assertions (which ids survive) deliberately orthogonal to
/// any updatedAt/version ordering, which this suite does not exercise.
@MainActor
struct WatchCacheApplierTests {
private static let ts = Date(timeIntervalSince1970: 1_700_000_000)
private func makeContext() throws -> ModelContext {
let schema = Schema([Split.self, Exercise.self, Workout.self, WorkoutLog.self])
// cloudKitDatabase: .none matches WorkoutsModelContainer (the watch's read-through cache).
let config = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)
return ModelContext(try ModelContainer(for: schema, configurations: [config]))
}
private func split(id: String, name: String) -> SplitDocument {
SplitDocument(
schemaVersion: SplitDocument.currentSchemaVersion, id: id, name: name, color: "blue",
systemImage: "dumbbell.fill", order: 0, createdAt: Self.ts, updatedAt: Self.ts,
exercises: [ExerciseDocument(id: "EX-\(id)", name: "Bench Press", order: 0, sets: 4,
reps: 10, weight: 135, loadType: LoadType.weight.rawValue,
durationSeconds: 0, machineSettings: nil)],
activityType: nil
)
}
private func workout(id: String, name: String = "Push") -> WorkoutDocument {
WorkoutDocument(
schemaVersion: WorkoutDocument.currentSchemaVersion, id: id, splitID: "S", splitName: name,
start: Self.ts, end: nil, status: WorkoutStatus.inProgress.rawValue,
createdAt: Self.ts, updatedAt: Self.ts,
logs: [WorkoutLogDocument(id: "L-\(id)", exerciseName: "Bench Press", order: 0, sets: 4,
reps: 10, weight: 135, loadType: LoadType.weight.rawValue,
durationSeconds: 0, currentStateIndex: 0,
status: WorkoutStatus.notStarted.rawValue, notes: nil, date: Self.ts)],
metrics: nil
)
}
private func splitIDs(in ctx: ModelContext) -> Set<String> {
Set((try? ctx.fetch(FetchDescriptor<Split>()))?.map(\.id) ?? [])
}
private func workoutIDs(in ctx: ModelContext) -> Set<String> {
Set((try? ctx.fetch(FetchDescriptor<Workout>()))?.map(\.id) ?? [])
}
// MARK: - Authoritative upsert
@Test func authoritativePushUpsertsSplitsAndWorkouts() throws {
let ctx = try makeContext()
WatchCacheApplier.apply(
splits: [split(id: "SP1", name: "Upper"), split(id: "SP2", name: "Lower")],
workouts: [workout(id: "01WKA"), workout(id: "01WKB")],
into: ctx
)
#expect(splitIDs(in: ctx) == ["SP1", "SP2"])
#expect(workoutIDs(in: ctx) == ["01WKA", "01WKB"])
}
@Test func reUpsertSameIDUpdatesInPlaceWithoutDuplicating() throws {
let ctx = try makeContext()
WatchCacheApplier.apply(splits: [split(id: "SP1", name: "Original")], workouts: [], into: ctx)
WatchCacheApplier.apply(splits: [split(id: "SP1", name: "Renamed")], workouts: [], into: ctx)
let splits = try ctx.fetch(FetchDescriptor<Split>())
#expect(splits.count == 1)
#expect(splits.first?.name == "Renamed")
}
// MARK: - Authoritative empty prunes stale rows (the recently-fixed case)
@Test func authoritativeEmptyPushPrunesAllStaleRows() throws {
let ctx = try makeContext()
// Seed the cache as if the phone had previously pushed real state.
WatchCacheApplier.apply(
splits: [split(id: "SP1", name: "Upper")],
workouts: [workout(id: "01WKA")],
into: ctx
)
#expect(splitIDs(in: ctx) == ["SP1"])
#expect(workoutIDs(in: ctx) == ["01WKA"])
// The user deleted everything on the phone (or all runs aged out): an authoritative
// EMPTY push must clear the now-stale rows rather than orphan them forever.
WatchCacheApplier.apply(splits: [], workouts: [], into: ctx)
#expect(splitIDs(in: ctx).isEmpty)
#expect(workoutIDs(in: ctx).isEmpty)
}
@Test func partialPushPrunesOnlyRowsThePhoneNoLongerSends() throws {
let ctx = try makeContext()
WatchCacheApplier.apply(
splits: [split(id: "SP1", name: "Keep"), split(id: "SP2", name: "Drop")],
workouts: [workout(id: "01WKKEEP"), workout(id: "01WKDROP")],
into: ctx
)
// The phone now sends only the survivors the omitted ones are pruned.
WatchCacheApplier.apply(
splits: [split(id: "SP1", name: "Keep")],
workouts: [workout(id: "01WKKEEP")],
into: ctx
)
#expect(splitIDs(in: ctx) == ["SP1"])
#expect(workoutIDs(in: ctx) == ["01WKKEEP"])
}
@Test func authoritativeEmptyPushOnEmptyCacheIsANoOp() throws {
let ctx = try makeContext()
WatchCacheApplier.apply(splits: [], workouts: [], into: ctx)
#expect(splitIDs(in: ctx).isEmpty)
#expect(workoutIDs(in: ctx).isEmpty)
}
// MARK: - nil-decode guard: a decode failure must NOT prune
@Test func nilSplitsSkipsEntirelyAndDoesNotPrune() throws {
let ctx = try makeContext()
WatchCacheApplier.apply(splits: [split(id: "SP1", name: "Upper")],
workouts: [workout(id: "01WKA")], into: ctx)
// A corrupt/absent splits payload decodes to nil (build mismatch). Skip the existing
// rows must survive, never pruned against a bogus set.
let applied = WatchCacheApplier.apply(splits: nil, workouts: [], into: ctx)
#expect(applied == false)
#expect(splitIDs(in: ctx) == ["SP1"])
#expect(workoutIDs(in: ctx) == ["01WKA"])
}
@Test func nilWorkoutsSkipsEntirelyAndDoesNotPrune() throws {
let ctx = try makeContext()
WatchCacheApplier.apply(splits: [split(id: "SP1", name: "Upper")],
workouts: [workout(id: "01WKA")], into: ctx)
let applied = WatchCacheApplier.apply(splits: [], workouts: nil, into: ctx)
#expect(applied == false)
#expect(splitIDs(in: ctx) == ["SP1"])
#expect(workoutIDs(in: ctx) == ["01WKA"])
}
@Test func optionalOverloadReturnsTrueWhenBothSetsDecode() throws {
let ctx = try makeContext()
// Typed optionals to disambiguate onto the nil-aware overload (an authoritative,
// successfully-decoded if empty push), whose Bool return is the applied/skip signal.
let splits: [SplitDocument]? = []
let workouts: [WorkoutDocument]? = []
let applied = WatchCacheApplier.apply(splits: splits, workouts: workouts, into: ctx)
#expect(applied == true)
}
}
@@ -0,0 +1,88 @@
import Foundation
import SwiftData
import Testing
@testable import Workouts_Watch_App
/// Exercises the real `WatchConnectivityBridge` constructed against an in-memory cache with no
/// live `WCSession` (its `init` never touches WatchConnectivity; only `activate()` does, which we
/// don't call). This pins the two things reachable without a session:
/// the optimistic local update: `update(workout:)` writes straight to the read-through cache
/// (the forward-to-phone step no-ops with no session), so the UI sees the edit immediately; and
/// the fresh-bridge state contract (no sync date, no edit lock, no follower frame).
///
/// It deliberately does not exercise updatedAt/version ordering on the apply path.
@MainActor
struct WatchConnectivityBridgeTests {
private static let ts = Date(timeIntervalSince1970: 1_700_000_000)
private func makeContainer() throws -> ModelContainer {
let schema = Schema([Split.self, Exercise.self, Workout.self, WorkoutLog.self])
let config = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)
return try ModelContainer(for: schema, configurations: [config])
}
private func workout(id: String, name: String, splitName: String) -> WorkoutDocument {
WorkoutDocument(
schemaVersion: WorkoutDocument.currentSchemaVersion, id: id, splitID: "S", splitName: splitName,
start: Self.ts, end: nil, status: WorkoutStatus.inProgress.rawValue,
createdAt: Self.ts, updatedAt: Self.ts,
logs: [WorkoutLogDocument(id: "L-\(id)", exerciseName: name, order: 0, sets: 4,
reps: 10, weight: 135, loadType: LoadType.weight.rawValue,
durationSeconds: 0, currentStateIndex: 0,
status: WorkoutStatus.notStarted.rawValue, notes: nil, date: Self.ts)],
metrics: nil
)
}
@Test func updateWritesWorkoutOptimisticallyIntoTheCache() throws {
let container = try makeContainer()
let bridge = WatchConnectivityBridge(container: container)
let doc = workout(id: "01WKOPT", name: "Bench Press", splitName: "Push")
#expect(CacheMapper.fetchWorkout(id: doc.id, in: container.mainContext) == nil)
bridge.update(workout: doc)
let fetched = try #require(CacheMapper.fetchWorkout(id: doc.id, in: container.mainContext))
#expect(fetched.id == "01WKOPT")
#expect(fetched.splitName == "Push")
#expect(fetched.logsArray.first?.exerciseName == "Bench Press")
}
@Test func updateAppliesAnEditInPlaceOnASecondCall() throws {
let container = try makeContainer()
let bridge = WatchConnectivityBridge(container: container)
bridge.update(workout: workout(id: "01WKEDIT", name: "Bench Press", splitName: "Push"))
var edited = workout(id: "01WKEDIT", name: "Incline Press", splitName: "Push Day")
edited.status = WorkoutStatus.completed.rawValue
bridge.update(workout: edited)
let all = try container.mainContext.fetch(FetchDescriptor<Workout>())
#expect(all.count == 1) // updated in place, not duplicated
let fetched = try #require(CacheMapper.fetchWorkout(id: "01WKEDIT", in: container.mainContext))
#expect(fetched.splitName == "Push Day")
#expect(fetched.status == .completed)
#expect(fetched.logsArray.first?.exerciseName == "Incline Press")
}
@Test func freshBridgeHasNoSyncDateEditLockOrFollowerFrame() throws {
let bridge = try WatchConnectivityBridge(container: makeContainer())
#expect(bridge.lastSyncDate == nil)
#expect(bridge.editingWorkoutID == nil)
#expect(bridge.editingSplitID == nil)
#expect(bridge.liveIncoming == nil)
#expect(bridge.presentable == nil)
#expect(bridge.navigatedRunID == nil)
}
/// `muteLive()` with no incoming frame is a harmless no-op `presentable` stays nil rather
/// than trapping on the optional it reads.
@Test func muteLiveWithoutIncomingFrameIsHarmless() throws {
let bridge = try WatchConnectivityBridge(container: makeContainer())
bridge.muteLive()
#expect(bridge.presentable == nil)
}
}
@@ -0,0 +1,78 @@
import Foundation
import Testing
@testable import Workouts_Watch_App
/// Locks the small pure helpers the watch UI leans on: the run-flow duration label, the
/// weight-unit formatter, the workout-volume roll-up the watch attaches to finished sessions,
/// and the heart-rate zone bucketing the live session folds sensor time into. All pure no
/// SwiftUI host, no `HKWorkoutSession`.
struct WatchHelpersTests {
// MARK: - ExerciseProgressView.durationLabel (run-flow "m/s" footer)
@Test func durationLabelFormatsMinutesAndSeconds() {
#expect(ExerciseProgressView.durationLabel(90) == "1m 30s")
#expect(ExerciseProgressView.durationLabel(605) == "10m 5s")
}
@Test func durationLabelDropsWholeSecondsAndWholeMinutes() {
#expect(ExerciseProgressView.durationLabel(60) == "1 min")
#expect(ExerciseProgressView.durationLabel(120) == "2 min")
#expect(ExerciseProgressView.durationLabel(45) == "45 sec")
#expect(ExerciseProgressView.durationLabel(0) == "0 sec")
}
// MARK: - WeightUnit.format (watch row / picker subtitle)
@Test func weightUnitFormatsWithAbbreviation() {
#expect(WeightUnit.lb.format(135) == "135 lb")
#expect(WeightUnit.kg.format(60) == "60 kg")
#expect(WeightUnit.lb.format(0) == "0 lb")
}
// MARK: - WorkoutVolume.total (metric the watch fills on finish)
private static let ts = Date(timeIntervalSince1970: 1_700_000_000)
private func log(id: String, sets: Int, reps: Int, weight: Int, loadType: LoadType) -> WorkoutLogDocument {
WorkoutLogDocument(
id: id, exerciseName: "Ex-\(id)", order: 0, sets: sets, reps: reps, weight: weight,
loadType: loadType.rawValue, durationSeconds: 0, currentStateIndex: 0,
status: WorkoutStatus.completed.rawValue, notes: nil, date: Self.ts
)
}
@Test func workoutVolumeSumsSetsRepsWeightAcrossWeightedLogs() {
let logs = [
log(id: "A", sets: 4, reps: 10, weight: 135, loadType: .weight), // 5400
log(id: "B", sets: 3, reps: 8, weight: 100, loadType: .weight), // 2400
]
#expect(WorkoutVolume.total(logs) == 7800)
}
@Test func workoutVolumeExcludesNonWeightedLogs() {
let logs = [
log(id: "A", sets: 4, reps: 10, weight: 135, loadType: .weight), // 5400
log(id: "B", sets: 3, reps: 30, weight: 999, loadType: .duration), // excluded (timed)
log(id: "C", sets: 2, reps: 5, weight: 50, loadType: .none), // excluded (no load)
]
#expect(WorkoutVolume.total(logs) == 5400)
}
@Test func workoutVolumeOfNoLogsIsZero() {
#expect(WorkoutVolume.total([]) == 0)
}
// MARK: - WorkoutSessionManager.zoneIndex (HR zone bucketing)
@Test func zoneIndexBucketsByFractionOfMaxHeartRate() {
let maxHR = 200.0 // thresholds land on 120 / 140 / 160 / 180 bpm
#expect(WorkoutSessionManager.zoneIndex(for: 100, maxHR: maxHR) == 0) // 50% zone 0
#expect(WorkoutSessionManager.zoneIndex(for: 119, maxHR: maxHR) == 0) // <60% zone 0
#expect(WorkoutSessionManager.zoneIndex(for: 120, maxHR: maxHR) == 1) // 60% zone 1
#expect(WorkoutSessionManager.zoneIndex(for: 140, maxHR: maxHR) == 2) // 70% zone 2
#expect(WorkoutSessionManager.zoneIndex(for: 160, maxHR: maxHR) == 3) // 80% zone 3
#expect(WorkoutSessionManager.zoneIndex(for: 180, maxHR: maxHR) == 4) // 90% zone 4
#expect(WorkoutSessionManager.zoneIndex(for: 220, maxHR: maxHR) == 4) // over max still 4
}
}