use quote::ToTokens as _;
use super::{
Dedup, Elected, ElectionBackend, ElectionLabel, FieldNumbers, IndexBackend, IndexGraphql,
IndexModel, IndexRename, Numbers, Upstream,
};
use crate::{
engine::{Engine, FieldEngines},
model::{GraphqlKind, NodeKind, Role},
prefix::EmissionPrefix,
};
fn ident(name: &str) -> syn::Ident {
syn::Ident::new(name, proc_macro2::Span::call_site())
}
fn leg(word: &str, typed: bool) -> Engine {
Engine {
resource: typed.then(|| syn::parse_quote!(crate::Store)),
..Engine::bare(ident(word))
}
}
fn declared(legs: Vec<Engine>, fanout: bool, label: ElectionLabel) -> IndexModel {
IndexModel {
prefix: EmissionPrefix::default(),
numbers: Numbers::default(),
field_numbers: Vec::new(),
index: ident("Shots"),
kind: NodeKind::Vector,
vis: syn::parse_quote!(pub),
krate: syn::parse_quote!(::ingraph),
source: Upstream {
node: syn::parse_quote!(Keyframe),
projections: Vec::new(),
},
dedup: Dedup::Hash,
embeddings: vec![Elected::new(
ident("clip"),
label,
syn::parse_quote!(::ingraph::Embedding<f32, 4, Clip>),
None,
)],
labelled: Vec::new(),
searchable: Vec::new(),
engines: vec![FieldEngines {
field: ident("clip"),
engines: legs,
fanout,
}],
stores: Vec::new(),
data: false,
keys: false,
subscribe: false,
extension: None,
graphql: Some(IndexGraphql::of(GraphqlKind::AsyncGraphql)),
rename: None,
slot: None,
fields: Vec::new(),
}
}
pub(super) fn plain() -> IndexModel {
declared(vec![leg("toy", true)], false, ElectionLabel::Embedding)
}
pub(super) fn fanned() -> IndexModel {
declared(
vec![leg("deep", true), leg("shallow", true)],
true,
ElectionLabel::Embedding,
)
}
fn tight(model: &IndexModel) -> String {
model.emit().to_string().split_whitespace().collect()
}
fn landed(model: &IndexModel) -> Vec<String> {
let file: syn::File = syn::parse2(model.emit()).expect("the emission parses");
file
.items
.into_iter()
.filter_map(|item| match item {
syn::Item::Struct(declared) => Some(declared.ident.to_string()),
syn::Item::Enum(declared) => Some(declared.ident.to_string()),
_ => None,
})
.collect()
}
pub(super) fn fields(model: &IndexModel) -> Vec<String> {
let file: syn::File = syn::parse2(model.emit()).expect("the emission parses");
let unit = model.queries_name();
crate::tests::ungate(file.items)
.into_iter()
.flat_map(|item| match item {
syn::Item::Const(anonymous) => match *anonymous.expr {
syn::Expr::Block(block) => block
.block
.stmts
.into_iter()
.filter_map(|statement| match statement {
syn::Stmt::Item(syn::Item::Impl(block)) => Some(block),
_ => None,
})
.collect::<Vec<_>>(),
_ => Vec::new(),
},
_ => Vec::new(),
})
.filter(|block| block.trait_.is_none() && unit == block.self_ty.to_token_stream().to_string())
.flat_map(|block| block.items)
.filter_map(|item| match item {
syn::ImplItem::Fn(method) => method.attrs.iter().find_map(|attribute| {
let written = attribute.to_token_stream().to_string().replace(' ', "");
written
.strip_prefix("#[graphql(name=\"")
.and_then(|rest| rest.strip_suffix("\")]"))
.map(ToOwned::to_owned)
}),
_ => None,
})
.collect()
}
#[test]
fn a_typed_unfanned_election_publishes_the_plain_road_at_both_tiers() {
let model = plain();
assert_eq!(
fields(&model),
vec![
"shotsByClipKeys".to_owned(),
"shotsSimilarByClipKeys".to_owned(),
"shotsByClip".to_owned(),
"shotsSimilarByClip".to_owned(),
],
);
let landed = landed(&model);
assert!(
landed.contains(&"ShotsClipQuestion".to_owned()),
"{landed:?}"
);
for absent in [
"ShotsClipFusedKeyMatch",
"ShotsClipSighting",
"ShotsClipEngines",
] {
assert!(
!landed.contains(&absent.to_owned()),
"the plain road minted a fused type: {landed:?}",
);
}
}
#[test]
fn the_keys_road_answers_the_frameworks_own_hit() {
let emitted = tight(&plain());
assert!(
emitted.contains("::ingraph::__private::graphql::Match<"),
"{emitted}",
);
assert!(
emitted.contains("::ingraph::__private::graphql::matches"),
"{emitted}",
);
assert!(
!landed(&plain()).contains(&"ShotsClipKeyMatch".to_owned()),
"a second hit shape was minted beside the framework's",
);
}
#[test]
fn a_fanned_election_publishes_the_fused_road() {
let model = fanned();
assert_eq!(fields(&model), vec!["shotsFusedByClipKeys".to_owned()]);
let landed = landed(&model);
for minted in [
"ShotsClipQuestion",
"ShotsClipEngines",
"ShotsClipDeepSighting",
"ShotsClipShallowSighting",
"ShotsClipSighting",
"ShotsClipFusedKeyMatch",
] {
assert!(landed.contains(&minted.to_owned()), "{minted}: {landed:?}");
}
}
#[test]
fn an_untyped_election_publishes_nothing() {
let model = declared(vec![leg("toy", false)], false, ElectionLabel::Embedding);
assert!(fields(&model).is_empty(), "{:?}", fields(&model));
assert!(
!landed(&model).contains(&"ShotsClipQuestion".to_owned()),
"{:?}",
landed(&model),
);
}
#[test]
fn an_undressed_declaration_publishes_nothing() {
let model = IndexModel {
prefix: EmissionPrefix::default(),
graphql: None,
..plain()
};
assert!(fields(&model).is_empty());
assert!(!landed(&model).contains(&"ShotsClipQuestion".to_owned()));
}
#[test]
fn a_fan_with_an_untyped_leg_publishes_no_fused_road() {
let model = declared(
vec![leg("deep", true), leg("shallow", false)],
true,
ElectionLabel::Embedding,
);
assert!(fields(&model).is_empty(), "{:?}", fields(&model));
assert!(!landed(&model).contains(&"ShotsClipFusedKeyMatch".to_owned()));
}
#[test]
fn a_fanned_set_election_publishes_no_fused_road() {
let model = declared(
vec![leg("deep", true), leg("shallow", true)],
true,
ElectionLabel::List,
);
assert!(fields(&model).is_empty(), "{:?}", fields(&model));
}
#[test]
fn every_answer_type_is_a_module_scope_item() {
let landed = landed(&fanned());
for minted in [
"ShotsClipQuestion",
"ShotsClipEngines",
"ShotsClipDeepSighting",
"ShotsClipSighting",
"ShotsClipFusedKeyMatch",
] {
assert!(landed.contains(&minted.to_owned()), "{minted}: {landed:?}");
}
}
#[test]
fn the_roster_names_every_answer_type() {
for model in [plain(), fanned()] {
let rostered: Vec<String> = model
.emitted_types()
.iter()
.map(|declared| declared.name.to_string())
.collect();
assert_eq!(landed(&model), rostered);
}
assert!(
fanned()
.emitted_types()
.iter()
.any(|declared| matches!(&declared.role, Role::Answer(field) if field == "clip")),
);
}
#[test]
fn the_base_rename_moves_the_answer_family_and_its_fields() {
let renamed = IndexModel {
prefix: EmissionPrefix::default(),
rename: Some(IndexRename::Base(ident("ShotSearch"))),
..fanned()
};
assert_eq!(
fields(&renamed),
vec!["shotSearchFusedByClipKeys".to_owned()]
);
assert!(
landed(&renamed).contains(&"ShotSearchClipFusedKeyMatch".to_owned()),
"{:?}",
landed(&renamed),
);
assert!(
!landed(&renamed).contains(&"ShotsClipFusedKeyMatch".to_owned()),
"a name kept the old stem",
);
}
#[test]
fn a_skin_prefix_moves_the_published_names_alone() {
let mut skin = IndexBackend::of(GraphqlKind::AsyncGraphql);
skin.prefix = Some(syn::LitStr::new("Reels", proc_macro2::Span::call_site()));
let model = IndexModel {
prefix: EmissionPrefix::default(),
graphql: Some(IndexGraphql {
backends: vec![skin],
}),
..plain()
};
let emitted = tight(&model);
assert!(
emitted.contains(r#"Cow::Borrowed("ReelsClipQuestion")"#),
"{emitted}"
);
assert!(
landed(&model).contains(&"ShotsClipQuestion".to_owned()),
"the Rust name moved with a schema word",
);
}
#[test]
fn a_declared_word_names_one_field_and_no_other() {
let named = |keys: Option<&str>, fused: Option<&str>, similar: Option<&str>| ElectionBackend {
keys: keys.map(|word| syn::LitStr::new(word, proc_macro2::Span::call_site())),
fused: fused.map(|word| syn::LitStr::new(word, proc_macro2::Span::call_site())),
similar: similar.map(|word| syn::LitStr::new(word, proc_macro2::Span::call_site())),
..ElectionBackend::of(GraphqlKind::AsyncGraphql)
};
let renamed = IndexModel {
prefix: EmissionPrefix::default(),
field_numbers: vec![FieldNumbers {
field: ident("clip"),
numbers: Numbers::default(),
skins: vec![named(Some("clipNeighbours"), None, None)],
}],
..plain()
};
assert_eq!(
fields(&renamed),
vec![
"clipNeighbours".to_owned(),
"shotsSimilarByClipKeys".to_owned(),
"shotsByClip".to_owned(),
"shotsSimilarByClip".to_owned(),
],
"the question road's word moved the by-example field or its own hydrated twin",
);
let renamed = IndexModel {
prefix: EmissionPrefix::default(),
field_numbers: vec![FieldNumbers {
field: ident("clip"),
numbers: Numbers::default(),
skins: vec![named(None, None, Some("clipLikeThis"))],
}],
..plain()
};
assert_eq!(
fields(&renamed),
vec![
"shotsByClipKeys".to_owned(),
"clipLikeThis".to_owned(),
"shotsByClip".to_owned(),
"shotsSimilarByClip".to_owned(),
],
"the by-example word moved the question field or its own hydrated twin",
);
let renamed = IndexModel {
prefix: EmissionPrefix::default(),
field_numbers: vec![FieldNumbers {
field: ident("clip"),
numbers: Numbers::default(),
skins: vec![named(
Some("clipNeighbours"),
Some("clipEverywhere"),
Some("clipLikeThis"),
)],
}],
..fanned()
};
assert_eq!(fields(&renamed), vec!["clipEverywhere".to_owned()]);
}
#[test]
fn the_published_numbers_are_the_resolved_chain() {
let model = IndexModel {
prefix: EmissionPrefix::default(),
field_numbers: vec![FieldNumbers {
field: ident("clip"),
numbers: Numbers::default(),
skins: vec![ElectionBackend {
first: core::num::NonZeroU32::new(7),
..ElectionBackend::of(GraphqlKind::AsyncGraphql)
}],
}],
..plain()
};
let emitted = tight(&model);
assert!(
emitted.contains(r#"#[graphql(name="first",default=7)]"#),
"{emitted}"
);
assert!(emitted.contains(r#"#[graphql(name="depth")]"#), "{emitted}");
assert!(!emitted.contains(r#"name="ceiling""#), "{emitted}");
}
#[test]
fn the_declared_ceiling_caps_the_published_default() {
let model = IndexModel {
prefix: EmissionPrefix::default(),
numbers: Numbers {
limit: core::num::NonZeroU32::new(50),
depth: None,
ceiling: core::num::NonZeroU32::new(4),
streams: None,
},
..plain()
};
assert!(
tight(&model).contains(r#"#[graphql(name="first",default=4)]"#),
"{}",
tight(&model),
);
}
#[test]
fn a_full_text_declaration_publishes_no_answer_family() {
let model = IndexModel {
prefix: EmissionPrefix::default(),
kind: NodeKind::Fulltext,
embeddings: Vec::new(),
searchable: vec![ident("body")],
..plain()
};
assert!(fields(&model).is_empty(), "{:?}", fields(&model));
}