use async_graphql::{EmptyMutation, EmptySubscription, Object, Schema};
use crate::{
BooleanFilter, BytesFilter, ConfidenceFilter, Count, EnumFilter, FieldName, GraphqlFilter,
ListFilter, Nullable, OrderDirection, QuantifiedFilter, Radians, ScalarFilter, Score, SetFilter,
TextFilter, Timestamp,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, async_graphql::Enum)]
enum Probe {
Near,
Far,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, async_graphql::Enum)]
enum Signal {
Lit,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, async_graphql::Enum)]
enum Trace {
Seen,
}
macro_rules! crosses_as_itself {
($($ty:ty),+ $(,)?) => {
$(
impl crate::ToGraphqlInput for $ty {
type Input = Self;
type Error = core::convert::Infallible;
fn cross(input: Self) -> Result<Self, core::convert::Infallible> {
Ok(input)
}
fn carry(operand: &Self) -> Self {
*operand
}
}
)+
};
}
crosses_as_itself!(Probe, Signal);
struct Query;
macro_rules! probe_fields {
($( $field:ident : $filter:ty ),+ $(,)?) => {
#[Object]
impl Query {
$(
async fn $field(&self, bare: $filter, nullable: Nullable<$filter>) -> bool {
GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable)
}
)+
}
};
}
probe_fields! {
boolean: BooleanFilter,
int8: ScalarFilter<i8>,
int16: ScalarFilter<i16>,
int32: ScalarFilter<i32>,
int64: ScalarFilter<i64>,
uint8: ScalarFilter<u8>,
uint16: ScalarFilter<u16>,
uint32: ScalarFilter<u32>,
uint64: ScalarFilter<u64>,
float32: ScalarFilter<f32>,
float64: ScalarFilter<f64>,
non_zero_int32: ScalarFilter<core::num::NonZeroI32>,
score: ConfidenceFilter,
timestamp: ScalarFilter<Timestamp>,
count: ScalarFilter<usize>,
cardinality: ScalarFilter<Count>,
int128: ScalarFilter<i128>,
uint128: ScalarFilter<u128>,
bytes: BytesFilter<Vec<u8>>,
string: TextFilter<String>,
boolean_list: ListFilter<bool>,
int8_list: ListFilter<i8>,
int16_list: ListFilter<i16>,
int32_list: ListFilter<i32>,
int64_list: ListFilter<i64>,
uint16_list: ListFilter<u16>,
uint32_list: ListFilter<u32>,
uint64_list: ListFilter<u64>,
float32_list: ListFilter<f32>,
float64_list: ListFilter<f64>,
boolean_set: SetFilter<bool>,
int8_set: SetFilter<i8>,
int16_set: SetFilter<i16>,
int32_set: SetFilter<i32>,
int64_set: SetFilter<i64>,
uint16_set: SetFilter<u16>,
uint32_set: SetFilter<u32>,
uint64_set: SetFilter<u64>,
float32_set: SetFilter<f32>,
float64_set: SetFilter<f64>,
string_list: ListFilter<String>,
string_set: SetFilter<String>,
probe: EnumFilter<Probe>,
trace: EnumFilter<Trace>,
probe_list: ListFilter<Probe, EnumFilter<Probe>>,
probe_set: SetFilter<Probe, EnumFilter<Probe>>,
trace_quantified: QuantifiedFilter<Trace, EnumFilter<Trace>>,
}
fn sdl() -> String {
Schema::build(Query, EmptyMutation, EmptySubscription)
.finish()
.sdl()
}
fn input_names(sdl: &str) -> Vec<&str> {
sdl
.lines()
.filter_map(|line| line.strip_prefix("input "))
.filter_map(|line| line.strip_suffix(" {"))
.collect()
}
#[test]
fn every_registration_reaches_the_schema() {
const EXPECTED: &[&str] = &[
"BooleanFilter",
"BooleanListFilter",
"BooleanSetFilter",
"CardinalityFilter",
"ConfidenceFilter",
"CountFilter",
"F32Filter",
"F32ListFilter",
"F32SetFilter",
"F64Filter",
"F64ListFilter",
"F64SetFilter",
"I128Filter",
"I16Filter",
"I16ListFilter",
"I16SetFilter",
"I32Filter",
"I32ListFilter",
"I32SetFilter",
"I64Filter",
"I64ListFilter",
"I64SetFilter",
"I8Filter",
"I8ListFilter",
"I8SetFilter",
"NonZeroI32Filter",
"NullableBooleanFilter",
"NullableBooleanListFilter",
"NullableBooleanSetFilter",
"NullableCardinalityFilter",
"NullableConfidenceFilter",
"NullableCountFilter",
"NullableF32Filter",
"NullableF32ListFilter",
"NullableF32SetFilter",
"NullableF64Filter",
"NullableF64ListFilter",
"NullableF64SetFilter",
"NullableI128Filter",
"NullableI16Filter",
"NullableI16ListFilter",
"NullableI16SetFilter",
"NullableI32Filter",
"NullableI32ListFilter",
"NullableI32SetFilter",
"NullableI64Filter",
"NullableI64ListFilter",
"NullableI64SetFilter",
"NullableI8Filter",
"NullableI8ListFilter",
"NullableI8SetFilter",
"NullableNonZeroI32Filter",
"NullableProbeFilter",
"NullableProbeListFilter",
"NullableProbeSetFilter",
"NullableStringFilter",
"NullableStringListFilter",
"NullableStringSetFilter",
"NullableTimestampFilter",
"NullableTraceFilter",
"NullableTraceQuantifiedFilter",
"NullableU128Filter",
"NullableU16Filter",
"NullableU16ListFilter",
"NullableU16SetFilter",
"NullableU32Filter",
"NullableU32ListFilter",
"NullableU32SetFilter",
"NullableU64Filter",
"NullableU64ListFilter",
"NullableU64SetFilter",
"NullableU8Filter",
"NullableU8VectorFilter",
"ProbeFilter",
"ProbeListFilter",
"ProbeSetFilter",
"StringFilter",
"StringListFilter",
"StringSetFilter",
"TimestampFilter",
"TraceFilter",
"TraceQuantifiedFilter",
"U128Filter",
"U16Filter",
"U16ListFilter",
"U16SetFilter",
"U32Filter",
"U32ListFilter",
"U32SetFilter",
"U64Filter",
"U64ListFilter",
"U64SetFilter",
"U8Filter",
"U8VectorFilter",
];
assert_eq!(input_names(&sdl()), EXPECTED);
}
#[test]
fn no_bare_input_object_is_missing_its_nullable_twin() {
let sdl = sdl();
let names = input_names(&sdl);
for bare in names.iter().filter(|n| !n.starts_with("Nullable")) {
let twin = format!("Nullable{bare}");
assert!(names.contains(&twin.as_str()), "{twin} is not registered");
}
}
#[test]
fn the_input_objects_render_their_operators() {
let sdl = sdl();
assert!(sdl.contains(
"input BooleanFilter {\n\teq: Boolean\n\tne: Boolean\n\tin: [Boolean!]\n\tnotIn: \
[Boolean!]\n}\n"
));
const I32: &str = "\teq: i32\n\tne: i32\n\tgt: i32\n\tgte: i32\n\tlt: i32\n\tlte: i32\n\tin: \
[i32!]\n\tnotIn: [i32!]\n";
assert!(sdl.contains(&format!("input I32Filter {{\n{I32}}}\n")));
assert!(sdl.contains(&format!("input NonZeroI32Filter {{\n{I32}}}\n")));
assert!(sdl.contains(&format!(
"input NullableI32Filter {{\n{I32}\tisNull: Boolean\n}}\n"
)));
assert!(sdl.contains(
"input I64ListFilter {\n\teq: [i64!]\n\tne: [i64!]\n\tgt: [i64!]\n\tgte: [i64!]\n\tlt: \
[i64!]\n\tlte: [i64!]\n\thasElement: i64\n\tany: I64Filter\n\tcount: CountFilter\n}\n"
));
assert!(sdl.contains(
"input I64SetFilter {\n\teq: [i64!]\n\tne: [i64!]\n\tencloses: [i64!]\n\tenclosedBy: \
[i64!]\n\toverlaps: [i64!]\n\thasElement: i64\n\tany: I64Filter\n\tcount: \
CountFilter\n}\n"
));
const INT: &str = "\teq: Int\n\tne: Int\n\tgt: Int\n\tgte: Int\n\tlt: Int\n\tlte: Int\n\tin: \
[Int!]\n\tnotIn: [Int!]\n";
assert!(sdl.contains(&format!("input CountFilter {{\n{INT}}}\n")));
assert!(sdl.contains(
"input StringFilter {\n\teq: String\n\tne: String\n\tgt: String\n\tgte: String\n\tlt: \
String\n\tlte: String\n\tcontains: String\n\tcontainsNocase: String\n\tnotContains: \
String\n\tnotContainsNocase: String\n\tstartsWith: String\n\tstartsWithNocase: \
String\n\tnotStartsWith: String\n\tnotStartsWithNocase: String\n\tendsWith: \
String\n\tendsWithNocase: String\n\tnotEndsWith: String\n\tnotEndsWithNocase: String\n\tin: \
[String!]\n\tnotIn: [String!]\n}\n"
));
}
#[test]
fn the_quantified_face_publishes_the_two_quantifiers_and_nothing_else() {
let sdl = sdl();
const QUANTIFIERS: &str = "\tany: TraceFilter\n\tcount: CountFilter\n";
assert!(
sdl.contains(&format!(
"input TraceQuantifiedFilter {{\n{QUANTIFIERS}}}\n"
)),
"{sdl}"
);
assert!(
sdl.contains(&format!(
"input NullableTraceQuantifiedFilter {{\n{QUANTIFIERS}\tisNull: Boolean\n}}\n"
)),
"{sdl}"
);
assert!(!sdl.contains("input TraceListFilter"), "{sdl}");
assert!(!sdl.contains("input TraceSetFilter"), "{sdl}");
}
#[test]
fn the_quantified_face_round_trips_its_two_slots() {
use async_graphql::{InputType, Name, Number, Value, indexmap::IndexMap};
type Face = QuantifiedFilter<Trace, EnumFilter<Trace>>;
let filter = Face::new()
.with_any(EnumFilter::new().with_eq(Trace::Seen))
.with_count(ScalarFilter::new().with_gte(2));
let written = InputType::to_value(&filter);
let Value::Object(object) = written.clone() else {
panic!("a filter writes back as an object: {written:?}");
};
assert!(object.contains_key(&Name::new("any")), "{object:?}");
assert!(object.contains_key(&Name::new("count")), "{object:?}");
assert_eq!(object.len(), 2, "{object:?}");
assert_eq!(
Face::parse(Some(written)).expect("what the face wrote, the face reads"),
filter
);
let empty = Face::parse(Some(Value::Object(IndexMap::new()))).expect("an empty object parses");
assert_eq!(empty, Face::new());
assert!(GraphqlFilter::is_empty(&empty));
assert!(Face::parse(Some(Value::Number(Number::from(7)))).is_err());
assert!(Face::parse(None).is_err());
}
#[test]
fn the_nullable_face_parses_one_flat_object() {
use async_graphql::{InputType, Name, Value, indexmap::IndexMap};
let mut obj = IndexMap::new();
obj.insert(Name::new("gte"), Value::String(String::from("7")));
obj.insert(Name::new("isNull"), Value::Boolean(false));
let parsed = <Nullable<ScalarFilter<i64>> as InputType>::parse(Some(Value::Object(obj.clone())))
.expect("a flat object with a known operator and the null test parses");
assert_eq!(
parsed,
Nullable::new(ScalarFilter::new().with_gte(7)).with_null(false)
);
let bare = <ScalarFilter<i64> as InputType>::parse(Some(Value::Object(obj)))
.expect("the inner filter ignores the key it does not declare");
assert_eq!(bare, ScalarFilter::new().with_gte(7));
let Value::Object(rendered) = InputType::to_value(&parsed) else {
panic!("an input object renders as an object");
};
assert_eq!(rendered.get("gte"), Some(&Value::Number(7.into())));
assert_eq!(rendered.get("isNull"), Some(&Value::Boolean(false)));
assert_eq!(rendered.get("eq"), Some(&Value::Null));
}
#[test]
fn the_boolean_membership_operands_cross_the_wire() {
use async_graphql::{InputType, Name, Value, indexmap::IndexMap};
let mut obj = IndexMap::new();
obj.insert(Name::new("in"), Value::List(vec![Value::Boolean(true)]));
obj.insert(Name::new("notIn"), Value::List(Vec::new()));
let parsed = <BooleanFilter as InputType>::parse(Some(Value::Object(obj)))
.expect("both membership operands parse");
assert_eq!(
parsed,
BooleanFilter::new().with_in_([true]).with_not_in([])
);
assert!(!GraphqlFilter::is_empty(&parsed));
let Value::Object(rendered) = InputType::to_value(&parsed) else {
panic!("an input object renders as an object");
};
assert_eq!(
rendered.get("in"),
Some(&Value::List(vec![Value::Boolean(true)]))
);
assert_eq!(rendered.get("notIn"), Some(&Value::List(Vec::new())));
assert_eq!(rendered.get("eq"), Some(&Value::Null));
}
#[test]
fn the_confidence_publishes_one_filter_and_returns_its_width() {
struct ConfidenceQuery;
#[Object]
impl ConfidenceQuery {
async fn confidence(
&self,
bare: ConfidenceFilter,
nullable: Nullable<ConfidenceFilter>,
) -> crate::F32 {
let answered = if GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable) {
Score::ZERO
} else {
Score::ONE
};
<Score as crate::ToGraphqlOutput>::to_graphql_output(&answered)
}
}
let sdl = Schema::build(ConfidenceQuery, EmptyMutation, EmptySubscription)
.finish()
.sdl();
assert_eq!(
input_names(&sdl),
["ConfidenceFilter", "NullableConfidenceFilter"]
);
assert_eq!(sdl.matches("Score").count(), 0);
assert_eq!(sdl.matches("scalar Float").count(), 0);
assert!(
sdl.contains("confidence(bare: ConfidenceFilter!, nullable: NullableConfidenceFilter!): f32!")
);
assert_eq!(sdl.matches("scalar f32\n").count(), 1);
const OPERATORS: &str = "\teq: ConfidenceOperand\n\tne: ConfidenceOperand\n\tgt: \
ConfidenceOperand\n\tgte: ConfidenceOperand\n\tlt: \
ConfidenceOperand\n\tlte: ConfidenceOperand\n";
assert!(sdl.contains(&format!("input ConfidenceFilter {{\n{OPERATORS}}}\n")));
assert!(sdl.contains(&format!(
"input NullableConfidenceFilter {{\n{OPERATORS}\tisNull: Boolean\n}}\n"
)));
assert_eq!(sdl.matches("\tin: [").count(), 0, "no membership slot");
assert_eq!(sdl.matches("scalar ConfidenceOperand").count(), 1);
assert!(sdl.contains("[0.0, 1.0]"));
assert!(sdl.contains("never clamped"));
}
#[test]
fn the_radians_filter_publishes_its_own_name_and_crosses_as_f32() {
struct RadiansQuery;
#[Object]
impl RadiansQuery {
async fn roll(
&self,
bare: ScalarFilter<Radians<f32>>,
nullable: Nullable<ScalarFilter<Radians<f32>>>,
) -> crate::F32 {
let answered = if GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable) {
Radians::new(0.0_f32)
} else {
Radians::new(1.0_f32)
};
<Radians<f32> as crate::ToGraphqlOutput>::to_graphql_output(&answered)
}
}
let sdl = Schema::build(RadiansQuery, EmptyMutation, EmptySubscription)
.finish()
.sdl();
assert_eq!(
input_names(&sdl),
["NullableRadiansFilter", "RadiansFilter"]
);
assert_eq!(sdl.matches("scalar Radians").count(), 0);
assert_eq!(sdl.matches("scalar f32\n").count(), 1);
assert!(sdl.contains("roll(bare: RadiansFilter!, nullable: NullableRadiansFilter!): f32!"));
const OPERATORS: &str = "\teq: f32\n\tne: f32\n\tgt: f32\n\tgte: f32\n\tlt: f32\n\tlte: \
f32\n\tin: [f32!]\n\tnotIn: [f32!]\n";
assert!(sdl.contains(&format!("input RadiansFilter {{\n{OPERATORS}}}\n")));
assert!(sdl.contains(&format!(
"input NullableRadiansFilter {{\n{OPERATORS}\tisNull: Boolean\n}}\n"
)));
}
#[test]
fn the_operand_refuses_what_a_confidence_is_not() {
use async_graphql::{Number, ScalarType, Value};
use crate::ConfidenceOperand;
for (operand, accepted) in [
(1.5, false),
(-0.1, false),
(0.0, true),
(1.0, true),
(0.25, true),
] {
let value = Value::Number(Number::from_f64(operand).expect("the operand is finite"));
assert_eq!(
<ConfidenceOperand as ScalarType>::parse(value.clone()).is_ok(),
accepted,
"{operand} parses"
);
assert_eq!(
<ConfidenceOperand as ScalarType>::is_valid(&value),
accepted,
"{operand} validates"
);
}
assert!(<ConfidenceOperand as ScalarType>::parse(Value::Number(1.into())).is_ok());
assert!(<ConfidenceOperand as ScalarType>::parse(Value::Number(2.into())).is_err());
assert!(<ConfidenceOperand as ScalarType>::parse(Value::String("0.5".into())).is_ok());
assert!(<ConfidenceOperand as ScalarType>::parse(Value::String("1.5".into())).is_err());
assert!(<ConfidenceOperand as ScalarType>::parse(Value::String("half".into())).is_err());
assert!(Number::from_f64(f64::NAN).is_none());
assert!(<ConfidenceOperand as ScalarType>::parse(Value::String("NaN".into())).is_err());
assert!(!<ConfidenceOperand as ScalarType>::is_valid(
&Value::String("NaN".into())
));
for value in [
Value::Number(Number::from_f64(0.82).expect("finite")),
Value::String("0.82".into()),
] {
let operand = <ConfidenceOperand as ScalarType>::parse(value.clone()).expect("it parses");
assert_eq!(ScalarType::to_value(&operand), value);
}
}
#[test]
fn the_timestamp_scalar_declares_itself_and_is_not_a_date_time() {
use async_graphql::registry::SDLExportOptions;
struct InstantQuery;
#[Object]
impl InstantQuery {
async fn at(
&self,
bare: ScalarFilter<Timestamp>,
nullable: Nullable<ScalarFilter<Timestamp>>,
) -> Timestamp {
if GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable) {
Timestamp::UNIX_EPOCH
} else {
Timestamp::MAX
}
}
}
let sdl = Schema::build(InstantQuery, EmptyMutation, EmptySubscription)
.finish()
.sdl_with_options(SDLExportOptions::new().include_specified_by());
assert_eq!(
input_names(&sdl),
["NullableTimestampFilter", "TimestampFilter"]
);
assert!(sdl.contains(
"\nscalar Timestamp @specifiedBy(url: \"https://datatracker.ietf.org/doc/html/rfc3339\")\n"
));
assert_eq!(sdl.matches("scalar DateTime").count(), 0);
const OPERATORS: &str = "\teq: Timestamp\n\tne: Timestamp\n\tgt: Timestamp\n\tgte: \
Timestamp\n\tlt: Timestamp\n\tlte: Timestamp\n\tin: \
[Timestamp!]\n\tnotIn: [Timestamp!]\n";
assert!(sdl.contains(&format!("input TimestampFilter {{\n{OPERATORS}}}\n")));
assert!(sdl.contains(&format!(
"input NullableTimestampFilter {{\n{OPERATORS}\tisNull: Boolean\n}}\n"
)));
assert_eq!(sdl.matches("Int").count(), 0);
assert!(sdl.contains("RFC 3339"));
assert!(sdl.contains("never a bare integer"));
assert!(sdl.contains("±9999 years"));
}
#[test]
fn timestamp_operands_cross_the_wire_as_rfc_3339_text() {
use async_graphql::{Number, ScalarType, Value};
const NANOS: &str = "2026-08-09T21:14:03.123456789Z";
let instant: Timestamp = NANOS
.parse()
.expect("nine digits of fraction is an instant");
let rendered = ScalarType::to_value(&instant);
assert_eq!(rendered, Value::String(NANOS.into()));
assert_eq!(
<Timestamp as ScalarType>::parse(rendered).expect("its own rendering parses"),
instant
);
let east =
<Timestamp as ScalarType>::parse(Value::String("2026-08-09T21:14:03.123456789+09:00".into()))
.expect("an offset spelling is an instant");
assert_eq!(
east,
"2026-08-09T12:14:03.123456789Z"
.parse::<Timestamp>()
.expect("the same instant in UTC")
);
let epoch_seconds = Value::Number(Number::from(1_786_310_043));
assert!(<Timestamp as ScalarType>::parse(epoch_seconds.clone()).is_err());
assert!(!<Timestamp as ScalarType>::is_valid(&epoch_seconds));
let refusal = <Timestamp as ScalarType>::parse(Value::String("2026-08-09T21:14:03".into()))
.expect_err("a civil datetime is not an instant")
.into_server_error(async_graphql::Pos::default());
assert!(
refusal.message.contains("failed to find offset component"),
"{}",
refusal.message
);
assert!(refusal.message.contains("Timestamp"), "{}", refusal.message);
for (operand, accepted) in [
("2026-08-09T21:14:03Z", true),
("2026-08-09T21:14:03.123456789Z", true),
("2026-08-09T21:14:03+09:00", true),
("2026-08-09T21:14:03", false),
("2026-08-09", false),
("not a time", false),
("", false),
] {
let value = Value::String(operand.into());
assert_eq!(
<Timestamp as ScalarType>::parse(value.clone()).is_ok(),
accepted,
"{operand} parses"
);
assert_eq!(
<Timestamp as ScalarType>::is_valid(&value),
accepted,
"{operand} validates"
);
}
}
#[cfg(feature = "smol_str")]
#[test]
fn the_smol_str_text_filter_owns_the_canonical_name() {
struct TextQuery;
#[Object]
impl TextQuery {
async fn text(
&self,
bare: TextFilter<smol_str::SmolStr>,
nullable: Nullable<TextFilter<smol_str::SmolStr>>,
) -> bool {
GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable)
}
}
let sdl = Schema::build(TextQuery, EmptyMutation, EmptySubscription)
.finish()
.sdl();
assert_eq!(input_names(&sdl), ["NullableTextFilter", "TextFilter"]);
assert!(sdl.contains("scalar SmolStr"));
assert!(sdl.contains("input TextFilter {\n\teq: SmolStr\n\tne: SmolStr\n"));
assert!(sdl.contains("\tin: [SmolStr!]\n\tnotIn: [SmolStr!]\n\tisNull: Boolean\n}\n"));
}
#[cfg(feature = "jiff")]
#[test]
fn the_jiff_filters_render_the_scalars_async_graphql_owns() {
use async_graphql::registry::SDLExportOptions;
use jiff::{
Timestamp, Zoned,
civil::{Date, Time},
};
struct TemporalQuery;
#[Object]
impl TemporalQuery {
async fn instant(
&self,
bare: ScalarFilter<Timestamp>,
nullable: Nullable<ScalarFilter<Timestamp>>,
) -> bool {
GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable)
}
async fn day(&self, bare: ScalarFilter<Date>, nullable: Nullable<ScalarFilter<Date>>) -> bool {
GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable)
}
async fn clock(
&self,
bare: ScalarFilter<Time>,
nullable: Nullable<ScalarFilter<Time>>,
) -> bool {
GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable)
}
async fn zoned(
&self,
bare: ScalarFilter<Zoned>,
nullable: Nullable<ScalarFilter<Zoned>>,
) -> bool {
GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable)
}
}
let sdl = Schema::build(TemporalQuery, EmptyMutation, EmptySubscription)
.finish()
.sdl_with_options(SDLExportOptions::new().include_specified_by());
assert_eq!(
input_names(&sdl),
[
"DateFilter",
"DateTimeFilter",
"NullableDateFilter",
"NullableDateTimeFilter",
"NullableTimeFilter",
"NullableZonedDateTimeFilter",
"TimeFilter",
"ZonedDateTimeFilter",
]
);
const OPERATORS: &str = "\teq: %S%\n\tne: %S%\n\tgt: %S%\n\tgte: %S%\n\tlt: %S%\n\tlte: \
%S%\n\tin: [%S%!]\n\tnotIn: [%S%!]\n";
for (input, scalar) in [
("DateTimeFilter", "DateTime"),
("DateFilter", "Date"),
("TimeFilter", "Time"),
("ZonedDateTimeFilter", "ZonedDateTime"),
] {
let operators = OPERATORS.replace("%S%", scalar);
assert!(
sdl.contains(&format!("input {input} {{\n{operators}}}\n")),
"{input}"
);
assert!(
sdl.contains(&format!(
"input Nullable{input} {{\n{operators}\tisNull: Boolean\n}}\n"
)),
"Nullable{input}"
);
}
assert!(sdl.contains(
"\nscalar DateTime @specifiedBy(url: \"https://datatracker.ietf.org/doc/html/rfc3339\")\n"
));
assert!(sdl.contains(
"\nscalar ZonedDateTime @specifiedBy(url: \"https://datatracker.ietf.org/doc/html/rfc8536\")\n"
));
assert!(sdl.contains("scalar Date\n"));
assert!(sdl.contains("scalar Time\n"));
}
#[cfg(feature = "jiff")]
#[test]
fn the_two_minted_temporal_filters_render_the_scalars_this_crate_names() {
use async_graphql::registry::SDLExportOptions;
use jiff::{civil::DateTime, tz::Offset};
struct MintedQuery;
#[Object]
impl MintedQuery {
async fn local(
&self,
bare: ScalarFilter<DateTime>,
nullable: Nullable<ScalarFilter<DateTime>>,
) -> bool {
GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable)
}
async fn offset(
&self,
bare: ScalarFilter<Offset>,
nullable: Nullable<ScalarFilter<Offset>>,
) -> bool {
GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable)
}
}
let sdl = Schema::build(MintedQuery, EmptyMutation, EmptySubscription)
.finish()
.sdl_with_options(SDLExportOptions::new().include_specified_by());
assert_eq!(
input_names(&sdl),
[
"LocalDateTimeFilter",
"NullableLocalDateTimeFilter",
"NullableUtcOffsetFilter",
"UtcOffsetFilter",
]
);
const OPERATORS: &str = "\teq: %S%\n\tne: %S%\n\tgt: %S%\n\tgte: %S%\n\tlt: %S%\n\tlte: \
%S%\n\tin: [%S%!]\n\tnotIn: [%S%!]\n";
for (input, scalar) in [
("LocalDateTimeFilter", "LocalDateTime"),
("UtcOffsetFilter", "UtcOffset"),
] {
let operators = OPERATORS.replace("%S%", scalar);
assert!(
sdl.contains(&format!("input {input} {{\n{operators}}}\n")),
"{input}"
);
assert!(
sdl.contains(&format!(
"input Nullable{input} {{\n{operators}\tisNull: Boolean\n}}\n"
)),
"Nullable{input}"
);
}
assert!(sdl.contains(
"\nscalar LocalDateTime @specifiedBy(url: \"https://en.wikipedia.org/wiki/ISO_8601\")\n"
));
assert!(sdl.contains(
"\nscalar UtcOffset @specifiedBy(url: \"https://en.wikipedia.org/wiki/ISO_8601#Time_offsets_from_UTC\")\n"
));
assert!(
!sdl.contains("scalar DateTime"),
"the minted name does not collide with async-graphql's own"
);
}
#[cfg(feature = "jiff")]
#[test]
fn an_unreferenced_scalar_leaves_the_duration_name_to_its_owner() {
use jiff::Timestamp;
use crate::DurationFilter;
struct MixedQuery;
#[Object]
impl MixedQuery {
async fn instant(&self, filter: ScalarFilter<Timestamp>) -> bool {
GraphqlFilter::is_empty(&filter)
}
async fn elapsed(&self, filter: DurationFilter) -> bool {
GraphqlFilter::is_empty(&filter)
}
}
let sdl = Schema::build(MixedQuery, EmptyMutation, EmptySubscription)
.finish()
.sdl();
assert_eq!(input_names(&sdl), ["DateTimeFilter", "DurationFilter"]);
assert_eq!(sdl.matches("scalar Duration\n").count(), 1);
assert!(sdl.contains("`ns` is a unit"));
}
#[cfg(feature = "jiff")]
#[test]
fn a_second_duration_scalar_is_dropped_rather_than_refused() {
use async_graphql::{InputType, Value, registry::SDLExportOptions};
use crate::DurationFilter;
struct SpanFirst;
#[Object]
impl SpanFirst {
async fn span(&self, operand: Option<jiff::Span>) -> bool {
operand.is_none()
}
async fn elapsed(&self, filter: DurationFilter) -> bool {
GraphqlFilter::is_empty(&filter)
}
}
struct FilterFirst;
#[Object]
impl FilterFirst {
async fn elapsed(&self, filter: DurationFilter) -> bool {
GraphqlFilter::is_empty(&filter)
}
async fn span(&self, operand: Option<jiff::Span>) -> bool {
operand.is_none()
}
}
let span_first = Schema::build(SpanFirst, EmptyMutation, EmptySubscription)
.finish()
.sdl_with_options(SDLExportOptions::new().include_specified_by());
let filter_first = Schema::build(FilterFirst, EmptyMutation, EmptySubscription)
.finish()
.sdl_with_options(SDLExportOptions::new().include_specified_by());
assert_eq!(span_first.matches("scalar Duration ").count(), 1);
assert_eq!(filter_first.matches("scalar Duration ").count(), 1);
assert!(!span_first.contains("`ns` is a unit"));
assert!(filter_first.contains("`ns` is a unit"));
for sdl in [&span_first, &filter_first] {
assert!(sdl.contains(
"scalar Duration @specifiedBy(url: \"https://en.wikipedia.org/wiki/ISO_8601#Durations\")"
));
}
let operand = |text: &str| {
<DurationFilter as InputType>::parse(Some(Value::Object(
[(async_graphql::Name::new("gte"), Value::String(text.into()))]
.into_iter()
.collect(),
)))
};
for text in ["2h", "PT2H"] {
assert!(operand(text).is_ok(), "{text}");
assert!(
<Option<jiff::Span> as InputType>::parse(Some(Value::String(text.into()))).is_ok(),
"{text}"
);
}
assert!(<Option<jiff::Span> as InputType>::parse(Some(Value::String("P1M".into()))).is_ok());
assert!(operand("P1M").is_err());
}
#[cfg(feature = "jiff")]
#[test]
fn the_duration_filter_renders_its_own_wire_face() {
use crate::DurationFilter;
struct DurationQuery;
#[Object]
impl DurationQuery {
async fn duration(&self, bare: DurationFilter, nullable: Nullable<DurationFilter>) -> bool {
GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable)
}
}
let sdl = Schema::build(DurationQuery, EmptyMutation, EmptySubscription)
.finish()
.sdl();
assert_eq!(
input_names(&sdl),
["DurationFilter", "NullableDurationFilter"]
);
const OPERATORS: &str = "\teq: Duration\n\tne: Duration\n\tgt: Duration\n\tgte: \
Duration\n\tlt: Duration\n\tlte: Duration\n\tin: [Duration!]\n\tnotIn: \
[Duration!]\n";
assert!(sdl.contains(&format!("input DurationFilter {{\n{OPERATORS}}}\n")));
assert!(sdl.contains(&format!(
"input NullableDurationFilter {{\n{OPERATORS}\tisNull: Boolean\n}}\n"
)));
assert!(sdl.contains("\nscalar Duration\n"));
assert!(sdl.contains("`ns` is a unit"));
assert!(sdl.contains("ISO 8601 is what comes back"));
assert!(sdl.contains("SIGNED"));
assert!(sdl.contains("APPROXIMATE"));
assert!(sdl.contains("30.44 days"));
assert!(sdl.contains("365.25 days"));
assert!(sdl.contains("`M` is a MONTH and `m` is a minute"));
assert!(sdl.contains("are refused"));
}
#[cfg(feature = "jiff")]
#[test]
fn duration_operands_cross_the_wire_as_jiff_text() {
use async_graphql::{InputType, Name, Value, indexmap::IndexMap};
use jiff::SignedDuration;
use crate::DurationFilter;
let mut obj = IndexMap::new();
obj.insert(Name::new("gte"), Value::String("1h30min".into()));
obj.insert(Name::new("lt"), Value::String("PT2H".into()));
obj.insert(
Name::new("in"),
Value::List(vec![
Value::String("500ms".into()),
Value::String("-PT2S".into()),
]),
);
let parsed = <DurationFilter as InputType>::parse(Some(Value::Object(obj)))
.expect("both an inline operand and a list operand parse");
assert_eq!(
parsed,
DurationFilter::new()
.with_gte(SignedDuration::from_secs(5400))
.with_lt(SignedDuration::from_secs(7200))
.with_in_([
SignedDuration::from_millis(500),
SignedDuration::from_secs(-2)
])
);
let Value::Object(rendered) = InputType::to_value(&parsed) else {
panic!("an input object renders as an object");
};
assert_eq!(rendered.get("gte"), Some(&Value::String("PT1H30M".into())));
assert_eq!(rendered.get("lt"), Some(&Value::String("PT2H".into())));
assert_eq!(
rendered.get("in"),
Some(&Value::List(vec![
Value::String("PT0.5S".into()),
Value::String("-PT2S".into()),
]))
);
assert_eq!(rendered.get("eq"), Some(&Value::Null));
let mut bad = IndexMap::new();
bad.insert(Name::new("lt"), Value::String("5400".into()));
let error = <DurationFilter as InputType>::parse(Some(Value::Object(bad)))
.expect_err("a bare number is not a duration")
.into_server_error(async_graphql::Pos::default());
assert!(
error
.message
.contains("expected to find unit designator suffix"),
"{}",
error.message
);
let mut calendar = IndexMap::new();
calendar.insert(Name::new("gt"), Value::String("1month".into()));
let parsed = <DurationFilter as InputType>::parse(Some(Value::Object(calendar)))
.expect("a month is 30.44 days here");
let Value::Object(rendered) = InputType::to_value(&parsed) else {
panic!("an input object renders as an object");
};
assert_eq!(
rendered.get("gt"),
Some(&Value::String("PT730H33M36S".into()))
);
let mut iso = IndexMap::new();
iso.insert(Name::new("gt"), Value::String("P1M".into()));
let error = <DurationFilter as InputType>::parse(Some(Value::Object(iso)))
.expect_err("no parser reads an ISO 8601 month here")
.into_server_error(async_graphql::Pos::default());
assert!(
error.message.contains("days or greater"),
"{}",
error.message
);
let mut nullable = IndexMap::new();
nullable.insert(Name::new("lte"), Value::String("2h".into()));
nullable.insert(Name::new("isNull"), Value::Boolean(true));
let parsed = <Nullable<DurationFilter> as InputType>::parse(Some(Value::Object(nullable)))
.expect("the null test sits beside the operators");
assert_eq!(
parsed,
Nullable::new(DurationFilter::new().with_lte(SignedDuration::from_secs(7200))).with_null(true)
);
}
#[derive(async_graphql::SimpleObject, Debug, Clone)]
struct MediaKeyOutput {
pub(crate) media_id: u64,
pub(crate) id: u64,
}
#[derive(async_graphql::SimpleObject, Debug, Clone)]
struct MediaGraphqlOutput {
pub(crate) id: u64,
pub(crate) key: MediaKeyOutput,
#[graphql(name = "titleText")]
pub(crate) title: String,
pub(crate) bit_rate: u64,
}
impl MediaGraphqlOutput {
const fn key_ref(&self) -> &MediaKeyOutput {
&self.key
}
const fn headline_ref(&self) -> &String {
&self.title
}
const fn bit_rate_ref(&self) -> &u64 {
&self.bit_rate
}
}
struct WireQuery;
#[Object]
impl WireQuery {
async fn media(&self) -> MediaGraphqlOutput {
MediaGraphqlOutput {
id: 1,
key: MediaKeyOutput { media_id: 2, id: 1 },
title: "a reel".to_owned(),
bit_rate: 320,
}
}
}
#[test]
fn a_non_pub_member_registers_and_the_three_faces_are_three_names() {
let sdl = Schema::build(WireQuery, EmptyMutation, EmptySubscription)
.finish()
.sdl();
assert!(
sdl.contains(
"type MediaGraphqlOutput {\n\tid: Int!\n\tkey: MediaKeyOutput!\n\ttitleText: \
String!\n\tbitRate: Int!\n}\n"
),
"{sdl}"
);
assert!(
sdl.contains("type MediaKeyOutput {\n\tmediaId: Int!\n\tid: Int!\n}\n"),
"{sdl}"
);
assert!(!sdl.contains("\ttitle: String!"), "{sdl}");
let media = MediaGraphqlOutput {
id: 1,
key: MediaKeyOutput { media_id: 2, id: 1 },
title: "a reel".to_owned(),
bit_rate: 320,
};
assert_eq!(media.headline_ref(), "a reel");
assert_eq!(*media.bit_rate_ref(), 320);
assert_eq!(media.key_ref().media_id, 2);
}
#[derive(async_graphql::OneofObject, Debug, Clone, Copy, PartialEq, Eq)]
enum MediaOrderBy {
Title(OrderDirection),
CreatedAt(OrderDirection),
}
impl MediaOrderBy {
const fn sqlite_column(self) -> &'static FieldName {
match self {
Self::Title(_) => FieldName::new("title"),
Self::CreatedAt(_) => FieldName::new("created_at"),
}
}
const fn direction(self) -> OrderDirection {
match self {
Self::Title(direction) | Self::CreatedAt(direction) => direction,
}
}
}
static ORDER_RESOLVER_ENTERED: core::sync::atomic::AtomicUsize =
core::sync::atomic::AtomicUsize::new(0);
struct OrderQuery;
#[Object]
impl OrderQuery {
async fn medias(&self, order_by: Vec<MediaOrderBy>) -> String {
ORDER_RESOLVER_ENTERED.fetch_add(1, core::sync::atomic::Ordering::SeqCst);
order_by
.into_iter()
.map(|term| {
let column: &str = term.sqlite_column();
let direction = if term.direction().is_descending() {
"DESC"
} else {
"ASC"
};
format!("{column} {direction}")
})
.collect::<Vec<_>>()
.join(", ")
}
}
fn order_sdl() -> String {
Schema::build(OrderQuery, EmptyMutation, EmptySubscription)
.finish()
.sdl()
}
#[test]
fn the_order_direction_renders_its_two_values_and_describes_neither() {
assert!(
order_sdl().contains("enum OrderDirection {\n\tASC\n\tDESC\n}\n"),
"{}",
order_sdl()
);
assert!(
!order_sdl().contains("Smallest first"),
"a Rust reader\'s sentence reached a client: {}",
order_sdl()
);
}
#[test]
fn an_order_by_term_is_a_oneof_input_object_and_a_query_takes_a_list_of_them() {
let sdl = order_sdl();
assert!(
sdl.contains(
"input MediaOrderBy @oneOf {\n\ttitle: OrderDirection\n\tcreatedAt: OrderDirection\n}\n"
),
"{sdl}"
);
assert!(sdl.contains("directive @oneOf on INPUT_OBJECT\n"), "{sdl}");
assert!(
sdl.contains("medias(orderBy: [MediaOrderBy!]!): String!"),
"{sdl}"
);
}
#[test]
fn exactly_one_field_is_a_validation_rule_that_no_resolver_ever_sees() {
use core::{
pin::pin,
sync::atomic::Ordering as Atomic,
task::{Context as TaskContext, Poll, Waker},
};
use async_graphql::{Request, Variables};
fn block_on<F: Future>(future: F) -> F::Output {
let mut future = pin!(future);
let mut cx = TaskContext::from_waker(Waker::noop());
loop {
if let Poll::Ready(value) = future.as_mut().poll(&mut cx) {
return value;
}
}
}
fn ask(query: &str, variables: Option<Variables>) -> (Result<String, String>, usize) {
ORDER_RESOLVER_ENTERED.store(0, Atomic::SeqCst);
let mut request = Request::new(query);
if let Some(variables) = variables {
request = request.variables(variables);
}
let response = block_on(
Schema::build(OrderQuery, EmptyMutation, EmptySubscription)
.finish()
.execute(request),
);
let entered = ORDER_RESOLVER_ENTERED.load(Atomic::SeqCst);
let answer = match response.errors.first() {
Some(error) => Err(error.message.clone()),
None => Ok(response.data.to_string()),
};
(answer, entered)
}
let (answer, entered) = ask(
r#"{ medias(orderBy: [{ createdAt: DESC }, { title: ASC }]) }"#,
None,
);
assert_eq!(
answer,
Ok(r#"{medias: "created_at DESC, title ASC"}"#.to_owned())
);
assert_eq!(entered, 1);
let (reversed, _) = ask(
r#"{ medias(orderBy: [{ title: ASC }, { createdAt: DESC }]) }"#,
None,
);
assert_eq!(
reversed,
Ok(r#"{medias: "title ASC, created_at DESC"}"#.to_owned())
);
const EXACTLY_ONE: &str = "Oneof input objects requires have exactly one field";
const NOT_NULL: &str = "Oneof Input Objects require that exactly one field must be supplied and \
that field must not be null";
for (label, query, variables, expected) in [
(
"two fields, spelled inline",
r#"{ medias(orderBy: [{ title: DESC, createdAt: ASC }]) }"#,
None,
EXACTLY_ONE,
),
(
"no field at all",
r#"{ medias(orderBy: [{}]) }"#,
None,
EXACTLY_ONE,
),
(
"one field, explicitly null",
r#"{ medias(orderBy: [{ title: null }]) }"#,
None,
NOT_NULL,
),
(
"two fields, through a variable",
r#"query Q($order: [MediaOrderBy!]!) { medias(orderBy: $order) }"#,
Some(Variables::from_value(async_graphql::value!({
"order": [{ "title": "DESC", "createdAt": "ASC" }]
}))),
EXACTLY_ONE,
),
(
"no field at all, through a variable",
r#"query Q($order: [MediaOrderBy!]!) { medias(orderBy: $order) }"#,
Some(Variables::from_value(async_graphql::value!({
"order": [{}]
}))),
EXACTLY_ONE,
),
] {
let (answer, entered) = ask(query, variables);
let message = answer.expect_err(label);
assert!(message.contains(expected), "{label}: {message}");
assert_eq!(entered, 0, "{label}: the resolver was entered anyway");
}
let (introspected, _) = ask(r#"{ __type(name: "MediaOrderBy") { isOneOf } }"#, None);
assert_eq!(introspected, Ok(r#"{__type: {isOneOf: true}}"#.to_owned()));
}
#[test]
fn the_text_collections_reach_a_schema() {
let sdl = sdl();
assert!(sdl.contains(
"input StringListFilter {\n\teq: [String!]\n\tne: [String!]\n\tgt: [String!]\n\tgte: \
[String!]\n\tlt: [String!]\n\tlte: [String!]\n\thasElement: String\n\tany: \
StringFilter\n\tcount: CountFilter\n}\n"
));
assert!(sdl.contains(
"input StringSetFilter {\n\teq: [String!]\n\tne: [String!]\n\tencloses: \
[String!]\n\tenclosedBy: [String!]\n\toverlaps: [String!]\n\thasElement: String\n\tany: \
StringFilter\n\tcount: CountFilter\n}\n"
));
assert!(sdl.contains("input NullableStringListFilter {"));
assert!(sdl.contains("input NullableStringSetFilter {"));
}
#[test]
fn a_128_bit_column_reaches_a_schema_under_its_own_grammar() {
let sdl = sdl();
const U128: &str = "\teq: u128\n\tne: u128\n\tgt: u128\n\tgte: u128\n\tlt: \
u128\n\tlte: u128\n\tin: [u128!]\n\tnotIn: [u128!]\n";
assert!(sdl.contains(&format!("input U128Filter {{\n{U128}}}\n")));
assert!(sdl.contains(&format!(
"input NullableU128Filter {{\n{U128}\tisNull: Boolean\n}}\n"
)));
const I128: &str = "\teq: i128\n\tne: i128\n\tgt: i128\n\tgte: i128\n\tlt: \
i128\n\tlte: i128\n\tin: [i128!]\n\tnotIn: [i128!]\n";
assert!(sdl.contains(&format!("input I128Filter {{\n{I128}}}\n")));
assert!(sdl.contains("scalar i128"), "{sdl}");
assert!(sdl.contains("scalar u128"), "{sdl}");
assert!(sdl.contains("decimal text"), "{sdl}");
assert!(sdl.contains("HYBRID at 2^53 \u{2212} 1"), "{sdl}");
assert!(sdl.contains("as a JSON number"), "{sdl}");
assert!(!sdl.contains("never a JSON number"), "{sdl}");
}
#[test]
fn a_blob_reaches_a_schema_as_hex() {
let sdl = sdl();
const BYTES: &str = "\teq: U8Vector\n\tne: U8Vector\n\tgt: U8Vector\n\tgte: U8Vector\n\tlt: \
U8Vector\n\tlte: U8Vector\n\tcontains: U8Vector\n\tnotContains: \
U8Vector\n\tin: [U8Vector!]\n\tnotIn: [U8Vector!]\n";
assert!(sdl.contains(&format!("input U8VectorFilter {{\n{BYTES}}}\n")));
assert!(sdl.contains(&format!(
"input NullableU8VectorFilter {{\n{BYTES}\tisNull: Boolean\n}}\n"
)));
assert!(sdl.contains("scalar U8Vector"), "{sdl}");
assert!(sdl.contains("two characters per byte"), "{sdl}");
assert!(!sdl.contains("eq: [Int!]\n\tne: [Int!]\n\tgt: [Int!]\n\tgte: [Int!]\n\tlt: [Int!]\n\tlte: [Int!]\n\tcontains"), "{sdl}");
}
#[cfg(feature = "jiff")]
#[test]
fn the_carriers_render_in_an_output_position() {
use crate::{HexBytes, I128, JiffDuration, U128};
struct OutputQuery;
#[Object]
impl OutputQuery {
async fn elapsed(&self) -> JiffDuration {
JiffDuration::from(jiff::SignedDuration::from_secs(5400))
}
async fn balance(&self) -> U128 {
U128::from(u128::MAX)
}
async fn drift(&self) -> I128 {
I128::from(i128::MIN)
}
async fn checksum(&self) -> HexBytes {
HexBytes::from(vec![0x89, 0x50, 0x4e, 0x47])
}
}
let schema = Schema::build(OutputQuery, EmptyMutation, EmptySubscription).finish();
let sdl = schema.sdl();
assert!(sdl.contains("elapsed: Duration!"), "{sdl}");
assert!(sdl.contains("balance: u128!"), "{sdl}");
assert!(sdl.contains("drift: i128!"), "{sdl}");
assert!(sdl.contains("checksum: bytes!"), "{sdl}");
let answered = {
use core::{
future::Future,
pin::pin,
task::{Context as TaskContext, Poll, Waker},
};
let mut request = pin!(schema.execute("{ elapsed balance drift checksum }"));
let mut cx = TaskContext::from_waker(Waker::noop());
loop {
if let Poll::Ready(response) = request.as_mut().poll(&mut cx) {
break response;
}
}
};
assert!(answered.errors.is_empty(), "{:?}", answered.errors);
assert_eq!(
answered.data.to_string(),
r#"{elapsed: "PT1H30M", balance: "340282366920938463463374607431768211455", drift: "-170141183460469231731687303715884105728", checksum: "89504e47"}"#
);
}
#[test]
fn the_enum_filters_name_follows_its_operand() {
use async_graphql::InputType;
assert_eq!(<EnumFilter<Probe> as InputType>::type_name(), "ProbeFilter");
assert_eq!(
<Nullable<EnumFilter<Probe>> as InputType>::type_name(),
"NullableProbeFilter"
);
assert_eq!(
<EnumFilter<Signal> as InputType>::type_name(),
"SignalFilter"
);
assert_ne!(
<EnumFilter<Probe> as InputType>::type_name(),
<EnumFilter<Signal> as InputType>::type_name()
);
assert_eq!(<Probe as InputType>::type_name(), "Probe");
}
#[test]
fn a_collection_filter_is_named_from_the_element_filter_because_the_element_cannot() {
use async_graphql::InputType;
assert_eq!(<i8 as InputType>::type_name(), "Int");
assert_eq!(<i64 as InputType>::type_name(), "Int");
assert_eq!(
<ScalarFilter<i8> as InputType>::type_name(),
"I8Filter",
"the FILTER is what distinguishes them"
);
assert_eq!(<ListFilter<i64> as InputType>::type_name(), "I64ListFilter");
assert_eq!(<SetFilter<i64> as InputType>::type_name(), "I64SetFilter");
assert_eq!(
<ListFilter<Probe, EnumFilter<Probe>> as InputType>::type_name(),
"ProbeListFilter"
);
assert_eq!(
<Nullable<ListFilter<Probe, EnumFilter<Probe>>> as InputType>::type_name(),
"NullableProbeListFilter"
);
assert_ne!(
<ListFilter<Probe, EnumFilter<Probe>> as InputType>::type_name(),
<ListFilter<Signal, EnumFilter<Signal>> as InputType>::type_name()
);
assert_ne!(
<ListFilter<i8> as InputType>::type_name(),
<ListFilter<i64> as InputType>::type_name()
);
assert_ne!(
<ListFilter<i64> as InputType>::type_name(),
<SetFilter<i64> as InputType>::type_name()
);
}
#[test]
fn the_enum_input_objects_render_their_operators() {
let sdl = sdl();
assert!(
sdl.contains(
"input ProbeFilter {\n\teq: Probe\n\tne: Probe\n\tin: [Probe!]\n\tnotIn: [Probe!]\n}"
),
"{sdl}"
);
assert!(
sdl.contains(
"input NullableProbeFilter {\n\teq: Probe\n\tne: Probe\n\tin: [Probe!]\n\tnotIn: [Probe!]\n\tisNull: Boolean\n}"
),
"{sdl}"
);
assert!(sdl.contains("enum Probe {\n\tNEAR\n\tFAR\n}"), "{sdl}");
}
#[test]
fn the_nullable_enum_face_parses_one_flat_object() {
use async_graphql::InputType;
let parsed = <Nullable<EnumFilter<Probe>> as InputType>::parse(Some(async_graphql::value!({
"eq": "NEAR",
"isNull": false,
})))
.expect("a flat object carries both halves");
assert_eq!(parsed.null(), Some(&false));
assert_eq!(parsed.inner().eq(), Some(&Probe::Near));
let rendered = InputType::to_value(&parsed);
assert_eq!(
<Nullable<EnumFilter<Probe>> as InputType>::parse(Some(rendered)).expect("the round trip"),
parsed
);
}
#[test]
fn every_confidence_width_reaches_one_filter_and_its_own_roster_scalar() {
use crate::Confidence;
struct WidthQuery;
#[Object]
impl WidthQuery {
async fn narrow(&self, filter: ConfidenceFilter) -> crate::F32 {
let _ = GraphqlFilter::is_empty(&filter);
<Score as crate::ToGraphqlOutput>::to_graphql_output(&Score::ONE)
}
async fn wide(&self, filter: ConfidenceFilter) -> crate::F64 {
let _ = GraphqlFilter::is_empty(&filter);
<Confidence<f64> as crate::ToGraphqlOutput>::to_graphql_output(&Confidence::ONE)
}
#[cfg(feature = "half")]
async fn half(&self, filter: ConfidenceFilter) -> crate::F16 {
let _ = GraphqlFilter::is_empty(&filter);
<Confidence<half::f16> as crate::ToGraphqlOutput>::to_graphql_output(&Confidence::ONE)
}
#[cfg(feature = "rust_decimal")]
async fn exact(&self, filter: ConfidenceFilter) -> crate::F128 {
let _ = GraphqlFilter::is_empty(&filter);
<Confidence<rust_decimal::Decimal> as crate::ToGraphqlOutput>::to_graphql_output(
&Confidence::ONE,
)
}
}
let sdl = Schema::build(WidthQuery, EmptyMutation, EmptySubscription)
.finish()
.sdl();
assert_eq!(input_names(&sdl), ["ConfidenceFilter"]);
assert_eq!(sdl.matches("scalar Float").count(), 0);
assert_eq!(sdl.matches("Score").count(), 0);
let mut returns = vec![("narrow", "f32"), ("wide", "f64")];
if cfg!(feature = "half") {
returns.push(("half", "f16"));
}
if cfg!(feature = "rust_decimal") {
returns.push(("exact", "f128"));
}
for (field, scalar) in &returns {
assert!(
sdl.contains(&format!("{field}(filter: ConfidenceFilter!): {scalar}!")),
"{field} returns {scalar}"
);
assert_eq!(
sdl.matches(&format!("scalar {scalar}\n")).count(),
1,
"{scalar} is declared once"
);
}
}
#[test]
fn the_interval_is_stated_once_at_the_wide_door() {
struct DescribedQuery;
#[Object]
impl DescribedQuery {
async fn wide(&self, filter: ConfidenceFilter) -> crate::F32 {
let _ = GraphqlFilter::is_empty(&filter);
<Score as crate::ToGraphqlOutput>::to_graphql_output(&Score::ONE)
}
}
let sdl = Schema::build(DescribedQuery, EmptyMutation, EmptySubscription)
.finish()
.sdl();
assert_eq!(sdl.matches("[0.0, 1.0]").count(), 1);
assert!(sdl.contains("never clamped"));
}
#[test]
fn each_width_narrows_the_one_operand_its_own_way() {
use crate::{Confidence, ConfidenceOperand, ScoreKind};
let tenth = ConfidenceOperand::decimal("0.1").expect("0.1 is a confidence");
assert_eq!(
Confidence::<f32>::from_operand(&tenth)
.expect("f32 holds it")
.get(),
0.1_f32
);
assert_eq!(
Confidence::<f64>::from_operand(&tenth)
.expect("f64 holds it")
.get(),
0.1_f64
);
#[cfg(feature = "half")]
assert_eq!(
Confidence::<half::f16>::from_operand(&tenth)
.expect("f16 holds it")
.get(),
half::f16::from_f64(0.1)
);
#[cfg(feature = "rust_decimal")]
assert_eq!(
Confidence::<rust_decimal::Decimal>::from_operand(&tenth)
.expect("a decimal holds it")
.get(),
rust_decimal::Decimal::from_str_exact("0.1").expect("0.1 is a decimal")
);
for refused in [1.5, -0.1] {
assert!(ConfidenceOperand::number(refused).is_err(), "{refused}");
}
for accepted in [0.0, 1.0] {
let operand = ConfidenceOperand::number(accepted).expect("in range");
assert!(Confidence::<f32>::from_operand(&operand).is_ok());
assert!(Confidence::<f64>::from_operand(&operand).is_ok());
#[cfg(feature = "half")]
assert!(Confidence::<half::f16>::from_operand(&operand).is_ok());
}
let wide = ConfidenceOperand::number(0.1).expect("0.1 is a confidence");
assert_eq!(
Confidence::<f64>::from_operand(&wide)
.expect("f64 holds its own double")
.get(),
0.1
);
}
#[cfg(feature = "rust_decimal")]
#[test]
fn the_decimal_width_reads_text_exactly_and_a_number_as_the_double() {
use rust_decimal::Decimal;
use crate::{Confidence, ConfidenceOperand, ScoreKind};
let exact = Decimal::from_str_exact("0.1").expect("0.1 is a decimal");
assert_eq!(
Confidence::<Decimal>::from_operand(&ConfidenceOperand::decimal("0.1").expect("in range"))
.expect("the text leg is exact")
.get(),
exact
);
assert_ne!(
Confidence::<Decimal>::from_operand(&ConfidenceOperand::number(0.1).expect("in range"))
.expect("the number leg carries the double")
.get(),
exact,
"a JSON number carries the DOUBLE's own value, which is not a tenth"
);
use async_graphql::{ScalarType, Value};
let one = <Confidence<Decimal> as crate::ToGraphqlOutput>::to_graphql_output(&Confidence::ONE);
assert_eq!(ScalarType::to_value(&one), Value::String("1".to_owned()));
}