//! Cotton Health's rule over synthetic readings only: the invented export//! in `fixtures/export.xml` and invented phone batches.use serde_json::{json, Map, Value};usesuper::catalog::{self, Fold};usesuper::export::{read_export_xml, read_export_zip, Export, ExportError};usesuper::land::{plan, Plan};usesuper::rows::{day_key, instant, measurement_key, workout_key, DayRow, Source};usesuper::summary;usecrate::import::zip::{ZipError, ZipRangeReader};const FIXTURE: &str = include_str!("fixtures/export.xml");fn export() -> Export { read_export_xml(FIXTURE.as_bytes()).expect("the invented export reads")}fn day<'a>(rows: &'a [DayRow], metric: &str, on: &str) -> &'a DayRow { rows.iter().find(|row| row.metric == metric && row.day == on).unwrap_or_else(|| panic!("{metric} on {on}: {rows:#?}"))}fn value(rows: &[DayRow], metric: &str, on: &str) -> f64 { day(rows, metric, on).value.unwrap_or_else(|| panic!("{metric} on {on} holds a value"))}fn close(a: f64, b: f64) -> bool { (a - b).abs() < 0.01}/// RULE (Cotton Health, 12 Nov 2026): the app asks HealthKit to read, never to write, every type its tables keep, each once, with the unit it sends in and how it sends it; no raw heart-rate stream (heart rate is read only for a workout's own statistics).#[test]fn the_app_reads_each_kept_type_once_and_never_the_heart_rate_stream() {let types = catalog::read_types();letmut seen = std::collections::HashSet::new();for read in &types { assert!(seen.insert(read.healthkit), "{} is asked once", read.healthkit); assert!(!read.sends.is_empty() && read.sends.iter().all(|sends| matches!(*sends, "days" | "intervals" | "measurements" | "workouts")), "{read:?}");if read.kind == "quantity" { assert!(!read.unit.is_empty(), "{} names its unit", read.healthkit); } }let heart = types.iter().find(|read| read.healthkit == catalog::HEART_RATE).expect("heart rate, for workouts"); assert_eq!(heart.sends, ["days", "workouts"], "heart rate is the day's average, least and most, and a workout's statistics: never its stream"); assert_eq!(heart.statistics, Some("discreteAverage"));let weight = types.iter().find(|read| read.healthkit == catalog::BODY_MASS).unwrap(); assert_eq!(weight.sends, ["days", "measurements"], "a weighing is the day's weight and a measurement");for wanted in [catalog::STEP_COUNT, catalog::SLEEP, catalog::BLOOD_PRESSURE, catalog::WORKOUT, catalog::MENSTRUAL_FLOW, catalog::TEMPERATURE] { assert!(types.iter().any(|read| read.healthkit == wanted), "{wanted} is read"); }let steps = types.iter().find(|read| read.healthkit == catalog::STEP_COUNT).unwrap(); assert_eq!((steps.sends.clone(), steps.statistics, steps.unit), (vec!["days"], Some("cumulativeSum"), "count"));let resting = types.iter().find(|read| read.healthkit == "HKQuantityTypeIdentifierRestingHeartRate").unwrap(); assert_eq!(resting.statistics, Some("discreteAverage"));for metric in catalog::METRICS { assert!(catalog::metric_of(metric.key).is_some());if metric.fold == Fold::Sleep { assert!(metric.stage.is_some(), "{} names its stage", metric.key); } }}/// RULE: units are converted on the way in and never guessed: a fraction is kept as a percentage, kJ as kcal, pounds as kilograms, mmol/L of glucose as mg/dL, °F as °C, km as metres; a unit not known is no value.#[test]fn units_are_converted_on_the_way_in_and_never_guessed() {use catalog::{canonical, Dimensionas D}; assert!(close(canonical(D::Fraction, 0.215, "%").unwrap(), 21.5)); assert!(close(canonical(D::Energy, 836.8, "kJ").unwrap(), 200.0)); assert!(close(canonical(D::Mass, 160.0, "lb").unwrap(), 72.575)); assert!(close(canonical(D::Glucose, 5.5, "mmol<180.15588000005408>/L").unwrap(), 99.086)); assert!(close(canonical(D::Temperature, 98.6, "degF").unwrap(), 37.0)); assert!(close(canonical(D::Length, 5.2, "km").unwrap(), 5200.0)); assert_eq!(canonical(D::Count, 3.0, "furlong"), None); assert_eq!(canonical(D::Mass, f64::NAN, "kg"), None);}/// RULE: rows are keyed so a re-read never duplicates: a day by (metric, day), a workout by (kind, start, end) and a measurement by (kind, instant), each to the second, so HealthKit and an export reading the same workout land one row (the planned key; the id the object keeps is keyed by the data key).#[test]fn keys_come_from_what_was_measured_never_who_read_it() { assert_eq!(day_key("steps", "2026-11-12"), day_key("steps", "2026-11-12")); assert_ne!(day_key("steps", "2026-11-12"), day_key("steps", "2026-11-11")); assert_ne!(day_key("steps", "2026-11-12"), day_key("distance", "2026-11-12")); assert_eq!(workout_key("running", 1_000_400, 2_000_900), workout_key("running", 1_000_000, 2_000_000), "to the second"); assert_eq!(measurement_key("weight", 5_000), measurement_key("weight", 5_999));let phone = instant("2026-11-11T06:25:00+05:30").unwrap();let file = instant("2026-11-11 06:25:00 +0530").unwrap(); assert_eq!(phone, file, "the phone's and the export's times read alike"); assert_eq!((phone.day.as_str(), phone.hour), ("2026-11-11", 6), "the person's own day and hour"); assert_eq!(instant("2026-11-11T00:30:00Z").unwrap().day, "2026-11-11"); assert_eq!(instant("yesterday"), None);}/// RULE: the export's records fold into the same days the phone sends: a sum keeps its fullest source (a watch and a phone counting the same walk are not added), a record taken twice counts once, an average keeps its least and most, a latest its last reading; sleep lands on the morning it ends, stages merged across sources; mindful minutes merge overlaps; stand hours count the hours stood; flow keeps the day's heaviest; a unit not known is skipped, and the heart-rate stream, routes and the Me element are never read.#[test]fn the_export_folds_into_the_days_the_phone_sends() {let read = export();let days = &read.days; assert_eq!(value(days, "steps", "2026-11-11"), 5700.0, "the watch's fuller day, its doubled record once"); assert_eq!(value(days, "steps", "2026-11-12"), 4200.0); assert_eq!(value(days, "distance", "2026-11-11"), 2400.0); assert!(close(value(days, "active_energy", "2026-11-11"), 200.0));let resting = day(days, "resting_heart_rate", "2026-11-11"); assert_eq!((resting.value, resting.min, resting.max), (Some(60.0), Some(58.0), Some(62.0))); assert_eq!(value(days, "heart_rate_variability", "2026-11-11"), 44.0); assert_eq!(value(days, "weight", "2026-11-11"), 72.4, "the day's last weighing"); assert!(close(value(days, "body_fat", "2026-11-11"), 21.5)); assert!(close(value(days, "glucose", "2026-11-11"), 99.086)); assert_eq!(value(days, "blood_pressure_systolic", "2026-11-11"), 121.0); assert_eq!(value(days, "blood_pressure_diastolic", "2026-11-11"), 78.0); assert_eq!(value(days, "sleep_in_bed", "2026-11-12"), 450.0, "the night lands on the morning"); assert_eq!(value(days, "sleep_asleep", "2026-11-12"), 440.0, "the phone's and the watch's sleep, merged"); assert_eq!(value(days, "sleep_core", "2026-11-12"), 270.0); assert_eq!(value(days, "sleep_deep", "2026-11-12"), 60.0); assert_eq!(value(days, "sleep_rem", "2026-11-12"), 90.0); assert_eq!(value(days, "sleep_awake", "2026-11-12"), 10.0); assert!(!days.iter().any(|row| row.metric.starts_with("sleep") && row.day == "2026-11-11")); assert_eq!(value(days, "mindful_minutes", "2026-11-11"), 15.0, "two overlapping sessions, merged"); assert_eq!(value(days, "stand_hours", "2026-11-11"), 2.0);let flow = day(days, "menstrual_flow", "2026-11-11"); assert_eq!((flow.value, flow.state.as_deref()), (None, Some("medium"))); assert!(!days.iter().any(|row| row.metric == "flights"), "a furlong is no unit of flights"); assert!(read.skipped >= 1); assert!(days.iter().all(|row| row.source == Source::Export)); assert_eq!(read.workouts.len(), 2);let run = &read.workouts[0]; assert_eq!((run.kind, run.day.as_str(), run.minutes), ("running", "2026-11-11", 32.5)); assert_eq!((run.distance_m, run.energy_kcal, run.heart_rate_avg, run.heart_rate_max), (Some(5200.0), Some(310.0), Some(152.0), Some(174.0))); assert_eq!(run.device.as_deref(), Some("Invented Watch"));let yoga = &read.workouts[1]; assert_eq!((yoga.kind, yoga.minutes, yoga.distance_m, yoga.energy_kcal), ("yoga", 45.0, None, Some(120.0)), "an older export's totals, its zero distance none");let kinds: Vec<&str> = read.measurements.iter().map(|row| row.kind).collect(); assert_eq!(kinds, ["weight", "glucose", "blood_pressure", "weight", "temperature"], "earliest first, the pressure paired once");let pressure = read.measurements.iter().find(|row| row.kind == "blood_pressure").unwrap(); assert_eq!((pressure.value, pressure.second, pressure.unit), (121.0, Some(78.0), "mmHg"));let glucose = read.measurements.iter().find(|row| row.kind == "glucose").unwrap(); assert_eq!(glucose.context.as_deref(), Some("before_meal")); assert!(close(read.measurements[0].value, 72.575), "160 lb"); assert!(close(read.measurements.iter().find(|row| row.kind == "temperature").unwrap().value, 37.0));}/// RULE: a row's data is what the table keeps: its key, the metric's own unit, numbers to three decimals.#[test]fn a_row_carries_its_key_and_its_unit() {let read = export();let steps = day(&read.days, "steps", "2026-11-11").data("a-keyed-id"); assert_eq!(steps["key"], json!("a-keyed-id")); assert_eq!(day(&read.days, "steps", "2026-11-11").key(), day_key("steps", "2026-11-11")); assert_eq!((steps["metric"].clone(), steps["value"].clone(), steps["unit"].clone(), steps["source"].clone()), (json!("steps"), json!(5700), json!("steps"), json!("export")));let glucose = day(&read.days, "glucose", "2026-11-11").data("g"); assert_eq!(glucose["value"], json!(99.086));let run = read.workouts[0].data("w"); assert_eq!((run["started_at"].clone(), run["ended_at"].clone()), (json!("2026-11-11T00:55:00.000Z"), json!("2026-11-11T01:27:30.000Z"))); assert_eq!(read.workouts[0].key(), workout_key("running", read.workouts[0].started_ms, read.workouts[0].ended_ms)); assert_eq!(read.workouts[0].key(), "workout|running|1794358500|1794360450");}structBytes(Vec<u8>);implZipRangeReaderforBytes {fn size(&self) -> u64 {self.0.len() as u64 }fn read(&self, offset: u64, length: u64) -> Result<Vec<u8>, ZipError> {self.0.get(offset as usize..(offset + length) as usize).map(<[u8]>::to_vec).ok_or_else(|| ZipError::Reader("past the end".into())) }}/// An archive of `(name, bytes, deflated)` entries, as Health writes one.fn zip(entries: &[(&str, &[u8], bool)]) -> Vec<u8> {letmut out = Vec::new();letmut central = Vec::new();for (name, bytes, deflated) in entries {let data = if *deflated { miniz_oxide::deflate::compress_to_vec(bytes, 6) } else { bytes.to_vec() };let method: u16 = if *deflated { 8 } else { 0 };let offset = out.len() as u32; out.extend_from_slice(&0x0403_4b50u32.to_le_bytes()); out.extend_from_slice(&20u16.to_le_bytes()); out.extend_from_slice(&0u16.to_le_bytes()); out.extend_from_slice(&method.to_le_bytes()); out.extend_from_slice(&[0; 8]); out.extend_from_slice(&(data.len() as u32).to_le_bytes()); out.extend_from_slice(&(bytes.len() as u32).to_le_bytes()); out.extend_from_slice(&(name.len() as u16).to_le_bytes()); out.extend_from_slice(&0u16.to_le_bytes()); out.extend_from_slice(name.as_bytes()); out.extend_from_slice(&data); central.extend_from_slice(&0x0201_4b50u32.to_le_bytes()); central.extend_from_slice(&20u16.to_le_bytes()); central.extend_from_slice(&20u16.to_le_bytes()); central.extend_from_slice(&0u16.to_le_bytes()); central.extend_from_slice(&method.to_le_bytes()); central.extend_from_slice(&[0; 8]); central.extend_from_slice(&(data.len() as u32).to_le_bytes()); central.extend_from_slice(&(bytes.len() as u32).to_le_bytes()); central.extend_from_slice(&(name.len() as u16).to_le_bytes()); central.extend_from_slice(&[0; 12]); central.extend_from_slice(&offset.to_le_bytes()); central.extend_from_slice(name.as_bytes()); }let at = out.len() as u32; out.extend_from_slice(¢ral); out.extend_from_slice(&0x0605_4b50u32.to_le_bytes()); out.extend_from_slice(&[0; 4]); out.extend_from_slice(&(entries.len() as u16).to_le_bytes()); out.extend_from_slice(&(entries.len() as u16).to_le_bytes()); out.extend_from_slice(&(central.len() as u32).to_le_bytes()); out.extend_from_slice(&at.to_le_bytes()); out.extend_from_slice(&0u16.to_le_bytes()); out}/// RULE: an export.zip is read through ranged reads, its export.xml inflated as it is parsed (a file far larger than one window reads whole), the clinical export_cda.xml never; an archive with no export.xml is not an Apple Health export.#[test]fn an_export_zip_inflates_as_it_is_parsed() {// Padded past several windows with records the reader passes over.let filler: String = (0..40_000) .map(|n| format!(" <Record type=\"HKQuantityTypeIdentifierElectrodermalActivity\" sourceName=\"Invented Watch\" unit=\"count/min\" startDate=\"2026-11-10 10:00:00 +0530\" endDate=\"2026-11-10 10:00:00 +0530\" value=\"{}\"/>\n", 60 + n % 40)) .collect();let xml = FIXTURE.replace(" <ActivitySummary", &format!("{filler} <ActivitySummary")); assert!(xml.len() > 3 << 20, "longer than three windows");let archive = zip(&[ ("apple_health_export/export_cda.xml", b"<ClinicalDocument/>", true), ("apple_health_export/workout-routes/route.gpx", b"<gpx/>", false), ("apple_health_export/export.xml", xml.as_bytes(), true), ]);let read = read_export_zip(&Bytes(archive)).expect("the archive reads");let whole = export(); assert_eq!(read.days, whole.days, "the same days as the file read bare"); assert_eq!(read.workouts, whole.workouts); assert_eq!(read.measurements, whole.measurements);let stored = zip(&[("apple_health_export/export.xml", FIXTURE.as_bytes(), false)]); assert_eq!(read_export_zip(&Bytes(stored)).expect("a stored entry reads").days, whole.days);let other = zip(&[("photos/one.jpg", b"not a picture", false)]); assert_eq!(read_export_zip(&Bytes(other)).unwrap_err(), ExportError::NoExport);}fn steps_and_sleep() -> Value { json!({"days": [ { "type": catalog::STEP_COUNT, "day": "2026-11-12", "value": 8123 }, { "type": "HKQuantityTypeIdentifierBodyFatPercentage", "day": "2026-11-12", "value": 0.2 }, { "type": catalog::STEP_COUNT, "day": "2026-11-10", "value": null }, ],"intervals": [{"type": catalog::SLEEP, "from": "2026-11-12", "to": "2026-11-12","samples": [ { "start": "2026-11-11T23:00:00+05:30", "end": "2026-11-12T03:00:00+05:30", "value": 3 }, { "start": "2026-11-12T03:00:00+05:30", "end": "2026-11-12T04:00:00+05:30", "value": 4 }, { "start": "2026-11-12T22:30:00+05:30", "end": "2026-11-13T06:00:00+05:30", "value": 3 }, ], }],"workouts": [{ "uuid": "00000000-0000-4000-8000-00000000a001", "activity": 37, "start": "2026-11-12T06:00:00+05:30", "end": "2026-11-12T06:30:00+05:30", "distance_m": 5000, "energy_kcal": 300, "heart_rate_avg": 150 }],"measurements": [ { "type": catalog::BLOOD_PRESSURE, "uuid": "00000000-0000-4000-8000-00000000b001", "at": "2026-11-12T08:00:00+05:30", "systolic": 118, "diastolic": 76 }, { "type": catalog::GLUCOSE, "uuid": "00000000-0000-4000-8000-00000000b002", "at": "2026-11-12T08:05:00+05:30", "value": 96, "meal": 2 }, ],"deleted": ["00000000-0000-4000-8000-00000000c001"], })}/// RULE: a phone's batch lands as the export does: a day's statistics in the unit health.types named (a fraction kept as a percentage), a day with none now cleared, a category type's days sent whole and folded again (a night ending past the days sent is left for its own batch), workouts by HealthKit's activity number, measurements paired and with their meal, deletions by uuid.#[test]fn a_phone_batch_plans_the_rows_it_lands() {let made = plan(&steps_and_sleep()).expect("the batch reads"); assert_eq!(value(&made.days, "steps", "2026-11-12"), 8123.0); assert!(close(value(&made.days, "body_fat", "2026-11-12"), 20.0)); assert_eq!(made.cleared, [("steps", "2026-11-10".to_string())]); assert_eq!(value(&made.days, "sleep_asleep", "2026-11-12"), 300.0); assert_eq!(value(&made.days, "sleep_core", "2026-11-12"), 240.0); assert_eq!(value(&made.days, "sleep_deep", "2026-11-12"), 60.0); assert!(!made.days.iter().any(|row| row.day == "2026-11-13"), "a night past the days sent waits"); assert!(made.days.iter().all(|row| row.source == Source::HealthKit)); assert!(made.removes_day("sleep_rem", "2026-11-12"), "a stage the night no longer holds goes"); assert!(!made.removes_day("sleep_core", "2026-11-12")); assert!(!made.removes_day("sleep_rem", "2026-11-11"), "a day not sent stays"); assert!(made.removes_day("steps", "2026-11-10"));let run = &made.workouts[0]; assert_eq!((run.kind, run.minutes, run.sample.as_deref()), ("running", 30.0, Some("00000000-0000-4000-8000-00000000a001"))); assert_eq!(made.measurements[0].second, Some(76.0)); assert_eq!(made.measurements[1].context.as_deref(), Some("after_meal")); assert_eq!(made.deleted, ["00000000-0000-4000-8000-00000000c001"]);}/// RULE: a batch that does not read is refused whole, by its words, so nothing lands and the phone's anchor stays.#[test]fn a_batch_that_does_not_read_is_refused_whole() {for (batch, says) in [ (json!({ "days": [{ "type": "HKQuantityTypeIdentifierElectrodermalActivity", "day": "2026-11-12", "value": 70 }] }), "not a type"), (json!({ "days": [{ "type": catalog::STEP_COUNT, "day": "12/11/2026", "value": 1 }] }), "YYYY-MM-DD"), (json!({ "intervals": [{ "type": catalog::STEP_COUNT, "from": "2026-11-12", "to": "2026-11-12", "samples": [] }] }), "intervals"), (json!({ "intervals": [{ "type": catalog::SLEEP, "from": "2026-11-12", "to": "2026-11-11", "samples": [] }] }), "on or after"), (json!({ "measurements": [{ "type": catalog::BLOOD_PRESSURE, "at": "2026-11-12T08:00:00Z", "systolic": 120 }] }), "diastolic"), (json!({ "workouts": [{ "start": "soon", "end": "later" }] }), "start"), (json!({ "source": "fitbit" }), "source"), (json!({ "days": "steps" }), "list"), ] {let refused = plan(&batch).expect_err("refused"); assert!(refused.contains(says), "{batch}: {refused}"); } assert_eq!(plan(&json!({})).unwrap(), Plan::default(), "an empty batch lands nothing");}fn rows_of(rows: Vec<Map<String, Value>>) -> Vec<Map<String, Value>> { rows}/// RULE: a day's summary is each metric it holds in the catalogue's order with its usual (the mean of the four weeks before), the night by stage, and the day's workouts and measurements; a range is each metric's days with mean, least, most, latest and, where days add up, total, and the workouts by kind.#[test]fn summaries_read_a_day_against_its_weeks_and_a_range_as_series() {letmut days: Vec<Map<String, Value>> = Vec::new();for (n, steps) in [(1, 6000.0), (2, 8000.0), (3, 7000.0)] {let on = summary::day_before("2026-11-12", n).unwrap(); days.push(DayRow { metric: "steps", day: on, value: Some(steps), min: None, max: None, samples: None, state: None, source: Source::HealthKit }.data("d")); }let read = export(); days.extend(read.days.iter().filter(|row| row.day == "2026-11-12").map(|row| row.data("d")).filter(|row| row["metric"] != "steps")); days.push(DayRow { metric: "steps", day: "2026-11-12".into(), value: Some(9000.0), min: None, max: None, samples: None, state: None, source: Source::HealthKit }.data("d"));let workouts = rows_of(read.workouts.iter().map(|row| row.data("w")).collect());let measurements = rows_of(read.measurements.iter().map(|row| row.data("m")).collect());let today = summary::day("2026-11-12", &days, &workouts, &measurements);let metrics: Vec<&str> = today["metrics"].as_array().unwrap().iter().map(|metric| metric["metric"].as_str().unwrap()).collect(); assert_eq!(metrics[0], "steps", "activity first"); assert!(metrics.iter().position(|m| *m == "steps") < metrics.iter().position(|m| *m == "sleep_asleep"));let steps = &today["metrics"][0]; assert_eq!((steps["value"].clone(), steps["usual"].clone(), steps["unit"].clone()), (json!(9000), json!(7000), json!("steps"))); assert_eq!((today["sleep"]["asleep"].clone(), today["sleep"]["deep"].clone()), (json!(440), json!(60))); assert_eq!(today["workouts"].as_array().unwrap().len(), 1, "the day's yoga"); assert_eq!(today["workouts"][0]["kind"], "yoga"); assert!(today["measurements"].as_array().unwrap().is_empty());let week = summary::range("2026-11-06", "2026-11-12", &days, &workouts);let steps = week["metrics"].as_array().unwrap().iter().find(|metric| metric["metric"] == "steps").unwrap(); assert_eq!((steps["days_with"].clone(), steps["total"].clone(), steps["mean"].clone()), (json!(4), json!(30000), json!(7500))); assert_eq!((steps["min"].clone(), steps["max"].clone(), steps["latest"].clone()), (json!(6000), json!(9000), json!(9000))); assert_eq!(steps["days"][0]["day"], "2026-11-09", "days ascending");let sleep = week["metrics"].as_array().unwrap().iter().find(|metric| metric["metric"] == "sleep_asleep").unwrap(); assert_eq!(sleep["total"], json!(440)); assert_eq!((week["workouts"]["count"].clone(), week["workouts"]["minutes"].clone()), (json!(2), json!(77.5))); assert_eq!(week["workouts"]["kinds"][0]["kind"], "yoga", "the most minutes first");}/// RULE (20 Nov 2026): every type Apple Health offers as a day's number is read; an event category is counted per day it starts on, and a new type lands through the same batch with no new shape.#[test]fn every_type_lands_as_a_day_and_events_are_counted() {let batch = json!({ "intervals": [{ "type": "HKCategoryTypeIdentifierHandwashingEvent", "from": "2026-11-12", "to": "2026-11-12", "samples": [ { "start": "2026-11-12T08:00:00+05:30", "end": "2026-11-12T08:00:25+05:30", "value": 0 }, { "start": "2026-11-12T13:00:00+05:30", "end": "2026-11-12T13:00:30+05:30", "value": 0 }, ] }], "days": [{ "type": "HKQuantityTypeIdentifierOxygenSaturation", "day": "2026-11-12", "value": 0.97, "min": 0.93, "max": 0.99 }, { "type": "HKQuantityTypeIdentifierDietaryWater", "day": "2026-11-12", "value": 1800 }] });let made = plan(&batch).expect("the batch reads"); assert_eq!(value(&made.days, "handwashing", "2026-11-12"), 2.0); assert!(close(value(&made.days, "oxygen_saturation", "2026-11-12"), 97.0), "a fraction is kept as a percentage"); assert_eq!(value(&made.days, "water", "2026-11-12"), 1800.0);let types = catalog::read_types();for wanted in ["HKQuantityTypeIdentifierRespiratoryRate", "HKQuantityTypeIdentifierWalkingSpeed", "HKQuantityTypeIdentifierDietaryProtein", "HKCategoryTypeIdentifierIrregularHeartRhythmEvent"] { assert!(types.iter().any(|read| read.healthkit == wanted), "{wanted} is read"); } assert!(catalog::METRICS.iter().all(|metric| metric.fold != Fold::Count || metric.healthkit_unit.is_empty()), "a count is of a category");}/// RULE (health-ios, 20 Nov 2026): a metric folds as its HealthKit type is made: a quantity's day is asked of HealthKit's statistics in the unit it names (one the reader converts), a category's samples are folded; every key is its own and is a labelled choice of `health_day.metric`. (Whether HealthKit itself knows each identifier, unit and aggregation style is the iPhone's test, `HealthTypesTests`.)#[test]fn every_metric_folds_as_its_type() {let table: Value = serde_json::from_str(include_str!("../../kits/personal/tables/health_day.json")).expect("health_day");let column = table["columns"].as_array().unwrap().iter().find(|column| column["key"] == "metric").unwrap().clone();letmut keys = std::collections::HashSet::new();for metric in catalog::METRICS { assert!(keys.insert(metric.key), "{} is its own key", metric.key); assert!(column["labels"][metric.key].as_str().is_some_and(|label| !label.is_empty()), "{} is labelled", metric.key);let quantity = metric.healthkit.starts_with("HKQuantity"); assert_eq!(quantity, matches!(metric.fold, Fold::Sum | Fold::Average | Fold::Latest), "{} folds as its type", metric.key); assert_eq!(quantity, !metric.healthkit_unit.is_empty(), "{} names a unit exactly when it is a quantity", metric.key);if quantity { assert!(catalog::canonical(metric.dimension, 1.0, metric.healthkit_unit).is_some(), "{} reads the unit the phone sends it in", metric.key); } } assert!(close(catalog::canonical(catalog::Dimension::Litres, 4200.0, "mL").unwrap(), 4.2)); assert!(close(catalog::canonical(catalog::Dimension::LitresPerMinute, 8.0, "L/s").unwrap(), 480.0));}