use liveactivity::{
AndroidContent, AndroidOptions, AndroidPresentation, AndroidVisibility, BigTextStyle, EndInput,
EndPolicy, ImageInput, Metric, MetricStyle, MetricValue, PresentationStyle, ProgressPoint,
ProgressSegment, ProgressStyle, PublicVersion, SamsungNowBar, Snapshot, StartInput, Template,
Timer, TimerStyle, UpdateInput, Validate,
};
use serde_json::json;
use std::{fs, path::Path};
fn sources(folder: &Path) -> Vec<(String, String)> {
let mut found = Vec::new();
for entry in fs::read_dir(folder).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
found.extend(sources(&path));
} else if path.extension().is_some_and(|extension| extension == "rs") {
let text = fs::read_to_string(&path).unwrap();
found.push((path.display().to_string(), text));
}
}
found
}
#[test]
fn req_c_012_every_public_enum_may_gain_a_variant() {
let mut enums = 0;
for (file, text) in sources(&Path::new(env!("CARGO_MANIFEST_DIR")).join("src")) {
let lines: Vec<&str> = text.lines().collect();
for (at, line) in lines.iter().enumerate() {
if !line.starts_with("pub enum ") {
continue;
}
enums += 1;
let above = lines[..at].iter().rev().take_while(|line| !line.is_empty());
let marked = above
.into_iter()
.any(|line| line.trim() == "#[non_exhaustive]");
assert!(marked, "{file}: `{line}` is not #[non_exhaustive]");
}
}
assert!(enums >= 12, "the crate's enums were found: {enums}");
#[deny(unreachable_patterns)]
fn named(template: Template, policy: &EndPolicy) -> (&'static str, &'static str) {
let template = match template {
Template::Progress => "progress",
Template::Timer => "timer",
_ => "later",
};
let policy = match policy {
EndPolicy::Immediate {} => "immediate",
EndPolicy::Default {} => "default",
EndPolicy::After { .. } => "after",
_ => "later",
};
(template, policy)
}
assert_eq!(
named(Template::Timer, &EndPolicy::After { at: 1 }),
("timer", "after")
);
}
#[test]
fn req_c_012_a_constructor_builds_what_the_literal_was() {
assert_eq!(
Timer::new(1, 2),
Timer {
started_at: 1,
ends_at: 2
}
);
let progress = Snapshot::progress(3, "Ride", "On the way", 0.5);
assert_eq!(
serde_json::to_value(&progress).unwrap(),
json!({ "revision": 3, "title": "Ride", "status": "On the way", "progress": 0.5 })
);
let timer = Snapshot::timer(0, "Nap", "Asleep", 10, 20);
assert_eq!(
serde_json::to_value(&timer).unwrap(),
json!({ "revision": 0, "title": "Nap", "status": "Asleep",
"timer": { "startedAt": 10, "endsAt": 20 } })
);
let start = StartInput::new("ride:7", Snapshot::progress(0, "Ride", "On the way", 0.5));
assert_eq!(
start,
StartInput::progress("ride:7", "Ride", "On the way", 0.5)
);
assert_eq!(start.validate(), Ok(()));
assert_eq!(
StartInput::new("nap:1", timer.clone()).template,
Template::Timer
);
let neither = Snapshot {
progress: None,
..Snapshot::progress(0, "Ride", "On the way", 0.5)
};
assert_eq!(
StartInput::new("ride:7", neither)
.validate()
.unwrap_err()
.code,
"INVALID_INPUT"
);
assert_eq!(
serde_json::to_value(UpdateInput::new("id", timer)).unwrap(),
json!({ "id": "id", "snapshot": { "revision": 0, "title": "Nap", "status": "Asleep",
"timer": { "startedAt": 10, "endsAt": 20 } } })
);
assert_eq!(
serde_json::to_value(EndInput::after("id", 9)).unwrap(),
json!({ "id": "id", "policy": { "kind": "after", "at": 9 } })
);
let content = AndroidContent::new(
"Ride",
"On the way",
AndroidPresentation::new(PresentationStyle::Standard),
);
assert_eq!(
serde_json::to_value(&content).unwrap(),
json!({ "title": "Ride", "status": "On the way",
"presentation": { "style": { "kind": "standard" } } })
);
assert_eq!(
serde_json::to_value(ImageInput::new("cat.png", vec![1, 2])).unwrap(),
json!({ "name": "cat.png", "png": [1, 2] })
);
assert_eq!(
serde_json::to_value(
AndroidOptions::new(AndroidVisibility::Private).with_wear_ongoing_activity(false)
)
.unwrap(),
json!({ "visibility": "private", "wearOngoingActivity": false })
);
assert_eq!(
serde_json::to_value(AndroidOptions::new(AndroidVisibility::Private)).unwrap(),
json!({ "visibility": "private" })
);
}
#[test]
fn req_a_040_the_options_of_a_mirrored_start() {
let mirrored = AndroidOptions::new(AndroidVisibility::Private).with_watch_mirror(true);
assert_eq!(mirrored.watch_mirror, Some(true));
assert_eq!(
serde_json::to_value(&mirrored).unwrap(),
json!({"visibility":"private","watchMirror":true})
);
let plain = AndroidOptions::new(AndroidVisibility::Private);
assert_eq!(plain.watch_mirror, None);
assert_eq!(
serde_json::to_value(&plain).unwrap(),
json!({"visibility":"private"})
);
let presentation = AndroidPresentation {
watch_mirror: true,
..AndroidPresentation::new(PresentationStyle::Standard)
};
assert_eq!(
serde_json::to_value(&presentation).unwrap()["watchMirror"],
true
);
assert!(
serde_json::to_value(AndroidPresentation::new(PresentationStyle::Standard))
.unwrap()
.get("watchMirror")
.is_none()
);
}
#[test]
fn req_a_032_the_options_of_a_start_kept_off_the_watch() {
let kept = AndroidOptions::new(AndroidVisibility::Private).with_local_only(true);
assert_eq!(kept.local_only, Some(true));
assert_eq!(
serde_json::to_value(&kept).unwrap(),
json!({"visibility":"private","localOnly":true})
);
let plain = AndroidOptions::new(AndroidVisibility::Private);
assert_eq!(plain.local_only, None);
assert_eq!(
serde_json::to_value(&plain).unwrap(),
json!({"visibility":"private"})
);
let presentation = AndroidPresentation {
local_only: true,
..AndroidPresentation::new(PresentationStyle::Standard)
};
assert_eq!(
serde_json::to_value(&presentation).unwrap()["localOnly"],
true
);
let plain = AndroidPresentation::new(PresentationStyle::Standard);
assert!(
serde_json::to_value(&plain)
.unwrap()
.get("localOnly")
.is_none()
);
}
#[test]
fn req_c_012_a_layout_is_built_on_activitykits_constructors() {
use liveactivity::activitykit::layout::{button, hstack, symbol, text, vstack};
use liveactivity::{Bound, Color, Element, Island, IslandExpanded, Layout, Style};
let layout = Layout::new(vstack([
text(Bound::key("title")).style("title"),
button("track", text("Track")),
]))
.island(
Island::new()
.expanded(IslandExpanded::new().center(text(Bound::key("title"))))
.compact_leading(symbol("shippingbox.fill"))
.compact_trailing(text(Bound::key("eta")))
.minimal(symbol("shippingbox.fill")),
)
.background(Color::adaptive("#F2F2F7", "#1C1C1E"))
.keyline(Color::Hex("#FF9500".into()))
.url("myapp://delivery/7")
.small(hstack([
symbol("shippingbox.fill"),
text(Bound::key("eta")),
]));
assert_eq!(
serde_json::to_value(&layout).unwrap(),
json!({
"lockScreen": {"type":"vstack","children":[
{"type":"text","bind":"title","style":"title"},
{"type":"button","actionId":"track","child":{"type":"text","value":"Track"}},
]},
"island": {
"expanded": {"center": {"type":"text","bind":"title"}},
"compactLeading": {"type":"symbol","name":"shippingbox.fill"},
"compactTrailing": {"type":"text","bind":"eta"},
"minimal": {"type":"symbol","name":"shippingbox.fill"},
},
"background": {"light":"#F2F2F7","dark":"#1C1C1E"},
"keyline": "#FF9500",
"url": "myapp://delivery/7",
"small": {"type":"hstack","children":[
{"type":"symbol","name":"shippingbox.fill"},
{"type":"text","bind":"eta"},
]},
})
);
let style = Style::new().color(Bound::key("tone"));
assert_eq!(
serde_json::to_value(&style).unwrap(),
json!({"color":{"bind":"tone"}})
);
let kind = match &layout.lock_screen.element {
Element::Vstack { .. } => "vstack",
_ => "another",
};
assert_eq!(kind, "vstack");
}
#[test]
fn req_c_012_the_reexported_vocabulary_is_built_on_its_constructors() {
let track = ProgressStyle {
points: vec![ProgressPoint::new(60)],
styled_by_progress: true,
..ProgressStyle::new(40, vec![ProgressSegment::new(60), ProgressSegment::new(40)])
};
let presentation = AndroidPresentation {
public_version: Some(PublicVersion::new("Ride", "On the way")),
samsung_now_bar: Some(SamsungNowBar::default()),
chronometer: Some(TimerStyle::new(
liveactivity::liveupdate::Timer::new(10, 20),
true,
)),
..AndroidPresentation::new(PresentationStyle::Progress(track))
};
assert!(presentation.wear_ongoing_activity);
let written = serde_json::to_value(&presentation).unwrap();
assert!(written.get("wearOngoingActivity").is_none());
assert_eq!(written["publicVersion"]["title"], "Ride");
let metrics = MetricStyle::new(vec![Metric::new(
"Steps",
MetricValue::Integer {
value: 42,
unit: None,
},
)]);
let styles = [
PresentationStyle::Standard,
PresentationStyle::BigText(BigTextStyle::new("A long text")),
PresentationStyle::Metric(metrics),
];
let kinds: Vec<&str> = styles
.iter()
.map(|style| match style {
PresentationStyle::Standard => "standard",
PresentationStyle::BigText(_) => "bigText",
_ => "another",
})
.collect();
assert_eq!(kinds, ["standard", "bigText", "another"]);
}
#[test]
fn req_a_028_a_progress_style_from_its_constructor_is_styled_by_its_progress() {
let built = ProgressStyle::new(40, vec![ProgressSegment::new(100)]);
assert!(built.styled_by_progress);
assert_eq!(
serde_json::to_value(&built).unwrap(),
json!({ "progress": 40, "styledByProgress": true, "segments": [{ "length": 100 }] })
);
let read: ProgressStyle =
serde_json::from_value(json!({ "progress": 40, "segments": [{ "length": 100 }] })).unwrap();
assert!(!read.styled_by_progress);
let plain = ProgressStyle {
styled_by_progress: false,
..built
};
assert!(
serde_json::to_value(&plain)
.unwrap()
.get("styledByProgress")
.is_none()
);
}