async-graphql/src/validation/test_harness.rs

437 lines
8.9 KiB
Rust
Raw Normal View History

2020-04-05 08:00:26 +00:00
#![allow(unused_variables)]
#![allow(dead_code)]
2020-05-01 23:57:34 +00:00
#![allow(unreachable_code)]
2020-04-05 08:00:26 +00:00
2020-10-15 06:38:10 +00:00
use once_cell::sync::Lazy;
2022-04-19 04:25:11 +00:00
use crate::{
futures_util::Stream,
parser::types::ExecutableDocument,
validation::visitor::{visit, RuleError, Visitor, VisitorContext},
*,
};
2020-04-05 08:00:26 +00:00
#[derive(InputObject)]
#[graphql(internal)]
2020-04-05 08:00:26 +00:00
struct TestInput {
id: i32,
name: String,
}
impl Default for TestInput {
fn default() -> Self {
Self {
id: 423,
name: "foo".to_string(),
}
}
}
#[derive(Enum, Eq, PartialEq, Copy, Clone)]
#[graphql(internal)]
2020-04-05 08:00:26 +00:00
enum DogCommand {
Sit,
Heel,
Down,
}
struct Dog;
#[Object(internal)]
2020-04-05 08:00:26 +00:00
impl Dog {
async fn name(&self, surname: Option<bool>) -> Option<String> {
unimplemented!()
}
async fn nickname(&self) -> Option<String> {
unimplemented!()
}
async fn bark_volume(&self) -> Option<i32> {
unimplemented!()
}
async fn barks(&self) -> Option<bool> {
unimplemented!()
}
async fn does_know_command(&self, dog_command: Option<DogCommand>) -> Option<bool> {
unimplemented!()
}
2020-09-28 09:44:00 +00:00
async fn is_housetrained(
&self,
#[graphql(default = true)] at_other_homes: bool,
) -> Option<bool> {
2020-04-05 08:00:26 +00:00
unimplemented!()
}
async fn is_at_location(&self, x: Option<i32>, y: Option<i32>) -> Option<bool> {
unimplemented!()
}
}
#[derive(Enum, Copy, Clone, Eq, PartialEq)]
#[graphql(internal)]
2020-04-05 08:00:26 +00:00
enum FurColor {
Brown,
Black,
Tan,
Spotted,
}
struct Cat;
#[Object(internal)]
2020-04-05 08:00:26 +00:00
impl Cat {
async fn name(&self, surname: Option<bool>) -> Option<String> {
unimplemented!()
}
async fn nickname(&self) -> Option<String> {
unimplemented!()
}
async fn meows(&self) -> Option<bool> {
unimplemented!()
}
async fn meow_volume(&self) -> Option<i32> {
unimplemented!()
}
async fn fur_color(&self) -> Option<FurColor> {
unimplemented!()
}
}
#[derive(Union)]
#[graphql(internal)]
enum CatOrDog {
Cat(Cat),
Dog(Dog),
}
2020-04-05 08:00:26 +00:00
struct Human;
#[Object(internal)]
2020-04-05 08:00:26 +00:00
impl Human {
async fn name(&self, surname: Option<bool>) -> Option<String> {
unimplemented!()
}
async fn pets(&self) -> Option<Vec<Option<Pet>>> {
unimplemented!()
}
async fn relatives(&self) -> Option<Vec<Human>> {
unimplemented!()
}
async fn iq(&self) -> Option<i32> {
unimplemented!()
}
}
struct Alien;
#[Object(internal)]
2020-04-05 08:00:26 +00:00
impl Alien {
async fn name(&self, surname: Option<bool>) -> Option<String> {
unimplemented!()
}
async fn iq(&self) -> Option<i32> {
unimplemented!()
}
async fn num_eyes(&self) -> Option<i32> {
unimplemented!()
}
}
#[derive(Union)]
#[graphql(internal)]
enum DogOrHuman {
Dog(Dog),
Human(Human),
}
2020-04-05 08:00:26 +00:00
#[derive(Union)]
#[graphql(internal)]
enum HumanOrAlien {
Human(Human),
Alien(Alien),
}
2020-04-05 08:00:26 +00:00
#[derive(Interface)]
#[graphql(
2020-04-05 08:00:26 +00:00
internal,
field(
name = "name",
type = "Option<String>",
arg(name = "surname", type = "Option<bool>")
)
)]
2020-05-11 03:25:49 +00:00
enum Being {
Dog(Dog),
Cat(Cat),
Human(Human),
Alien(Alien),
}
2020-04-05 08:00:26 +00:00
#[derive(Interface)]
#[graphql(
2020-04-05 08:00:26 +00:00
internal,
field(
name = "name",
type = "Option<String>",
arg(name = "surname", type = "Option<bool>")
)
)]
2020-05-11 03:25:49 +00:00
enum Pet {
Dog(Dog),
Cat(Cat),
}
2020-04-05 08:00:26 +00:00
#[derive(Interface)]
#[graphql(
2020-04-05 08:00:26 +00:00
internal,
field(
name = "name",
type = "Option<String>",
arg(name = "surname", type = "Option<bool>")
)
)]
2020-05-11 03:25:49 +00:00
enum Canine {
Dog(Dog),
}
2020-04-05 08:00:26 +00:00
#[derive(Interface)]
#[graphql(internal, field(name = "iq", type = "Option<i32>"))]
2020-05-11 03:25:49 +00:00
enum Intelligent {
Human(Human),
Alien(Alien),
}
2020-04-05 08:00:26 +00:00
#[derive(InputObject)]
#[graphql(internal)]
2020-04-05 08:00:26 +00:00
struct ComplexInput {
required_field: bool,
int_field: Option<i32>,
string_field: Option<String>,
boolean_field: Option<bool>,
string_list_field: Option<Vec<Option<String>>>,
}
struct ComplicatedArgs;
#[Object(internal)]
2020-04-05 08:00:26 +00:00
impl ComplicatedArgs {
async fn int_arg_field(&self, int_arg: Option<i32>) -> Option<String> {
unimplemented!()
}
async fn non_null_int_arg_field(&self, non_null_int_arg: i32) -> Option<String> {
unimplemented!()
}
async fn string_arg_field(&self, string_arg: Option<String>) -> Option<String> {
unimplemented!()
}
async fn boolean_arg_field(&self, boolean_arg: Option<bool>) -> Option<String> {
unimplemented!()
}
async fn enum_arg_field(&self, enum_arg: Option<FurColor>) -> Option<String> {
unimplemented!()
}
async fn float_arg_field(&self, float_arg: Option<f64>) -> Option<String> {
unimplemented!()
}
async fn id_arg_field(&self, id_arg: Option<ID>) -> Option<String> {
unimplemented!()
}
async fn string_list_arg_field(
&self,
string_list_arg: Option<Vec<Option<String>>>,
) -> Option<String> {
unimplemented!()
}
async fn complex_arg_field(&self, complex_arg: Option<ComplexInput>) -> Option<String> {
unimplemented!()
}
async fn multiple_reqs(&self, req1: i32, req2: i32) -> Option<String> {
unimplemented!()
}
async fn multiple_opts(
&self,
2020-09-28 09:44:00 +00:00
#[graphql(default)] opt1: i32,
#[graphql(default)] opt2: i32,
2020-04-05 08:00:26 +00:00
) -> Option<String> {
unimplemented!()
}
async fn multiple_opt_and_req(
&self,
req1: i32,
req2: i32,
2020-09-28 09:44:00 +00:00
#[graphql(default)] opt1: i32,
#[graphql(default)] opt2: i32,
2020-04-05 08:00:26 +00:00
) -> Option<String> {
unimplemented!()
}
}
#[derive(OneofObject)]
#[graphql(internal)]
enum OneofArg {
A(i32),
B(String),
}
2021-11-20 03:16:48 +00:00
pub struct Query;
2020-04-05 08:00:26 +00:00
#[Object(internal)]
2021-11-20 03:16:48 +00:00
impl Query {
2020-04-05 08:00:26 +00:00
async fn human(&self, id: Option<ID>) -> Option<Human> {
unimplemented!()
}
async fn alien(&self) -> Option<Alien> {
unimplemented!()
}
async fn dog(&self) -> Option<Dog> {
unimplemented!()
}
async fn cat(&self) -> Option<Cat> {
unimplemented!()
}
async fn pet(&self) -> Option<Pet> {
unimplemented!()
}
async fn being(&self) -> Option<Being> {
unimplemented!()
}
async fn intelligent(&self) -> Option<Intelligent> {
unimplemented!()
}
async fn cat_or_dog(&self) -> Option<CatOrDog> {
unimplemented!()
}
async fn dog_or_human(&self) -> Option<DogOrHuman> {
unimplemented!()
}
async fn human_or_alien(&self) -> Option<HumanOrAlien> {
unimplemented!()
}
async fn complicated_args(&self) -> Option<ComplicatedArgs> {
unimplemented!()
}
async fn oneof_arg(&self, arg: OneofArg) -> String {
unimplemented!()
}
async fn oneof_opt(&self, arg: Option<OneofArg>) -> String {
unimplemented!()
}
2020-04-05 08:00:26 +00:00
}
2021-11-20 03:16:48 +00:00
pub struct Mutation;
2020-04-05 08:00:26 +00:00
#[Object(internal)]
2021-11-20 03:16:48 +00:00
impl Mutation {
2020-09-28 09:44:00 +00:00
async fn test_input(&self, #[graphql(default)] input: TestInput) -> i32 {
2020-04-05 08:00:26 +00:00
unimplemented!()
}
}
2021-11-20 03:16:48 +00:00
pub struct Subscription;
#[Subscription(internal)]
2021-11-20 03:16:48 +00:00
impl Subscription {
async fn values(&self) -> impl Stream<Item = i32> {
futures_util::stream::once(async move { 10 })
}
}
2021-11-20 03:16:48 +00:00
static TEST_HARNESS: Lazy<Schema<Query, Mutation, Subscription>> =
Lazy::new(|| Schema::new(Query, Mutation, Subscription));
2020-04-05 08:00:26 +00:00
Rework errors This completely overhauls the error system used in async-graphql. - `Error` has been renamed to `ServerError` and `FieldError` has been renamed to just `Error`. This is because `FieldError` is by far the most common error that users will have to use so it makes sense to use the most obvious error name. Also, the current name didn't make sense as it was used for things other than field errors, such as the data callback for websockets. - `ServerError` has been made completely opaque. Before it was an enum of all the possible errors, but now it just contains an error message, the locations, the path and extensions. It is a shame that we lose information, it makes more sense as _conceptually_ GraphQL does not provide that information. It also frees us to change the internals of async-graphql a lot more. - The path of errors is no longer an opaque JSON value but a regular type, `Vec<PathSegment>`. The type duplication of `PathSegment` and `QueryPathSegment` is unfortunate, I plan to work on this in the future. - Now that `ServerError` is opaque, `RuleError` has been removed from the public API, making it simpler. - Additionally `QueryError` has been completely removed. Instead the error messages are constructed ad-hoc; I took care to never repeat an error message. - Instead of constructing field-not-found errors inside the implementations of field resolvers they now return `Option`s, where a `None` value is representative of the field not being found. - As an unfortunate consequence of the last change, self-referential types based on the output of a subscription resolver can no longer be created. This does not mean anything for users, but causes lifetime issues in the implementation of merged objects. I fixed it with a bit of a hack, but this'll have to be looked into further. - `InputValueError` now has a generic parameter - it's kind of weird but it's necessary for ergonomics. It also improves error messages. - The `ErrorExtensions` trait has been removed. I didn't think the `extend` method was necessary since `From` impls exist. But the ergonomics are still there with a new trait `ExtendError`, which is implemented for both errors and results. - `Response` now supports serializing multiple errors. This allows for nice things like having multiple validation errors not be awkwardly shoved into a single error. - When an error occurs in execution, data is sent as `null`. This is slightly more compliant with the spec but the algorithm described in <https://spec.graphql.org/June2018/#sec-Errors-and-Non-Nullability> has yet to be implemented.
2020-09-29 19:06:44 +00:00
pub(crate) fn validate<'a, V, F>(
doc: &'a ExecutableDocument,
factory: F,
) -> Result<(), Vec<RuleError>>
2020-04-05 08:00:26 +00:00
where
V: Visitor<'a> + 'a,
F: Fn() -> V,
{
2020-05-29 09:29:15 +00:00
let schema = &*TEST_HARNESS;
let registry = &schema.env.registry;
let mut ctx = VisitorContext::new(registry, doc, None);
2020-04-05 08:00:26 +00:00
let mut visitor = factory();
2020-05-29 09:29:15 +00:00
visit(&mut visitor, &mut ctx, doc);
Rework errors This completely overhauls the error system used in async-graphql. - `Error` has been renamed to `ServerError` and `FieldError` has been renamed to just `Error`. This is because `FieldError` is by far the most common error that users will have to use so it makes sense to use the most obvious error name. Also, the current name didn't make sense as it was used for things other than field errors, such as the data callback for websockets. - `ServerError` has been made completely opaque. Before it was an enum of all the possible errors, but now it just contains an error message, the locations, the path and extensions. It is a shame that we lose information, it makes more sense as _conceptually_ GraphQL does not provide that information. It also frees us to change the internals of async-graphql a lot more. - The path of errors is no longer an opaque JSON value but a regular type, `Vec<PathSegment>`. The type duplication of `PathSegment` and `QueryPathSegment` is unfortunate, I plan to work on this in the future. - Now that `ServerError` is opaque, `RuleError` has been removed from the public API, making it simpler. - Additionally `QueryError` has been completely removed. Instead the error messages are constructed ad-hoc; I took care to never repeat an error message. - Instead of constructing field-not-found errors inside the implementations of field resolvers they now return `Option`s, where a `None` value is representative of the field not being found. - As an unfortunate consequence of the last change, self-referential types based on the output of a subscription resolver can no longer be created. This does not mean anything for users, but causes lifetime issues in the implementation of merged objects. I fixed it with a bit of a hack, but this'll have to be looked into further. - `InputValueError` now has a generic parameter - it's kind of weird but it's necessary for ergonomics. It also improves error messages. - The `ErrorExtensions` trait has been removed. I didn't think the `extend` method was necessary since `From` impls exist. But the ergonomics are still there with a new trait `ExtendError`, which is implemented for both errors and results. - `Response` now supports serializing multiple errors. This allows for nice things like having multiple validation errors not be awkwardly shoved into a single error. - When an error occurs in execution, data is sent as `null`. This is slightly more compliant with the spec but the algorithm described in <https://spec.graphql.org/June2018/#sec-Errors-and-Non-Nullability> has yet to be implemented.
2020-09-29 19:06:44 +00:00
if ctx.errors.is_empty() {
Ok(())
} else {
Err(ctx.errors)
2020-04-05 08:00:26 +00:00
}
}
pub(crate) fn expect_passes_rule_<'a, V, F>(doc: &'a ExecutableDocument, factory: F)
2020-05-29 09:29:15 +00:00
where
2020-04-05 08:00:26 +00:00
V: Visitor<'a> + 'a,
F: Fn() -> V,
{
Rework errors This completely overhauls the error system used in async-graphql. - `Error` has been renamed to `ServerError` and `FieldError` has been renamed to just `Error`. This is because `FieldError` is by far the most common error that users will have to use so it makes sense to use the most obvious error name. Also, the current name didn't make sense as it was used for things other than field errors, such as the data callback for websockets. - `ServerError` has been made completely opaque. Before it was an enum of all the possible errors, but now it just contains an error message, the locations, the path and extensions. It is a shame that we lose information, it makes more sense as _conceptually_ GraphQL does not provide that information. It also frees us to change the internals of async-graphql a lot more. - The path of errors is no longer an opaque JSON value but a regular type, `Vec<PathSegment>`. The type duplication of `PathSegment` and `QueryPathSegment` is unfortunate, I plan to work on this in the future. - Now that `ServerError` is opaque, `RuleError` has been removed from the public API, making it simpler. - Additionally `QueryError` has been completely removed. Instead the error messages are constructed ad-hoc; I took care to never repeat an error message. - Instead of constructing field-not-found errors inside the implementations of field resolvers they now return `Option`s, where a `None` value is representative of the field not being found. - As an unfortunate consequence of the last change, self-referential types based on the output of a subscription resolver can no longer be created. This does not mean anything for users, but causes lifetime issues in the implementation of merged objects. I fixed it with a bit of a hack, but this'll have to be looked into further. - `InputValueError` now has a generic parameter - it's kind of weird but it's necessary for ergonomics. It also improves error messages. - The `ErrorExtensions` trait has been removed. I didn't think the `extend` method was necessary since `From` impls exist. But the ergonomics are still there with a new trait `ExtendError`, which is implemented for both errors and results. - `Response` now supports serializing multiple errors. This allows for nice things like having multiple validation errors not be awkwardly shoved into a single error. - When an error occurs in execution, data is sent as `null`. This is slightly more compliant with the spec but the algorithm described in <https://spec.graphql.org/June2018/#sec-Errors-and-Non-Nullability> has yet to be implemented.
2020-09-29 19:06:44 +00:00
if let Err(errors) = validate(doc, factory) {
for err in errors {
if let Some(position) = err.locations.first() {
print!("[{}:{}] ", position.line, position.column);
2020-04-05 08:00:26 +00:00
}
Rework errors This completely overhauls the error system used in async-graphql. - `Error` has been renamed to `ServerError` and `FieldError` has been renamed to just `Error`. This is because `FieldError` is by far the most common error that users will have to use so it makes sense to use the most obvious error name. Also, the current name didn't make sense as it was used for things other than field errors, such as the data callback for websockets. - `ServerError` has been made completely opaque. Before it was an enum of all the possible errors, but now it just contains an error message, the locations, the path and extensions. It is a shame that we lose information, it makes more sense as _conceptually_ GraphQL does not provide that information. It also frees us to change the internals of async-graphql a lot more. - The path of errors is no longer an opaque JSON value but a regular type, `Vec<PathSegment>`. The type duplication of `PathSegment` and `QueryPathSegment` is unfortunate, I plan to work on this in the future. - Now that `ServerError` is opaque, `RuleError` has been removed from the public API, making it simpler. - Additionally `QueryError` has been completely removed. Instead the error messages are constructed ad-hoc; I took care to never repeat an error message. - Instead of constructing field-not-found errors inside the implementations of field resolvers they now return `Option`s, where a `None` value is representative of the field not being found. - As an unfortunate consequence of the last change, self-referential types based on the output of a subscription resolver can no longer be created. This does not mean anything for users, but causes lifetime issues in the implementation of merged objects. I fixed it with a bit of a hack, but this'll have to be looked into further. - `InputValueError` now has a generic parameter - it's kind of weird but it's necessary for ergonomics. It also improves error messages. - The `ErrorExtensions` trait has been removed. I didn't think the `extend` method was necessary since `From` impls exist. But the ergonomics are still there with a new trait `ExtendError`, which is implemented for both errors and results. - `Response` now supports serializing multiple errors. This allows for nice things like having multiple validation errors not be awkwardly shoved into a single error. - When an error occurs in execution, data is sent as `null`. This is slightly more compliant with the spec but the algorithm described in <https://spec.graphql.org/June2018/#sec-Errors-and-Non-Nullability> has yet to be implemented.
2020-09-29 19:06:44 +00:00
println!("{}", err.message);
2020-04-05 08:00:26 +00:00
}
panic!("Expected rule to pass, but errors found");
}
}
2020-05-29 09:29:15 +00:00
macro_rules! expect_passes_rule {
2020-09-06 05:38:31 +00:00
($factory:expr, $query_source:literal $(,)?) => {
2020-05-29 09:29:15 +00:00
let doc = crate::parser::parse_query($query_source).expect("Parse error");
crate::validation::test_harness::expect_passes_rule_(&doc, $factory);
};
}
pub(crate) fn expect_fails_rule_<'a, V, F>(doc: &'a ExecutableDocument, factory: F)
2020-05-29 09:29:15 +00:00
where
2020-04-05 08:00:26 +00:00
V: Visitor<'a> + 'a,
F: Fn() -> V,
{
if validate(doc, factory).is_ok() {
2020-04-05 08:00:26 +00:00
panic!("Expected rule to fail, but no errors were found");
}
}
2020-05-29 09:29:15 +00:00
macro_rules! expect_fails_rule {
2020-09-06 05:38:31 +00:00
($factory:expr, $query_source:literal $(,)?) => {
2020-05-29 09:29:15 +00:00
let doc = crate::parser::parse_query($query_source).expect("Parse error");
crate::validation::test_harness::expect_fails_rule_(&doc, $factory);
};
}