use ingraph_codegen::{fields::FieldsModel, prelude::*};
use quote::ToTokens as _;
fn parse(input: &syn::DeriveInput) -> syn::Result<ingraph_codegen::fields::FieldsModel> {
let (host, mut arguments) = crate::host::split(input);
arguments.push(syn::parse_quote!(#[ingraph(record, entity, graphql)]));
super::parse(&host, &arguments)
}
fn unactivated(input: &syn::DeriveInput) -> syn::Result<ingraph_codegen::fields::FieldsModel> {
let (host, arguments) = crate::host::split(input);
super::parse(&host, &arguments)
}
fn names(model: &FieldsModel) -> Vec<String> {
model
.fields
.iter()
.map(|field| field.column.name.to_string())
.collect()
}
fn refusals(input: syn::DeriveInput) -> String {
parse(&input)
.expect_err("the declaration is refused")
.into_iter()
.map(|e| e.to_string())
.collect::<Vec<_>>()
.join("\n")
}
#[test]
fn a_fragment_is_its_fields_in_order() {
let m = parse(&syn::parse_quote! {
pub struct Dimensions {
#[ingraph(copy)] width: u32,
#[ingraph(copy)] height: u32,
label: String,
}
})
.expect("a field-fragment declaration");
assert_eq!(names(&m), ["width", "height", "label"]);
assert_eq!(m.fragment, "Dimensions");
}
#[test]
fn the_three_projection_words_reach_the_model() {
let m = parse(&syn::parse_quote! {
struct Shape {
#[ingraph(copy)] width: u32,
#[ingraph(repeated)] tags: Vec<String>,
#[ingraph(optional)] note: Option<String>,
plain: String,
}
})
.expect("a field-fragment declaration");
let project = |name: &str| {
m.fields
.iter()
.map(|field| &field.column)
.find(|column| column.name == name)
.unwrap_or_else(|| panic!("`{name}` is a field"))
.project
};
assert_eq!(project("width"), Projection::Copied);
assert_eq!(project("tags"), Projection::Repeated);
assert_eq!(project("note"), Projection::Optional);
assert_eq!(
project("plain"),
Projection::Borrowed,
"and none is the default"
);
}
#[test]
fn the_crate_path_defaults_and_is_moveable() {
let m = parse(&syn::parse_quote! { struct D { w: u32 } }).expect("the default");
assert_eq!(m.krate.to_token_stream().to_string(), ":: ingraph");
let m = parse(&syn::parse_quote! {
#[ingraph(crate = "shim::vendored")]
struct D { w: u32 }
})
.expect("a re-export shim");
assert_eq!(m.krate.to_token_stream().to_string(), "shim :: vendored");
}
#[test]
fn every_family_a_node_claims_is_refused_by_name() {
let e = refusals(syn::parse_quote! {
#[ingraph(
subscribe = "a::A",
implements(Media),
key(rename = "DKey"),
lineage(fields(a)),
sqlite,
fulltext(tantivy),
vector(lance),
blob(fs))]
struct D { a: u32 }
});
for rule in [
"a field fragment subscribes to nothing",
"an interface's members are NODES WITH ROWS",
"a field fragment has no key",
"a field fragment has no lineage",
"a field fragment is stored in no table of its own",
"a field fragment owns no full-text index",
"a field fragment owns no embedding index",
"a field fragment owns no artifact store",
] {
assert!(e.contains(rule), "missing `{rule}` in: {e}");
}
assert!(
e.contains("A field fragment is HELD by whatever declares it"),
"and every one of them carries the tier's own reason: {e}"
);
assert!(
e.contains("is an `entity`, and one that holds rows besides is a `record`"),
"which names BOTH rungs above it, so a migrating author reads which one they wanted: {e}"
);
}
#[test]
fn a_fragment_has_no_id_and_the_refusal_says_why() {
let e = refusals(syn::parse_quote! { struct D { #[ingraph(id)] id: u128, w: u32 } });
assert!(
e.contains("cannot be a fragment's id, because a fragment has none")
&& e.contains("bearing no identity is what this tier means"),
"{e}"
);
}
#[test]
fn a_reference_out_of_a_fragment_is_named_and_tracked() {
let e = refusals(syn::parse_quote! {
struct D { #[ingraph(ref = "media::Media")] media: MediaId, w: u32 }
});
assert!(
e.contains("cannot reference another node from inside a fragment") && e.contains("issues/168"),
"{e}"
);
}
#[test]
fn the_inherited_field_grammar_is_a_named_refuse_until() {
let e = refusals(syn::parse_quote! {
struct D { #[ingraph(string)] label: String }
});
assert!(
e.contains("a fragment's field takes the projection words")
&& e.contains("inherited by every holder"),
"{e}"
);
}
#[test]
fn a_fragment_with_no_fields_extracts_nothing() {
let e = refusals(syn::parse_quote! { struct D {} });
assert!(
e.contains("a field fragment with no fields extracts nothing"),
"{e}"
);
}
#[test]
fn the_shape_rules_are_the_tiers_own() {
let e = refusals(syn::parse_quote! { enum D { A } });
assert!(
e.contains("`#[ingraph::fields(record, entity)]` supports structs only"),
"{e}"
);
let e = refusals(syn::parse_quote! { struct D(u32); });
assert!(
e.contains("what a holder inherits is a field's name as much as its type"),
"{e}"
);
let e = refusals(syn::parse_quote! { struct D<T> { w: T } });
assert!(
e.contains("generic field fragments are not supported"),
"{e}"
);
}
#[test]
fn the_emission_rules_hold_over_a_fragment_too() {
let e = refusals(syn::parse_quote! { struct D { __width__: u32 } });
assert!(
e.contains("__width__"),
"the framework namespace is fenced: {e}"
);
let e = refusals(syn::parse_quote! {
struct D { width: u32, #[ingraph(copy)] set_width: u32 }
});
assert!(e.contains("would declare `set_width` twice"), "{e}");
}
#[test]
fn the_rewrite_word_reaches_the_model_and_is_declared_once() {
let m = parse(&syn::parse_quote! {
#[ingraph(remote = "upstream::Dimensions")]
struct D { #[ingraph(copy)] width: u32 }
})
.expect("a wrapping fragment");
assert_eq!(
m.remote
.as_ref()
.expect("the word reached the model")
.to_token_stream()
.to_string(),
"upstream :: Dimensions"
);
assert!(
parse(&syn::parse_quote! { struct D { w: u32 } })
.expect("an ordinary fragment")
.remote
.is_none()
);
let e = refusals(syn::parse_quote! {
#[ingraph(remote = "a::A", remote = "b::B")]
struct D { w: u32 }
});
assert!(e.contains("one declaration wraps one type"), "{e}");
}
#[test]
fn a_wrapping_fragment_does_not_choose_its_own_representation() {
let e = refusals(syn::parse_quote! {
#[repr(C)]
#[ingraph(remote = "upstream::Dimensions")]
struct D { w: u32 }
});
assert!(
e.contains("does not choose its own representation"),
"the wrapper's `repr(transparent)` is the emission's: {e}"
);
parse(&syn::parse_quote! {
#[repr(C)]
struct D { w: u32 }
})
.expect("an ordinary fragment keeps its own item, and its own representation with it");
}
#[test]
fn a_manifest_field_carries_no_attribute_that_cannot_land() {
let e = refusals(syn::parse_quote! {
#[ingraph(remote = "upstream::Dimensions")]
struct D { #[serde(skip)] w: u32 }
});
assert!(
e.contains("is a MANIFEST entry") && e.contains("Doc comments migrate to the field's reader"),
"{e}"
);
parse(&syn::parse_quote! {
struct D { #[serde(skip)] w: u32 }
})
.expect("an ordinary fragment's field is a real field, and carries what its author wrote");
}
#[test]
fn a_wrapping_fragment_still_bears_no_id() {
let e = refusals(syn::parse_quote! {
#[ingraph(remote = "upstream::Frame")]
struct D { #[ingraph(id)] id: u128, #[ingraph(copy)] width: u32 }
});
assert!(
e.contains("cannot be a fragment's id, because a fragment has none")
&& e.contains("bearing no identity is what this tier means"),
"{e}"
);
}
#[test]
fn an_unknown_entry_names_the_words_a_fragment_takes() {
let e = refusals(syn::parse_quote! {
#[ingraph(derived(a))]
struct D { w: u32 }
});
assert!(
e.contains("it takes its HOST-KIND activations (`record[(<db>, …)]`, `entity`)")
&& e.contains(
"`crate = \"…\"`, `remote = \"…\"`, `builder(…)`, `cursor[(…)]`, `filter = \"…\"` and \
`delegate(fn …)`"
),
"{e}"
);
}
#[test]
fn a_declaration_that_names_no_host_kind_is_refused() {
let e = unactivated(&syn::parse_quote! {
struct Dimensions { #[ingraph(copy)] width: u32 }
})
.expect_err("no host kind is a refusal")
.to_string();
assert!(
e.contains("activates no host kind, so no declaration can consume it")
&& e.contains("`record[(<db>, …)]`")
&& e.contains("write `entity` to be held by the rung that bears an identity and no rows"),
"{e}"
);
}
#[test]
fn one_word_is_an_activation_and_two_are_two() {
let stored = unactivated(&syn::parse_quote! {
#[ingraph(record(sqlite, postgres))]
struct Dimensions { #[ingraph(copy)] width: u32 }
})
.expect("a record-hosted fragment");
assert_eq!(
stored
.record
.as_ref()
.expect("the activation")
.databases
.iter()
.map(|db| db.kind.as_str())
.collect::<Vec<_>>(),
["sqlite", "postgres"]
);
assert!(!stored.entity);
let held = unactivated(&syn::parse_quote! {
#[ingraph(entity)]
struct Dimensions { #[ingraph(copy)] width: u32 }
})
.expect("an entity-hosted fragment");
assert!(held.record.is_none() && held.entity);
let both = unactivated(&syn::parse_quote! {
#[ingraph(record, entity)]
struct Dimensions { #[ingraph(copy)] width: u32 }
})
.expect("a fragment both kinds may hold");
assert!(
both
.record
.as_ref()
.expect("the activation")
.databases
.is_empty()
&& both.entity
);
}
#[test]
fn entity_hosting_has_nothing_to_configure_yet() {
for written in [
quote::quote!(entity(anything)),
quote::quote!(entity = "yes"),
quote::quote!(entity()),
] {
let e = unactivated(&syn::parse_quote! {
#[ingraph(#written, record)]
struct D { w: u32 }
})
.expect_err("the door refuses a configuration")
.to_string();
assert!(
e.contains("entity-hosting has nothing to configure yet")
&& e.contains("a configuration you need is a ruling away"),
"{written}: {e}"
);
}
}
#[test]
fn the_record_namespace_names_databases_and_nothing_else() {
let e = unactivated(&syn::parse_quote! {
#[ingraph(record(table = "frames"))]
struct D { w: u32 }
})
.expect_err("the row's own word is refused")
.to_string();
assert!(
e.contains("the namespace names DIALECTS")
&& e.contains("`table` and `schema` name where a row lives"),
"{e}"
);
let twice = unactivated(&syn::parse_quote! {
#[ingraph(record(sqlite, sqlite))]
struct D { w: u32 }
})
.expect_err("one entry per database")
.to_string();
assert!(
twice.contains("is named more than once in `record(…)`"),
"{twice}"
);
}
#[test]
fn the_wire_face_is_declared_and_names_its_two_types() {
let silent = unactivated(&syn::parse_quote! {
#[ingraph(record)]
struct Dimensions { #[ingraph(copy)] width: u32 }
})
.expect("a storage-only fragment");
assert!(
silent.wire.is_none(),
"a fragment publishes nothing unless it asks"
);
let named = unactivated(&syn::parse_quote! {
#[ingraph(record, graphql(rename = "Size", filter(rename = "SizeWhere")))]
struct Dimensions { #[ingraph(copy)] width: u32 }
})
.expect("a published fragment");
let face = named.wire.as_ref().expect("the activation");
assert_eq!(
face.object.as_ref().map(|name| name.external()),
Some("Size")
);
assert_eq!(
face.filter.as_ref().map(|name| name.external()),
Some("SizeWhere")
);
let bare = unactivated(&syn::parse_quote! {
#[ingraph(record, graphql)]
struct Dimensions { #[ingraph(copy)] width: u32 }
})
.expect("a published fragment that renames nothing");
let face = bare.wire.as_ref().expect("the activation");
assert!(face.object.is_none() && face.filter.is_none());
}
#[test]
fn a_fragments_wire_block_names_types_and_never_a_root() {
let e = unactivated(&syn::parse_quote! {
#[ingraph(record, graphql(plural = "sizes"))]
struct Dimensions { #[ingraph(copy)] width: u32 }
})
.expect_err("a root word")
.to_string();
assert!(
e.contains("the queryable-root words (`plural`, `connection`, `edge`, `key`, `order_by`)")
&& e.contains("a fragment shows on the wire as a fragment of whatever holds it"),
"{e}"
);
}
#[test]
fn a_field_names_itself_only_where_there_is_a_face() {
let m = unactivated(&syn::parse_quote! {
#[ingraph(record, graphql)]
struct Dimensions {
#[ingraph(copy, graphql(rename = "w"))]
width: u32,
}
})
.expect("a renamed field");
assert_eq!(m.fields[0].wire_name.as_deref(), Some("w"));
let e = unactivated(&syn::parse_quote! {
#[ingraph(record)]
struct Dimensions {
#[ingraph(copy, graphql(rename = "w"))]
width: u32,
}
})
.expect_err("a name on nothing")
.to_string();
assert!(
e.contains("names itself on a wire face this fragment does not have"),
"{e}"
);
}
#[test]
fn a_cursor_needs_the_record_host() {
let e = unactivated(&syn::parse_quote! {
#[ingraph(entity, cursor)]
struct CalendarDay { #[ingraph(copy)] year: i32 }
})
.expect_err("an entity-only fragment pages nothing")
.to_string();
assert!(
e.contains("paging is the record host's")
&& e.contains("add `record[(<db>, …)]` beside the word"),
"{e}"
);
}
#[test]
fn the_bare_cursor_word_is_the_declared_order() {
let m = parse(&syn::parse_quote! {
#[ingraph(cursor)]
pub struct CalendarDay {
#[ingraph(copy)] year: i32,
#[ingraph(copy)] month: i32,
}
})
.expect("the word parses");
assert_eq!(m.cursor.as_deref(), Some(&[][..]));
}
#[test]
fn a_pinned_cursor_key_is_the_declaration_spelled_out() {
let m = parse(&syn::parse_quote! {
#[ingraph(cursor(year, month))]
pub struct CalendarDay {
#[ingraph(copy)] year: i32,
#[ingraph(copy)] month: i32,
}
})
.expect("the pin holds");
assert_eq!(
m.cursor
.as_ref()
.map(|key| key.iter().map(ToString::to_string).collect::<Vec<_>>()),
Some(vec!["year".to_owned(), "month".to_owned()])
);
}
#[test]
fn a_reordered_cursor_key_is_refused_with_the_key_written_out() {
let e = refusals(syn::parse_quote! {
#[ingraph(cursor(month, year))]
struct CalendarDay {
#[ingraph(copy)] year: i32,
#[ingraph(copy)] month: i32,
}
});
assert!(e.contains("`cursor(year, month)`"), "{e}");
assert!(e.contains("the SQL keyset compares"), "{e}");
}
#[test]
fn a_partial_cursor_key_is_refused() {
let e = refusals(syn::parse_quote! {
#[ingraph(cursor(year))]
struct CalendarDay {
#[ingraph(copy)] year: i32,
#[ingraph(copy)] month: i32,
}
});
assert!(e.contains("a pin states the declared order in full"), "{e}");
}
#[test]
fn an_optional_column_is_no_cursor_position() {
let e = refusals(syn::parse_quote! {
#[ingraph(cursor)]
struct Window {
#[ingraph(copy)] start: i64,
#[ingraph(optional)] end: Option<i64>,
}
});
assert!(e.contains("`end` is `optional`"), "{e}");
assert!(e.contains("STRICTLY AFTER"), "{e}");
}
#[test]
fn a_fallible_protocol_is_no_cursor_position() {
let e = refusals(syn::parse_quote! {
#[ingraph(remote = "up::Day", cursor, builder(fallible))]
struct Day {
#[ingraph(copy)] year: i32,
}
});
assert!(e.contains("nowhere in that answer for an `Err`"), "{e}");
assert!(
e.contains("mount a codec at every dialect this fragment declares"),
"the third exit is offered: {e}"
);
assert!(
e.contains("names no dialect to mount one at"),
"and a declaration with no dialect group is told why the exit is shut to it: {e}"
);
}
#[test]
fn a_partly_mounted_cursor_keeps_the_fallible_refusal() {
let e = unactivated(&syn::parse_quote! {
#[ingraph(
record(sqlite(cursor = "up::DayCursor"), postgres),
remote = "up::Day",
cursor,
builder(fallible)
)]
struct Day {
#[ingraph(copy)] year: i32,
}
})
.expect_err("a framed dialect is still a framed dialect")
.into_iter()
.map(|one| one.to_string())
.collect::<Vec<_>>()
.join("\n");
assert!(e.contains("nowhere in that answer for an `Err`"), "{e}");
assert!(
e.contains("No codec is mounted at `postgres`"),
"the unmounted dialect is named: {e}"
);
}
#[test]
fn a_cursor_mounted_at_every_dialect_admits_a_fallible_protocol() {
let m = unactivated(&syn::parse_quote! {
#[ingraph(
record(sqlite(cursor = "up::DayCursor"), postgres(cursor = "up::PgDayCursor")),
remote = "up::Day",
cursor,
builder(fallible)
)]
struct Day {
#[ingraph(copy)] year: i32,
}
})
.expect("no framed body is emitted, so nothing raises");
assert!(m.construction.fallible, "the protocol is kept as written");
assert!(m.cursor.is_some(), "and so is the paging position");
}
#[test]
fn a_wrapping_fragment_takes_the_construction_vocabulary() {
let m = parse(&syn::parse_quote! {
#[ingraph(remote = "up::Spec", builder(entry = "open", finish = "seal"))]
struct Spec {
#[ingraph(copy, builder(arg))] count: u32,
#[ingraph(builder(with = "labelled"))] label: String,
}
})
.expect("the protocol parses");
assert_eq!(m.construction.entry, "open");
assert_eq!(
m.construction.finish.as_ref().map(ToString::to_string),
Some("seal".to_owned())
);
assert!(m.fields[0].build.seat.is_some(), "the first field's seat");
assert!(m.fields[1].build.seat.is_some(), "and the second's");
}
#[test]
fn a_held_fragment_takes_no_construction_word() {
let e = refusals(syn::parse_quote! {
#[ingraph(builder(entry = "open"))]
struct Spec {
#[ingraph(copy, builder(arg))] count: u32,
}
});
assert_eq!(
e.matches("this field fragment is its own fields").count(),
2,
"one refusal per seat: {e}"
);
}
#[test]
fn a_flattened_inner_mount_reaches_the_model() {
let m = parse(&syn::parse_quote! {
pub struct ObjectDetection {
bounds: BoundingBox,
#[ingraph(record(flatten))]
classification: Classification,
}
})
.expect("a nesting fragment");
assert_eq!(
m.fields
.iter()
.map(|field| field.flatten)
.collect::<Vec<_>>(),
[false, true]
);
}
#[test]
fn a_database_scoped_flatten_is_refused_at_a_fragments_field() {
let e = unactivated(&syn::parse_quote! {
#[ingraph(record(sqlite))]
struct ObjectDetection {
#[ingraph(record(sqlite(flatten)))]
classification: Classification,
}
})
.expect_err("a dialect-scoped layout")
.to_string();
assert!(e.contains("scopes a LAYOUT to one dialect"), "{e}");
assert!(e.contains("Write `record(flatten)`"), "{e}");
}
#[test]
fn the_retired_persist_word_carries_its_migration() {
for written in [
quote::quote!(#[ingraph(persist)]),
quote::quote!(#[ingraph(persist(flatten))]),
quote::quote!(#[ingraph(persist = "flatten")]),
quote::quote!(#[ingraph(persist(rename = "label"))]),
] {
let e = refusals(syn::parse_quote! {
struct ObjectDetection {
#written
classification: Classification,
}
});
assert!(
e.contains("`persist` is retired at a fragment's field")
&& e.contains("write `#[ingraph(record(flatten))]`"),
"{written}: {e}"
);
}
}
#[test]
fn the_record_namespace_takes_the_words_it_can_honour() {
for written in [
quote::quote!(#[ingraph(record)]),
quote::quote!(#[ingraph(record())]),
quote::quote!(#[ingraph(record = "flatten")]),
] {
let e = refusals(syn::parse_quote! {
struct ObjectDetection {
#written
classification: Classification,
}
});
assert!(
e.contains("`record(…)` on a field takes the storage words"),
"{written}: {e}"
);
}
let e = refusals(syn::parse_quote! {
struct ObjectDetection {
#[ingraph(record(sortable))]
classification: Classification,
}
});
assert!(
e.contains("there is no order for a companion column to preserve on `classification`"),
"{e}"
);
let m = parse(&syn::parse_quote! {
struct ObjectDetection {
#[ingraph(record(rename = "kind"))]
classification: Classification,
}
})
.expect("the column names itself where it is stored");
assert_eq!(m.fields[0].stored_name.as_deref(), Some("kind"));
}
#[test]
fn a_skipped_column_reaches_the_model_with_its_fill() {
let m = parse(&syn::parse_quote! {
pub struct Detection {
#[ingraph(copy)]
score: u32,
#[ingraph(record(skip(default = "crate::none")))]
cached: String,
}
})
.expect("a fragment with a skipped column");
assert!(m.fields[0].skip.is_none());
let fill = m.fields[1].skip.as_ref().expect("the declared absence");
assert_eq!(
fill
.named
.as_ref()
.map(|path| quote::quote!(#path).to_string()),
Some("crate :: none".to_owned())
);
}
#[test]
fn a_per_dialect_claim_names_the_wall_and_the_seat_that_has_one() {
let narrowed = unactivated(&syn::parse_quote! {
#[ingraph(record(sqlite, postgres))]
struct Detection {
#[ingraph(record(sqlite))]
score: u32,
}
})
.expect_err("a proper subset is a narrowing")
.to_string();
assert!(
narrowed.contains("two `Assemble` impls constrained to different `Row::Database`s are `E0119`"),
"the wall is a measurement rather than a wait: {narrowed}"
);
assert!(
narrowed.contains("is the HOLDER's to write, on the field that mounts this fragment"),
"and the seat that HAS a row per database is named: {narrowed}"
);
let absent = unactivated(&syn::parse_quote! {
#[ingraph(record(sqlite, postgres))]
struct Detection {
#[ingraph(record(sqlite(skip(default = "crate::none"))))]
score: u32,
}
})
.expect_err("a per-dialect absence needs a per-dialect read")
.to_string();
assert!(
absent.contains("withholds `score` from ONE dialect"),
"the record seat's own per-database fill reaches this seat through the shared reader, and is \
answered by name: {absent}"
);
let restated = unactivated(&syn::parse_quote! {
#[ingraph(record(sqlite, postgres))]
struct Detection {
#[ingraph(record(sqlite, postgres))]
score: u32,
}
});
assert!(restated.is_ok(), "naming every database takes nothing away");
let undeclared = unactivated(&syn::parse_quote! {
#[ingraph(record(sqlite))]
struct Detection {
#[ingraph(record(mongo))]
score: u32,
}
})
.expect_err("a database the head never named")
.to_string();
assert!(
undeclared.contains("`mongo` is not a database this fragment names"),
"{undeclared}"
);
let configured = unactivated(&syn::parse_quote! {
#[ingraph(record(sqlite))]
struct Detection {
#[ingraph(record(sqlite(rename = "s")))]
score: u32,
}
})
.expect_err("a per-dialect rendering has no list to render into")
.to_string();
assert!(
configured.contains("says how ONE database renders `score`"),
"{configured}"
);
}
#[test]
fn a_column_word_needs_the_record_host() {
let e = unactivated(&syn::parse_quote! {
#[ingraph(entity)]
struct Detection {
#[ingraph(record(flatten))]
inner: Classification,
}
})
.expect_err("no record host to speak to")
.to_string();
assert!(
e.contains("says something to the RECORD host and this fragment declares none"),
"{e}"
);
}
#[test]
fn a_field_is_flattened_once() {
let e = refusals(syn::parse_quote! {
struct ObjectDetection {
#[ingraph(record(flatten, flatten))]
classification: Classification,
}
});
assert!(e.contains("`flatten` is declared more than once"), "{e}");
}
#[test]
fn a_fragment_that_holds_itself_is_refused() {
for held in [quote::quote!(Detection), quote::quote!(Option<Detection>)] {
let e = refusals(syn::parse_quote! {
struct Detection { inner: #held }
});
assert!(
e.contains("`Detection` → `Detection` is a cycle"),
"{held}: {e}"
);
assert!(e.contains("has no width"), "{held}: {e}");
}
}
#[test]
fn a_collection_of_the_fragments_own_type_is_not_a_cycle() {
let m = parse(&syn::parse_quote! {
struct Detection {
#[ingraph(repeated)]
children: Vec<Detection>,
}
})
.expect("a collection is one column");
assert_eq!(names(&m), ["children"]);
}
#[test]
fn the_filter_word_mounts_the_authors_predicate() {
let m = parse(&syn::parse_quote! {
#[ingraph(filter = "crate::faces::DimensionsWhere")]
pub struct Dimensions {
#[ingraph(copy)] width: u32,
}
})
.expect("a field-fragment declaration");
assert_eq!(
m.filter.map(|path| path.to_token_stream().to_string()),
Some("crate :: faces :: DimensionsWhere".to_owned())
);
}
#[test]
fn the_filter_word_is_written_once_and_takes_a_path_in_a_string() {
let twice = refusals(syn::parse_quote! {
#[ingraph(filter = "A", filter = "B")]
struct D { w: u32 }
});
assert!(
twice.contains("`filter` is declared more than once"),
"{twice}"
);
let bare = refusals(syn::parse_quote! {
#[ingraph(filter)]
struct D { w: u32 }
});
assert!(bare.contains("in a string literal"), "{bare}");
}
#[test]
fn a_mounted_predicate_does_not_activate_a_host_kind() {
let e = unactivated(&syn::parse_quote! {
#[ingraph(filter = "DimensionsWhere")]
struct Dimensions { #[ingraph(copy)] width: u32 }
})
.expect_err("a declaration that names no host kind is refused")
.into_iter()
.map(|e| e.to_string())
.collect::<Vec<_>>()
.join("\n");
assert!(e.contains("activates no host kind"), "{e}");
assert!(
!e.contains("`filter`"),
"and the mount itself earns no sentence: {e}"
);
}
#[test]
fn an_own_fragment_may_publish_a_method_of_its_own() {
let m = parse(&syn::parse_quote! {
#[ingraph(delegate(
#[graphql(async_graphql)]
fn aspect_ratio(&self) -> f64,
#[graphql(async_graphql(rename = "wide"))]
fn is_landscape(&self) -> bool,
))]
pub struct Dimensions { #[ingraph(copy)] width: u32 }
})
.expect("a fragment that wraps nothing may still name its own methods");
assert_eq!(m.delegates.len(), 2);
assert_eq!(
m.delegates[0].word(GraphqlKind::AsyncGraphql).as_deref(),
Some("aspectRatio")
);
assert_eq!(
m.delegates[1].word(GraphqlKind::AsyncGraphql).as_deref(),
Some("wide")
);
}
#[test]
fn an_own_entry_that_publishes_nothing_has_no_reader() {
let e = refusals(syn::parse_quote! {
#[ingraph(delegate(fn aspect(&self) -> u32))]
struct D { w: u32 }
});
assert!(e.contains("`aspect` publishes nothing"), "{e}");
assert!(
!e.contains("forwards onto the value a declaration WRAPS"),
"and the ORIGIN refusal is withdrawn: {e}"
);
let wrapped = parse(&syn::parse_quote! {
#[ingraph(remote = "upstream::Dimensions", delegate(fn aspect(&self) -> u32))]
struct D { #[ingraph(copy)] w: u32 }
})
.expect("a wrapper's plain entry mints the forwarding method");
assert_eq!(wrapped.delegates.len(), 1);
}
#[test]
fn the_seat_reads_the_shared_grammar() {
let m = parse(&syn::parse_quote! {
#[ingraph(remote = "upstream::Dimensions", delegate(
fn aspect_ratio(&self) -> u32,
#[graphql(async_graphql)]
fn orientation(&self) -> u64,
#[graphql(async_graphql(rename = "wide"))]
fn is_landscape(&self) -> bool,
fn normalise(&mut self),
))]
struct Dimensions { w: u32 }
})
.expect("a wrapping fragment with a delegate seat");
let spelled: Vec<String> = m
.delegates
.iter()
.map(|delegate| delegate.signature.ident.to_string())
.collect();
assert_eq!(
spelled,
["aspect_ratio", "orientation", "is_landscape", "normalise"]
);
assert!(
m.delegates[0].wire.is_empty(),
"a plain entry publishes nothing"
);
assert_eq!(
m.delegates[1].word(GraphqlKind::AsyncGraphql).as_deref(),
Some("orientation")
);
assert_eq!(
m.delegates[2].word(GraphqlKind::AsyncGraphql).as_deref(),
Some("wide"),
"and `rename` moves the word a client writes"
);
assert!(
m.delegates[3].exclusive,
"an exclusive receiver is delegable — it mutates the wrapped value in place"
);
}
#[test]
fn the_full_form_carries_the_target_on_its_own_entry() {
let m = parse(&syn::parse_quote! {
#[ingraph(
remote = "upstream::Dimensions",
delegate(fn label(&self) -> String),
delegate(
#[graphql(async_graphql(rename = "diagonal"))]
signature = fn diagonal_pixels(&self) -> u64,
on = self,
),
)]
struct D { #[ingraph(copy)] w: u32 }
})
.expect("a wrapper naming a method of its own");
assert_eq!(m.delegates.len(), 2);
assert_eq!(m.delegates[0].signature.ident, "label");
assert!(
m.delegates[0].on_self.is_none(),
"a shorthand entry waives nothing"
);
assert_eq!(m.delegates[1].signature.ident, "diagonal_pixels");
assert!(
m.delegates[1].on_self.is_some(),
"and the full form's own carries the word"
);
assert_eq!(
m.delegates[1].word(GraphqlKind::AsyncGraphql).as_deref(),
Some("diagonal"),
"the LIFTED half is untouched by the waiver — `#[graphql(…)]` leads the properties and says \
exactly what it says in the shorthand"
);
}
#[test]
fn a_bare_signature_and_a_named_property_are_not_one_block() {
let e = refusals(syn::parse_quote! {
#[ingraph(remote = "upstream::Dimensions", delegate(fn aspect(&self) -> u32, on = self))]
struct D { #[ingraph(copy)] w: u32 }
});
assert!(e.contains("written in ONE of two spellings"), "{e}");
assert!(
e.contains("delegate(signature = fn m(&self) -> T, on = self)"),
"and the sentence spells the full form out: {e}"
);
let reversed = refusals(syn::parse_quote! {
#[ingraph(remote = "upstream::Dimensions", delegate(
signature = fn aspect(&self) -> u32,
fn ratio(&self) -> u32,
))]
struct D { #[ingraph(copy)] w: u32 }
});
assert!(
reversed.contains("written in ONE of two spellings"),
"the other order is the same mistake: {reversed}"
);
}
#[test]
fn on_admits_self_and_nothing_else() {
let e = refusals(syn::parse_quote! {
#[ingraph(remote = "upstream::Dimensions", delegate(
signature = fn aspect(&self) -> u32,
on = remote,
))]
struct D { #[ingraph(copy)] w: u32 }
});
assert!(e.contains("`on = remote` names no target"), "{e}");
assert!(
e.contains("`on` takes `self`, and `self` is the whole of it"),
"and the roster is named: {e}"
);
}
#[test]
fn the_full_form_names_two_properties_and_no_others() {
let e = refusals(syn::parse_quote! {
#[ingraph(remote = "upstream::Dimensions", delegate(
signature = fn aspect(&self) -> u32,
rename = "ratio",
))]
struct D { #[ingraph(copy)] w: u32 }
});
assert!(e.contains("unknown property in `delegate(…)`"), "{e}");
let headless = refusals(syn::parse_quote! {
#[ingraph(remote = "upstream::Dimensions", delegate(on = self))]
struct D { #[ingraph(copy)] w: u32 }
});
assert!(
headless.contains("names no method here"),
"and an entry without its signature restates nothing: {headless}"
);
}
#[test]
fn a_waiver_needs_a_mint_to_waive() {
let e = refusals(syn::parse_quote! {
#[ingraph(delegate(
#[graphql(async_graphql)]
signature = fn aspect(&self) -> u32,
on = self,
))]
struct D { #[ingraph(copy)] w: u32 }
});
assert!(
e.contains("`on = self` suppresses the FORWARDING method"),
"{e}"
);
assert!(
e.contains("this fragment wraps nothing"),
"and it names what the word was waiting for: {e}"
);
assert!(
!e.contains("publishes nothing"),
"the ENTRY has a reader — it publishes — so only the word beside it is refused: {e}"
);
}
#[test]
fn a_waived_entry_that_publishes_nothing_has_no_reader() {
let e = refusals(syn::parse_quote! {
#[ingraph(remote = "upstream::Dimensions", delegate(
signature = fn aspect(&self) -> u32,
on = self,
))]
struct D { #[ingraph(copy)] w: u32 }
});
assert!(
e.contains("`on = self` waives its forwarding half, so the entry has no reader"),
"{e}"
);
}
#[test]
fn an_exclusive_delegate_is_delegable_and_never_liftable() {
let e = refusals(syn::parse_quote! {
#[ingraph(remote = "upstream::Dimensions", delegate(
#[graphql(async_graphql)]
fn normalise(&mut self) -> u32,
))]
struct D { w: u32 }
});
assert!(e.contains("a published delegate takes `&self`"), "{e}");
assert!(
e.contains("mutates the value it was called on"),
"in THIS tier's terms — a wrapper holds what it forwards to: {e}"
);
}
#[test]
fn two_entries_may_not_publish_one_word() {
let column = refusals(syn::parse_quote! {
#[ingraph(remote = "upstream::Dimensions", delegate(
#[graphql(async_graphql(rename = "width"))]
fn widest(&self) -> u32,
))]
struct D { #[ingraph(copy)] width: u32 }
});
assert!(column.contains("`width` already does"), "{column}");
let twice = refusals(syn::parse_quote! {
#[ingraph(remote = "upstream::Dimensions", delegate(
#[graphql(async_graphql)]
fn aspect(&self) -> u32,
#[graphql(async_graphql(rename = "aspect"))]
fn ratio(&self) -> u32,
))]
struct D { #[ingraph(copy)] w: u32 }
});
assert!(twice.contains("`aspect` already does"), "{twice}");
}
#[test]
fn a_delegate_may_not_take_an_accessors_name() {
let e = refusals(syn::parse_quote! {
#[ingraph(remote = "upstream::Dimensions", delegate(fn width(&self) -> u32))]
struct D { #[ingraph(copy)] width: u32 }
});
assert!(e.contains("would declare `width` twice"), "{e}");
}
#[test]
fn a_published_entry_needs_a_face_to_be_a_field_of() {
let e = unactivated(&syn::parse_quote! {
#[ingraph(entity, remote = "upstream::Dimensions", delegate(
#[graphql(async_graphql)]
fn label(&self) -> String,
))]
struct Dimensions { #[ingraph(copy)] width: u32 }
})
.expect_err("a published entry on a faceless fragment is refused")
.into_iter()
.map(|e| e.to_string())
.collect::<Vec<_>>()
.join("\n");
assert!(
e.contains("published onto a wire face this fragment does not have"),
"{e}"
);
let m = unactivated(&syn::parse_quote! {
#[ingraph(entity, remote = "upstream::Dimensions", delegate(fn label(&self) -> String))]
struct Dimensions { #[ingraph(copy)] width: u32 }
})
.expect("a plain entry needs no face");
assert_eq!(m.delegates.len(), 1);
assert!(
m.delegates[0].wire.is_empty(),
"and it publishes nothing, which is why it costs nothing"
);
}
#[test]
fn the_transform_seats_reach_the_model_as_paths() {
let m = parse(&syn::parse_quote! {
pub struct Track {
#[ingraph(record(write = "Rate::reduced"))]
frame_rate: Rate,
#[ingraph(record(write = "Codec::folded", read = "Codec::displayed"))]
codec: Codec,
title: String,
}
})
.expect("the words are the record namespace's own");
assert_eq!(
rendered(m.fields[0].write.as_ref()).as_deref(),
Some("Rate::reduced")
);
assert_eq!(
m.fields[0].read.as_ref(),
None,
"a canonicalisation undoes nothing on the way out"
);
assert_eq!(
rendered(m.fields[1].write.as_ref()).as_deref(),
Some("Codec::folded")
);
assert_eq!(
rendered(m.fields[1].read.as_ref()).as_deref(),
Some("Codec::displayed")
);
assert!(
m.fields[2].write.is_none() && m.fields[2].read.is_none(),
"and a field that wrote neither carries neither"
);
}
fn rendered(path: Option<&syn::Path>) -> Option<String> {
Some(
path?
.to_token_stream()
.to_string()
.split_whitespace()
.collect(),
)
}
#[test]
fn a_skipped_field_has_no_boundary_for_a_transform_to_cross() {
let e = refusals(syn::parse_quote! {
pub struct Track {
#[ingraph(record(skip(default = "crate::unrated"), write = "Rate::reduced", read = "Rate::spelled"))]
frame_rate: Rate,
}
});
assert!(
e.contains("carries `skip` and `write = \"…\"`, and the word has no site left to be spent at")
&& e.contains("carries `skip` and `read = \"…\"`")
&& e.contains("hands back what `skip(default = \"…\")` named"),
"{e}"
);
}
#[test]
fn a_dialect_at_a_fragments_head_mounts_its_own_lowering() {
let mounted = unactivated(&syn::parse_quote! {
#[ingraph(record(sqlite(comparison = "lowering::SqlSpanComparison"), postgres), entity)]
struct Span { #[ingraph(copy)] start: i64, #[ingraph(copy)] end: i64 }
})
.expect("a fragment mounting a lowering");
let host = mounted.record.as_ref().expect("the activation");
assert_eq!(
host
.databases
.iter()
.map(|one| (
one.kind.as_str(),
one
.comparison
.as_ref()
.map(|path| quote::quote!(#path).to_string().replace(' ', ""))
))
.collect::<Vec<_>>(),
[
("sqlite", Some("lowering::SqlSpanComparison".to_owned())),
("postgres", None),
],
"the mount rides its own dialect and the bare word beside it keeps the product"
);
}
#[test]
fn a_lowering_has_no_bare_seat_to_be_mounted_at() {
let e = unactivated(&syn::parse_quote! {
#[ingraph(record(comparison = "SqlSpanComparison"), entity)]
struct Span { #[ingraph(copy)] start: i64 }
})
.expect_err("the bare seat is refused")
.to_string();
assert!(
e.contains("there is no bare `comparison = \"…\"`")
&& e.contains("a lowering is mounted PER DIALECT")
&& e.contains("serves three dialects and not MongoDB")
&& e.contains("record(sqlite(comparison = \"…\"), postgres(comparison = \"…\"))"),
"{e}"
);
}
#[test]
fn a_dialects_block_at_a_fragments_head_takes_one_word() {
for (written, expected) in [
(
quote::quote!(record(sqlite(collation = "nocase"))),
"the block takes the two TYPE seats, `comparison = \"…\"` and `cursor[(codec = \"…\")]`, and \
nothing else",
),
(
quote::quote!(record(sqlite(comparison = "One", comparison = "Two"))),
"`comparison` is mounted more than once at `sqlite` — one dialect, one lowering",
),
(
quote::quote!(record(sqlite = "SqlSpanComparison")),
"names the DIALECT and takes no value",
),
(
quote::quote!(record(sqlite())),
"`sqlite()` says nothing — write the dialect BARE to name it",
),
] {
let e = unactivated(&syn::parse_quote! {
#[ingraph(#written, entity)]
struct Span { #[ingraph(copy)] start: i64 }
})
.expect_err("the entry is refused")
.to_string();
assert!(e.contains(expected), "{written}: {e}");
}
}
#[test]
fn the_head_transform_seats_reach_the_model_as_paths() {
let m = unactivated(&syn::parse_quote! {
#[ingraph(record(sqlite, write = "Ratio::reduced", read = "Ratio::spread"), entity)]
pub struct Ratio {
num: u32,
den: u32,
}
})
.expect("the words are the activation's own");
let host = m.record.as_ref().expect("the activation");
assert_eq!(
rendered(host.write.as_ref()).as_deref(),
Some("Ratio::reduced")
);
assert_eq!(
rendered(host.read.as_ref()).as_deref(),
Some("Ratio::spread")
);
assert_eq!(
host.databases.len(),
1,
"and the dialect beside them is read exactly as it was"
);
let canonical = unactivated(&syn::parse_quote! {
#[ingraph(record(write = "Ratio::reduced"), entity)]
pub struct Ratio {
num: u32,
den: u32,
}
})
.expect("the bare activation takes the word too");
let host = canonical.record.as_ref().expect("the activation");
assert!(
host.read.is_none(),
"a canonicalisation undoes nothing on the way out, which is what the absent mirror means"
);
let plain = unactivated(&syn::parse_quote! {
#[ingraph(record, entity)]
pub struct Ratio {
num: u32,
den: u32,
}
})
.expect("a fragment may write neither");
let host = plain.record.as_ref().expect("the activation");
assert!(host.write.is_none() && host.read.is_none());
}
#[test]
fn the_head_transform_words_live_inside_the_activation() {
let e = unactivated(&syn::parse_quote! {
#[ingraph(record(writes = "Ratio::reduced"), entity)]
pub struct Ratio {
num: u32,
den: u32,
}
})
.expect_err("the declaration is refused")
.to_string();
assert!(
e.contains("the WHOLE VALUE's two paths across the storage boundary") && e.contains("`write`"),
"{e}"
);
let e = unactivated(&syn::parse_quote! {
#[ingraph(entity, write = "Ratio::reduced")]
pub struct Ratio {
num: u32,
den: u32,
}
})
.expect_err("the declaration is refused")
.to_string();
assert!(
!e.contains("WHOLE VALUE"),
"the word at the head's TOP level is not this seat at all — it never reaches the activation's \
namespace, so it earns the head's own unknown-word row: {e}"
);
}
#[test]
fn the_codec_shorthand_is_the_group_form_written_inline() {
let parsed = |written: proc_macro2::TokenStream| {
let m = unactivated(&syn::parse_quote! {
#[ingraph(#written, entity, cursor)]
struct Rate { #[ingraph(copy)] num: u32, #[ingraph(copy)] den: u32 }
})
.expect("a fragment mounting a codec");
m.record
.as_ref()
.expect("the activation")
.databases
.iter()
.map(|one| (one.kind.as_str(), rendered(one.cursor.as_ref())))
.collect::<Vec<_>>()
};
let shorthand = parsed(quote::quote!(record(
sqlite(cursor = "codecs::RateCursor"),
postgres
)));
let group = parsed(quote::quote!(record(
sqlite(cursor(codec = "codecs::RateCursor")),
postgres
)));
assert_eq!(
shorthand, group,
"one reader, one refusal, one model — the shorthand is the block's required entry written \
inline"
);
assert_eq!(
shorthand,
[
("sqlite", Some("codecs::RateCursor".to_owned())),
("postgres", None),
],
"and the mount rides its own dialect, the bare word beside it keeping the frame"
);
}
#[test]
fn each_dialect_carries_the_codec_it_named() {
let m = unactivated(&syn::parse_quote! {
#[ingraph(
record(
sqlite(cursor = "codecs::RateSqlite"),
postgres(cursor = "codecs::RatePostgres"),
mysql
),
entity,
cursor
)]
struct Rate { #[ingraph(copy)] num: u32, #[ingraph(copy)] den: u32 }
})
.expect("differing codecs are legal");
assert_eq!(
m.record
.as_ref()
.expect("the activation")
.databases
.iter()
.map(|one| (one.kind.as_str(), rendered(one.cursor.as_ref())))
.collect::<Vec<_>>(),
[
("sqlite", Some("codecs::RateSqlite".to_owned())),
("postgres", Some("codecs::RatePostgres".to_owned())),
("mysql", None),
],
"each store keeps the byte form it named, and one that named none rides the frame"
);
}
#[test]
fn a_dialect_group_holds_both_type_seats_at_once() {
let m = unactivated(&syn::parse_quote! {
#[ingraph(
record(sqlite(comparison = "lowering::SqlRateComparison", cursor = "codecs::RateCursor")),
entity,
cursor
)]
struct Rate { #[ingraph(copy)] num: u32, #[ingraph(copy)] den: u32 }
})
.expect("a fragment mounting both");
let built = &m.record.as_ref().expect("the activation").databases[0];
assert_eq!(
rendered(built.comparison.as_ref()).as_deref(),
Some("lowering::SqlRateComparison")
);
assert_eq!(
rendered(built.cursor.as_ref()).as_deref(),
Some("codecs::RateCursor"),
"what a predicate LOWERS INTO and what a boundary is WRITTEN BY are two questions, and one \
group answers both without either word reading the other"
);
}
#[test]
fn a_codec_mounted_on_no_position_has_no_reader() {
let e = unactivated(&syn::parse_quote! {
#[ingraph(record(sqlite(cursor = "codecs::RateCursor")), entity)]
struct Rate { #[ingraph(copy)] num: u32, #[ingraph(copy)] den: u32 }
})
.expect_err("the mount is refused")
.to_string();
assert!(
e.contains("this fragment is no paging position")
&& e.contains("only the bare `cursor` word at the head emits any")
&& e.contains("Write `cursor` beside `record(…)`"),
"the refusal names the row a codec is spent at and the word that emits it: {e}"
);
}
#[test]
fn a_codec_has_no_bare_seat_to_be_mounted_at() {
let e = unactivated(&syn::parse_quote! {
#[ingraph(record(cursor = "codecs::RateCursor"), entity)]
struct Rate { #[ingraph(copy)] num: u32 }
})
.expect_err("the bare seat is refused")
.to_string();
assert!(
e.contains("there is no bare `cursor = \"…\"` in `record(…)`")
&& e.contains("record(sqlite(cursor = \"…\"), postgres(cursor = \"…\"))")
&& e.contains("A codec's bytes are that STORE's")
&& e.contains("The bare `cursor` at the HEAD, outside `record(…)`, is a different word"),
"{e}"
);
}
#[test]
fn a_codec_mount_written_wrong_is_told_which_form_it_nearly_is() {
for (written, expected) in [
(
quote::quote!(record(sqlite(cursor))),
"`cursor` says nothing on its own at `sqlite`",
),
(
quote::quote!(record(sqlite(cursor()))),
"`cursor` says nothing on its own at `sqlite`",
),
(
quote::quote!(record(sqlite(cursor(rename = "RateCursor")))),
"unknown entry in `cursor(…)` at `sqlite` — `cursor(…)` knows `codec`",
),
(
quote::quote!(record(sqlite(cursor(comparison = "X")))),
"unknown entry in `cursor(…)` at `sqlite` — `cursor(…)` knows `codec`",
),
(
quote::quote!(record(sqlite(cursor(codec)))),
"`cursor` names the type that WRITES AND READS this fragment's cursor bytes",
),
(
quote::quote!(record(sqlite(cursor = "One", cursor = "Two"))),
"`cursor` is mounted more than once at `sqlite` — one dialect, one codec",
),
(
quote::quote!(record(sqlite(cursor(codec = "One", codec = "Two")))),
"`codec` is declared more than once in `cursor(…)` at `sqlite` — one option, one value",
),
] {
let e = unactivated(&syn::parse_quote! {
#[ingraph(#written, entity, cursor)]
struct Rate { #[ingraph(copy)] num: u32 }
})
.expect_err("the entry is refused")
.to_string();
assert!(e.contains(expected), "{written}: {e}");
}
}