use std::collections::BTreeMap;
use super::{Delegate, EnumModel, EnumVariant, Escape, GraphqlKind, Remote};
use crate::enumeration::DelegateSkin;
fn open() -> EnumModel {
escaping(Escape::Total)
}
fn escaping(posture: Escape) -> EnumModel {
let mut model = closed();
model.variants.push(EnumVariant {
ident: ident("Other"),
rename: None,
names: BTreeMap::new(),
upstream: None,
escape: Some(posture),
carrier: Some(syn::parse_quote!(::ingraph::Utf8Bytes)),
});
model
}
fn closed() -> EnumModel {
EnumModel {
krate: syn::parse_quote!(::ingraph),
vis: syn::parse_quote!(pub),
name: ident("PixelFormat"),
width: None,
variants: vec![variant("Yuv420p", None), variant("Rgb24", Some("Rgb888"))],
forms: BTreeMap::new(),
wire_name: None,
error: None,
remote: Some(Remote {
path: syn::parse_quote!(mediaframe::PixelFormat),
delegates: Vec::new(),
}),
}
}
fn variant(name: &str, upstream: Option<&str>) -> EnumVariant {
EnumVariant {
ident: ident(name),
rename: None,
names: BTreeMap::new(),
upstream: upstream.map(ident),
escape: None,
carrier: None,
}
}
fn ident(name: &str) -> syn::Ident {
syn::parse_str(name).expect("an identifier")
}
fn emission(model: &EnumModel) -> syn::File {
syn::parse2(model.emit()).expect("the expansion parses")
}
fn squashed(model: &EnumModel) -> String {
model.emit().to_string().replace(' ', "")
}
#[test]
fn a_mirror_emits_no_word_of_its_own() {
let squashed = squashed(&open());
assert!(
!squashed.contains("fnas_str"),
"a mirror has no canonical-word table: {squashed}"
);
assert!(
!squashed.contains("as_graphql_str"),
"a mirror has no per-face word: {squashed}"
);
assert!(
squashed.contains("impl::core::fmt::DisplayforPixelFormat"),
"the rendering is the upstream's, reached through `Display`: {squashed}"
);
}
#[test]
fn the_two_conversions_are_written_by_variant_name() {
let squashed = squashed(&open());
assert!(
squashed.contains("::core::convert::From<mediaframe::PixelFormat>forPixelFormat"),
"{squashed}"
);
assert!(
squashed.contains("::core::convert::From<PixelFormat>formediaframe::PixelFormat"),
"{squashed}"
);
assert!(
squashed.contains("mediaframe::PixelFormat::Yuv420p=>PixelFormat::Yuv420p"),
"a variant spelled alike restates itself: {squashed}"
);
assert!(
squashed.contains("mediaframe::PixelFormat::Rgb888=>PixelFormat::Rgb24"),
"`rename` names the UPSTREAM variant: {squashed}"
);
assert!(
squashed.contains("Self::Rgb24=>mediaframe::PixelFormat::Rgb888"),
"and it names it in both directions: {squashed}"
);
}
#[test]
fn an_open_mirror_absorbs_an_upstream_it_does_not_name() {
let squashed = squashed(&open());
assert!(
squashed.contains("__ingraph_unknown=>PixelFormat::Other(::core::convert::Into::into("),
"the unnamed upstream lands in the escape, carrying its word: {squashed}"
);
}
#[test]
fn a_closed_mirror_leaves_no_arm_for_an_unnamed_upstream() {
let squashed = squashed(&closed());
assert!(
!squashed.contains("__ingraph_unknown"),
"no wildcard: {squashed}"
);
assert!(
!squashed.contains("__IngraphTotalFromStr"),
"and no totality obligation, a closed upstream being allowed to refuse: {squashed}"
);
}
#[test]
fn an_open_mirror_names_the_totality_it_claims() {
let squashed = squashed(&open());
assert!(
squashed.contains("diagnostic::on_unimplemented"),
"the refusal is NAMED rather than an associated-type mismatch: {squashed}"
);
assert!(
squashed.contains("cannotbemirroredasanOPENvocabulary"),
"{squashed}"
);
assert!(
squashed.contains("<Tas::core::str::FromStr>::Err:__IngraphNever"),
"and the obligation is a BOUND on the refusal type, which is what carries a named \
diagnostic where an associated-type equality carries none: {squashed}"
);
}
#[test]
fn an_unconditional_gate_carries_the_totality_the_upstreams_type_does_not() {
let squashed = squashed(&escaping(Escape::Gate(syn::parse_quote!(
mediaframe::PixelFormat::other
))));
assert!(
!squashed.contains("__IngraphNever"),
"the bound on the upstream's error type is gone — the gate is where the totality is now: \
{squashed}"
);
assert!(
squashed.contains(
"fn__ingraph_upstream(text:&::core::primitive::str)->mediaframe::PixelFormat{match<mediaframe\
::PixelFormatas::core::str::FromStr>::from_str(text)"
),
"the door PARSES first and answers with an upstream value: {squashed}"
);
assert!(
squashed.contains(
"::core::result::Result::Err(_)=>__IngraphGate::__ingraph_gated(mediaframe::PixelFormat::\
other(text))"
),
"and gates only what the parse turned away: {squashed}"
);
assert!(
squashed.contains("impl__IngraphGateformediaframe::PixelFormat"),
"the gate's return type is checked against the upstream itself, which is what makes a gate \
answering with a `Result` a NAMED refusal: {squashed}"
);
assert!(
squashed.contains("typeErr=::core::convert::Infallible"),
"and the mirror is as open as a bare marker leaves it: {squashed}"
);
}
#[test]
fn a_refusable_gate_wraps_its_upstreams_own_refusal() {
let squashed = squashed(&escaping(Escape::TryGate(syn::parse_quote!(
mediaframe::PixelFormat::try_other
))));
assert!(
squashed.contains(
"fn__ingraph_upstream(text:&::core::primitive::str,)->::core::result::Result<mediaframe::\
PixelFormat,<mediaframe::PixelFormatas::core::str::FromStr>::Err>"
),
"the SAME-TYPE law is emitted as the projection, which is the only spelling this side can \
write without seeing the upstream's declaration: {squashed}"
);
assert!(
squashed.contains("pubstructPixelFormatParseError(())"),
"a half-open mirror casts the refusal type an open one has none of: {squashed}"
);
assert!(
squashed.contains("typeErr=PixelFormatParseError"),
"and answers with it: {squashed}"
);
assert!(
squashed.contains("::core::result::Result::Err(_)=>::core::option::Option::None"),
"the reader is the CLOSED mirror's, to the token, with the door spent where that one spends \
the upstream's parse: {squashed}"
);
assert!(
squashed.contains("::core::panic!"),
"and the escape's arm STOPS rather than substituting a value nobody wrote, `remote()` having \
no channel to report a refusal on: {squashed}"
);
}
#[test]
fn every_posture_keeps_the_absorbing_arm() {
for posture in [
Escape::Total,
Escape::Gate(syn::parse_quote!(mediaframe::PixelFormat::other)),
Escape::TryGate(syn::parse_quote!(mediaframe::PixelFormat::try_other)),
] {
let squashed = squashed(&escaping(posture));
assert!(
squashed.contains("__ingraph_unknown=>PixelFormat::Other"),
"the unnamed upstream lands in the escape: {squashed}"
);
}
}
#[test]
fn only_a_closed_mirror_declares_a_refusal_type() {
let open = squashed(&open());
let closed = squashed(&closed());
assert!(
!open.contains("structPixelFormatParseError"),
"an open mirror declares no refusal type: {open}"
);
assert!(
open.contains("typeErr=::core::convert::Infallible"),
"{open}"
);
assert!(
closed.contains("pubstructPixelFormatParseError(())"),
"a closed one does: {closed}"
);
assert!(closed.contains("typeErr=PixelFormatParseError"), "{closed}");
}
#[test]
fn a_mirror_stores_its_upstreams_word() {
let squashed = squashed(&open());
assert!(
squashed.contains("<::core::primitive::stras::ingraph::__private::sqlx::Type"),
"the column is text: {squashed}"
);
assert!(
!squashed.contains("as::core::primitive::i64"),
"and no discriminant is cast anywhere: {squashed}"
);
assert!(
squashed.contains("qb.push_bind(::std::string::ToString::to_string(self));"),
"the bind is the upstream's rendering: {squashed}"
);
}
#[test]
fn an_open_mirror_delegates_its_own_word_and_the_carried_one() {
let squashed = squashed(&open());
assert!(
squashed.contains("unsafeimpl::ingraph::__private::id::DelegatesIdforPixelFormat"),
"{squashed}"
);
assert!(
squashed.contains("typeInner=::ingraph::Utf8Bytes;"),
"{squashed}"
);
for word in ["\"Yuv420p\"", "\"Rgb24\""] {
assert!(
squashed.contains(&format!(
"<::ingraph::Utf8Bytesas__IngraphCarriesAWord>::__ingraph_word({word})"
)),
"{word}: {squashed}"
);
}
assert!(
!squashed.contains("\"Rgb888\""),
"the upstream identifier is not a word this vocabulary keys by: {squashed}"
);
assert!(
squashed.contains("Self::Other(__ingraph_word)=>__ingraph_word,"),
"the escape delegates the word it CARRIES: {squashed}"
);
}
#[test]
fn a_closed_mirror_keys_by_the_house_text_member() {
let squashed = squashed(&closed());
assert!(
squashed.contains("typeInner=::ingraph::__private::smol_bytes::Utf8Bytes;"),
"{squashed}"
);
assert!(
squashed.contains("::from_static(\"Yuv420p\")"),
"{squashed}"
);
assert!(!squashed.contains("Self::Other"), "{squashed}");
}
#[test]
fn the_wire_face_is_a_scalar_over_the_upstreams_grammar() {
let squashed = squashed(&open());
assert!(
squashed.contains(
"async_graphql::Scalar(crate=\"::ingraph::__private::async_graphql\",name=\"PixelFormat\")"
),
"{squashed}"
);
assert!(
!squashed.contains("resolver_utils::EnumType"),
"no member list is published, the upstream's set not being this crate's to freeze: {squashed}"
);
assert!(
squashed.contains("<Selfas::core::str::FromStr>::from_str(&__ingraph_text)"),
"the parse is this vocabulary's own, which is the upstream's: {squashed}"
);
}
#[test]
fn the_variant_list_is_the_restatement() {
let squashed = squashed(&open());
assert!(
squashed.contains("VARIANTS:&'static[Self]=&[Self::Yuv420p,Self::Rgb24]"),
"{squashed}"
);
assert!(
squashed.contains("pubconstfnis_other(&self)->::core::primitive::bool"),
"the escape still earns a predicate: {squashed}"
);
assert!(
squashed.contains("::core::matches!(self,Self::Other(..))"),
"matched with its word: {squashed}"
);
}
#[test]
fn a_delegate_forwards_onto_the_materialized_upstream() {
let mut model = open();
model.remote.as_mut().expect("a mirror").delegates =
vec![borrows(syn::parse_quote!(fn bits(&self, scale: u8) -> u8))];
let squashed = squashed(&model);
assert!(
squashed.contains("pubfnbits(&self,scale:u8)->u8"),
"{squashed}"
);
assert!(
squashed.contains("let__ingraph_remote=PixelFormat::remote(self);"),
"{squashed}"
);
assert!(
squashed.contains("__ingraph_remote.bits(scale)"),
"{squashed}"
);
}
#[test]
fn an_exclusive_delegate_writes_the_upstream_home() {
let mut model = open();
model.remote.as_mut().expect("a mirror").delegates =
vec![mutates(syn::parse_quote!(fn demote(&mut self) -> bool))];
let squashed = squashed(&model);
assert!(
squashed.contains("pubfndemote(&mutself)->bool"),
"{squashed}"
);
assert!(
squashed.contains("letmut__ingraph_remote=PixelFormat::remote(&*self);"),
"{squashed}"
);
assert!(
squashed.contains("let__ingraph_answer=__ingraph_remote.demote();"),
"{squashed}"
);
assert!(
squashed.contains("*self=<Selfas::core::convert::From<_>>::from(__ingraph_remote);"),
"and the answer is still the upstream's: {squashed}"
);
assert!(squashed.contains("__ingraph_answer}"), "{squashed}");
}
#[test]
fn an_unpublished_delegate_moves_no_wire_token() {
const BASE: &str = include_str!("unpromoted_wire_block.txt");
let bare = squashed(&open());
let mut model = open();
model.remote.as_mut().expect("a mirror").delegates = vec![
borrows(syn::parse_quote!(fn planar(&self) -> bool)),
mutates(syn::parse_quote!(fn demote(&mut self) -> bool)),
];
assert_eq!(
wire_face(&bare),
BASE,
"the wire face is what it was before the axis existed"
);
assert_eq!(
wire_face(&squashed(&model)),
BASE,
"an unpublished delegate is Rust and nothing else"
);
}
#[test]
fn a_waived_entry_mints_no_forwarding_half() {
let mut model = open();
model.remote.as_mut().expect("a mirror").delegates = vec![waives(published(
syn::parse_quote!(fn is_bayer(&self) -> bool),
None,
))];
let squashed = squashed(&model);
assert!(
!squashed.contains("__ingraph_remote.is_bayer()"),
"the forwarding half is not emitted: {squashed}"
);
assert!(
!squashed.contains("pubfnis_bayer(&self)->bool"),
"and no method head with it: {squashed}"
);
assert!(
squashed.contains("let__ingraph_answer=PixelFormat::is_bayer(self);"),
"the PROMOTED half is untouched, reaching the author's method through the mirror: {squashed}"
);
assert!(
squashed.contains(r#""isBayer""#),
"and it is still a field of the object: {squashed}"
);
}
#[test]
fn a_waiver_moves_one_entry_and_no_other() {
let entries = || {
vec![
published(syn::parse_quote!(fn is_bayer(&self) -> bool), None),
borrows(syn::parse_quote!(fn planar(&self) -> bool)),
]
};
let mut before = open();
before.remote.as_mut().expect("a mirror").delegates = entries();
let mut after = open();
let mirror = after.remote.as_mut().expect("a mirror");
mirror.delegates = entries();
mirror.delegates[0] = waives(mirror.delegates[0].clone());
let (before, after) = (squashed(&before), squashed(&after));
assert!(
before.contains("__ingraph_remote.is_bayer()"),
"without the word the entry mints: {before}"
);
assert!(!after.contains("__ingraph_remote.is_bayer()"), "{after}");
assert!(
after.contains("__ingraph_remote.planar()"),
"the entry beside it is minted unchanged: {after}"
);
assert!(
after.contains("let__ingraph_answer=PixelFormat::is_bayer(self);"),
"and the promoted half is where it was: {after}"
);
}
#[test]
fn a_published_delegate_mints_an_object_and_an_input_scalar() {
let mut model = open();
model.remote.as_mut().expect("a mirror").delegates = vec![
published(syn::parse_quote!(fn is_bayer(&self) -> bool), None),
published(syn::parse_quote!(fn is_hdr(&self) -> bool), Some("bayer")),
borrows(syn::parse_quote!(fn planar(&self) -> bool)),
];
let squashed = squashed(&model);
assert!(
squashed.contains("MetaTypeId::Object"),
"the output seat is an object: {squashed}"
);
assert!(
squashed.contains(r#"::std::string::String::from("PixelFormatInput")"#),
"and the scalar took the input name: {squashed}"
);
assert!(
!squashed.contains("#[::ingraph::__private::async_graphql::Scalar"),
"the library's own attribute is gone, its `OutputType` being ours now: {squashed}"
);
for word in [r#""text""#, r#""isBayer""#, r#""bayer""#] {
assert!(squashed.contains(word), "missing field {word}: {squashed}");
}
assert!(
!squashed.contains(r#""planar""#),
"and an unpublished delegate is not a field: {squashed}"
);
}
#[test]
fn a_published_rename_is_a_string_in_two_places() {
let mut model = open();
model.remote.as_mut().expect("a mirror").delegates = vec![published(
syn::parse_quote!(fn is_hdr(&self) -> bool),
Some("bayer"),
)];
let squashed = squashed(&model);
assert!(
squashed.contains(r#""bayer"=>{let__ingraph_answer=PixelFormat::is_hdr(self);"#),
"the arm calls the method under its OWN name: {squashed}"
);
assert!(
!squashed.contains("__bayer_resolver"),
"and mints nothing to reach it by: {squashed}"
);
}
fn wire_face(squashed: &str) -> &str {
let at = squashed.rfind("const_:()={").expect("the wire block");
&squashed[at..]
}
fn borrows(signature: syn::Signature) -> Delegate {
Delegate {
signature,
exclusive: false,
wire: Vec::new(),
on_self: None,
}
}
fn mutates(signature: syn::Signature) -> Delegate {
Delegate {
signature,
exclusive: true,
wire: Vec::new(),
on_self: None,
}
}
fn waives(delegate: Delegate) -> Delegate {
Delegate {
on_self: Some(syn::Ident::new("self", proc_macro2::Span::call_site())),
..delegate
}
}
fn published(signature: syn::Signature, rename: Option<&str>) -> Delegate {
Delegate {
signature,
exclusive: false,
wire: vec![DelegateSkin {
kind: GraphqlKind::AsyncGraphql,
rename: rename.map(|word| syn::parse_str(&format!("{word:?}")).expect("a literal")),
}],
on_self: None,
}
}
#[test]
fn a_mirror_is_filtered_as_a_vocabulary() {
let squashed = squashed(&open());
for row in [
"::ingraph::__private::marker::EnumFilterMarkerforPixelFormat",
"::ingraph::__private::marker::DefaultMarkerforPixelFormat",
"::ingraph::__private::marker::DefaultVecMarkerforPixelFormat",
"::ingraph::__private::cursor::CursorValueforPixelFormat",
] {
assert!(squashed.contains(row), "missing {row}: {squashed}");
}
}
#[test]
fn the_expansion_parses_as_two_blocks_beside_what_it_declares() {
for (model, declared) in [(open(), 0), (closed(), 1)] {
let file = emission(&model);
let blocks = file
.items
.iter()
.filter(|item| matches!(item, syn::Item::Const(anonymous) if anonymous.ident == "_"))
.count();
let outside = file
.items
.iter()
.filter(|item| matches!(item, syn::Item::Struct(_)))
.count();
assert_eq!(blocks, 2, "the rows and the wire face");
assert_eq!(outside, declared, "and what stands beside the enum");
}
}
fn declared(model: &EnumModel) -> Vec<String> {
let file: syn::File = syn::parse2(model.emit()).expect("the expansion parses");
file
.items
.iter()
.filter_map(|item| match item {
syn::Item::Const(anonymous) if anonymous.ident == "_" => match anonymous.expr.as_ref() {
syn::Expr::Block(block) => Some(&block.block.stmts),
_ => None,
},
_ => None,
})
.flatten()
.filter_map(|stmt| match stmt {
syn::Stmt::Item(syn::Item::Impl(item)) if item.trait_.is_none() => Some(&item.items),
_ => None,
})
.flatten()
.filter_map(|item| match item {
syn::ImplItem::Fn(item) => Some(item.sig.ident.to_string()),
syn::ImplItem::Const(item) => Some(item.ident.to_string()),
_ => None,
})
.collect()
}
fn enumerated(model: &EnumModel) -> Vec<String> {
model
.emitted_methods()
.iter()
.map(|emitted| emitted.name.to_string())
.collect()
}
#[test]
fn the_enumeration_names_exactly_the_items_the_emission_declares() {
let mut delegating = open();
delegating.remote.as_mut().expect("a mirror").delegates = vec![
borrows(syn::parse_quote!(fn planar(&self) -> bool)),
published(syn::parse_quote!(fn is_bayer_grid(&self) -> bool), None),
mutates(syn::parse_quote!(fn demote(&mut self) -> bool)),
];
let half_open = escaping(Escape::TryGate(syn::parse_quote!(
mediaframe::PixelFormat::try_other
)));
for model in [closed(), open(), half_open, delegating] {
assert_eq!(enumerated(&model), declared(&model), "`{}`", model.name);
}
}
#[test]
fn a_declared_vocabulary_puts_no_authored_name_in_its_namespace() {
let vocabulary = EnumModel {
remote: None,
..open()
};
assert!(
vocabulary.emitted_methods().is_empty(),
"the accessor answers about the MODE, so a caller needs no second question first"
);
assert!(
!declared(&vocabulary).is_empty(),
"and the emission still declares names — they are simply nobody's to collide with"
);
}
#[test]
fn a_waived_entry_is_enumerated_and_never_emitted() {
let mut model = open();
model.remote.as_mut().expect("a mirror").delegates = vec![waives(published(
syn::parse_quote!(fn depth(&self) -> u32),
None,
))];
assert!(
enumerated(&model).contains(&"depth".to_owned()),
"the author's own method occupies the namespace: {:?}",
enumerated(&model)
);
assert!(
!declared(&model).contains(&"depth".to_owned()),
"and the emission wrote no forwarding half for it: {:?}",
declared(&model)
);
}