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
@@ -97,13 +97,16 @@ final class WatchConnectivityBridge: NSObject {
/// Apply a decoded state push. `nil` (decode failure the phone runs a build with
/// a different document schema) is logged and skipped so we neither prune the cache
/// against a bogus empty set nor silently show stale data forever.
/// against a bogus empty set nor silently show stale data forever. The upsert/prune
/// itself is delegated to the pure, session-free `WatchCacheApplier` seam so the
/// apply/prune contract is unit-testable.
private func applyState(_ splits: [SplitDocument]?, workouts: [WorkoutDocument]?) {
guard let splits, let workouts else {
guard WatchCacheApplier.apply(splits: splits, workouts: workouts, into: context) else {
Self.log.error("applyState: payload failed to decode (splits=\(splits == nil ? "failed" : "ok", privacy: .public), workouts=\(workouts == nil ? "failed" : "ok", privacy: .public)) — phone/watch build mismatch?")
return
}
applyState(splits, workouts: workouts)
Self.log.info("applyState: applied \(splits?.count ?? 0) splits, \(workouts?.count ?? 0) workouts")
lastSyncDate = Date()
}
func requestSync() {
@@ -210,8 +213,35 @@ final class WatchConnectivityBridge: NSObject {
}
}
private func applyState(_ splits: [SplitDocument], workouts: [WorkoutDocument]) {
Self.log.info("applyState: \(splits.count) splits, \(workouts.count) workouts")
}
// MARK: - Cache apply/prune seam
/// The pure, session-free core of the phonewatch state apply: it upserts the authoritative
/// splits/workouts into the watch's SwiftData cache and prunes anything the phone no longer
/// sends. Split out of `WatchConnectivityBridge` (which wraps `WCSession`) so the apply/prune
/// contract including the authoritative-empty prune and the nil-decode skip is unit-testable
/// against an in-memory `ModelContext` without a live WatchConnectivity session.
enum WatchCacheApplier {
/// Entry point mirroring the wire decode: `nil` for *either* set means the phone's payload
/// failed to decode (a build/schema mismatch). We skip entirely no upsert, no prune so a
/// bogus empty set can never wipe real rows. Returns `true` when an authoritative push was
/// applied, `false` when skipped, so the caller can log / stamp `lastSyncDate` accordingly.
@MainActor
@discardableResult
static func apply(splits: [SplitDocument]?, workouts: [WorkoutDocument]?, into context: ModelContext) -> Bool {
guard let splits, let workouts else { return false }
apply(splits: splits, workouts: workouts, into: context)
return true
}
/// Upsert every split/workout the phone sent, then prune anything it *didn't*. Both sets are
/// authoritative, so an authoritative empty push clears rows the phone no longer has (a deleted
/// split; a run discarded/deleted on the phone, completed-and-aged-out, or otherwise dropped
/// from the ~24h window). On first launch the cache is empty, so the prune is a harmless no-op.
/// The watch never originates a split/workout, so pruning can't lose local-only data.
@MainActor
static func apply(splits: [SplitDocument], workouts: [WorkoutDocument], into context: ModelContext) {
var liveSplitIDs = Set<String>()
for s in splits {
CacheMapper.upsertSplit(s, relativePath: s.relativePath, into: context)
@@ -222,11 +252,6 @@ final class WatchConnectivityBridge: NSObject {
CacheMapper.upsertWorkout(w, relativePath: w.relativePath, into: context)
liveWorkoutIDs.insert(w.id)
}
// Both are authoritative sets prune anything the phone no longer sends. For
// workouts that set is every active run plus recently-completed ones (~24h), so a
// run that was discarded/deleted on the phone (or aged out of the window) drops out
// of the push and is pruned here which empties the active list and ends the
// session. The watch never originates a workout, so pruning can't lose local data.
if let allSplits = try? context.fetch(FetchDescriptor<Split>()) {
for s in allSplits where !liveSplitIDs.contains(s.id) { context.delete(s) }
}
@@ -234,7 +259,6 @@ final class WatchConnectivityBridge: NSObject {
for w in allWorkouts where !liveWorkoutIDs.contains(w.id) { context.delete(w) }
}
try? context.save()
lastSyncDate = Date()
}
}
@@ -142,7 +142,7 @@ final class WorkoutSessionManager: NSObject {
if let maxHeartRate, let prevHR = currentHeartRate, let last = lastHRSampleDate {
let dt = now.timeIntervalSince(last)
if dt > 0, dt < 60 { hrZoneSeconds[zoneIndex(for: prevHR, maxHR: maxHeartRate)] += dt }
if dt > 0, dt < 60 { hrZoneSeconds[Self.zoneIndex(for: prevHR, maxHR: maxHeartRate)] += dt }
}
if let newHR { currentHeartRate = newHR }
lastHRSampleDate = now
@@ -151,7 +151,10 @@ final class WorkoutSessionManager: NSObject {
.sumQuantity()?.doubleValue(for: .kilocalorie())
}
private func zoneIndex(for hr: Double, maxHR: Double) -> Int {
/// Bucket an instantaneous heart rate into one of five zones (04) by its fraction of the
/// user's max HR: <60% 0, 6070% 1, 7080% 2, 8090% 3, 90% 4. Pure (no session
/// or sensor state), so it's `nonisolated static` and unit-testable off the main actor.
nonisolated static func zoneIndex(for hr: Double, maxHR: Double) -> Int {
let ratio = hr / maxHR
let thresholds = [0.6, 0.7, 0.8, 0.9]
return thresholds.reduce(0) { $0 + (ratio >= $1 ? 1 : 0) }
@@ -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
}
}
+18 -1
View File
@@ -126,7 +126,24 @@ targets:
TARGETED_DEVICE_FAMILY: "4"
DEVELOPMENT_ASSET_PATHS: "\"Workouts Watch App/Preview Content\""
scheme:
testTargets: []
testTargets:
- Workouts Watch AppTests
# ---- watchOS unit tests (bridge apply/prune seam + watch-side helpers) ------
Workouts Watch AppTests:
type: bundle.unit-test
platform: watchOS
sources:
- Workouts Watch AppTests
dependencies:
- target: Workouts Watch App
- package: IndieSync
settings:
base:
PRODUCT_BUNDLE_IDENTIFIER: dev.rzen.indie.Workouts.watchkitapp.tests
GENERATE_INFOPLIST_FILE: true
SWIFT_STRICT_CONCURRENCY: complete
WATCHOS_DEPLOYMENT_TARGET: "26.0"
# ---- watchOS widget extension (a launcher complication for the watch face) --
Workouts Watch Widget: