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:
@@ -0,0 +1,163 @@
|
||||
import Foundation
|
||||
import SwiftData
|
||||
import Testing
|
||||
@testable import Workouts_Watch_App
|
||||
|
||||
/// Locks the phone→watch 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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user