use quote::{ToTokens as _, format_ident};
use crate::{
model::{
Grant, Grants, PollBody, PollCadence, PollEntry, PollMode, Polls, RecordModel,
default_polling_name, default_sweeps_name, poll_grants_name,
},
name::RustSafeName,
tests::{emission, model, struct_named},
};
fn granting() -> RecordModel {
let mut model = model("Reaper", &["media_id"], "id");
model.polls = Some(Polls {
entries: vec![
entry("hourly", &["media::Media", "media::KeyframeVec"]),
entry("nightly", &["media::Transcript"]),
],
});
model
}
fn entry(name: &str, granted: &[&str]) -> PollEntry {
use heck::ToUpperCamelCase as _;
PollEntry {
name: format_ident!("{name}"),
variant: format_ident!("{}", name.to_upper_camel_case()),
cadence: PollCadence::Every(core::time::Duration::new(600, 0)),
grants: (!granted.is_empty()).then(|| Grants {
grants: granted.iter().copied().map(grant).collect(),
}),
body: PollBody::Light,
mode: PollMode::AsyncInline,
concurrent: false,
}
}
fn running(name: &str, granted: &[&str], mode: PollMode, mounted: Option<&str>) -> PollEntry {
PollEntry {
body: mounted.map_or(PollBody::Light, |path| {
PollBody::Citizen(syn::parse_str(path).expect("a type path"))
}),
mode,
..entry(name, granted)
}
}
fn grant(path: &str) -> Grant {
let node: syn::Path = syn::parse_str(path).expect("a type path");
let segment = &node
.segments
.last()
.expect("a path has at least one segment")
.ident;
let mount = RustSafeName::new(segment.to_string(), proc_macro2::Span::call_site());
Grant { node, mount }
}
fn tight(model: &RecordModel) -> String {
model.emit().to_string().replace(' ', "")
}
#[test]
fn each_granting_clock_gets_its_own_context() {
let model = granting();
let file = emission(&model);
for (clock, mounts, handles) in [
(
"Hourly",
&["media", "keyframe_vec"][..],
&["MediaHandle", "KeyframeVecHandle"][..],
),
("Nightly", &["transcript"][..], &["TranscriptHandle"][..]),
] {
let named = poll_grants_name(&model.record, &format_ident!("{clock}")).to_string();
let context = struct_named(&file, &named);
assert_eq!(
context
.fields
.iter()
.map(|field| field.ident.as_ref().expect("a named field").to_string())
.collect::<Vec<_>>(),
mounts,
"{named}",
);
assert_eq!(
context
.generics
.type_params()
.map(|param| param.ident.to_string())
.collect::<Vec<_>>(),
handles,
"{named}",
);
assert!(
context.generics.where_clause.is_none()
&& context
.generics
.type_params()
.all(|param| param.bounds.is_empty()),
"{}",
context.to_token_stream(),
);
}
}
#[test]
fn each_grant_mints_its_own_write_socket_on_its_own_clock() {
let emitted = tight(&granting());
for (context, params, node, handle, mount) in [
(
"ReaperHourlyGrants",
"MediaHandle,KeyframeVecHandle",
"media::Media",
"MediaHandle",
"media",
),
(
"ReaperHourlyGrants",
"MediaHandle,KeyframeVecHandle",
"media::KeyframeVec",
"KeyframeVecHandle",
"keyframe_vec",
),
(
"ReaperNightlyGrants",
"TranscriptHandle",
"media::Transcript",
"TranscriptHandle",
"transcript",
),
] {
let lands = format!("::ingraph::__private::drive::AsyncLands<{node}>");
assert!(
emitted.contains(&format!(
"impl<{params}>{lands}for{context}<{params}>where{handle}:{lands},"
)),
"the `{node}` socket is emitted on `{context}`, bounding `{handle}` alone: {emitted}"
);
assert!(
emitted.contains(&format!("typeError=<{handle}as{lands}>::Error;")),
"the `{node}` socket carries the handle's own error: {emitted}"
);
assert!(
emitted.contains(&format!(
"<{handle}as{lands}>::land(&mutself.{mount},items)"
)),
"the `{node}` socket forwards to the handle it holds: {emitted}"
);
}
for gone in ["media_write", "keyframe_vec_write", "transcript_write"] {
assert!(
!emitted.contains(gone),
"`{gone}` is not emitted: {emitted}"
);
}
}
#[test]
fn no_clock_lands_a_sibling_clocks_store() {
let emitted = tight(&granting());
for (context, forbidden) in [
("ReaperHourlyGrants", "media::Transcript"),
("ReaperNightlyGrants", "media::Media"),
("ReaperNightlyGrants", "media::KeyframeVec"),
] {
let lands = format!("::ingraph::__private::drive::AsyncLands<{forbidden}>");
assert!(
!emitted.contains(&format!("{lands}for{context}<")),
"`{context}` mints no socket for `{forbidden}`: {emitted}"
);
}
}
#[test]
fn each_context_takes_its_own_handles_in_declaration_order() {
let emitted = tight(&granting());
for expected in [
"constfnnew(media:MediaHandle,keyframe_vec:KeyframeVecHandle)->Self",
"constfnnew(transcript:TranscriptHandle)->Self",
] {
assert!(emitted.contains(expected), "{expected}: {emitted}");
}
}
#[test]
fn the_lending_holds_one_context_per_granting_clock() {
let model = granting();
let file = emission(&model);
let lending = struct_named(&file, &default_polling_name(&model.record).to_string());
assert_eq!(
lending
.fields
.iter()
.map(|field| field.ident.as_ref().expect("a named field").to_string())
.collect::<Vec<_>>(),
["hourly", "nightly"],
);
assert_eq!(
lending
.generics
.type_params()
.map(|param| param.ident.to_string())
.collect::<Vec<_>>(),
["MediaHandle", "KeyframeVecHandle", "TranscriptHandle"],
);
assert!(
tight(&model).contains(
"constfnnew(hourly:ReaperHourlyGrants<MediaHandle,KeyframeVecHandle>,nightly:\
ReaperNightlyGrants<TranscriptHandle>)->Self"
),
"{}",
tight(&model),
);
}
#[test]
fn the_sweep_trait_seats_one_entry_per_clock() {
let mut model = granting();
let Some(polls) = model.polls.as_mut() else {
panic!("the fixture declares clocks");
};
polls.entries.insert(0, entry("watch", &[]));
let emitted = tight(&model);
let named = default_sweeps_name(&model.record).to_string();
assert!(
emitted.contains(&format!(
"trait{named}<MediaHandle,KeyframeVecHandle,TranscriptHandle>"
)),
"{emitted}"
);
for expected in [
"fnhourly(&mutself,grants:&mutReaperHourlyGrants<MediaHandle,KeyframeVecHandle>)->",
"fnnightly(&mutself,grants:&mutReaperNightlyGrants<TranscriptHandle>)->",
"fnwatch(&mutself)->",
] {
assert!(emitted.contains(expected), "{expected}: {emitted}");
}
assert_eq!(emitted.matches("typeInfo;").count(), 1, "{emitted}");
assert_eq!(emitted.matches("typeError;").count(), 1, "{emitted}");
assert!(
!emitted.contains("PollUpstream,)->impl::core::future"),
"{emitted}"
);
}
#[test]
fn the_lending_routes_every_clocks_position_to_its_entry() {
let mut model = granting();
let Some(polls) = model.polls.as_mut() else {
panic!("the fixture declares clocks");
};
polls.entries.insert(0, entry("watch", &[]));
let emitted = tight(&model);
assert!(
emitted.contains(
"impl<O,MediaHandle,KeyframeVecHandle,TranscriptHandle>::ingraph::__private::drive::Seats<O>\
forReaperPolling<MediaHandle,KeyframeVecHandle,TranscriptHandle>"
),
"{emitted}"
);
let sweeps = "<Oas ReaperSweeps<MediaHandle,KeyframeVecHandle,TranscriptHandle>>";
let ran = ".map(::ingraph::__private::drive::Swept::Ran),";
for expected in [
format!("matchsource.index(){{0usize=>{sweeps}::watch(operator).await{ran}"),
format!("1usize=>{sweeps}::hourly(operator,&mutself.hourly).await{ran}"),
format!("2usize=>{sweeps}::nightly(operator,&mutself.nightly).await{ran}"),
] {
let expected = expected.replace(' ', "");
assert!(emitted.contains(&expected), "{expected}: {emitted}");
}
assert!(
emitted.contains("structReaperPolling<MediaHandle,KeyframeVecHandle,TranscriptHandle>"),
"{emitted}"
);
assert!(!emitted.contains("watch:ReaperWatchGrants"), "{emitted}");
assert!(
emitted.contains(
"typeError=<Oas ReaperSweeps<MediaHandle,KeyframeVecHandle,TranscriptHandle>>::Error;"
.replace(' ', "")
.as_str()
),
"{emitted}"
);
}
#[test]
fn the_facts_impl_carries_one_grant_per_granted_store_naming_its_clock() {
let emitted = tight(&granting());
assert!(
emitted.contains(
"constGRANTS:&'static[::ingraph::__private::drive::Grant]=&[::ingraph::__private::drive::Grant::of::<media::Media>\
(\"hourly\",\"media::Media\"),::ingraph::__private::drive::Grant::of::<media::KeyframeVec>(\"hourly\",\
\"media::KeyframeVec\"),::ingraph::__private::drive::Grant::of::<media::Transcript>(\"nightly\",\
\"media::Transcript\"),]"
),
"{emitted}"
);
}
#[test]
fn one_store_granted_by_two_clocks_mints_two_contexts_and_two_handles() {
let mut model = model("Reaper", &["media_id"], "id");
model.polls = Some(Polls {
entries: vec![
entry("hourly", &["media::Media"]),
entry("nightly", &["media::Media"]),
],
});
let emitted = tight(&model);
assert!(
emitted.contains("structReaperHourlyGrants<MediaHandle>")
&& emitted.contains("structReaperNightlyGrants<NightlyMediaHandle>"),
"{emitted}"
);
assert!(
emitted.contains("structReaperPolling<MediaHandle,NightlyMediaHandle>"),
"{emitted}"
);
assert!(
emitted.contains("Grant::of::<media::Media>(\"hourly\",\"media::Media\")")
&& emitted.contains("Grant::of::<media::Media>(\"nightly\",\"media::Media\")"),
"{emitted}"
);
}
#[test]
fn a_node_with_no_grant_lends_the_sealed_empty_struct() {
let mut model = model("Plain", &["media_id"], "id");
model.polls = Some(Polls {
entries: vec![entry("watch", &[])],
});
let file = emission(&model);
let absent = poll_grants_name(&model.record, &format_ident!("Watch")).to_string();
assert!(
!file.items.iter().any(|item| matches!(
item,
syn::Item::Struct(item) if item.ident == absent
)),
"`{absent}` is not emitted for a clock that was granted nothing"
);
let emitted = tight(&model);
assert!(
emitted.contains("pubstructPlainPolling(());"),
"the sealed lending: {emitted}"
);
assert!(
emitted.contains("pubconstfnnew()->Self{Self(())}"),
"the empty-struct law's constructor: {emitted}"
);
assert!(
emitted.contains(&default_sweeps_name(&model.record).to_string()),
"an unmounted clock is still a sweep entry: {emitted}"
);
assert!(
emitted.contains("constGRANTS:&'static[::ingraph::__private::drive::Grant]=&[];"),
"{emitted}",
);
}
#[test]
fn an_all_mounted_node_emits_no_sweep_trait() {
let mut model = model("Exporter", &["media_id"], "id");
model.polls = Some(Polls {
entries: vec![
running("scrape", &[], PollMode::AsyncInline, Some("app::Scraper")),
running("push", &[], PollMode::Block, Some("app::Pusher")),
],
});
let emitted = tight(&model);
assert!(
!emitted.contains(&default_sweeps_name(&model.record).to_string()),
"{emitted}"
);
assert!(
emitted.contains("pubstructExporterPolling{"),
"the lending: {emitted}"
);
assert!(
emitted.contains("scrape_handler:app::Scraper,")
&& emitted.contains("push_handler:app::Pusher,"),
"the citizens: {emitted}"
);
assert!(
emitted.contains("typeInfo=<app::Scraperas::ingraph::__private::drive::AsyncTick<()>>::Info;"),
"the anchor: {emitted}"
);
}
#[test]
fn a_mounted_clock_leaves_the_sweep_trait() {
let mut model = model("Exporter", &["media_id"], "id");
model.polls = Some(Polls {
entries: vec![
running("scrape", &[], PollMode::AsyncInline, Some("app::Scraper")),
entry("watch", &[]),
],
});
let emitted = tight(&model);
assert!(emitted.contains("pubtraitExporterSweeps{"), "{emitted}");
assert!(emitted.contains("fnwatch(&mutself)->"), "{emitted}");
assert!(
!emitted.contains("fnscrape("),
"a mounted clock is not a sweep entry: {emitted}"
);
assert!(
emitted.contains(
"O:ExporterSweeps<Info=<app::Scraperas::ingraph::__private::drive::AsyncTick<()>>::Info,\
Error=<app::Scraperas::ingraph::__private::drive::AsyncTick<()>>::Error>"
),
"{emitted}"
);
}
#[test]
fn the_detached_words_default_to_the_shipped_citizens() {
let mut model = model("Exporter", &["media_id"], "id");
model.polls = Some(Polls {
entries: vec![
running("threaded", &[], PollMode::Spawn, Some("app::Scraper")),
running("pooled", &[], PollMode::Rayon, Some("app::Scraper")),
running("tasked", &[], PollMode::AsyncSpawn, Some("app::Scraper")),
],
});
let emitted = tight(&model);
assert!(
emitted.contains(
"pubstructExporterPolling<TaskedExecutor,ThreadedExecutor=::ingraph::__private::drive::Thread,\
PooledExecutor=::ingraph::__private::drive::Rayon>"
),
"{emitted}"
);
for held in [
"threaded_executor:ThreadedExecutor,",
"pooled_executor:PooledExecutor,",
"tasked_executor:TaskedExecutor,",
] {
assert!(emitted.contains(held), "{held}: {emitted}");
}
assert!(
emitted.contains("ThreadedExecutor:::ingraph::__private::drive::Spawn+::core::marker::Send")
&& emitted
.contains("TaskedExecutor:::ingraph::__private::drive::AsyncSpawn+::core::marker::Send"),
"{emitted}"
);
}
#[test]
fn the_at_most_one_cell_is_the_default_and_concurrent_removes_it() {
let mut model = model("Exporter", &["media_id"], "id");
model.polls = Some(Polls {
entries: vec![running(
"threaded",
&[],
PollMode::Spawn,
Some("app::Scraper"),
)],
});
let guarded = tight(&model);
assert!(
guarded.contains("threaded_in_flight:::ingraph::__private::drive::AtMostOne,"),
"{guarded}"
);
assert!(
guarded.contains("pubfnnew(threaded_handler:app::Scraper,threaded_executor:ThreadedExecutor)"),
"the cell is not an argument, and the constructor is no longer const: {guarded}"
);
let Some(polls) = model.polls.as_mut() else {
panic!("the fixture declares a clock");
};
polls.entries[0].concurrent = true;
let free = tight(&model);
assert!(!free.contains("threaded_in_flight"), "{free}");
assert!(
free
.contains("pubconstfnnew(threaded_handler:app::Scraper,threaded_executor:ThreadedExecutor)"),
"with no cell the constructor is const again: {free}"
);
}
#[test]
fn the_mode_word_decides_the_sweep_entrys_face() {
let mut model = model("Exporter", &["media_id"], "id");
model.polls = Some(Polls {
entries: vec![
running("here", &[], PollMode::Block, None),
running("awaited", &[], PollMode::AsyncInline, None),
],
});
let emitted = tight(&model);
assert!(
emitted.contains("fnhere(&mutself)->::core::result::Result<Self::Info,Self::Error>;"),
"{emitted}"
);
assert!(
emitted.contains("fnawaited(&mutself)->impl::core::future::Future<"),
"{emitted}"
);
assert!(
emitted.contains("0usize=><OasExporterSweeps>::here(operator).map("),
"{emitted}"
);
assert!(
emitted.contains("1usize=><OasExporterSweeps>::awaited(operator).await.map("),
"{emitted}"
);
}