use async_graphql::{EmptyMutation, EmptySubscription, InputType, Object, Pos, Schema, Value};
use super::MediaOrderBy;
use crate::{
OrderDirection::{Asc, Desc},
Orderings, ToSubjectPath,
};
fn written(terms: &[MediaOrderBy]) -> Value {
Value::List(terms.iter().map(InputType::to_value).collect())
}
fn decode(terms: &[MediaOrderBy]) -> Result<Orderings<MediaOrderBy>, String> {
InputType::parse(Some(written(terms)))
.map_err(|error| error.into_server_error(Pos::default()).message)
}
fn subjects(order: &Orderings<MediaOrderBy>) -> Vec<String> {
order
.terms()
.map(|term| term.subject_path().to_string())
.collect()
}
#[test]
fn a_repeated_subject_is_refused_at_the_term_that_repeats_it() {
let refusal = decode(&[
MediaOrderBy::Title(Asc),
MediaOrderBy::Name(Desc),
MediaOrderBy::Title(Desc),
])
.expect_err("the third term repeats the first");
assert!(
refusal.contains("ordering term 2 names `title`, which term 0 already orders by"),
"the refusal names the repeat's position, the subject, and the term it repeats: {refusal}"
);
let refusal = decode(&[MediaOrderBy::Title(Asc), MediaOrderBy::Title(Asc)])
.expect_err("the second term repeats the first");
assert!(
refusal.contains("ordering term 1 names `title`, which term 0 already orders by"),
"{refusal}"
);
}
#[test]
fn a_shared_segment_is_not_a_shared_subject() {
let order = decode(&[MediaOrderBy::CoverTitle(Asc), MediaOrderBy::Title(Desc)])
.expect("a nested subject and a root subject are two subjects");
assert_eq!(subjects(&order), ["cover.title", "title"]);
let order = decode(&[
MediaOrderBy::CoverTitle(Asc),
MediaOrderBy::CoverDuration(Desc),
])
.expect("two subjects under one prefix are two subjects");
assert_eq!(subjects(&order), ["cover.title", "cover.duration"]);
}
#[test]
fn the_sequence_a_client_wrote_is_the_sequence_that_survives() {
let order = decode(&[
MediaOrderBy::Name(Desc),
MediaOrderBy::CoverTitle(Asc),
MediaOrderBy::Id(Asc),
MediaOrderBy::Title(Desc),
])
.expect("four distinct subjects");
assert_eq!(subjects(&order), ["name", "cover.title", "id", "title"]);
assert_eq!(
order.into_terms(),
[
MediaOrderBy::Name(Desc),
MediaOrderBy::CoverTitle(Asc),
MediaOrderBy::Id(Asc),
MediaOrderBy::Title(Desc),
],
"the terms themselves travel with their directions, in the written sequence"
);
}
#[test]
fn an_empty_list_is_the_empty_order() {
let order = decode(&[]).expect("an empty list is a legal order");
assert!(order.is_empty());
assert_eq!(order.len(), 0);
assert_eq!(subjects(&order), Vec::<String>::new());
assert!(order.into_terms().is_empty());
}
#[test]
fn a_term_naming_the_key_is_legal() {
let order = decode(&[MediaOrderBy::Title(Asc), MediaOrderBy::Id(Desc)])
.expect("naming the key is naming a column");
assert_eq!(subjects(&order), ["title", "id"]);
assert_eq!(
order.term(MediaOrderBy::Id(Asc).subject_path()),
Some(&MediaOrderBy::Id(Desc)),
"the subject is keyed on the column and not on the direction, so the lookup finds the term \
that was actually written"
);
}
#[test]
fn a_lone_term_coerces_to_the_one_term_list() {
let order: Orderings<MediaOrderBy> =
InputType::parse(Some(InputType::to_value(&MediaOrderBy::Title(Asc))))
.expect("a lone term is a one-term order");
assert_eq!(subjects(&order), ["title"]);
}
struct Query;
#[Object]
impl Query {
async fn media(&self, order: Option<Orderings<MediaOrderBy>>) -> String {
order.map_or_else(
|| String::from("none"),
|order| {
order
.terms()
.map(|term| term.subject_path().to_string())
.collect::<Vec<_>>()
.join(",")
},
)
}
async fn control(&self, order: Option<Vec<MediaOrderBy>>) -> usize {
order.map_or(0, |order| order.len())
}
}
fn schema() -> Schema<Query, EmptyMutation, EmptySubscription> {
Schema::new(Query, EmptyMutation, EmptySubscription)
}
#[test]
fn the_wrapper_renders_as_the_array_and_declares_no_type_of_its_own() {
let sdl = schema().sdl();
let argument = |field: &str| {
sdl
.lines()
.map(str::trim)
.find(|line| line.starts_with(field))
.unwrap_or_else(|| panic!("`{field}` is a field of the schema: {sdl}"))
.to_owned()
};
assert_eq!(argument("media("), "media(order: [MediaOrderBy!]): String!");
assert_eq!(
argument("control("),
"control(order: [MediaOrderBy!]): Int!"
);
assert_eq!(
<Orderings<MediaOrderBy> as InputType>::type_name(),
"[MediaOrderBy!]",
"the wrapper PRESENTS a list type reference, which is why no name of its own reaches the SDL"
);
assert_eq!(
<Option<Orderings<MediaOrderBy>> as InputType>::qualified_type_name(),
<Option<Vec<MediaOrderBy>> as InputType>::qualified_type_name(),
"and it is the same reference the `Vec` presents, nullability included"
);
let inputs: Vec<&str> = sdl
.lines()
.filter_map(|line| line.strip_prefix("input "))
.filter_map(|line| line.strip_suffix(" {"))
.collect();
assert_eq!(
inputs,
["MediaOrderBy @oneOf"],
"one input type, and it is the TERM's — nothing is registered for the wrapper"
);
}
#[tokio::test]
async fn the_refusal_reaches_a_client_positioned_at_the_argument() {
let response = schema()
.execute("{ media(order: [{title: ASC}, {name: DESC}, {title: DESC}]) }")
.await;
let error = response
.errors
.first()
.expect("the repeated subject is refused");
assert!(
error
.message
.contains("ordering term 2 names `title`, which term 0 already orders by"),
"{}",
error.message
);
assert_eq!(
error.locations.first().map(|at| at.column),
Some(16),
"positioned at the order argument's value"
);
let response = schema()
.execute("{ media(order: [{title: ASC}, {name: DESC}]) }")
.await;
assert!(response.errors.is_empty(), "{:?}", response.errors);
assert_eq!(
response.data.to_string(),
r#"{media: "title,name"}"#,
"and the accepted order keeps the sequence the client wrote"
);
}