(ci) Check formatting with cargo fmt (#302)

This adds a new extra CI job for checking the formatting
with cargo fmt --check.
This commit is contained in:
theduke 2018-12-19 19:27:49 +01:00 committed by Christian Legnitto
parent aa80ec51bb
commit d015a3ca66
74 changed files with 1903 additions and 1684 deletions

View file

@ -1,14 +1,27 @@
jobs: jobs:
- template: _build/azure-pipelines-template.yml
parameters: - job: check_formatting
name: macOS pool:
vmImage: macOS-10.13 vmImage: ubuntu-16.04
steps:
- script: |
curl https://sh.rustup.rs -sSf | sh -s -- -y
$HOME/.cargo/bin/rustup component add rustfmt
displayName: Install rust
- script: |
$HOME/.cargo/bin/cargo fmt -- --check
displayName: Check formatting
- template: _build/azure-pipelines-template.yml - template: _build/azure-pipelines-template.yml
parameters: parameters:
name: Linux name: Linux
vmImage: ubuntu-16.04 vmImage: ubuntu-16.04
- template: _build/azure-pipelines-template.yml
parameters:
name: macOS
vmImage: macOS-10.13
- template: _build/azure-pipelines-template.yml - template: _build/azure-pipelines-template.yml
parameters: parameters:
name: Windows name: Windows

View file

@ -31,6 +31,4 @@ juniper::graphql_object!(Query: () |&self| {
} }
}); });
fn main() {}
fn main() {
}

View file

@ -8,11 +8,7 @@ use juniper::{self, DefaultScalarValue, FromInputValue, GraphQLType, InputValue,
#[graphql(name = "Some", description = "enum descr")] #[graphql(name = "Some", description = "enum descr")]
enum SomeEnum { enum SomeEnum {
Regular, Regular,
#[graphql( #[graphql(name = "FULL", description = "field descr", deprecated = "depr")]
name = "FULL",
description = "field descr",
deprecated = "depr"
)]
Full, Full,
} }

View file

@ -105,7 +105,8 @@ fn test_derived_input_object() {
let input_no_defaults: InputValue = ::serde_json::from_value(json!({ let input_no_defaults: InputValue = ::serde_json::from_value(json!({
"regularField": "a", "regularField": "a",
})).unwrap(); }))
.unwrap();
let output_no_defaults: Input = FromInputValue::from_input_value(&input_no_defaults).unwrap(); let output_no_defaults: Input = FromInputValue::from_input_value(&input_no_defaults).unwrap();
assert_eq!( assert_eq!(
@ -123,7 +124,8 @@ fn test_derived_input_object() {
"regularField": "a", "regularField": "a",
"haha": 55, "haha": 55,
"other": true, "other": true,
})).unwrap(); }))
.unwrap();
let output: Input = FromInputValue::from_input_value(&input).unwrap(); let output: Input = FromInputValue::from_input_value(&input).unwrap();
assert_eq!( assert_eq!(

View file

@ -189,10 +189,12 @@ fn test_derived_object() {
vec![ vec![
("regularField", Value::scalar(true)), ("regularField", Value::scalar(true)),
("renamedField", Value::scalar(22)), ("renamedField", Value::scalar(22)),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]
@ -252,13 +254,16 @@ fn test_derived_object_nested() {
vec![ vec![
("regularField", Value::scalar(false)), ("regularField", Value::scalar(false)),
("renamedField", Value::scalar(333)), ("renamedField", Value::scalar(333)),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]
@ -297,15 +302,14 @@ fn check_descriptions(
type_info.get_field_value("description"), type_info.get_field_value("description"),
Some(object_description) Some(object_description)
); );
assert!( assert!(values.contains(&Value::object(
values.contains(&Value::object(
vec![ vec![
("name", Value::scalar(field_name)), ("name", Value::scalar(field_name)),
("description", field_value.clone()), ("description", field_value.clone()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }

View file

@ -220,7 +220,8 @@ fn querying_long_variable() {
vec![( vec![(
"test".to_owned(), "test".to_owned(),
InputValue::Scalar(MyScalarValue::Long((::std::i32::MAX as i64) + 42)), InputValue::Scalar(MyScalarValue::Long((::std::i32::MAX as i64) + 42)),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
|result| { |result| {
assert_eq!( assert_eq!(

View file

@ -8,7 +8,7 @@ use indexmap::IndexMap;
use executor::Variables; use executor::Variables;
use parser::Spanning; use parser::Spanning;
use value::{ScalarRefValue, ScalarValue, DefaultScalarValue}; use value::{DefaultScalarValue, ScalarRefValue, ScalarValue};
/// A type literal in the syntax tree /// A type literal in the syntax tree
/// ///
@ -285,7 +285,8 @@ where
Spanning::unlocated(k.as_ref().to_owned()), Spanning::unlocated(k.as_ref().to_owned()),
Spanning::unlocated(v), Spanning::unlocated(v),
) )
}).collect(), })
.collect(),
) )
} }
@ -346,10 +347,7 @@ where
} }
/// View the underlying int value, if present. /// View the underlying int value, if present.
#[deprecated( #[deprecated(since = "0.11.0", note = "Use `InputValue::as_scalar_value` instead")]
since = "0.11.0",
note = "Use `InputValue::as_scalar_value` instead"
)]
pub fn as_int_value<'a>(&'a self) -> Option<i32> pub fn as_int_value<'a>(&'a self) -> Option<i32>
where where
&'a S: Into<Option<&'a i32>>, &'a S: Into<Option<&'a i32>>,
@ -358,10 +356,7 @@ where
} }
/// View the underlying float value, if present. /// View the underlying float value, if present.
#[deprecated( #[deprecated(since = "0.11.0", note = "Use `InputValue::as_scalar_value` instead")]
since = "0.11.0",
note = "Use `InputValue::as_scalar_value` instead"
)]
pub fn as_float_value<'a>(&'a self) -> Option<f64> pub fn as_float_value<'a>(&'a self) -> Option<f64>
where where
&'a S: Into<Option<&'a f64>>, &'a S: Into<Option<&'a f64>>,
@ -370,10 +365,7 @@ where
} }
/// View the underlying string value, if present. /// View the underlying string value, if present.
#[deprecated( #[deprecated(since = "0.11.0", note = "Use `InputValue::as_scalar_value` instead")]
since = "0.11.0",
note = "Use `InputValue::as_scalar_value` instead"
)]
pub fn as_string_value<'a>(&'a self) -> Option<&'a str> pub fn as_string_value<'a>(&'a self) -> Option<&'a str>
where where
&'a S: Into<Option<&'a String>>, &'a S: Into<Option<&'a String>>,
@ -453,7 +445,8 @@ where
.zip(l2.iter()) .zip(l2.iter())
.all(|(v1, v2)| v1.item.unlocated_eq(&v2.item)), .all(|(v1, v2)| v1.item.unlocated_eq(&v2.item)),
(&Object(ref o1), &Object(ref o2)) => { (&Object(ref o1), &Object(ref o2)) => {
o1.len() == o2.len() && o1.iter().all(|&(ref sk1, ref sv1)| { o1.len() == o2.len()
&& o1.iter().all(|&(ref sk1, ref sv1)| {
o2.iter().any(|&(ref sk2, ref sv2)| { o2.iter().any(|&(ref sk2, ref sv2)| {
sk1.item == sk2.item && sv1.item.unlocated_eq(&sv2.item) sk1.item == sk2.item && sv1.item.unlocated_eq(&sv2.item)
}) })

View file

@ -52,7 +52,8 @@ where
&n.item as &str, &n.item as &str,
LookAheadValue::from_input_value(&i.item, vars), LookAheadValue::from_input_value(&i.item, vars),
) )
}).collect(), })
.collect(),
), ),
} }
} }
@ -134,7 +135,8 @@ where
} else { } else {
false false
} }
}).unwrap_or(false), })
.unwrap_or(false),
("skip", &Some(ref a)) => a ("skip", &Some(ref a)) => a
.item .item
.items .items
@ -150,13 +152,15 @@ where
} else { } else {
false false
} }
}).unwrap_or(false), })
.unwrap_or(false),
("skip", &None) => false, ("skip", &None) => false,
("include", &None) => true, ("include", &None) => true,
(_, _) => unreachable!(), (_, _) => unreachable!(),
} }
}) })
}).unwrap_or(true) })
.unwrap_or(true)
} }
pub(super) fn build_from_selection( pub(super) fn build_from_selection(
@ -192,7 +196,8 @@ where
.iter() .iter()
.map(|p| LookAheadArgument::new(p, vars)) .map(|p| LookAheadArgument::new(p, vars))
.collect() .collect()
}).unwrap_or_else(Vec::new); })
.unwrap_or_else(Vec::new);
let mut ret = LookAheadSelection { let mut ret = LookAheadSelection {
name, name,
alias, alias,
@ -280,7 +285,8 @@ where
} }
Applies::All => Some(c.inner.for_explicit_type(type_name)), Applies::All => Some(c.inner.for_explicit_type(type_name)),
Applies::OnlyType(_) => None, Applies::OnlyType(_) => None,
}).collect(), })
.collect(),
name: self.name, name: self.name,
alias: self.alias, alias: self.alias,
arguments: self.arguments.clone(), arguments: self.arguments.clone(),
@ -390,7 +396,8 @@ query Hero {
} }
} }
", ",
).unwrap(); )
.unwrap();
let fragments = extract_fragments(&docs); let fragments = extract_fragments(&docs);
if let ::ast::Definition::Operation(ref op) = docs[0] { if let ::ast::Definition::Operation(ref op) = docs[0] {
@ -442,7 +449,8 @@ query Hero {
} }
} }
", ",
).unwrap(); )
.unwrap();
let fragments = extract_fragments(&docs); let fragments = extract_fragments(&docs);
if let ::ast::Definition::Operation(ref op) = docs[0] { if let ::ast::Definition::Operation(ref op) = docs[0] {
@ -498,7 +506,8 @@ query Hero {
} }
} }
", ",
).unwrap(); )
.unwrap();
let fragments = extract_fragments(&docs); let fragments = extract_fragments(&docs);
if let ::ast::Definition::Operation(ref op) = docs[0] { if let ::ast::Definition::Operation(ref op) = docs[0] {
@ -578,7 +587,8 @@ query Hero {
} }
} }
", ",
).unwrap(); )
.unwrap();
let fragments = extract_fragments(&docs); let fragments = extract_fragments(&docs);
if let ::ast::Definition::Operation(ref op) = docs[0] { if let ::ast::Definition::Operation(ref op) = docs[0] {
@ -636,7 +646,8 @@ query Hero($episode: Episode) {
} }
} }
", ",
).unwrap(); )
.unwrap();
let fragments = extract_fragments(&docs); let fragments = extract_fragments(&docs);
if let ::ast::Definition::Operation(ref op) = docs[0] { if let ::ast::Definition::Operation(ref op) = docs[0] {
@ -697,7 +708,8 @@ fragment commonFields on Character {
appearsIn appearsIn
} }
", ",
).unwrap(); )
.unwrap();
let fragments = extract_fragments(&docs); let fragments = extract_fragments(&docs);
if let ::ast::Definition::Operation(ref op) = docs[0] { if let ::ast::Definition::Operation(ref op) = docs[0] {
@ -759,7 +771,8 @@ query Hero {
height @skip(if: false) height @skip(if: false)
} }
}", }",
).unwrap(); )
.unwrap();
let fragments = extract_fragments(&docs); let fragments = extract_fragments(&docs);
if let ::ast::Definition::Operation(ref op) = docs[0] { if let ::ast::Definition::Operation(ref op) = docs[0] {
@ -815,7 +828,8 @@ query Hero {
} }
} }
}", }",
).unwrap(); )
.unwrap();
let fragments = extract_fragments(&docs); let fragments = extract_fragments(&docs);
if let ::ast::Definition::Operation(ref op) = docs[0] { if let ::ast::Definition::Operation(ref op) = docs[0] {
@ -887,7 +901,8 @@ fragment comparisonFields on Character {
... on Droid { primaryFunction } ... on Droid { primaryFunction }
... on Human { height } ... on Human { height }
}", }",
).unwrap(); )
.unwrap();
let fragments = extract_fragments(&docs); let fragments = extract_fragments(&docs);
if let ::ast::Definition::Operation(ref op) = docs[0] { if let ::ast::Definition::Operation(ref op) = docs[0] {
@ -1043,7 +1058,8 @@ query Hero {
} }
} }
}", }",
).unwrap(); )
.unwrap();
let fragments = extract_fragments(&docs); let fragments = extract_fragments(&docs);
if let ::ast::Definition::Operation(ref op) = docs[0] { if let ::ast::Definition::Operation(ref op) = docs[0] {
@ -1052,7 +1068,8 @@ query Hero {
&op.item.selection_set[0], &op.item.selection_set[0],
&vars, &vars,
&fragments, &fragments,
).for_explicit_type("Human"); )
.for_explicit_type("Human");
let expected = ConcreteLookAheadSelection { let expected = ConcreteLookAheadSelection {
name: "hero", name: "hero",
alias: None, alias: None,

View file

@ -515,7 +515,8 @@ where
self.parent_selection_set self.parent_selection_set
.map(|p| { .map(|p| {
LookAheadSelection::build_from_selection(&p[0], self.variables, self.fragments) LookAheadSelection::build_from_selection(&p[0], self.variables, self.fragments)
}).unwrap_or_else(|| LookAheadSelection { })
.unwrap_or_else(|| LookAheadSelection {
name: self.current_type.innermost_concrete().name().unwrap_or(""), name: self.current_type.innermost_concrete().name().unwrap_or(""),
alias: None, alias: None,
arguments: Vec::new(), arguments: Vec::new(),
@ -530,8 +531,10 @@ where
self.fragments, self.fragments,
), ),
applies_for: Applies::All, applies_for: Applies::All,
}).collect() })
}).unwrap_or_else(Vec::new), .collect()
})
.unwrap_or_else(Vec::new),
}) })
} }
} }
@ -627,7 +630,8 @@ where
def.default_value def.default_value
.as_ref() .as_ref()
.map(|i| (name.item.to_owned(), i.item.clone())) .map(|i| (name.item.to_owned(), i.item.clone()))
}).collect::<HashMap<String, InputValue<S>>>() })
.collect::<HashMap<String, InputValue<S>>>()
}); });
let errors = RwLock::new(Vec::new()); let errors = RwLock::new(Vec::new());

View file

@ -1,7 +1,7 @@
use executor::Variables; use executor::Variables;
use schema::model::RootNode; use schema::model::RootNode;
use types::scalars::EmptyMutation; use types::scalars::EmptyMutation;
use value::{Value, Object, DefaultScalarValue}; use value::{DefaultScalarValue, Object, Value};
struct TestType; struct TestType;

View file

@ -103,7 +103,8 @@ mod field_execution {
vec![ vec![
("a", Value::scalar("Apple")), ("a", Value::scalar("Apple")),
("b", Value::scalar("Banana")), ("b", Value::scalar("Banana")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
Value::null(), Value::null(),
@ -111,16 +112,19 @@ mod field_execution {
vec![ vec![
("a", Value::scalar("Apple")), ("a", Value::scalar("Apple")),
("b", Value::scalar("Banana")), ("b", Value::scalar("Banana")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
]), ]),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect() .collect()
) )
); );
@ -180,17 +184,20 @@ mod merge_parallel_fragments {
vec![ vec![
("b", Value::scalar("Banana")), ("b", Value::scalar("Banana")),
("c", Value::scalar("Cherry")), ("c", Value::scalar("Cherry")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
("c", Value::scalar("Cherry")), ("c", Value::scalar("Cherry")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
("c", Value::scalar("Cherry")), ("c", Value::scalar("Cherry")),
].into_iter() ]
.into_iter()
.collect() .collect()
) )
); );
@ -278,10 +285,12 @@ mod merge_parallel_inline_fragments {
vec![ vec![
("b", Value::scalar("Banana")), ("b", Value::scalar("Banana")),
("c", Value::scalar("Cherry")), ("c", Value::scalar("Cherry")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
), ),
Value::object( Value::object(
@ -291,21 +300,25 @@ mod merge_parallel_inline_fragments {
vec![ vec![
("b", Value::scalar("Banana")), ("b", Value::scalar("Banana")),
("c", Value::scalar("Cherry")), ("c", Value::scalar("Cherry")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
), ),
]), ]),
), ),
("c", Value::scalar("Cherry")), ("c", Value::scalar("Cherry")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
("c", Value::scalar("Cherry")), ("c", Value::scalar("Cherry")),
].into_iter() ]
.into_iter()
.collect() .collect()
) )
); );
@ -345,7 +358,8 @@ mod threads_context_correctly {
&TestContext { &TestContext {
value: "Context value".to_owned(), value: "Context value".to_owned(),
}, },
).expect("Execution failed"); )
.expect("Execution failed");
assert_eq!(errs, []); assert_eq!(errs, []);
@ -438,7 +452,8 @@ mod dynamic_context_switching {
value: "Second value".to_owned(), value: "Second value".to_owned(),
}, },
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
}; };
@ -461,7 +476,8 @@ mod dynamic_context_switching {
), ),
), ),
("missing", Value::null()), ("missing", Value::null()),
].into_iter() ]
.into_iter()
.collect() .collect()
) )
); );
@ -492,7 +508,8 @@ mod dynamic_context_switching {
value: "Second value".to_owned(), value: "Second value".to_owned(),
}, },
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
}; };
@ -512,7 +529,8 @@ mod dynamic_context_switching {
.into_iter() .into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect() .collect()
) )
); );
@ -543,7 +561,8 @@ mod dynamic_context_switching {
value: "Second value".to_owned(), value: "Second value".to_owned(),
}, },
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
}; };
@ -590,7 +609,8 @@ mod dynamic_context_switching {
value: "Second value".to_owned(), value: "Second value".to_owned(),
}, },
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
}; };
@ -621,7 +641,8 @@ mod dynamic_context_switching {
), ),
("missing", Value::null()), ("missing", Value::null()),
("tooLarge", Value::null()), ("tooLarge", Value::null()),
].into_iter() ]
.into_iter()
.collect() .collect()
) )
); );
@ -648,7 +669,8 @@ mod dynamic_context_switching {
value: "Second value".to_owned(), value: "Second value".to_owned(),
}, },
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
}; };
@ -668,7 +690,8 @@ mod dynamic_context_switching {
.into_iter() .into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect() .collect()
) )
); );

View file

@ -123,18 +123,21 @@ mod interface {
vec![ vec![
("name", Value::scalar("Odie")), ("name", Value::scalar("Odie")),
("woofs", Value::scalar(true)), ("woofs", Value::scalar(true)),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
Value::object( Value::object(
vec![ vec![
("name", Value::scalar("Garfield")), ("name", Value::scalar("Garfield")),
("meows", Value::scalar(false)), ("meows", Value::scalar(false)),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
]), ]),
)].into_iter() )]
.into_iter()
.collect() .collect()
) )
); );
@ -255,7 +258,8 @@ mod union {
("__typename", Value::scalar("Dog")), ("__typename", Value::scalar("Dog")),
("name", Value::scalar("Odie")), ("name", Value::scalar("Odie")),
("woofs", Value::scalar(true)), ("woofs", Value::scalar(true)),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
Value::object( Value::object(
@ -263,11 +267,13 @@ mod union {
("__typename", Value::scalar("Cat")), ("__typename", Value::scalar("Cat")),
("name", Value::scalar("Garfield")), ("name", Value::scalar("Garfield")),
("meows", Value::scalar(false)), ("meows", Value::scalar(false)),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
]), ]),
)].into_iter() )]
.into_iter()
.collect() .collect()
) )
); );

View file

@ -1,7 +1,7 @@
use executor::Variables; use executor::Variables;
use schema::model::RootNode; use schema::model::RootNode;
use types::scalars::EmptyMutation; use types::scalars::EmptyMutation;
use value::{Value, Object, DefaultScalarValue}; use value::{DefaultScalarValue, Object, Value};
/* /*
@ -53,7 +53,10 @@ enum EnumValueDescription {
enum EnumDeprecation { enum EnumDeprecation {
#[graphql(deprecated = "Please don't use FOO any more")] #[graphql(deprecated = "Please don't use FOO any more")]
Foo, Foo,
#[graphql(description = "The BAR value", deprecated = "Please don't use BAR any more")] #[graphql(
description = "The BAR value",
deprecated = "Please don't use BAR any more"
)]
Bar, Bar,
} }
@ -116,34 +119,38 @@ fn default_name_introspection() {
"#; "#;
run_type_info_query(doc, |(type_info, values)| { run_type_info_query(doc, |(type_info, values)| {
assert_eq!(type_info.get_field_value("name"), Some(&Value::scalar("DefaultName"))); assert_eq!(
assert_eq!(type_info.get_field_value("description"), Some(&Value::null())); type_info.get_field_value("name"),
Some(&Value::scalar("DefaultName"))
);
assert_eq!(
type_info.get_field_value("description"),
Some(&Value::null())
);
assert_eq!(values.len(), 2); assert_eq!(values.len(), 2);
assert!( assert!(values.contains(&Value::object(
values.contains(&Value::object(
vec![ vec![
("name", Value::scalar("FOO")), ("name", Value::scalar("FOO")),
("description", Value::null()), ("description", Value::null()),
("isDeprecated", Value::scalar(false)), ("isDeprecated", Value::scalar(false)),
("deprecationReason", Value::null()), ("deprecationReason", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(values.contains(&Value::object(
values.contains(&Value::object(
vec![ vec![
("name", Value::scalar("BAR")), ("name", Value::scalar("BAR")),
("description", Value::null()), ("description", Value::null()),
("isDeprecated", Value::scalar(false)), ("isDeprecated", Value::scalar(false)),
("deprecationReason", Value::null()), ("deprecationReason", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -165,34 +172,38 @@ fn named_introspection() {
"#; "#;
run_type_info_query(doc, |(type_info, values)| { run_type_info_query(doc, |(type_info, values)| {
assert_eq!(type_info.get_field_value("name"), Some(&Value::scalar("ANamedEnum"))); assert_eq!(
assert_eq!(type_info.get_field_value("description"), Some(&Value::null())); type_info.get_field_value("name"),
Some(&Value::scalar("ANamedEnum"))
);
assert_eq!(
type_info.get_field_value("description"),
Some(&Value::null())
);
assert_eq!(values.len(), 2); assert_eq!(values.len(), 2);
assert!( assert!(values.contains(&Value::object(
values.contains(&Value::object(
vec![ vec![
("name", Value::scalar("FOO")), ("name", Value::scalar("FOO")),
("description", Value::null()), ("description", Value::null()),
("isDeprecated", Value::scalar(false)), ("isDeprecated", Value::scalar(false)),
("deprecationReason", Value::null()), ("deprecationReason", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(values.contains(&Value::object(
values.contains(&Value::object(
vec![ vec![
("name", Value::scalar("BAR")), ("name", Value::scalar("BAR")),
("description", Value::null()), ("description", Value::null()),
("isDeprecated", Value::scalar(false)), ("isDeprecated", Value::scalar(false)),
("deprecationReason", Value::null()), ("deprecationReason", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -218,33 +229,34 @@ fn no_trailing_comma_introspection() {
type_info.get_field_value("name"), type_info.get_field_value("name"),
Some(&Value::scalar("NoTrailingComma")) Some(&Value::scalar("NoTrailingComma"))
); );
assert_eq!(type_info.get_field_value("description"), Some(&Value::null())); assert_eq!(
type_info.get_field_value("description"),
Some(&Value::null())
);
assert_eq!(values.len(), 2); assert_eq!(values.len(), 2);
assert!( assert!(values.contains(&Value::object(
values.contains(&Value::object(
vec![ vec![
("name", Value::scalar("FOO")), ("name", Value::scalar("FOO")),
("description", Value::null()), ("description", Value::null()),
("isDeprecated", Value::scalar(false)), ("isDeprecated", Value::scalar(false)),
("deprecationReason", Value::null()), ("deprecationReason", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(values.contains(&Value::object(
values.contains(&Value::object(
vec![ vec![
("name", Value::scalar("BAR")), ("name", Value::scalar("BAR")),
("description", Value::null()), ("description", Value::null()),
("isDeprecated", Value::scalar(false)), ("isDeprecated", Value::scalar(false)),
("deprecationReason", Value::null()), ("deprecationReason", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -277,29 +289,27 @@ fn enum_description_introspection() {
assert_eq!(values.len(), 2); assert_eq!(values.len(), 2);
assert!( assert!(values.contains(&Value::object(
values.contains(&Value::object(
vec![ vec![
("name", Value::scalar("FOO")), ("name", Value::scalar("FOO")),
("description", Value::null()), ("description", Value::null()),
("isDeprecated", Value::scalar(false)), ("isDeprecated", Value::scalar(false)),
("deprecationReason", Value::null()), ("deprecationReason", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(values.contains(&Value::object(
values.contains(&Value::object(
vec![ vec![
("name", Value::scalar("BAR")), ("name", Value::scalar("BAR")),
("description", Value::null()), ("description", Value::null()),
("isDeprecated", Value::scalar(false)), ("isDeprecated", Value::scalar(false)),
("deprecationReason", Value::null()), ("deprecationReason", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -325,33 +335,34 @@ fn enum_value_description_introspection() {
type_info.get_field_value("name"), type_info.get_field_value("name"),
Some(&Value::scalar("EnumValueDescription")) Some(&Value::scalar("EnumValueDescription"))
); );
assert_eq!(type_info.get_field_value("description"), Some(&Value::null())); assert_eq!(
type_info.get_field_value("description"),
Some(&Value::null())
);
assert_eq!(values.len(), 2); assert_eq!(values.len(), 2);
assert!( assert!(values.contains(&Value::object(
values.contains(&Value::object(
vec![ vec![
("name", Value::scalar("FOO")), ("name", Value::scalar("FOO")),
("description", Value::scalar("The FOO value")), ("description", Value::scalar("The FOO value")),
("isDeprecated", Value::scalar(false)), ("isDeprecated", Value::scalar(false)),
("deprecationReason", Value::null()), ("deprecationReason", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(values.contains(&Value::object(
values.contains(&Value::object(
vec![ vec![
("name", Value::scalar("BAR")), ("name", Value::scalar("BAR")),
("description", Value::scalar("The BAR value")), ("description", Value::scalar("The BAR value")),
("isDeprecated", Value::scalar(false)), ("isDeprecated", Value::scalar(false)),
("deprecationReason", Value::null()), ("deprecationReason", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -377,12 +388,14 @@ fn enum_deprecation_introspection() {
type_info.get_field_value("name"), type_info.get_field_value("name"),
Some(&Value::scalar("EnumDeprecation")) Some(&Value::scalar("EnumDeprecation"))
); );
assert_eq!(type_info.get_field_value("description"), Some(&Value::null())); assert_eq!(
type_info.get_field_value("description"),
Some(&Value::null())
);
assert_eq!(values.len(), 2); assert_eq!(values.len(), 2);
assert!( assert!(values.contains(&Value::object(
values.contains(&Value::object(
vec![ vec![
("name", Value::scalar("FOO")), ("name", Value::scalar("FOO")),
("description", Value::null()), ("description", Value::null()),
@ -391,13 +404,12 @@ fn enum_deprecation_introspection() {
"deprecationReason", "deprecationReason",
Value::scalar("Please don't use FOO any more"), Value::scalar("Please don't use FOO any more"),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(values.contains(&Value::object(
values.contains(&Value::object(
vec![ vec![
("name", Value::scalar("BAR")), ("name", Value::scalar("BAR")),
("description", Value::scalar("The BAR value")), ("description", Value::scalar("The BAR value")),
@ -406,10 +418,10 @@ fn enum_deprecation_introspection() {
"deprecationReason", "deprecationReason",
Value::scalar("Please don't use BAR any more"), Value::scalar("Please don't use BAR any more"),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -435,7 +447,10 @@ fn enum_deprecation_no_values_introspection() {
type_info.get_field_value("name"), type_info.get_field_value("name"),
Some(&Value::scalar("EnumDeprecation")) Some(&Value::scalar("EnumDeprecation"))
); );
assert_eq!(type_info.get_field_value("description"), Some(&Value::null())); assert_eq!(
type_info.get_field_value("description"),
Some(&Value::null())
);
assert_eq!(values.len(), 0); assert_eq!(values.len(), 0);
}); });

View file

@ -49,7 +49,7 @@ pub struct PublicWithDescription {
#[derive(GraphQLInputObjectInternal, Debug)] #[derive(GraphQLInputObjectInternal, Debug)]
#[graphql( #[graphql(
name = "APublicNamedInputObjectWithDescription", name = "APublicNamedInputObjectWithDescription",
description = "Description for the input object", description = "Description for the input object"
)] )]
pub struct NamedPublicWithDescription { pub struct NamedPublicWithDescription {
field_one: String, field_one: String,
@ -158,8 +158,7 @@ fn default_name_introspection() {
assert_eq!(fields.len(), 2); assert_eq!(fields.len(), 2);
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![ vec![
("name", Value::scalar("fieldOne")), ("name", Value::scalar("fieldOne")),
("description", Value::null()), ("description", Value::null()),
@ -173,18 +172,18 @@ fn default_name_introspection() {
.into_iter() .into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
), ),
), ),
("defaultValue", Value::null()), ("defaultValue", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![ vec![
("name", Value::scalar("fieldTwo")), ("name", Value::scalar("fieldTwo")),
("description", Value::null()), ("description", Value::null()),
@ -198,15 +197,16 @@ fn default_name_introspection() {
.into_iter() .into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
), ),
), ),
("defaultValue", Value::null()), ("defaultValue", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -216,7 +216,8 @@ fn default_name_input_value() {
vec![ vec![
("fieldOne", InputValue::scalar("number one")), ("fieldOne", InputValue::scalar("number one")),
("fieldTwo", InputValue::scalar("number two")), ("fieldTwo", InputValue::scalar("number two")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
); );
@ -263,8 +264,7 @@ fn no_trailing_comma_introspection() {
assert_eq!(fields.len(), 2); assert_eq!(fields.len(), 2);
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![ vec![
("name", Value::scalar("fieldOne")), ("name", Value::scalar("fieldOne")),
("description", Value::null()), ("description", Value::null()),
@ -278,18 +278,18 @@ fn no_trailing_comma_introspection() {
.into_iter() .into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
), ),
), ),
("defaultValue", Value::null()), ("defaultValue", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![ vec![
("name", Value::scalar("fieldTwo")), ("name", Value::scalar("fieldTwo")),
("description", Value::null()), ("description", Value::null()),
@ -303,15 +303,16 @@ fn no_trailing_comma_introspection() {
.into_iter() .into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
), ),
), ),
("defaultValue", Value::null()), ("defaultValue", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -348,8 +349,7 @@ fn derive_introspection() {
assert_eq!(fields.len(), 1); assert_eq!(fields.len(), 1);
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![ vec![
("name", Value::scalar("fieldOne")), ("name", Value::scalar("fieldOne")),
("description", Value::null()), ("description", Value::null()),
@ -363,15 +363,16 @@ fn derive_introspection() {
.into_iter() .into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
), ),
), ),
("defaultValue", Value::null()), ("defaultValue", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -421,8 +422,7 @@ fn named_introspection() {
assert_eq!(fields.len(), 1); assert_eq!(fields.len(), 1);
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![ vec![
("name", Value::scalar("fieldOne")), ("name", Value::scalar("fieldOne")),
("description", Value::null()), ("description", Value::null()),
@ -436,15 +436,16 @@ fn named_introspection() {
.into_iter() .into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
), ),
), ),
("defaultValue", Value::null()), ("defaultValue", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -481,8 +482,7 @@ fn description_introspection() {
assert_eq!(fields.len(), 1); assert_eq!(fields.len(), 1);
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![ vec![
("name", Value::scalar("fieldOne")), ("name", Value::scalar("fieldOne")),
("description", Value::null()), ("description", Value::null()),
@ -496,15 +496,16 @@ fn description_introspection() {
.into_iter() .into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
), ),
), ),
("defaultValue", Value::null()), ("defaultValue", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -541,8 +542,7 @@ fn field_description_introspection() {
assert_eq!(fields.len(), 2); assert_eq!(fields.len(), 2);
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![ vec![
("name", Value::scalar("fieldOne")), ("name", Value::scalar("fieldOne")),
("description", Value::scalar("The first field")), ("description", Value::scalar("The first field")),
@ -556,18 +556,18 @@ fn field_description_introspection() {
.into_iter() .into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
), ),
), ),
("defaultValue", Value::null()), ("defaultValue", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![ vec![
("name", Value::scalar("fieldTwo")), ("name", Value::scalar("fieldTwo")),
("description", Value::scalar("The second field")), ("description", Value::scalar("The second field")),
@ -581,15 +581,16 @@ fn field_description_introspection() {
.into_iter() .into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
), ),
), ),
("defaultValue", Value::null()), ("defaultValue", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -618,8 +619,7 @@ fn field_with_defaults_introspection() {
assert_eq!(fields.len(), 2); assert_eq!(fields.len(), 2);
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![ vec![
("name", Value::scalar("fieldOne")), ("name", Value::scalar("fieldOne")),
( (
@ -627,13 +627,12 @@ fn field_with_defaults_introspection() {
Value::object(vec![("name", Value::scalar("Int"))].into_iter().collect()), Value::object(vec![("name", Value::scalar("Int"))].into_iter().collect()),
), ),
("defaultValue", Value::scalar("123")), ("defaultValue", Value::scalar("123")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![ vec![
("name", Value::scalar("fieldTwo")), ("name", Value::scalar("fieldTwo")),
( (
@ -641,9 +640,9 @@ fn field_with_defaults_introspection() {
Value::object(vec![("name", Value::scalar("Int"))].into_iter().collect()), Value::object(vec![("name", Value::scalar("Int"))].into_iter().collect()),
), ),
("defaultValue", Value::scalar("456")), ("defaultValue", Value::scalar("456")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }

View file

@ -91,7 +91,8 @@ fn test_execution() {
("sampleEnum", Value::scalar("ONE")), ("sampleEnum", Value::scalar("ONE")),
("first", Value::scalar(123)), ("first", Value::scalar(123)),
("second", Value::scalar(30)), ("second", Value::scalar(30)),
].into_iter() ]
.into_iter()
.collect() .collect()
) )
); );
@ -169,29 +170,27 @@ fn enum_introspection() {
assert_eq!(values.len(), 2); assert_eq!(values.len(), 2);
assert!( assert!(values.contains(&Value::object(
values.contains(&Value::object(
vec![ vec![
("name", Value::scalar("ONE")), ("name", Value::scalar("ONE")),
("description", Value::null()), ("description", Value::null()),
("isDeprecated", Value::scalar(false)), ("isDeprecated", Value::scalar(false)),
("deprecationReason", Value::null()), ("deprecationReason", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(values.contains(&Value::object(
values.contains(&Value::object(
vec![ vec![
("name", Value::scalar("TWO")), ("name", Value::scalar("TWO")),
("description", Value::null()), ("description", Value::null()),
("isDeprecated", Value::scalar(false)), ("isDeprecated", Value::scalar(false)),
("deprecationReason", Value::null()), ("deprecationReason", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
} }
#[test] #[test]
@ -292,8 +291,7 @@ fn interface_introspection() {
assert_eq!(fields.len(), 1); assert_eq!(fields.len(), 1);
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![ vec![
("name", Value::scalar("sampleEnum")), ("name", Value::scalar("sampleEnum")),
( (
@ -313,20 +311,22 @@ fn interface_introspection() {
vec![ vec![
("name", Value::scalar("SampleEnum")), ("name", Value::scalar("SampleEnum")),
("kind", Value::scalar("ENUM")), ("kind", Value::scalar("ENUM")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
("isDeprecated", Value::scalar(false)), ("isDeprecated", Value::scalar(false)),
("deprecationReason", Value::null()), ("deprecationReason", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
} }
#[test] #[test]
@ -436,8 +436,7 @@ fn object_introspection() {
println!("Fields: {:#?}", fields); println!("Fields: {:#?}", fields);
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![ vec![
("name", Value::scalar("sampleEnum")), ("name", Value::scalar("sampleEnum")),
("description", Value::null()), ("description", Value::null()),
@ -454,23 +453,24 @@ fn object_introspection() {
vec![ vec![
("name", Value::scalar("SampleEnum")), ("name", Value::scalar("SampleEnum")),
("kind", Value::scalar("ENUM")), ("kind", Value::scalar("ENUM")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
("isDeprecated", Value::scalar(false)), ("isDeprecated", Value::scalar(false)),
("deprecationReason", Value::null()), ("deprecationReason", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![ vec![
("name", Value::scalar("sampleScalar")), ("name", Value::scalar("sampleScalar")),
( (
@ -497,16 +497,19 @@ fn object_introspection() {
("name", Value::scalar("Int")), ("name", Value::scalar("Int")),
("kind", Value::scalar("SCALAR")), ("kind", Value::scalar("SCALAR")),
("ofType", Value::null()), ("ofType", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
("defaultValue", Value::null()), ("defaultValue", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
Value::object( Value::object(
@ -520,12 +523,14 @@ fn object_introspection() {
("name", Value::scalar("Int")), ("name", Value::scalar("Int")),
("kind", Value::scalar("SCALAR")), ("kind", Value::scalar("SCALAR")),
("ofType", Value::null()), ("ofType", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
("defaultValue", Value::scalar("123")), ("defaultValue", Value::scalar("123")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
]), ]),
@ -542,20 +547,22 @@ fn object_introspection() {
vec![ vec![
("name", Value::scalar("SampleScalar")), ("name", Value::scalar("SampleScalar")),
("kind", Value::scalar("SCALAR")), ("kind", Value::scalar("SCALAR")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
("isDeprecated", Value::scalar(false)), ("isDeprecated", Value::scalar(false)),
("deprecationReason", Value::null()), ("deprecationReason", Value::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
} }
#[test] #[test]
@ -603,7 +610,8 @@ fn scalar_introspection() {
("enumValues", Value::null()), ("enumValues", Value::null()),
("inputFields", Value::null()), ("inputFields", Value::null()),
("ofType", Value::null()), ("ofType", Value::null()),
].into_iter() ]
.into_iter()
.collect() .collect()
) )
); );

View file

@ -185,10 +185,12 @@ fn variable_complex_input() {
("a", InputValue::scalar("foo")), ("a", InputValue::scalar("foo")),
("b", InputValue::list(vec![InputValue::scalar("bar")])), ("b", InputValue::list(vec![InputValue::scalar("bar")])),
("c", InputValue::scalar("baz")), ("c", InputValue::scalar("baz")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
|result: &Object<DefaultScalarValue>| { |result: &Object<DefaultScalarValue>| {
assert_eq!( assert_eq!(
@ -209,10 +211,12 @@ fn variable_parse_single_value_to_list() {
("a", InputValue::scalar("foo")), ("a", InputValue::scalar("foo")),
("b", InputValue::scalar("bar")), ("b", InputValue::scalar("bar")),
("c", InputValue::scalar("baz")), ("c", InputValue::scalar("baz")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
|result: &Object<DefaultScalarValue>| { |result: &Object<DefaultScalarValue>| {
assert_eq!( assert_eq!(
@ -232,10 +236,12 @@ fn variable_runs_from_input_value_on_scalar() {
vec![ vec![
("c", InputValue::scalar("baz")), ("c", InputValue::scalar("baz")),
("d", InputValue::scalar("SerializedValue")), ("d", InputValue::scalar("SerializedValue")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
|result: &Object<DefaultScalarValue>| { |result: &Object<DefaultScalarValue>| {
assert_eq!( assert_eq!(
@ -257,10 +263,12 @@ fn variable_error_on_nested_non_null() {
("a", InputValue::scalar("foo")), ("a", InputValue::scalar("foo")),
("b", InputValue::scalar("bar")), ("b", InputValue::scalar("bar")),
("c", InputValue::null()), ("c", InputValue::null()),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect(); .collect();
let error = ::execute(query, None, &schema, &vars, &()).unwrap_err(); let error = ::execute(query, None, &schema, &vars, &()).unwrap_err();
@ -304,10 +312,12 @@ fn variable_error_on_omit_non_null() {
vec![ vec![
("a", InputValue::scalar("foo")), ("a", InputValue::scalar("foo")),
("b", InputValue::scalar("bar")), ("b", InputValue::scalar("bar")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect(); .collect();
let error = ::execute(query, None, &schema, &vars, &()).unwrap_err(); let error = ::execute(query, None, &schema, &vars, &()).unwrap_err();
@ -333,10 +343,12 @@ fn variable_multiple_errors_with_nesting() {
vec![( vec![(
"na", "na",
InputValue::object(vec![("a", InputValue::scalar("foo"))].into_iter().collect()), InputValue::object(vec![("a", InputValue::scalar("foo"))].into_iter().collect()),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect(); .collect();
let error = ::execute(query, None, &schema, &vars, &()).unwrap_err(); let error = ::execute(query, None, &schema, &vars, &()).unwrap_err();
@ -366,10 +378,12 @@ fn variable_error_on_additional_field() {
("b", InputValue::scalar("bar")), ("b", InputValue::scalar("bar")),
("c", InputValue::scalar("baz")), ("c", InputValue::scalar("baz")),
("extra", InputValue::scalar("dog")), ("extra", InputValue::scalar("dog")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect(); .collect();
let error = ::execute(query, None, &schema, &vars, &()).unwrap_err(); let error = ::execute(query, None, &schema, &vars, &()).unwrap_err();
@ -557,7 +571,8 @@ fn allow_lists_to_contain_values() {
vec![( vec![(
"input".to_owned(), "input".to_owned(),
InputValue::list(vec![InputValue::scalar("A")]), InputValue::list(vec![InputValue::scalar("A")]),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
|result| { |result| {
assert_eq!( assert_eq!(
@ -579,7 +594,8 @@ fn allow_lists_to_contain_null() {
InputValue::null(), InputValue::null(),
InputValue::scalar("B"), InputValue::scalar("B"),
]), ]),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
|result| { |result| {
assert_eq!( assert_eq!(
@ -617,7 +633,8 @@ fn allow_non_null_lists_to_contain_values() {
vec![( vec![(
"input".to_owned(), "input".to_owned(),
InputValue::list(vec![InputValue::scalar("A")]), InputValue::list(vec![InputValue::scalar("A")]),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
|result| { |result| {
assert_eq!( assert_eq!(
@ -638,7 +655,8 @@ fn allow_non_null_lists_to_contain_null() {
InputValue::null(), InputValue::null(),
InputValue::scalar("B"), InputValue::scalar("B"),
]), ]),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
|result| { |result| {
assert_eq!( assert_eq!(
@ -672,7 +690,8 @@ fn allow_lists_of_non_null_to_contain_values() {
vec![( vec![(
"input".to_owned(), "input".to_owned(),
InputValue::list(vec![InputValue::scalar("A")]), InputValue::list(vec![InputValue::scalar("A")]),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
|result| { |result| {
assert_eq!( assert_eq!(
@ -695,7 +714,8 @@ fn does_not_allow_lists_of_non_null_to_contain_null() {
InputValue::null(), InputValue::null(),
InputValue::scalar("B"), InputValue::scalar("B"),
]), ]),
)].into_iter() )]
.into_iter()
.collect(); .collect();
let error = ::execute(query, None, &schema, &vars, &()).unwrap_err(); let error = ::execute(query, None, &schema, &vars, &()).unwrap_err();
@ -720,7 +740,8 @@ fn does_not_allow_non_null_lists_of_non_null_to_contain_null() {
InputValue::null(), InputValue::null(),
InputValue::scalar("B"), InputValue::scalar("B"),
]), ]),
)].into_iter() )]
.into_iter()
.collect(); .collect();
let error = ::execute(query, None, &schema, &vars, &()).unwrap_err(); let error = ::execute(query, None, &schema, &vars, &()).unwrap_err();
@ -760,7 +781,8 @@ fn allow_non_null_lists_of_non_null_to_contain_values() {
vec![( vec![(
"input".to_owned(), "input".to_owned(),
InputValue::list(vec![InputValue::scalar("A")]), InputValue::list(vec![InputValue::scalar("A")]),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
|result| { |result| {
assert_eq!( assert_eq!(
@ -779,7 +801,8 @@ fn does_not_allow_invalid_types_to_be_used_as_values() {
let vars = vec![( let vars = vec![(
"value".to_owned(), "value".to_owned(),
InputValue::list(vec![InputValue::scalar("A"), InputValue::scalar("B")]), InputValue::list(vec![InputValue::scalar("A"), InputValue::scalar("B")]),
)].into_iter() )]
.into_iter()
.collect(); .collect();
let error = ::execute(query, None, &schema, &vars, &()).unwrap_err(); let error = ::execute(query, None, &schema, &vars, &()).unwrap_err();
@ -800,7 +823,8 @@ fn does_not_allow_unknown_types_to_be_used_as_values() {
let vars = vec![( let vars = vec![(
"value".to_owned(), "value".to_owned(),
InputValue::list(vec![InputValue::scalar("A"), InputValue::scalar("B")]), InputValue::list(vec![InputValue::scalar("A"), InputValue::scalar("B")]),
)].into_iter() )]
.into_iter()
.collect(); .collect();
let error = ::execute(query, None, &schema, &vars, &()).unwrap_err(); let error = ::execute(query, None, &schema, &vars, &()).unwrap_err();

View file

@ -47,7 +47,8 @@ where
.map(|(k, v)| (k.to_owned(), v.clone())) .map(|(k, v)| (k.to_owned(), v.clone()))
.collect() .collect()
}) })
}).unwrap_or_default() })
.unwrap_or_default()
} }
/// Construct a new GraphQL request from parts /// Construct a new GraphQL request from parts
@ -207,7 +208,8 @@ pub mod tests {
.body .body
.as_ref() .as_ref()
.expect("No data returned from request"), .expect("No data returned from request"),
).expect("Could not parse JSON object") )
.expect("Could not parse JSON object")
} }
fn test_simple_get<T: HTTPIntegration>(integration: &T) { fn test_simple_get<T: HTTPIntegration>(integration: &T) {
@ -249,7 +251,8 @@ pub mod tests {
} }
} }
}"# }"#
).expect("Invalid JSON constant in test") )
.expect("Invalid JSON constant in test")
); );
} }
@ -279,7 +282,8 @@ pub mod tests {
} }
} }
}"# }"#
).expect("Invalid JSON constant in test") )
.expect("Invalid JSON constant in test")
); );
} }
@ -309,7 +313,8 @@ pub mod tests {
unwrap_json_response(&response), unwrap_json_response(&response),
serde_json::from_str::<Json>( serde_json::from_str::<Json>(
r#"[{"data": {"hero": {"name": "R2-D2"}}}, {"data": {"hero": {"name": "R2-D2"}}}]"# r#"[{"data": {"hero": {"name": "R2-D2"}}}, {"data": {"hero": {"name": "R2-D2"}}}]"#
).expect("Invalid JSON constant in test") )
.expect("Invalid JSON constant in test")
); );
} }
@ -332,9 +337,12 @@ pub mod tests {
// {hero{name}} // {hero{name}}
let response = integration.get("/?query=%7B%22query%22%3A%20%22%7Bhero%7Bname%7D%7D%22%2C%20%22query%22%3A%20%22%7Bhero%7Bname%7D%7D%22%7D"); let response = integration.get("/?query=%7B%22query%22%3A%20%22%7Bhero%7Bname%7D%7D%22%2C%20%22query%22%3A%20%22%7Bhero%7Bname%7D%7D%22%7D");
assert_eq!(response.status_code, 400); assert_eq!(response.status_code, 400);
let response = integration.post("/", r#" let response = integration.post(
"/",
r#"
{"query": "{hero{name}}", "query": "{hero{name}}"} {"query": "{hero{name}}", "query": "{hero{name}}"}
"#); "#,
);
assert_eq!(response.status_code, 400); assert_eq!(response.status_code, 400);
} }
} }

View file

@ -203,7 +203,7 @@ mod integration_test {
use executor::Variables; use executor::Variables;
use schema::model::RootNode; use schema::model::RootNode;
use types::scalars::EmptyMutation; use types::scalars::EmptyMutation;
use value::{Value}; use value::Value;
#[test] #[test]
fn test_serialization() { fn test_serialization() {
@ -232,7 +232,7 @@ mod integration_test {
} }
"#; "#;
let schema= RootNode::new(Root, EmptyMutation::<()>::new()); let schema = RootNode::new(Root, EmptyMutation::<()>::new());
let (result, errs) = let (result, errs) =
::execute(doc, None, &schema, &Variables::new(), &()).expect("Execution failed"); ::execute(doc, None, &schema, &Variables::new(), &()).expect("Execution failed");
@ -253,7 +253,8 @@ mod integration_test {
"exampleDateTimeUtc", "exampleDateTimeUtc",
Value::scalar("1970-01-01T00:01:01+00:00"), Value::scalar("1970-01-01T00:01:01+00:00"),
), ),
].into_iter() ]
.into_iter()
.collect() .collect()
) )
); );

View file

@ -167,7 +167,7 @@ where
self.0.visit_u64(value).map(InputValue::Scalar) self.0.visit_u64(value).map(InputValue::Scalar)
} }
serde_if_integer128!{ serde_if_integer128! {
fn visit_u128<E>(self, value: u128) -> Result<InputValue<S>, E> fn visit_u128<E>(self, value: u128) -> Result<InputValue<S>, E>
where where
E: de::Error, E: de::Error,

View file

@ -37,7 +37,9 @@ macro_rules! __juniper_impl_trait {
#[doc(hidden)] #[doc(hidden)]
#[macro_export] #[macro_export]
macro_rules! __juniper_insert_generic { macro_rules! __juniper_insert_generic {
(<DefaultScalarValue>) => {$crate::DefaultScalarValue}; (<DefaultScalarValue>) => {
$crate::DefaultScalarValue
};
( (
<$generic:tt $(: $bound: tt)*> <$generic:tt $(: $bound: tt)*>
) => { ) => {
@ -50,7 +52,6 @@ macro_rules! __juniper_insert_generic {
}; };
} }
#[doc(hidden)] #[doc(hidden)]
#[macro_export] #[macro_export]
macro_rules! __juniper_parse_object_header { macro_rules! __juniper_parse_object_header {
@ -560,7 +561,6 @@ macro_rules! __juniper_parse_field_list {
} }
#[doc(hidden)] #[doc(hidden)]
#[macro_export] #[macro_export]
macro_rules! __juniper_parse_instance_resolver { macro_rules! __juniper_parse_instance_resolver {

View file

@ -139,7 +139,8 @@ where
.as_scalar_value::<String>() .as_scalar_value::<String>()
.expect("name is not a string") .expect("name is not a string")
== field_name == field_name
}).next() })
.next()
.expect("Field not found") .expect("Field not found")
.as_object_value() .as_object_value()
.expect("Field is not an object"); .expect("Field is not an object");
@ -176,8 +177,7 @@ fn introspect_field_exec_arg_and_more() {
run_args_info_query("execArgAndMore", |args| { run_args_info_query("execArgAndMore", |args| {
assert_eq!(args.len(), 1); assert_eq!(args.len(), 1);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg")), ("name", Value::scalar("arg")),
("description", Value::null()), ("description", Value::null()),
@ -193,14 +193,15 @@ fn introspect_field_exec_arg_and_more() {
vec![("name", Value::scalar("Int"))].into_iter().collect(), vec![("name", Value::scalar("Int"))].into_iter().collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -209,8 +210,7 @@ fn introspect_field_single_arg() {
run_args_info_query("singleArg", |args| { run_args_info_query("singleArg", |args| {
assert_eq!(args.len(), 1); assert_eq!(args.len(), 1);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg")), ("name", Value::scalar("arg")),
("description", Value::null()), ("description", Value::null()),
@ -226,14 +226,15 @@ fn introspect_field_single_arg() {
vec![("name", Value::scalar("Int"))].into_iter().collect(), vec![("name", Value::scalar("Int"))].into_iter().collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -242,8 +243,7 @@ fn introspect_field_multi_args() {
run_args_info_query("multiArgs", |args| { run_args_info_query("multiArgs", |args| {
assert_eq!(args.len(), 2); assert_eq!(args.len(), 2);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg1")), ("name", Value::scalar("arg1")),
("description", Value::null()), ("description", Value::null()),
@ -259,17 +259,17 @@ fn introspect_field_multi_args() {
vec![("name", Value::scalar("Int"))].into_iter().collect(), vec![("name", Value::scalar("Int"))].into_iter().collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg2")), ("name", Value::scalar("arg2")),
("description", Value::null()), ("description", Value::null()),
@ -285,14 +285,15 @@ fn introspect_field_multi_args() {
vec![("name", Value::scalar("Int"))].into_iter().collect(), vec![("name", Value::scalar("Int"))].into_iter().collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -301,8 +302,7 @@ fn introspect_field_multi_args_trailing_comma() {
run_args_info_query("multiArgsTrailingComma", |args| { run_args_info_query("multiArgsTrailingComma", |args| {
assert_eq!(args.len(), 2); assert_eq!(args.len(), 2);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg1")), ("name", Value::scalar("arg1")),
("description", Value::null()), ("description", Value::null()),
@ -318,17 +318,17 @@ fn introspect_field_multi_args_trailing_comma() {
vec![("name", Value::scalar("Int"))].into_iter().collect(), vec![("name", Value::scalar("Int"))].into_iter().collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg2")), ("name", Value::scalar("arg2")),
("description", Value::null()), ("description", Value::null()),
@ -344,14 +344,15 @@ fn introspect_field_multi_args_trailing_comma() {
vec![("name", Value::scalar("Int"))].into_iter().collect(), vec![("name", Value::scalar("Int"))].into_iter().collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -360,8 +361,7 @@ fn introspect_field_single_arg_descr() {
run_args_info_query("singleArgDescr", |args| { run_args_info_query("singleArgDescr", |args| {
assert_eq!(args.len(), 1); assert_eq!(args.len(), 1);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg")), ("name", Value::scalar("arg")),
("description", Value::scalar("The arg")), ("description", Value::scalar("The arg")),
@ -377,14 +377,15 @@ fn introspect_field_single_arg_descr() {
vec![("name", Value::scalar("Int"))].into_iter().collect(), vec![("name", Value::scalar("Int"))].into_iter().collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -393,8 +394,7 @@ fn introspect_field_multi_args_descr() {
run_args_info_query("multiArgsDescr", |args| { run_args_info_query("multiArgsDescr", |args| {
assert_eq!(args.len(), 2); assert_eq!(args.len(), 2);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg1")), ("name", Value::scalar("arg1")),
("description", Value::scalar("The first arg")), ("description", Value::scalar("The first arg")),
@ -410,17 +410,17 @@ fn introspect_field_multi_args_descr() {
vec![("name", Value::scalar("Int"))].into_iter().collect(), vec![("name", Value::scalar("Int"))].into_iter().collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg2")), ("name", Value::scalar("arg2")),
("description", Value::scalar("The second arg")), ("description", Value::scalar("The second arg")),
@ -436,14 +436,15 @@ fn introspect_field_multi_args_descr() {
vec![("name", Value::scalar("Int"))].into_iter().collect(), vec![("name", Value::scalar("Int"))].into_iter().collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -452,8 +453,7 @@ fn introspect_field_multi_args_descr_trailing_comma() {
run_args_info_query("multiArgsDescrTrailingComma", |args| { run_args_info_query("multiArgsDescrTrailingComma", |args| {
assert_eq!(args.len(), 2); assert_eq!(args.len(), 2);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg1")), ("name", Value::scalar("arg1")),
("description", Value::scalar("The first arg")), ("description", Value::scalar("The first arg")),
@ -469,17 +469,17 @@ fn introspect_field_multi_args_descr_trailing_comma() {
vec![("name", Value::scalar("Int"))].into_iter().collect(), vec![("name", Value::scalar("Int"))].into_iter().collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg2")), ("name", Value::scalar("arg2")),
("description", Value::scalar("The second arg")), ("description", Value::scalar("The second arg")),
@ -495,14 +495,15 @@ fn introspect_field_multi_args_descr_trailing_comma() {
vec![("name", Value::scalar("Int"))].into_iter().collect(), vec![("name", Value::scalar("Int"))].into_iter().collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -511,8 +512,7 @@ fn introspect_field_attr_arg_descr() {
run_args_info_query("attrArgDescr", |args| { run_args_info_query("attrArgDescr", |args| {
assert_eq!(args.len(), 1); assert_eq!(args.len(), 1);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg")), ("name", Value::scalar("arg")),
("description", Value::scalar("The arg")), ("description", Value::scalar("The arg")),
@ -528,14 +528,15 @@ fn introspect_field_attr_arg_descr() {
vec![("name", Value::scalar("Int"))].into_iter().collect(), vec![("name", Value::scalar("Int"))].into_iter().collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -544,8 +545,7 @@ fn introspect_field_attr_arg_descr_collapse() {
run_args_info_query("attrArgDescrCollapse", |args| { run_args_info_query("attrArgDescrCollapse", |args| {
assert_eq!(args.len(), 1); assert_eq!(args.len(), 1);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg")), ("name", Value::scalar("arg")),
("description", Value::scalar("The arg\nand more details")), ("description", Value::scalar("The arg\nand more details")),
@ -561,14 +561,15 @@ fn introspect_field_attr_arg_descr_collapse() {
vec![("name", Value::scalar("Int"))].into_iter().collect(), vec![("name", Value::scalar("Int"))].into_iter().collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -577,8 +578,7 @@ fn introspect_field_arg_with_default() {
run_args_info_query("argWithDefault", |args| { run_args_info_query("argWithDefault", |args| {
assert_eq!(args.len(), 1); assert_eq!(args.len(), 1);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg")), ("name", Value::scalar("arg")),
("description", Value::null()), ("description", Value::null()),
@ -591,10 +591,10 @@ fn introspect_field_arg_with_default() {
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -603,8 +603,7 @@ fn introspect_field_multi_args_with_default() {
run_args_info_query("multiArgsWithDefault", |args| { run_args_info_query("multiArgsWithDefault", |args| {
assert_eq!(args.len(), 2); assert_eq!(args.len(), 2);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg1")), ("name", Value::scalar("arg1")),
("description", Value::null()), ("description", Value::null()),
@ -617,13 +616,12 @@ fn introspect_field_multi_args_with_default() {
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg2")), ("name", Value::scalar("arg2")),
("description", Value::null()), ("description", Value::null()),
@ -636,10 +634,10 @@ fn introspect_field_multi_args_with_default() {
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -648,8 +646,7 @@ fn introspect_field_multi_args_with_default_trailing_comma() {
run_args_info_query("multiArgsWithDefaultTrailingComma", |args| { run_args_info_query("multiArgsWithDefaultTrailingComma", |args| {
assert_eq!(args.len(), 2); assert_eq!(args.len(), 2);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg1")), ("name", Value::scalar("arg1")),
("description", Value::null()), ("description", Value::null()),
@ -662,13 +659,12 @@ fn introspect_field_multi_args_with_default_trailing_comma() {
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg2")), ("name", Value::scalar("arg2")),
("description", Value::null()), ("description", Value::null()),
@ -681,10 +677,10 @@ fn introspect_field_multi_args_with_default_trailing_comma() {
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -693,8 +689,7 @@ fn introspect_field_arg_with_default_descr() {
run_args_info_query("argWithDefaultDescr", |args| { run_args_info_query("argWithDefaultDescr", |args| {
assert_eq!(args.len(), 1); assert_eq!(args.len(), 1);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg")), ("name", Value::scalar("arg")),
("description", Value::scalar("The arg")), ("description", Value::scalar("The arg")),
@ -707,10 +702,10 @@ fn introspect_field_arg_with_default_descr() {
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -719,8 +714,7 @@ fn introspect_field_multi_args_with_default_descr() {
run_args_info_query("multiArgsWithDefaultDescr", |args| { run_args_info_query("multiArgsWithDefaultDescr", |args| {
assert_eq!(args.len(), 2); assert_eq!(args.len(), 2);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg1")), ("name", Value::scalar("arg1")),
("description", Value::scalar("The first arg")), ("description", Value::scalar("The first arg")),
@ -733,13 +727,12 @@ fn introspect_field_multi_args_with_default_descr() {
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg2")), ("name", Value::scalar("arg2")),
("description", Value::scalar("The second arg")), ("description", Value::scalar("The second arg")),
@ -752,10 +745,10 @@ fn introspect_field_multi_args_with_default_descr() {
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -764,8 +757,7 @@ fn introspect_field_multi_args_with_default_trailing_comma_descr() {
run_args_info_query("multiArgsWithDefaultTrailingCommaDescr", |args| { run_args_info_query("multiArgsWithDefaultTrailingCommaDescr", |args| {
assert_eq!(args.len(), 2); assert_eq!(args.len(), 2);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg1")), ("name", Value::scalar("arg1")),
("description", Value::scalar("The first arg")), ("description", Value::scalar("The first arg")),
@ -778,13 +770,12 @@ fn introspect_field_multi_args_with_default_trailing_comma_descr() {
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg2")), ("name", Value::scalar("arg2")),
("description", Value::scalar("The second arg")), ("description", Value::scalar("The second arg")),
@ -797,10 +788,10 @@ fn introspect_field_multi_args_with_default_trailing_comma_descr() {
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -809,8 +800,7 @@ fn introspect_field_args_with_complex_default() {
run_args_info_query("argsWithComplexDefault", |args| { run_args_info_query("argsWithComplexDefault", |args| {
assert_eq!(args.len(), 2); assert_eq!(args.len(), 2);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg1")), ("name", Value::scalar("arg1")),
("description", Value::scalar("A string default argument")), ("description", Value::scalar("A string default argument")),
@ -823,13 +813,12 @@ fn introspect_field_args_with_complex_default() {
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
assert!( assert!(args.contains(&Value::object(
args.contains(&Value::object(
vec![ vec![
("name", Value::scalar("arg2")), ("name", Value::scalar("arg2")),
( (
@ -845,9 +834,9 @@ fn introspect_field_args_with_complex_default() {
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }

View file

@ -154,7 +154,8 @@ where
.as_scalar_value::<String>() .as_scalar_value::<String>()
.expect("name is not a string") .expect("name is not a string")
== field_name == field_name
}).next() })
.next()
.expect("Field not found") .expect("Field not found")
.as_object_value() .as_object_value()
.expect("Field is not an object"); .expect("Field is not an object");
@ -425,7 +426,9 @@ fn introspect_object_field_attr_description_collapse() {
); );
assert_eq!( assert_eq!(
field.get_field_value("description"), field.get_field_value("description"),
Some(&Value::scalar("Field description\nwith `collapse_docs` behavior")) Some(&Value::scalar(
"Field description\nwith `collapse_docs` behavior"
))
); );
assert_eq!( assert_eq!(
field.get_field_value("isDeprecated"), field.get_field_value("isDeprecated"),
@ -447,7 +450,9 @@ fn introspect_interface_field_attr_description_collapse() {
); );
assert_eq!( assert_eq!(
field.get_field_value("description"), field.get_field_value("description"),
Some(&Value::scalar("Field description\nwith `collapse_docs` behavior")) Some(&Value::scalar(
"Field description\nwith `collapse_docs` behavior"
))
); );
assert_eq!( assert_eq!(
field.get_field_value("isDeprecated"), field.get_field_value("isDeprecated"),

View file

@ -3,7 +3,7 @@ use std::marker::PhantomData;
use ast::InputValue; use ast::InputValue;
use schema::model::RootNode; use schema::model::RootNode;
use types::scalars::EmptyMutation; use types::scalars::EmptyMutation;
use value::{Value, Object, DefaultScalarValue}; use value::{DefaultScalarValue, Object, Value};
/* /*
@ -179,102 +179,105 @@ fn introspect_custom_name() {
); );
assert_eq!(object.get_field_value("description"), Some(&Value::null())); assert_eq!(object.get_field_value("description"), Some(&Value::null()));
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![("name", Value::scalar("simple"))] vec![("name", Value::scalar("simple"))]
.into_iter() .into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
#[test] #[test]
fn introspect_with_lifetime() { fn introspect_with_lifetime() {
run_type_info_query("WithLifetime", |object, fields| { run_type_info_query("WithLifetime", |object, fields| {
assert_eq!(object.get_field_value("name"), Some(&Value::scalar("WithLifetime"))); assert_eq!(
object.get_field_value("name"),
Some(&Value::scalar("WithLifetime"))
);
assert_eq!(object.get_field_value("description"), Some(&Value::null())); assert_eq!(object.get_field_value("description"), Some(&Value::null()));
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![("name", Value::scalar("simple"))] vec![("name", Value::scalar("simple"))]
.into_iter() .into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
#[test] #[test]
fn introspect_with_generics() { fn introspect_with_generics() {
run_type_info_query("WithGenerics", |object, fields| { run_type_info_query("WithGenerics", |object, fields| {
assert_eq!(object.get_field_value("name"), Some(&Value::scalar("WithGenerics"))); assert_eq!(
object.get_field_value("name"),
Some(&Value::scalar("WithGenerics"))
);
assert_eq!(object.get_field_value("description"), Some(&Value::null())); assert_eq!(object.get_field_value("description"), Some(&Value::null()));
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![("name", Value::scalar("simple"))] vec![("name", Value::scalar("simple"))]
.into_iter() .into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
#[test] #[test]
fn introspect_description_first() { fn introspect_description_first() {
run_type_info_query("DescriptionFirst", |object, fields| { run_type_info_query("DescriptionFirst", |object, fields| {
assert_eq!(object.get_field_value("name"), Some(&Value::scalar("DescriptionFirst"))); assert_eq!(
object.get_field_value("name"),
Some(&Value::scalar("DescriptionFirst"))
);
assert_eq!( assert_eq!(
object.get_field_value("description"), object.get_field_value("description"),
Some(&Value::scalar("A description")) Some(&Value::scalar("A description"))
); );
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![("name", Value::scalar("simple"))] vec![("name", Value::scalar("simple"))]
.into_iter() .into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
#[test] #[test]
fn introspect_fields_first() { fn introspect_fields_first() {
run_type_info_query("FieldsFirst", |object, fields| { run_type_info_query("FieldsFirst", |object, fields| {
assert_eq!(object.get_field_value("name"), Some(&Value::scalar("FieldsFirst"))); assert_eq!(
object.get_field_value("name"),
Some(&Value::scalar("FieldsFirst"))
);
assert_eq!( assert_eq!(
object.get_field_value("description"), object.get_field_value("description"),
Some(&Value::scalar("A description")) Some(&Value::scalar("A description"))
); );
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![("name", Value::scalar("simple"))] vec![("name", Value::scalar("simple"))]
.into_iter() .into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
#[test] #[test]
fn introspect_interfaces_first() { fn introspect_interfaces_first() {
run_type_info_query("InterfacesFirst", |object, fields| { run_type_info_query("InterfacesFirst", |object, fields| {
assert_eq!(object.get_field_value("name"), Some(&Value::scalar("InterfacesFirst"))); assert_eq!(
object.get_field_value("name"),
Some(&Value::scalar("InterfacesFirst"))
);
assert_eq!( assert_eq!(
object.get_field_value("description"), object.get_field_value("description"),
Some(&Value::scalar("A description")) Some(&Value::scalar("A description"))
); );
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![("name", Value::scalar("simple"))] vec![("name", Value::scalar("simple"))]
.into_iter() .into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -290,32 +293,31 @@ fn introspect_commas_with_trailing() {
Some(&Value::scalar("A description")) Some(&Value::scalar("A description"))
); );
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![("name", Value::scalar("simple"))] vec![("name", Value::scalar("simple"))]
.into_iter() .into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
#[test] #[test]
fn introspect_commas_on_meta() { fn introspect_commas_on_meta() {
run_type_info_query("CommasOnMeta", |object, fields| { run_type_info_query("CommasOnMeta", |object, fields| {
assert_eq!(object.get_field_value("name"), Some(&Value::scalar("CommasOnMeta"))); assert_eq!(
object.get_field_value("name"),
Some(&Value::scalar("CommasOnMeta"))
);
assert_eq!( assert_eq!(
object.get_field_value("description"), object.get_field_value("description"),
Some(&Value::scalar("A description")) Some(&Value::scalar("A description"))
); );
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![("name", Value::scalar("simple"))] vec![("name", Value::scalar("simple"))]
.into_iter() .into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -331,12 +333,10 @@ fn introspect_resolvers_with_trailing_comma() {
Some(&Value::scalar("A description")) Some(&Value::scalar("A description"))
); );
assert!( assert!(fields.contains(&Value::object(
fields.contains(&Value::object(
vec![("name", Value::scalar("simple"))] vec![("name", Value::scalar("simple"))]
.into_iter() .into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }

View file

@ -274,7 +274,8 @@ fn introspect_description_first() {
vec![ vec![
("name", Value::scalar("Interface")), ("name", Value::scalar("Interface")),
("kind", Value::scalar("INTERFACE")), ("kind", Value::scalar("INTERFACE")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)])) )]))
); );
@ -303,7 +304,8 @@ fn introspect_fields_first() {
vec![ vec![
("name", Value::scalar("Interface")), ("name", Value::scalar("Interface")),
("kind", Value::scalar("INTERFACE")), ("kind", Value::scalar("INTERFACE")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)])) )]))
); );
@ -332,7 +334,8 @@ fn introspect_interfaces_first() {
vec![ vec![
("name", Value::scalar("Interface")), ("name", Value::scalar("Interface")),
("kind", Value::scalar("INTERFACE")), ("kind", Value::scalar("INTERFACE")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)])) )]))
); );
@ -361,7 +364,8 @@ fn introspect_commas_with_trailing() {
vec![ vec![
("name", Value::scalar("Interface")), ("name", Value::scalar("Interface")),
("kind", Value::scalar("INTERFACE")), ("kind", Value::scalar("INTERFACE")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)])) )]))
); );
@ -390,7 +394,8 @@ fn introspect_commas_on_meta() {
vec![ vec![
("name", Value::scalar("Interface")), ("name", Value::scalar("Interface")),
("kind", Value::scalar("INTERFACE")), ("kind", Value::scalar("INTERFACE")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
)])) )]))
); );

View file

@ -1,7 +1,7 @@
use executor::Variables; use executor::Variables;
use schema::model::RootNode; use schema::model::RootNode;
use types::scalars::EmptyMutation; use types::scalars::EmptyMutation;
use value::{Value, Object, DefaultScalarValue, ParseScalarValue, ParseScalarResult}; use value::{DefaultScalarValue, Object, ParseScalarResult, ParseScalarValue, Value};
struct DefaultName(i32); struct DefaultName(i32);
struct OtherOrder(i32); struct OtherOrder(i32);
@ -140,8 +140,14 @@ fn default_name_introspection() {
"#; "#;
run_type_info_query(doc, |type_info| { run_type_info_query(doc, |type_info| {
assert_eq!(type_info.get_field_value("name"), Some(&Value::scalar("DefaultName"))); assert_eq!(
assert_eq!(type_info.get_field_value("description"), Some(&Value::null())); type_info.get_field_value("name"),
Some(&Value::scalar("DefaultName"))
);
assert_eq!(
type_info.get_field_value("description"),
Some(&Value::null())
);
}); });
} }
@ -157,8 +163,14 @@ fn other_order_introspection() {
"#; "#;
run_type_info_query(doc, |type_info| { run_type_info_query(doc, |type_info| {
assert_eq!(type_info.get_field_value("name"), Some(&Value::scalar("OtherOrder"))); assert_eq!(
assert_eq!(type_info.get_field_value("description"), Some(&Value::null())); type_info.get_field_value("name"),
Some(&Value::scalar("OtherOrder"))
);
assert_eq!(
type_info.get_field_value("description"),
Some(&Value::null())
);
}); });
} }
@ -174,8 +186,14 @@ fn named_introspection() {
"#; "#;
run_type_info_query(doc, |type_info| { run_type_info_query(doc, |type_info| {
assert_eq!(type_info.get_field_value("name"), Some(&Value::scalar("ANamedScalar"))); assert_eq!(
assert_eq!(type_info.get_field_value("description"), Some(&Value::null())); type_info.get_field_value("name"),
Some(&Value::scalar("ANamedScalar"))
);
assert_eq!(
type_info.get_field_value("description"),
Some(&Value::null())
);
}); });
} }

View file

@ -3,7 +3,7 @@ use std::marker::PhantomData;
use ast::InputValue; use ast::InputValue;
use schema::model::RootNode; use schema::model::RootNode;
use types::scalars::EmptyMutation; use types::scalars::EmptyMutation;
use value::{Value, Object, DefaultScalarValue}; use value::{DefaultScalarValue, Object, Value};
/* /*
@ -154,86 +154,91 @@ where
#[test] #[test]
fn introspect_custom_name() { fn introspect_custom_name() {
run_type_info_query("ACustomNamedUnion", |union, possible_types| { run_type_info_query("ACustomNamedUnion", |union, possible_types| {
assert_eq!(union.get_field_value("name"), Some(&Value::scalar("ACustomNamedUnion"))); assert_eq!(
union.get_field_value("name"),
Some(&Value::scalar("ACustomNamedUnion"))
);
assert_eq!(union.get_field_value("description"), Some(&Value::null())); assert_eq!(union.get_field_value("description"), Some(&Value::null()));
assert!( assert!(possible_types.contains(&Value::object(
possible_types.contains(&Value::object(
vec![("name", Value::scalar("Concrete"))] vec![("name", Value::scalar("Concrete"))]
.into_iter() .into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
#[test] #[test]
fn introspect_with_lifetime() { fn introspect_with_lifetime() {
run_type_info_query("WithLifetime", |union, possible_types| { run_type_info_query("WithLifetime", |union, possible_types| {
assert_eq!(union.get_field_value("name"), Some(&Value::scalar("WithLifetime"))); assert_eq!(
union.get_field_value("name"),
Some(&Value::scalar("WithLifetime"))
);
assert_eq!(union.get_field_value("description"), Some(&Value::null())); assert_eq!(union.get_field_value("description"), Some(&Value::null()));
assert!( assert!(possible_types.contains(&Value::object(
possible_types.contains(&Value::object(
vec![("name", Value::scalar("Concrete"))] vec![("name", Value::scalar("Concrete"))]
.into_iter() .into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
#[test] #[test]
fn introspect_with_generics() { fn introspect_with_generics() {
run_type_info_query("WithGenerics", |union, possible_types| { run_type_info_query("WithGenerics", |union, possible_types| {
assert_eq!(union.get_field_value("name"), Some(&Value::scalar("WithGenerics"))); assert_eq!(
union.get_field_value("name"),
Some(&Value::scalar("WithGenerics"))
);
assert_eq!(union.get_field_value("description"), Some(&Value::null())); assert_eq!(union.get_field_value("description"), Some(&Value::null()));
assert!( assert!(possible_types.contains(&Value::object(
possible_types.contains(&Value::object(
vec![("name", Value::scalar("Concrete"))] vec![("name", Value::scalar("Concrete"))]
.into_iter() .into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
#[test] #[test]
fn introspect_description_first() { fn introspect_description_first() {
run_type_info_query("DescriptionFirst", |union, possible_types| { run_type_info_query("DescriptionFirst", |union, possible_types| {
assert_eq!(union.get_field_value("name"), Some(&Value::scalar("DescriptionFirst"))); assert_eq!(
union.get_field_value("name"),
Some(&Value::scalar("DescriptionFirst"))
);
assert_eq!( assert_eq!(
union.get_field_value("description"), union.get_field_value("description"),
Some(&Value::scalar("A description")) Some(&Value::scalar("A description"))
); );
assert!( assert!(possible_types.contains(&Value::object(
possible_types.contains(&Value::object(
vec![("name", Value::scalar("Concrete"))] vec![("name", Value::scalar("Concrete"))]
.into_iter() .into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
#[test] #[test]
fn introspect_resolvers_first() { fn introspect_resolvers_first() {
run_type_info_query("ResolversFirst", |union, possible_types| { run_type_info_query("ResolversFirst", |union, possible_types| {
assert_eq!(union.get_field_value("name"), Some(&Value::scalar("ResolversFirst"))); assert_eq!(
union.get_field_value("name"),
Some(&Value::scalar("ResolversFirst"))
);
assert_eq!( assert_eq!(
union.get_field_value("description"), union.get_field_value("description"),
Some(&Value::scalar("A description")) Some(&Value::scalar("A description"))
); );
assert!( assert!(possible_types.contains(&Value::object(
possible_types.contains(&Value::object(
vec![("name", Value::scalar("Concrete"))] vec![("name", Value::scalar("Concrete"))]
.into_iter() .into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -249,13 +254,11 @@ fn introspect_commas_with_trailing() {
Some(&Value::scalar("A description")) Some(&Value::scalar("A description"))
); );
assert!( assert!(possible_types.contains(&Value::object(
possible_types.contains(&Value::object(
vec![("name", Value::scalar("Concrete"))] vec![("name", Value::scalar("Concrete"))]
.into_iter() .into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }
@ -271,12 +274,10 @@ fn introspect_resolvers_with_trailing_comma() {
Some(&Value::scalar("A description")) Some(&Value::scalar("A description"))
); );
assert!( assert!(possible_types.contains(&Value::object(
possible_types.contains(&Value::object(
vec![("name", Value::scalar("Concrete"))] vec![("name", Value::scalar("Concrete"))]
.into_iter() .into_iter()
.collect(), .collect(),
)) )));
);
}); });
} }

View file

@ -129,11 +129,13 @@ where
start: start_pos, .. start: start_pos, ..
} = parser.expect(&Token::Name("fragment"))?; } = parser.expect(&Token::Name("fragment"))?;
let name = match parser.expect_name() { let name = match parser.expect_name() {
Ok(n) => if n.item == "on" { Ok(n) => {
if n.item == "on" {
return Err(n.map(|_| ParseError::UnexpectedToken(Token::Name("on")))); return Err(n.map(|_| ParseError::UnexpectedToken(Token::Name("on"))));
} else { } else {
n n
}, }
}
Err(e) => return Err(e), Err(e) => return Err(e),
}; };
@ -354,7 +356,8 @@ where
&Token::ParenOpen, &Token::ParenOpen,
|p| parse_argument(p, schema, arguments), |p| parse_argument(p, schema, arguments),
&Token::ParenClose, &Token::ParenClose,
)?.map(|args| Arguments { )?
.map(|args| Arguments {
items: args.into_iter().map(|s| s.item).collect(), items: args.into_iter().map(|s| s.item).collect(),
}), }),
)) ))
@ -408,7 +411,8 @@ where
&Token::ParenOpen, &Token::ParenOpen,
|p| parse_variable_definition(p, schema), |p| parse_variable_definition(p, schema),
&Token::ParenClose, &Token::ParenClose,
)?.map(|defs| VariableDefinitions { )?
.map(|defs| VariableDefinitions {
items: defs.into_iter().map(|s| s.item).collect(), items: defs.into_iter().map(|s| s.item).collect(),
}), }),
)) ))

View file

@ -24,7 +24,7 @@ pub struct Lexer<'a> {
pub enum ScalarToken<'a> { pub enum ScalarToken<'a> {
String(&'a str), String(&'a str),
Float(&'a str), Float(&'a str),
Int(&'a str) Int(&'a str),
} }
/// A single token in the input source /// A single token in the input source
@ -231,17 +231,17 @@ impl<'a> Lexer<'a> {
let mut old_pos = self.position; let mut old_pos = self.position;
while let Some((idx, ch)) = self.next_char() { while let Some((idx, ch)) = self.next_char() {
match ch { match ch {
'b' |'f' |'n'|'r' |'t'|'\\'|'/'| '"' if escaped => { 'b' | 'f' | 'n' | 'r' | 't' | '\\' | '/' | '"' if escaped => {
escaped = false; escaped = false;
} }
'u' if escaped => { 'u' if escaped => {
self.scan_escaped_unicode(&old_pos)?; self.scan_escaped_unicode(&old_pos)?;
escaped = false; escaped = false;
}, }
c if escaped => { c if escaped => {
return Err(Spanning::zero_width( return Err(Spanning::zero_width(
&old_pos, &old_pos,
LexerError::UnknownEscapeSequence(format!("\\{}", c)) LexerError::UnknownEscapeSequence(format!("\\{}", c)),
)) ))
} }
'\\' => escaped = true, '\\' => escaped = true,
@ -249,7 +249,7 @@ impl<'a> Lexer<'a> {
return Ok(Spanning::start_end( return Ok(Spanning::start_end(
&start_pos, &start_pos,
&self.position, &self.position,
Token::Scalar(ScalarToken::String(&self.source[start_idx+1..idx])), Token::Scalar(ScalarToken::String(&self.source[start_idx + 1..idx])),
)); ));
} }
'\n' | '\r' => { '\n' | '\r' => {
@ -316,12 +316,14 @@ impl<'a> Lexer<'a> {
) )
})?; })?;
char::from_u32(code_point).ok_or_else(|| { char::from_u32(code_point)
.ok_or_else(|| {
Spanning::zero_width( Spanning::zero_width(
start_pos, start_pos,
LexerError::UnknownEscapeSequence("\\u".to_owned() + escape), LexerError::UnknownEscapeSequence("\\u".to_owned() + escape),
) )
}).map(|_|()) })
.map(|_| ())
} }
fn scan_number(&mut self) -> LexerResult<'a> { fn scan_number(&mut self) -> LexerResult<'a> {
@ -424,15 +426,11 @@ impl<'a> Lexer<'a> {
let token = if is_float { let token = if is_float {
Token::Scalar(ScalarToken::Float(number)) Token::Scalar(ScalarToken::Float(number))
}else { } else {
Token::Scalar(ScalarToken::Int(number)) Token::Scalar(ScalarToken::Int(number))
}; };
Ok(Spanning::start_end( Ok(Spanning::start_end(&start_pos, end_pos, token))
&start_pos,
end_pos,
token,
))
} }
} }
@ -463,7 +461,8 @@ impl<'a> Iterator for Lexer<'a> {
Some('|') => Ok(self.emit_single_char(Token::Pipe)), Some('|') => Ok(self.emit_single_char(Token::Pipe)),
Some('.') => self.scan_ellipsis(), Some('.') => self.scan_ellipsis(),
Some('"') => self.scan_string(), Some('"') => self.scan_string(),
Some(ch) => if is_number_start(ch) { Some(ch) => {
if is_number_start(ch) {
self.scan_number() self.scan_number()
} else if is_name_start(ch) { } else if is_name_start(ch) {
self.scan_name() self.scan_name()
@ -472,7 +471,8 @@ impl<'a> Iterator for Lexer<'a> {
&self.position, &self.position,
LexerError::UnknownCharacter(ch), LexerError::UnknownCharacter(ch),
)) ))
}, }
}
None => { None => {
self.has_reached_eof = true; self.has_reached_eof = true;
Ok(Spanning::zero_width(&self.position, Token::EndOfFile)) Ok(Spanning::zero_width(&self.position, Token::EndOfFile))
@ -485,10 +485,12 @@ impl<'a> fmt::Display for Token<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { match *self {
Token::Name(name) => write!(f, "{}", name), Token::Name(name) => write!(f, "{}", name),
Token::Scalar(ScalarToken::Int(s)) | Token::Scalar(ScalarToken::Float(s)) => write!(f, "{}", s), Token::Scalar(ScalarToken::Int(s)) | Token::Scalar(ScalarToken::Float(s)) => {
write!(f, "{}", s)
}
Token::Scalar(ScalarToken::String(s)) => { Token::Scalar(ScalarToken::String(s)) => {
write!(f, "\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")) write!(f, "\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
}, }
Token::ExclamationMark => write!(f, "!"), Token::ExclamationMark => write!(f, "!"),
Token::Dollar => write!(f, "$"), Token::Dollar => write!(f, "$"),
Token::ParenOpen => write!(f, "("), Token::ParenOpen => write!(f, "("),

View file

@ -11,6 +11,6 @@ mod tests;
pub use self::document::parse_document_source; pub use self::document::parse_document_source;
pub use self::lexer::{Lexer, LexerError, Token, ScalarToken}; pub use self::lexer::{Lexer, LexerError, ScalarToken, Token};
pub use self::parser::{OptionParseResult, ParseError, ParseResult, Parser, UnlocatedParseResult}; pub use self::parser::{OptionParseResult, ParseError, ParseResult, Parser, UnlocatedParseResult};
pub use self::utils::{SourcePosition, Spanning}; pub use self::utils::{SourcePosition, Spanning};

View file

@ -5,7 +5,7 @@ use parser::document::parse_document_source;
use parser::{ParseError, SourcePosition, Spanning, Token}; use parser::{ParseError, SourcePosition, Spanning, Token};
use schema::model::SchemaType; use schema::model::SchemaType;
use validation::test_harness::{MutationRoot, QueryRoot}; use validation::test_harness::{MutationRoot, QueryRoot};
use value::{ScalarRefValue, ScalarValue, DefaultScalarValue}; use value::{DefaultScalarValue, ScalarRefValue, ScalarValue};
fn parse_document<S>(s: &str) -> Document<S> fn parse_document<S>(s: &str) -> Document<S>
where where

View file

@ -1,4 +1,4 @@
use parser::{Lexer, LexerError, SourcePosition, Spanning, Token, ScalarToken}; use parser::{Lexer, LexerError, ScalarToken, SourcePosition, Spanning, Token};
fn tokenize_to_vec<'a>(s: &'a str) -> Vec<Spanning<Token<'a>>> { fn tokenize_to_vec<'a>(s: &'a str) -> Vec<Spanning<Token<'a>>> {
let mut tokens = Vec::new(); let mut tokens = Vec::new();
@ -35,9 +35,11 @@ fn tokenize_error(s: &str) -> Spanning<LexerError> {
loop { loop {
match lexer.next() { match lexer.next() {
Some(Ok(t)) => if t.item == Token::EndOfFile { Some(Ok(t)) => {
if t.item == Token::EndOfFile {
panic!("Tokenizer did not return error for {:#?}", s); panic!("Tokenizer did not return error for {:#?}", s);
}, }
}
Some(Err(e)) => { Some(Err(e)) => {
return e; return e;
} }
@ -133,7 +135,8 @@ fn error_positions() {
? ?
"# "#
).next(), )
.next(),
Some(Err(Spanning::zero_width( Some(Err(Spanning::zero_width(
&SourcePosition::new(14, 2, 12), &SourcePosition::new(14, 2, 12),
LexerError::UnknownCharacter('?') LexerError::UnknownCharacter('?')
@ -654,7 +657,10 @@ fn display() {
assert_eq!(format!("{}", Token::Scalar(ScalarToken::Int("123"))), "123"); assert_eq!(format!("{}", Token::Scalar(ScalarToken::Int("123"))), "123");
assert_eq!(format!("{}", Token::Scalar(ScalarToken::Float("4.5"))), "4.5"); assert_eq!(
format!("{}", Token::Scalar(ScalarToken::Float("4.5"))),
"4.5"
);
assert_eq!( assert_eq!(
format!("{}", Token::Scalar(ScalarToken::String("some string"))), format!("{}", Token::Scalar(ScalarToken::String("some string"))),

View file

@ -5,13 +5,13 @@ use parser::value::parse_value_literal;
use parser::{Lexer, Parser, SourcePosition, Spanning}; use parser::{Lexer, Parser, SourcePosition, Spanning};
use value::{DefaultScalarValue, ParseScalarValue, ScalarRefValue, ScalarValue}; use value::{DefaultScalarValue, ParseScalarValue, ScalarRefValue, ScalarValue};
use schema::meta::{MetaType, ScalarMeta, EnumMeta, EnumValue, InputObjectMeta, Argument}; use schema::meta::{Argument, EnumMeta, EnumValue, InputObjectMeta, MetaType, ScalarMeta};
use schema::model::SchemaType; use schema::model::SchemaType;
use types::scalars::EmptyMutation; use types::scalars::EmptyMutation;
#[derive(GraphQLEnumInternal)] #[derive(GraphQLEnumInternal)]
enum Enum { enum Enum {
EnumValue EnumValue,
} }
#[derive(GraphQLInputObjectInternal)] #[derive(GraphQLInputObjectInternal)]
@ -168,8 +168,10 @@ fn input_value_literals() {
]) ])
) )
); );
let fields = [ Argument::new("key", Type::NonNullNamed("Int".into())), let fields = [
Argument::new("other", Type::NonNullNamed("Bar".into()))]; Argument::new("key", Type::NonNullNamed("Int".into())),
Argument::new("other", Type::NonNullNamed("Bar".into())),
];
let meta = &MetaType::InputObject(InputObjectMeta::new::<Foo>("foo".into(), &fields)); let meta = &MetaType::InputObject(InputObjectMeta::new::<Foo>("foo".into(), &fields));
assert_eq!( assert_eq!(
parse_value::<DefaultScalarValue>("{}", meta), parse_value::<DefaultScalarValue>("{}", meta),
@ -181,10 +183,7 @@ fn input_value_literals() {
); );
assert_eq!( assert_eq!(
parse_value::<DefaultScalarValue>( parse_value::<DefaultScalarValue>(r#"{key: 123, other: {foo: "bar"}}"#, meta),
r#"{key: 123, other: {foo: "bar"}}"#,
meta
),
Spanning::start_end( Spanning::start_end(
&SourcePosition::new(0, 0, 0), &SourcePosition::new(0, 0, 0),
&SourcePosition::new(31, 0, 31), &SourcePosition::new(31, 0, 31),

View file

@ -42,11 +42,7 @@ where
.. ..
}, },
_, _,
) ) if !is_const => parse_variable_literal(parser),
if !is_const =>
{
parse_variable_literal(parser)
}
( (
&Spanning { &Spanning {
item: Token::Scalar(_), item: Token::Scalar(_),
@ -133,7 +129,8 @@ where
&Token::BracketOpen, &Token::BracketOpen,
|p| parse_value_literal(p, is_const, schema, tpe), |p| parse_value_literal(p, is_const, schema, tpe),
&Token::BracketClose, &Token::BracketClose,
)?.map(InputValue::parsed_list)) )?
.map(InputValue::parsed_list))
} }
fn parse_object_literal<'a, 'b, S>( fn parse_object_literal<'a, 'b, S>(
@ -150,7 +147,8 @@ where
&Token::CurlyOpen, &Token::CurlyOpen,
|p| parse_object_field(p, is_const, schema, object_tpe), |p| parse_object_field(p, is_const, schema, object_tpe),
&Token::CurlyClose, &Token::CurlyClose,
)?.map(|items| InputValue::parsed_object(items.into_iter().map(|s| s.item).collect()))) )?
.map(|items| InputValue::parsed_object(items.into_iter().map(|s| s.item).collect())))
} }
fn parse_object_field<'a, 'b, S>( fn parse_object_field<'a, 'b, S>(

View file

@ -365,8 +365,9 @@ impl<'a, S> MetaType<'a, S> {
} }
pub(crate) fn fields<'b>(&self, schema: &'b SchemaType<S>) -> Option<Vec<&'b Field<'b, S>>> { pub(crate) fn fields<'b>(&self, schema: &'b SchemaType<S>) -> Option<Vec<&'b Field<'b, S>>> {
schema.lookup_type(&self.as_type()).and_then(|tpe| { schema
match *tpe { .lookup_type(&self.as_type())
.and_then(|tpe| match *tpe {
MetaType::Interface(ref i) => Some(i.fields.iter().collect()), MetaType::Interface(ref i) => Some(i.fields.iter().collect()),
MetaType::Object(ref o) => Some(o.fields.iter().collect()), MetaType::Object(ref o) => Some(o.fields.iter().collect()),
MetaType::Union(ref u) => Some( MetaType::Union(ref u) => Some(
@ -378,7 +379,6 @@ impl<'a, S> MetaType<'a, S> {
.collect(), .collect(),
), ),
_ => None, _ => None,
}
}) })
} }
} }
@ -687,9 +687,7 @@ impl<'a, S> Argument<'a, S> {
desc.push('\n'); desc.push('\n');
desc.push_str(&docstring); desc.push_str(&docstring);
} }
desc @ &mut None => { desc @ &mut None => *desc = Some(docstring),
*desc = Some(docstring)
}
} }
} }
self self
@ -800,6 +798,7 @@ fn clean_docstring(multiline: &[&str]) -> Option<String> {
.take_while(move |_| line < multiline.len() - 1) .take_while(move |_| line < multiline.len() - 1)
.cloned(), .cloned(),
) )
}).collect::<String>(), })
.collect::<String>(),
) )
} }

View file

@ -302,7 +302,8 @@ impl<'a, S> SchemaType<'a, S> {
.. ..
}) => interface_names.iter().any(|iname| iname == name), }) => interface_names.iter().any(|iname| iname == name),
_ => false, _ => false,
}).collect(), })
.collect(),
_ => panic!("Can't retrieve possible types from non-abstract meta type"), _ => panic!("Can't retrieve possible types from non-abstract meta type"),
} }
} }

View file

@ -31,10 +31,12 @@ fn test_query_type_name() {
Value::object( Value::object(
vec![("name", Value::scalar("Query"))].into_iter().collect(), vec![("name", Value::scalar("Query"))].into_iter().collect(),
), ),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]
@ -60,7 +62,8 @@ fn test_specific_type_name() {
vec![( vec![(
"__type", "__type",
Value::object(vec![("name", Value::scalar("Droid"))].into_iter().collect()), Value::object(vec![("name", Value::scalar("Droid"))].into_iter().collect()),
)].into_iter() )]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]
@ -91,10 +94,12 @@ fn test_specific_object_type_name_and_kind() {
vec![ vec![
("name", Value::scalar("Droid")), ("name", Value::scalar("Droid")),
("kind", Value::scalar("OBJECT")), ("kind", Value::scalar("OBJECT")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]
@ -125,10 +130,12 @@ fn test_specific_interface_type_name_and_kind() {
vec![ vec![
("name", Value::scalar("Character")), ("name", Value::scalar("Character")),
("kind", Value::scalar("INTERFACE")), ("kind", Value::scalar("INTERFACE")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]
@ -162,10 +169,12 @@ fn test_documentation() {
"description", "description",
Value::scalar("A mechanical creature in the Star Wars universe."), Value::scalar("A mechanical creature in the Star Wars universe."),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]
@ -214,7 +223,8 @@ fn test_possible_types() {
.expect("'name' not present in type") .expect("'name' not present in type")
.as_scalar_value::<String>() .as_scalar_value::<String>()
.expect("'name' not a string") as &str .expect("'name' not a string") as &str
}).collect::<HashSet<_>>(); })
.collect::<HashSet<_>>();
assert_eq!(possible_types, vec!["Human", "Droid"].into_iter().collect()); assert_eq!(possible_types, vec!["Human", "Droid"].into_iter().collect());
} }

View file

@ -23,7 +23,8 @@ fn test_hero_name() {
vec![( vec![(
"hero", "hero",
Value::object(vec![("name", Value::scalar("R2-D2"))].into_iter().collect()), Value::object(vec![("name", Value::scalar("R2-D2"))].into_iter().collect()),
)].into_iter() )]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]
@ -53,10 +54,12 @@ fn test_hero_field_order() {
vec![ vec![
("id", Value::scalar("2001")), ("id", Value::scalar("2001")),
("name", Value::scalar("R2-D2")), ("name", Value::scalar("R2-D2")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]
@ -80,10 +83,12 @@ fn test_hero_field_order() {
vec![ vec![
("name", Value::scalar("R2-D2")), ("name", Value::scalar("R2-D2")),
("id", Value::scalar("2001")), ("id", Value::scalar("2001")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]
@ -136,10 +141,12 @@ fn test_hero_name_and_friends() {
), ),
]), ]),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]
@ -202,7 +209,8 @@ fn test_hero_name_and_friends_and_friends_of_friends() {
vec![( vec![(
"name", "name",
Value::scalar("Leia Organa"), Value::scalar("Leia Organa"),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
), ),
Value::object( Value::object(
@ -217,7 +225,8 @@ fn test_hero_name_and_friends_and_friends_of_friends() {
), ),
]), ]),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
Value::object( Value::object(
@ -238,14 +247,16 @@ fn test_hero_name_and_friends_and_friends_of_friends() {
vec![( vec![(
"name", "name",
Value::scalar("Luke Skywalker"), Value::scalar("Luke Skywalker"),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
), ),
Value::object( Value::object(
vec![( vec![(
"name", "name",
Value::scalar("Leia Organa"), Value::scalar("Leia Organa"),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
), ),
Value::object( Value::object(
@ -255,7 +266,8 @@ fn test_hero_name_and_friends_and_friends_of_friends() {
), ),
]), ]),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
Value::object( Value::object(
@ -276,7 +288,8 @@ fn test_hero_name_and_friends_and_friends_of_friends() {
vec![( vec![(
"name", "name",
Value::scalar("Luke Skywalker"), Value::scalar("Luke Skywalker"),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
), ),
Value::object( Value::object(
@ -296,15 +309,18 @@ fn test_hero_name_and_friends_and_friends_of_friends() {
), ),
]), ]),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
]), ]),
), ),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]
@ -329,7 +345,8 @@ fn test_query_name() {
.into_iter() .into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]
@ -354,7 +371,8 @@ fn test_query_alias_single() {
.into_iter() .into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]
@ -393,7 +411,8 @@ fn test_query_alias_multiple() {
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]
@ -427,7 +446,8 @@ fn test_query_alias_multiple_with_fragment() {
vec![ vec![
("name", Value::scalar("Luke Skywalker")), ("name", Value::scalar("Luke Skywalker")),
("homePlanet", Value::scalar("Tatooine")), ("homePlanet", Value::scalar("Tatooine")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
@ -437,11 +457,13 @@ fn test_query_alias_multiple_with_fragment() {
vec![ vec![
("name", Value::scalar("Leia Organa")), ("name", Value::scalar("Leia Organa")),
("homePlanet", Value::scalar("Alderaan")), ("homePlanet", Value::scalar("Alderaan")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
), ),
].into_iter() ]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]
@ -470,7 +492,8 @@ fn test_query_name_variable() {
.into_iter() .into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]
@ -530,10 +553,12 @@ fn test_query_friends_names() {
vec![("name", Value::scalar("R2-D2"))].into_iter().collect(), vec![("name", Value::scalar("R2-D2"))].into_iter().collect(),
), ),
]), ]),
)].into_iter() )]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]
@ -569,10 +594,12 @@ fn test_query_inline_fragments_droid() {
("name", Value::scalar("R2-D2")), ("name", Value::scalar("R2-D2")),
("__typename", Value::scalar("Droid")), ("__typename", Value::scalar("Droid")),
("primaryFunction", Value::scalar("Astromech")), ("primaryFunction", Value::scalar("Astromech")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]
@ -603,10 +630,12 @@ fn test_query_inline_fragments_human() {
vec![ vec![
("name", Value::scalar("Luke Skywalker")), ("name", Value::scalar("Luke Skywalker")),
("__typename", Value::scalar("Human")), ("__typename", Value::scalar("Human")),
].into_iter() ]
.into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]
@ -636,7 +665,8 @@ fn test_object_typename() {
.into_iter() .into_iter()
.collect(), .collect(),
), ),
)].into_iter() )]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]

View file

@ -82,7 +82,8 @@ fn test_node() {
("foo", Value::scalar("1")), ("foo", Value::scalar("1")),
("bar", Value::scalar("2")), ("bar", Value::scalar("2")),
("baz", Value::scalar("3")), ("baz", Value::scalar("3")),
].into_iter() ]
.into_iter()
.collect() .collect()
), ),
vec![] vec![]

View file

@ -355,7 +355,8 @@ where
T::name(info) T::name(info)
.expect("Resolving named type's selection set") .expect("Resolving named type's selection set")
.as_ref(), .as_ref(),
).expect("Type not found in schema"); )
.expect("Type not found in schema");
for selection in selection_set { for selection in selection_set {
match *selection { match *selection {
@ -404,7 +405,8 @@ where
.iter() .iter()
.map(|&(ref k, ref v)| { .map(|&(ref k, ref v)| {
(k.item, v.item.clone().into_const(exec_vars)) (k.item, v.item.clone().into_const(exec_vars))
}).collect() })
.collect()
}), }),
&meta_field.arguments, &meta_field.arguments,
), ),

View file

@ -121,11 +121,13 @@ where
None None
} }
} }
ref other => if let Some(e) = other.convert() { ref other => {
if let Some(e) = other.convert() {
Some(vec![e]) Some(vec![e])
} else { } else {
None None
}, }
}
} }
} }
} }

View file

@ -11,7 +11,7 @@ impl<S, T, CtxT> GraphQLType<S> for Box<T>
where where
S: ScalarValue, S: ScalarValue,
T: GraphQLType<S, Context = CtxT>, T: GraphQLType<S, Context = CtxT>,
for<'b> &'b S: ScalarRefValue<'b> for<'b> &'b S: ScalarRefValue<'b>,
{ {
type Context = CtxT; type Context = CtxT;
type TypeInfo = T::TypeInfo; type TypeInfo = T::TypeInfo;
@ -65,7 +65,7 @@ where
{ {
fn from_input_value<'a>(v: &'a InputValue<S>) -> Option<Box<T>> fn from_input_value<'a>(v: &'a InputValue<S>) -> Option<Box<T>>
where where
for<'b> &'b S: ScalarRefValue<'b> for<'b> &'b S: ScalarRefValue<'b>,
{ {
match <T as FromInputValue<S>>::from_input_value(v) { match <T as FromInputValue<S>>::from_input_value(v) {
Some(v) => Some(Box::new(v)), Some(v) => Some(Box::new(v)),
@ -88,7 +88,7 @@ impl<'a, S, T, CtxT> GraphQLType<S> for &'a T
where where
S: ScalarValue, S: ScalarValue,
T: GraphQLType<S, Context = CtxT>, T: GraphQLType<S, Context = CtxT>,
for<'b> &'b S: ScalarRefValue<'b> for<'b> &'b S: ScalarRefValue<'b>,
{ {
type Context = CtxT; type Context = CtxT;
type TypeInfo = T::TypeInfo; type TypeInfo = T::TypeInfo;
@ -149,7 +149,7 @@ impl<S, T> GraphQLType<S> for Arc<T>
where where
S: ScalarValue, S: ScalarValue,
T: GraphQLType<S>, T: GraphQLType<S>,
for<'b> &'b S: ScalarRefValue<'b> for<'b> &'b S: ScalarRefValue<'b>,
{ {
type Context = T::Context; type Context = T::Context;
type TypeInfo = T::TypeInfo; type TypeInfo = T::TypeInfo;

View file

@ -116,14 +116,16 @@ where
.next() .next()
.ok_or_else(|| { .ok_or_else(|| {
ParseError::LexerError(LexerError::UnknownEscapeSequence(String::from("\\u"))) ParseError::LexerError(LexerError::UnknownEscapeSequence(String::from("\\u")))
}).and_then(|c1| { })
.and_then(|c1| {
char_iter char_iter
.next() .next()
.map(|c2| format!("{}{}", c1, c2)) .map(|c2| format!("{}{}", c1, c2))
.ok_or_else(|| { .ok_or_else(|| {
ParseError::LexerError(LexerError::UnknownEscapeSequence(format!("\\u{}", c1))) ParseError::LexerError(LexerError::UnknownEscapeSequence(format!("\\u{}", c1)))
}) })
}).and_then(|mut s| { })
.and_then(|mut s| {
char_iter char_iter
.next() .next()
.ok_or_else(|| { .ok_or_else(|| {
@ -131,11 +133,13 @@ where
"\\u{}", "\\u{}",
s.clone() s.clone()
))) )))
}).map(|c2| { })
.map(|c2| {
s.push(c2); s.push(c2);
s s
}) })
}).and_then(|mut s| { })
.and_then(|mut s| {
char_iter char_iter
.next() .next()
.ok_or_else(|| { .ok_or_else(|| {
@ -143,7 +147,8 @@ where
"\\u{}", "\\u{}",
s.clone() s.clone()
))) )))
}).map(|c2| { })
.map(|c2| {
s.push(c2); s.push(c2);
s s
}) })

View file

@ -13,11 +13,13 @@ where
S: ScalarValue, S: ScalarValue,
{ {
match *arg_type { match *arg_type {
TypeType::NonNull(ref inner) => if arg_value.is_null() { TypeType::NonNull(ref inner) => {
if arg_value.is_null() {
false false
} else { } else {
is_valid_literal_value(schema, inner, arg_value) is_valid_literal_value(schema, inner, arg_value)
}, }
}
TypeType::List(ref inner) => match *arg_value { TypeType::List(ref inner) => match *arg_value {
InputValue::List(ref items) => items InputValue::List(ref items) => items
.iter() .iter()
@ -35,16 +37,17 @@ where
match *arg_value { match *arg_value {
InputValue::Null | InputValue::Variable(_) => true, InputValue::Null | InputValue::Variable(_) => true,
ref v @ InputValue::Scalar(_) ref v @ InputValue::Scalar(_) | ref v @ InputValue::Enum(_) => {
| ref v @ InputValue::Enum(_) => if let Some(parse_fn) = t.input_value_parse_fn() { if let Some(parse_fn) = t.input_value_parse_fn() {
parse_fn(v) parse_fn(v)
} else { } else {
false false
}, }
}
InputValue::List(_) => false, InputValue::List(_) => false,
InputValue::Object(ref obj) => if let MetaType::InputObject(InputObjectMeta { InputValue::Object(ref obj) => {
ref input_fields, if let MetaType::InputObject(InputObjectMeta {
.. ref input_fields, ..
}) = *t }) = *t
{ {
let mut remaining_required_fields = input_fields let mut remaining_required_fields = input_fields
@ -75,7 +78,8 @@ where
all_types_ok && remaining_required_fields.is_empty() all_types_ok && remaining_required_fields.is_empty()
} else { } else {
false false
}, }
}
} }
} }
} }

View file

@ -11,7 +11,8 @@ pub fn to_camel_case<'a>(s: &'a str) -> Cow<'a, str> {
if i > 0 && part.len() == 1 { if i > 0 && part.len() == 1 {
dest += Cow::Owned(part.to_uppercase()); dest += Cow::Owned(part.to_uppercase());
} else if i > 0 && part.len() > 1 { } else if i > 0 && part.len() > 1 {
let first = part.chars() let first = part
.chars()
.next() .next()
.unwrap() .unwrap()
.to_uppercase() .to_uppercase()

View file

@ -93,7 +93,8 @@ where
let mut errors: Vec<RuleError> = vec![]; let mut errors: Vec<RuleError> = vec![];
match *meta_type { match *meta_type {
TypeType::NonNull(ref inner) => if value.is_null() { TypeType::NonNull(ref inner) => {
if value.is_null() {
errors.push(unification_error( errors.push(unification_error(
var_name, var_name,
var_pos, var_pos,
@ -104,7 +105,8 @@ where
errors.append(&mut unify_value( errors.append(&mut unify_value(
var_name, var_pos, value, inner, schema, path, var_name, var_pos, value, inner, schema, path,
)); ));
}, }
}
TypeType::List(ref inner) => { TypeType::List(ref inner) => {
if value.is_null() { if value.is_null() {
@ -112,7 +114,8 @@ where
} }
match value.to_list_value() { match value.to_list_value() {
Some(l) => for (i, v) in l.iter().enumerate() { Some(l) => {
for (i, v) in l.iter().enumerate() {
errors.append(&mut unify_value( errors.append(&mut unify_value(
var_name, var_name,
var_pos, var_pos,
@ -121,7 +124,8 @@ where
schema, schema,
Path::ArrayElement(i, &path), Path::ArrayElement(i, &path),
)); ));
}, }
}
_ => errors.append(&mut unify_value( _ => errors.append(&mut unify_value(
var_name, var_pos, value, inner, schema, path, var_name, var_pos, value, inner, schema, path,
)), )),

View file

@ -14,7 +14,6 @@ impl<'a, S> Visitor<'a, S> for FieldsOnCorrectType
where where
S: ScalarValue, S: ScalarValue,
{ {
fn enter_field( fn enter_field(
&mut self, &mut self,
context: &mut ValidatorContext<'a, S>, context: &mut ValidatorContext<'a, S>,

View file

@ -18,7 +18,6 @@ impl<'a, S> Visitor<'a, S> for KnownDirectives
where where
S: ScalarValue, S: ScalarValue,
{ {
fn enter_operation_definition( fn enter_operation_definition(
&mut self, &mut self,
_: &mut ValidatorContext<'a, S>, _: &mut ValidatorContext<'a, S>,

View file

@ -13,7 +13,6 @@ impl<'a, S> Visitor<'a, S> for KnownFragmentNames
where where
S: ScalarValue, S: ScalarValue,
{ {
fn enter_fragment_spread( fn enter_fragment_spread(
&mut self, &mut self,
context: &mut ValidatorContext<'a, S>, context: &mut ValidatorContext<'a, S>,

View file

@ -23,7 +23,8 @@ where
.filter(|d| match **d { .filter(|d| match **d {
Definition::Operation(_) => true, Definition::Operation(_) => true,
Definition::Fragment(_) => false, Definition::Fragment(_) => false,
}).count(), })
.count(),
); );
} }

View file

@ -30,7 +30,6 @@ impl<'a, S> Visitor<'a, S> for NoFragmentCycles<'a>
where where
S: ScalarValue, S: ScalarValue,
{ {
fn exit_document(&mut self, ctx: &mut ValidatorContext<'a, S>, _: &'a Document<S>) { fn exit_document(&mut self, ctx: &mut ValidatorContext<'a, S>, _: &'a Document<S>) {
assert!(self.current_fragment.is_none()); assert!(self.current_fragment.is_none());

View file

@ -79,7 +79,8 @@ where
&error_message(var.item, *op_name), &error_message(var.item, *op_name),
&[var.start.clone(), pos.clone()], &[var.start.clone(), pos.clone()],
) )
}).collect(), })
.collect(),
); );
} }
} }
@ -144,7 +145,8 @@ where
.iter() .iter()
.map(|&var_name| { .map(|&var_name| {
Spanning::start_end(&value.start.clone(), &value.end.clone(), var_name) Spanning::start_end(&value.start.clone(), &value.end.clone(), var_name)
}).collect(), })
.collect(),
); );
} }
} }

View file

@ -515,14 +515,16 @@ impl<'a, S: Debug> OverlappingFieldsCanBeMerged<'a, S> {
conflicts conflicts
.iter() .iter()
.flat_map(|&Conflict(_, ref fs1, _)| fs1.clone()), .flat_map(|&Conflict(_, ref fs1, _)| fs1.clone()),
).collect(), )
.collect(),
vec![pos2.clone()] vec![pos2.clone()]
.into_iter() .into_iter()
.chain( .chain(
conflicts conflicts
.iter() .iter()
.flat_map(|&Conflict(_, _, ref fs2)| fs2.clone()), .flat_map(|&Conflict(_, _, ref fs2)| fs2.clone()),
).collect(), )
.collect(),
)) ))
} }
@ -653,9 +655,11 @@ impl<'a, S: Debug> OverlappingFieldsCanBeMerged<'a, S> {
Selection::FragmentSpread(Spanning { Selection::FragmentSpread(Spanning {
item: FragmentSpread { ref name, .. }, item: FragmentSpread { ref name, .. },
.. ..
}) => if fragment_names.iter().find(|n| *n == &name.item).is_none() { }) => {
if fragment_names.iter().find(|n| *n == &name.item).is_none() {
fragment_names.push(name.item); fragment_names.push(name.item);
}, }
}
Selection::InlineFragment(Spanning { Selection::InlineFragment(Spanning {
item: ref inline, .. item: ref inline, ..
}) => { }) => {
@ -725,7 +729,8 @@ fn format_reason(reason: &ConflictReasonMessage) -> String {
name, name,
format_reason(subreason) format_reason(subreason)
) )
}).collect::<Vec<_>>() })
.collect::<Vec<_>>()
.join(" and "), .join(" and "),
} }
} }
@ -1004,7 +1009,10 @@ mod tests {
} }
"#, "#,
&[RuleError::new( &[RuleError::new(
&error_message("x", &Message("name and barks are different fields".to_owned())), &error_message(
"x",
&Message("name and barks are different fields".to_owned()),
),
&[ &[
SourcePosition::new(101, 6, 12), SourcePosition::new(101, 6, 12),
SourcePosition::new(163, 9, 12), SourcePosition::new(163, 9, 12),
@ -1042,21 +1050,30 @@ mod tests {
"#, "#,
&[ &[
RuleError::new( RuleError::new(
&error_message("x", &Message("name and barks are different fields".to_owned())), &error_message(
"x",
&Message("name and barks are different fields".to_owned()),
),
&[ &[
SourcePosition::new(235, 13, 14), SourcePosition::new(235, 13, 14),
SourcePosition::new(311, 17, 12), SourcePosition::new(311, 17, 12),
], ],
), ),
RuleError::new( RuleError::new(
&error_message("x", &Message("name and nickname are different fields".to_owned())), &error_message(
"x",
&Message("name and nickname are different fields".to_owned()),
),
&[ &[
SourcePosition::new(235, 13, 14), SourcePosition::new(235, 13, 14),
SourcePosition::new(374, 20, 12), SourcePosition::new(374, 20, 12),
], ],
), ),
RuleError::new( RuleError::new(
&error_message("x", &Message("barks and nickname are different fields".to_owned())), &error_message(
"x",
&Message("barks and nickname are different fields".to_owned()),
),
&[ &[
SourcePosition::new(311, 17, 12), SourcePosition::new(311, 17, 12),
SourcePosition::new(374, 20, 12), SourcePosition::new(374, 20, 12),
@ -1495,7 +1512,8 @@ mod tests {
.interfaces(&[ .interfaces(&[
registry.get_type::<NonNullStringBox1>(i), registry.get_type::<NonNullStringBox1>(i),
registry.get_type::<SomeBox>(i), registry.get_type::<SomeBox>(i),
]).into_meta() ])
.into_meta()
} }
} }
@ -1548,7 +1566,8 @@ mod tests {
.interfaces(&[ .interfaces(&[
registry.get_type::<NonNullStringBox2>(i), registry.get_type::<NonNullStringBox2>(i),
registry.get_type::<SomeBox>(i), registry.get_type::<SomeBox>(i),
]).into_meta() ])
.into_meta()
} }
} }

View file

@ -21,7 +21,6 @@ impl<'a, S> Visitor<'a, S> for PossibleFragmentSpreads<'a, S>
where where
S: ScalarValue, S: ScalarValue,
{ {
fn enter_document(&mut self, ctx: &mut ValidatorContext<'a, S>, defs: &'a Document<S>) { fn enter_document(&mut self, ctx: &mut ValidatorContext<'a, S>, defs: &'a Document<S>) {
for def in defs { for def in defs {
if let Definition::Fragment(Spanning { ref item, .. }) = *def { if let Definition::Fragment(Spanning { ref item, .. }) = *def {

View file

@ -24,13 +24,13 @@ where
}) = ctx.parent_type().and_then(|t| t.field_by_name(field_name)) }) = ctx.parent_type().and_then(|t| t.field_by_name(field_name))
{ {
for meta_arg in meta_args { for meta_arg in meta_args {
if meta_arg.arg_type.is_non_null() && field if meta_arg.arg_type.is_non_null()
&& field
.item .item
.arguments .arguments
.as_ref() .as_ref()
.and_then(|args| { .and_then(|args| args.item.get(&meta_arg.name))
args.item.get(&meta_arg.name) .is_none()
}).is_none()
{ {
ctx.report_error( ctx.report_error(
&field_error_message( &field_error_message(
@ -58,7 +58,8 @@ where
}) = ctx.schema.directive_by_name(directive_name) }) = ctx.schema.directive_by_name(directive_name)
{ {
for meta_arg in meta_args { for meta_arg in meta_args {
if meta_arg.arg_type.is_non_null() && directive if meta_arg.arg_type.is_non_null()
&& directive
.item .item
.arguments .arguments
.as_ref() .as_ref()

View file

@ -13,12 +13,7 @@ impl<'a, S> Visitor<'a, S> for ScalarLeafs
where where
S: ScalarValue, S: ScalarValue,
{ {
fn enter_field(&mut self, ctx: &mut ValidatorContext<'a, S>, field: &'a Spanning<Field<S>>) {
fn enter_field(
&mut self,
ctx: &mut ValidatorContext<'a, S>,
field: &'a Spanning<Field<S>>,
) {
let field_name = &field.item.name.item; let field_name = &field.item.name.item;
let error = if let (Some(field_type), Some(field_type_literal)) = let error = if let (Some(field_type), Some(field_type_literal)) =

View file

@ -19,20 +19,11 @@ impl<'a, S> Visitor<'a, S> for UniqueArgumentNames<'a>
where where
S: ScalarValue, S: ScalarValue,
{ {
fn enter_directive(&mut self, _: &mut ValidatorContext<'a, S>, _: &'a Spanning<Directive<S>>) {
fn enter_directive(
&mut self,
_: &mut ValidatorContext<'a, S>,
_: &'a Spanning<Directive<S>>,
) {
self.known_names = HashMap::new(); self.known_names = HashMap::new();
} }
fn enter_field( fn enter_field(&mut self, _: &mut ValidatorContext<'a, S>, _: &'a Spanning<Field<S>>) {
&mut self,
_: &mut ValidatorContext<'a, S>,
_: &'a Spanning<Field<S>>,
) {
self.known_names = HashMap::new(); self.known_names = HashMap::new();
} }

View file

@ -19,7 +19,6 @@ impl<'a, S> Visitor<'a, S> for UniqueFragmentNames<'a>
where where
S: ScalarValue, S: ScalarValue,
{ {
fn enter_fragment_definition( fn enter_fragment_definition(
&mut self, &mut self,
context: &mut ValidatorContext<'a, S>, context: &mut ValidatorContext<'a, S>,

View file

@ -19,7 +19,6 @@ impl<'a, S> Visitor<'a, S> for UniqueOperationNames<'a>
where where
S: ScalarValue, S: ScalarValue,
{ {
fn enter_operation_definition( fn enter_operation_definition(
&mut self, &mut self,
ctx: &mut ValidatorContext<'a, S>, ctx: &mut ValidatorContext<'a, S>,

View file

@ -19,7 +19,6 @@ impl<'a, S> Visitor<'a, S> for UniqueVariableNames<'a>
where where
S: ScalarValue, S: ScalarValue,
{ {
fn enter_operation_definition( fn enter_operation_definition(
&mut self, &mut self,
_: &mut ValidatorContext<'a, S>, _: &mut ValidatorContext<'a, S>,

View file

@ -156,7 +156,8 @@ where
EnumValue::new("HEEL"), EnumValue::new("HEEL"),
EnumValue::new("DOWN"), EnumValue::new("DOWN"),
], ],
).into_meta() )
.into_meta()
} }
} }
@ -218,7 +219,8 @@ where
registry.get_type::<Being>(i), registry.get_type::<Being>(i),
registry.get_type::<Pet>(i), registry.get_type::<Pet>(i),
registry.get_type::<Canine>(i), registry.get_type::<Canine>(i),
]).into_meta() ])
.into_meta()
} }
} }
@ -247,7 +249,8 @@ where
EnumValue::new("TAN"), EnumValue::new("TAN"),
EnumValue::new("SPOTTED"), EnumValue::new("SPOTTED"),
], ],
).into_meta() )
.into_meta()
} }
} }
@ -377,7 +380,8 @@ where
.interfaces(&[ .interfaces(&[
registry.get_type::<Being>(i), registry.get_type::<Being>(i),
registry.get_type::<Intelligent>(i), registry.get_type::<Intelligent>(i),
]).into_meta() ])
.into_meta()
} }
} }
@ -410,7 +414,8 @@ where
.interfaces(&[ .interfaces(&[
registry.get_type::<Being>(i), registry.get_type::<Being>(i),
registry.get_type::<Intelligent>(i), registry.get_type::<Intelligent>(i),
]).into_meta() ])
.into_meta()
} }
} }
@ -768,6 +773,5 @@ fn print_errors(errs: &[RuleError]) {
print!("[{:>3},{:>3},{:>3}] ", p.index(), p.line(), p.column()); print!("[{:>3},{:>3},{:>3}] ", p.index(), p.line(), p.column());
} }
println!("{}", err.message()); println!("{}", err.message());
} }
} }

View file

@ -305,7 +305,8 @@ fn visit_input_value<'a, S, V>(
enter_input_value(v, ctx, input_value); enter_input_value(v, ctx, input_value);
match input_value.item { match input_value.item {
InputValue::Object(ref fields) => for field in fields { InputValue::Object(ref fields) => {
for field in fields {
let inner_type = ctx let inner_type = ctx
.current_input_type_literal() .current_input_type_literal()
.and_then(|t| match *t { .and_then(|t| match *t {
@ -313,7 +314,8 @@ fn visit_input_value<'a, S, V>(
ctx.schema.concrete_type_by_name(name) ctx.schema.concrete_type_by_name(name)
} }
_ => None, _ => None,
}).and_then(|ct| ct.input_field_by_name(&field.0.item)) })
.and_then(|ct| ct.input_field_by_name(&field.0.item))
.map(|f| &f.arg_type); .map(|f| &f.arg_type);
ctx.with_pushed_input_type(inner_type, |ctx| { ctx.with_pushed_input_type(inner_type, |ctx| {
@ -321,7 +323,8 @@ fn visit_input_value<'a, S, V>(
visit_input_value(v, ctx, &field.1); visit_input_value(v, ctx, &field.1);
v.exit_object_field(ctx, field); v.exit_object_field(ctx, field);
}) })
}, }
}
InputValue::List(ref ls) => { InputValue::List(ref ls) => {
let inner_type = ctx.current_input_type_literal().and_then(|t| match *t { let inner_type = ctx.current_input_type_literal().and_then(|t| match *t {
Type::List(ref inner) | Type::NonNullList(ref inner) => { Type::List(ref inner) | Type::NonNullList(ref inner) => {

View file

@ -102,10 +102,7 @@ where
} }
/// View the underlying float value, if present. /// View the underlying float value, if present.
#[deprecated( #[deprecated(since = "0.11", note = "Use `Value::as_scalar_value` instead")]
since = "0.11",
note = "Use `Value::as_scalar_value` instead"
)]
pub fn as_float_value(&self) -> Option<f64> pub fn as_float_value(&self) -> Option<f64>
where where
for<'a> &'a S: ScalarRefValue<'a>, for<'a> &'a S: ScalarRefValue<'a>,
@ -146,10 +143,7 @@ where
} }
/// View the underlying string value, if present. /// View the underlying string value, if present.
#[deprecated( #[deprecated(since = "0.11", note = "Use `Value::as_scalar_value` instead")]
since = "0.11",
note = "Use `Value::as_scalar_value` instead"
)]
pub fn as_string_value<'a>(&'a self) -> Option<&'a str> pub fn as_string_value<'a>(&'a self) -> Option<&'a str>
where where
Option<&'a String>: From<&'a S>, Option<&'a String>: From<&'a S>,
@ -175,7 +169,8 @@ impl<S: ScalarValue> ToInputValue<S> for Value<S> {
Spanning::unlocated(k.clone()), Spanning::unlocated(k.clone()),
Spanning::unlocated(v.to_input_value()), Spanning::unlocated(v.to_input_value()),
) )
}).collect(), })
.collect(),
), ),
} }
} }

View file

@ -246,7 +246,8 @@ where
+ Into<Option<&'a i32>> + Into<Option<&'a i32>>
+ Into<Option<&'a String>> + Into<Option<&'a String>>
+ Into<Option<&'a f64>>, + Into<Option<&'a f64>>,
{} {
}
/// The default scalar value representation in juniper /// The default scalar value representation in juniper
/// ///

View file

@ -1,4 +1,4 @@
use proc_macro2::{TokenStream}; use proc_macro2::TokenStream;
use syn; use syn;
use syn::{Data, DeriveInput, Fields, Variant}; use syn::{Data, DeriveInput, Fields, Variant};
@ -139,8 +139,8 @@ pub fn impl_enum(ast: &syn::DeriveInput, is_internal: bool) -> TokenStream {
let name = attrs.name.unwrap_or(ast.ident.to_string()); let name = attrs.name.unwrap_or(ast.ident.to_string());
let meta_description = match attrs.description { let meta_description = match attrs.description {
Some(descr) => quote!{ let meta = meta.description(#descr); }, Some(descr) => quote! { let meta = meta.description(#descr); },
None => quote!{ let meta = meta; }, None => quote! { let meta = meta; },
}; };
let mut values = TokenStream::new(); let mut values = TokenStream::new();
@ -167,21 +167,21 @@ pub fn impl_enum(ast: &syn::DeriveInput, is_internal: bool) -> TokenStream {
.name .name
.unwrap_or(::util::to_upper_snake_case(&variant.ident.to_string())); .unwrap_or(::util::to_upper_snake_case(&variant.ident.to_string()));
let descr = match var_attrs.description { let descr = match var_attrs.description {
Some(s) => quote!{ Some(#s.to_string()) }, Some(s) => quote! { Some(#s.to_string()) },
None => quote!{ None }, None => quote! { None },
}; };
let depr = match var_attrs.deprecation { let depr = match var_attrs.deprecation {
Some(DeprecationAttr { reason: Some(s) }) => quote!{ Some(DeprecationAttr { reason: Some(s) }) => quote! {
#juniper_path::meta::DeprecationStatus::Deprecated(Some(#s.to_string())) #juniper_path::meta::DeprecationStatus::Deprecated(Some(#s.to_string()))
}, },
Some(DeprecationAttr { reason: None }) => quote!{ Some(DeprecationAttr { reason: None }) => quote! {
#juniper_path::meta::DeprecationStatus::Deprecated(None) #juniper_path::meta::DeprecationStatus::Deprecated(None)
}, },
None => quote!{ None => quote! {
#juniper_path::meta::DeprecationStatus::Current #juniper_path::meta::DeprecationStatus::Current
}, },
}; };
values.extend(quote!{ values.extend(quote! {
#juniper_path::meta::EnumValue{ #juniper_path::meta::EnumValue{
name: #name.to_string(), name: #name.to_string(),
description: #descr, description: #descr,
@ -190,17 +190,17 @@ pub fn impl_enum(ast: &syn::DeriveInput, is_internal: bool) -> TokenStream {
}); });
// Build resolve match clause. // Build resolve match clause.
resolves.extend(quote!{ resolves.extend(quote! {
&#ident::#var_ident => #juniper_path::Value::scalar(String::from(#name)), &#ident::#var_ident => #juniper_path::Value::scalar(String::from(#name)),
}); });
// Build from_input clause. // Build from_input clause.
from_inputs.extend(quote!{ from_inputs.extend(quote! {
Some(#name) => Some(#ident::#var_ident), Some(#name) => Some(#ident::#var_ident),
}); });
// Build to_input clause. // Build to_input clause.
to_inputs.extend(quote!{ to_inputs.extend(quote! {
&#ident::#var_ident => &#ident::#var_ident =>
#juniper_path::InputValue::scalar(#name.to_string()), #juniper_path::InputValue::scalar(#name.to_string()),
}); });

View file

@ -149,8 +149,8 @@ pub fn impl_input_object(ast: &syn::DeriveInput, is_internal: bool) -> TokenStre
let generics = &ast.generics; let generics = &ast.generics;
let meta_description = match attrs.description { let meta_description = match attrs.description {
Some(descr) => quote!{ let meta = meta.description(#descr); }, Some(descr) => quote! { let meta = meta.description(#descr); },
None => quote!{ let meta = meta; }, None => quote! { let meta = meta; },
}; };
let mut meta_fields = TokenStream::new(); let mut meta_fields = TokenStream::new();
@ -174,8 +174,8 @@ pub fn impl_input_object(ast: &syn::DeriveInput, is_internal: bool) -> TokenStre
} }
}; };
let field_description = match field_attrs.description { let field_description = match field_attrs.description {
Some(s) => quote!{ let field = field.description(#s); }, Some(s) => quote! { let field = field.description(#s); },
None => quote!{}, None => quote! {},
}; };
let default = { let default = {
@ -205,17 +205,17 @@ pub fn impl_input_object(ast: &syn::DeriveInput, is_internal: bool) -> TokenStre
let create_meta_field = match default { let create_meta_field = match default {
Some(ref def) => { Some(ref def) => {
quote!{ quote! {
let field = registry.arg_with_default::<#field_ty>( #name, &#def, &()); let field = registry.arg_with_default::<#field_ty>( #name, &#def, &());
} }
} }
None => { None => {
quote!{ quote! {
let field = registry.arg::<#field_ty>(#name, &()); let field = registry.arg::<#field_ty>(#name, &());
} }
} }
}; };
meta_fields.extend(quote!{ meta_fields.extend(quote! {
{ {
#create_meta_field #create_meta_field
#field_description #field_description
@ -227,11 +227,11 @@ pub fn impl_input_object(ast: &syn::DeriveInput, is_internal: bool) -> TokenStre
let from_input_default = match default { let from_input_default = match default {
Some(ref def) => { Some(ref def) => {
quote!{ quote! {
Some(&&#juniper_path::InputValue::Null) | None if true => #def, Some(&&#juniper_path::InputValue::Null) | None if true => #def,
} }
} }
None => quote!{}, None => quote! {},
}; };
from_inputs.extend(quote!{ from_inputs.extend(quote!{
@ -249,7 +249,7 @@ pub fn impl_input_object(ast: &syn::DeriveInput, is_internal: bool) -> TokenStre
}); });
// Build to_input clause. // Build to_input clause.
to_inputs.extend(quote!{ to_inputs.extend(quote! {
(#name, self.#field_ident.to_input_value()), (#name, self.#field_ident.to_input_value()),
}); });
} }

View file

@ -147,8 +147,8 @@ pub fn impl_object(ast: &syn::DeriveInput) -> TokenStream {
let attrs = ObjAttrs::from_input(ast); let attrs = ObjAttrs::from_input(ast);
let name = attrs.name.unwrap_or(ast.ident.to_string()); let name = attrs.name.unwrap_or(ast.ident.to_string());
let build_description = match attrs.description { let build_description = match attrs.description {
Some(s) => quote!{ builder.description(#s) }, Some(s) => quote! { builder.description(#s) },
None => quote!{ builder }, None => quote! { builder },
}; };
let mut meta_fields = TokenStream::new(); let mut meta_fields = TokenStream::new();
@ -176,17 +176,17 @@ pub fn impl_object(ast: &syn::DeriveInput) -> TokenStream {
} }
}; };
let build_description = match field_attrs.description { let build_description = match field_attrs.description {
Some(s) => quote!{ field.description(#s) }, Some(s) => quote! { field.description(#s) },
None => quote!{ field }, None => quote! { field },
}; };
let build_deprecation = match field_attrs.deprecation { let build_deprecation = match field_attrs.deprecation {
Some(DeprecationAttr { reason: Some(s) }) => quote!{ field.deprecated(Some(#s)) }, Some(DeprecationAttr { reason: Some(s) }) => quote! { field.deprecated(Some(#s)) },
Some(DeprecationAttr { reason: None }) => quote!{ field.deprecated(None) }, Some(DeprecationAttr { reason: None }) => quote! { field.deprecated(None) },
None => quote!{ field }, None => quote! { field },
}; };
meta_fields.extend(quote!{ meta_fields.extend(quote! {
{ {
let field = registry.field::<#field_ty>(#name, &()); let field = registry.field::<#field_ty>(#name, &());
let field = #build_description; let field = #build_description;
@ -197,7 +197,7 @@ pub fn impl_object(ast: &syn::DeriveInput) -> TokenStream {
// Build from_input clause. // Build from_input clause.
resolvers.extend(quote!{ resolvers.extend(quote! {
#name => executor.resolve_with_ctx(&(), &self.#field_ident), #name => executor.resolve_with_ctx(&(), &self.#field_ident),
}); });
} }

View file

@ -1,4 +1,4 @@
use proc_macro2::{TokenStream}; use proc_macro2::TokenStream;
use syn::{self, Data, Fields, Ident, Variant}; use syn::{self, Data, Fields, Ident, Variant};
@ -22,7 +22,7 @@ pub fn impl_scalar_value(ast: &syn::DeriveInput, is_internal: bool) -> TokenStre
let display = derive_display(variants.iter(), ident); let display = derive_display(variants.iter(), ident);
quote!{ quote! {
#(#froms)* #(#froms)*
#serialize #serialize
@ -39,7 +39,7 @@ where
quote!(#ident::#variant(ref v) => write!(f, "{}", v),) quote!(#ident::#variant(ref v) => write!(f, "{}", v),)
}); });
quote!{ quote! {
impl std::fmt::Display for #ident { impl std::fmt::Display for #ident {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match *self { match *self {
@ -65,7 +65,7 @@ where
quote!(juniper::serde) quote!(juniper::serde)
}; };
quote!{ quote! {
impl #serde_path::Serialize for #ident { impl #serde_path::Serialize for #ident {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where S: #serde_path::Serializer where S: #serde_path::Serializer
@ -91,7 +91,7 @@ fn derive_from_variant(variant: &Variant, ident: &Ident) -> Result<TokenStream,
let variant = &variant.ident; let variant = &variant.ident;
Ok(quote!{ Ok(quote! {
impl std::convert::From<#ty> for #ident { impl std::convert::From<#ty> for #ident {
fn from(t: #ty) -> Self { fn from(t: #ty) -> Self {
#ident::#variant(t) #ident::#variant(t)

View file

@ -34,14 +34,14 @@ pub fn get_deprecated(attrs: &Vec<Attribute>) -> Option<DeprecationAttr> {
fn get_deprecated_meta_list(list: &MetaList) -> DeprecationAttr { fn get_deprecated_meta_list(list: &MetaList) -> DeprecationAttr {
for meta in &list.nested { for meta in &list.nested {
match meta { match meta {
&NestedMeta::Meta(Meta::NameValue(ref nv)) if nv.ident == "note" => { &NestedMeta::Meta(Meta::NameValue(ref nv)) if nv.ident == "note" => match &nv.lit {
match &nv.lit {
&Lit::Str(ref strlit) => { &Lit::Str(ref strlit) => {
return DeprecationAttr { reason: Some(strlit.value().to_string()) }; return DeprecationAttr {
reason: Some(strlit.value().to_string()),
};
} }
_ => panic!("deprecated attribute note value only has string literal"), _ => panic!("deprecated attribute note value only has string literal"),
} },
}
_ => {} _ => {}
} }
} }
@ -60,7 +60,8 @@ pub fn get_doc_comment(attrs: &Vec<Attribute>) -> Option<String> {
// Concatenates doc strings into one string. // Concatenates doc strings into one string.
fn join_doc_strings(docs: &Vec<String>) -> String { fn join_doc_strings(docs: &Vec<String>) -> String {
let s: String = docs.iter() let s: String = docs
.iter()
// Trim any extra spaces. // Trim any extra spaces.
.map(|x| x.trim().to_string()) .map(|x| x.trim().to_string())
// Convert empty comments to newlines. // Convert empty comments to newlines.
@ -118,7 +119,11 @@ pub fn get_graphql_attr(attrs: &Vec<Attribute>) -> Option<Vec<NestedMeta>> {
None None
} }
pub fn keyed_item_value(item: &NestedMeta, name: &str, validation: AttributeValidation) -> Option<AttributeValue> { pub fn keyed_item_value(
item: &NestedMeta,
name: &str,
validation: AttributeValidation,
) -> Option<AttributeValue> {
match item { match item {
// Attributes in the form of `#[graphql(name = "value")]`. // Attributes in the form of `#[graphql(name = "value")]`.
&NestedMeta::Meta(Meta::NameValue(ref nameval)) if nameval.ident == name => { &NestedMeta::Meta(Meta::NameValue(ref nameval)) if nameval.ident == name => {
@ -130,23 +135,21 @@ pub fn keyed_item_value(item: &NestedMeta, name: &str, validation: AttributeVali
"Invalid format for attribute \"{:?}\": expected a bare attribute without a value", "Invalid format for attribute \"{:?}\": expected a bare attribute without a value",
item item
)); ));
}, }
_ => Some(AttributeValue::String(strlit.value())), _ => Some(AttributeValue::String(strlit.value())),
}, },
_ => None, _ => None,
} }
}, }
// Attributes in the form of `#[graphql(name)]`. // Attributes in the form of `#[graphql(name)]`.
&NestedMeta::Meta(Meta::Word(ref ident)) if ident.to_string() == name => { &NestedMeta::Meta(Meta::Word(ref ident)) if ident.to_string() == name => match validation {
match validation {
AttributeValidation::String => { AttributeValidation::String => {
panic!(format!( panic!(format!(
"Invalid format for attribute \"{:?}\": expected a string value", "Invalid format for attribute \"{:?}\": expected a string value",
item item
)); ));
},
_ => Some(AttributeValue::Bare),
} }
_ => Some(AttributeValue::Bare),
}, },
_ => None, _ => None,
} }
@ -161,7 +164,8 @@ pub fn to_camel_case(s: &str) -> String {
if i > 0 && part.len() == 1 { if i > 0 && part.len() == 1 {
dest.push_str(&part.to_uppercase()); dest.push_str(&part.to_uppercase());
} else if i > 0 && part.len() > 1 { } else if i > 0 && part.len() > 1 {
let first = part.chars() let first = part
.chars()
.next() .next()
.unwrap() .unwrap()
.to_uppercase() .to_uppercase()

View file

@ -50,11 +50,13 @@ where
.unwrap_or(Err(GraphQLRequestError::Invalid( .unwrap_or(Err(GraphQLRequestError::Invalid(
"'query' parameter is missing".to_string(), "'query' parameter is missing".to_string(),
))), ))),
).and_then(move |gql_req| { )
.and_then(move |gql_req| {
execute_request(root_node, context, gql_req).map_err(|_| { execute_request(root_node, context, gql_req).map_err(|_| {
unreachable!("thread pool has shut down?!"); unreachable!("thread pool has shut down?!");
}) })
}).or_else(|err| future::ok(render_error(err))), })
.or_else(|err| future::ok(render_error(err))),
)), )),
&Method::POST => Either::A(Either::B( &Method::POST => Either::A(Either::B(
request request
@ -70,11 +72,13 @@ where
.map_err(GraphQLRequestError::BodyJSONError) .map_err(GraphQLRequestError::BodyJSONError)
}) })
}) })
}).and_then(move |gql_req| { })
.and_then(move |gql_req| {
execute_request(root_node, context, gql_req).map_err(|_| { execute_request(root_node, context, gql_req).map_err(|_| {
unreachable!("thread pool has shut down?!"); unreachable!("thread pool has shut down?!");
}) })
}).or_else(|err| future::ok(render_error(err))), })
.or_else(|err| future::ok(render_error(err))),
)), )),
_ => return Either::B(future::ok(new_response(StatusCode::METHOD_NOT_ALLOWED))), _ => return Either::B(future::ok(new_response(StatusCode::METHOD_NOT_ALLOWED))),
} }
@ -239,7 +243,8 @@ where
let body = serde_json::to_string_pretty(&res).unwrap(); let body = serde_json::to_string_pretty(&res).unwrap();
Ok(Async::Ready((is_ok, body))) Ok(Async::Ready((is_ok, body)))
}) })
})).map(|results| { }))
.map(|results| {
let is_ok = results.iter().all(|&(is_ok, _)| is_ok); let is_ok = results.iter().all(|&(is_ok, _)| is_ok);
// concatenate json bodies as array // concatenate json bodies as array
// TODO: maybe use Body chunks instead? // TODO: maybe use Body chunks instead?

View file

@ -488,7 +488,8 @@ mod tests {
.get_raw("content-type") .get_raw("content-type")
.expect("No content type header from handler")[0] .expect("No content type header from handler")[0]
.clone(), .clone(),
).expect("Content-type header invalid UTF-8"); )
.expect("Content-type header invalid UTF-8");
let body = response::extract_body_to_string(response); let body = response::extract_body_to_string(response);
http_tests::TestResponse { http_tests::TestResponse {

View file

@ -2,7 +2,8 @@
extern crate juniper; extern crate juniper;
extern crate juniper_rocket; extern crate juniper_rocket;
#[macro_use] extern crate rocket; #[macro_use]
extern crate rocket;
use rocket::response::content; use rocket::response::content;
use rocket::State; use rocket::State;

View file

@ -300,7 +300,8 @@ where
} }
impl<'v, S> FromFormValue<'v> for GraphQLRequest<S> impl<'v, S> FromFormValue<'v> for GraphQLRequest<S>
where S: ScalarValue where
S: ScalarValue,
{ {
type Error = String; type Error = String;
@ -459,12 +460,12 @@ mod fromform_tests {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use rocket::{self, get, post, routes};
use rocket::request::Form;
use rocket::http::ContentType; use rocket::http::ContentType;
use rocket::local::{Client, LocalRequest}; use rocket::local::{Client, LocalRequest};
use rocket::request::Form;
use rocket::Rocket; use rocket::Rocket;
use rocket::State; use rocket::State;
use rocket::{self, get, post, routes};
use juniper::http::tests as http_tests; use juniper::http::tests as http_tests;
use juniper::tests::model::Database; use juniper::tests::model::Database;
@ -522,7 +523,8 @@ mod tests {
.manage(Schema::new( .manage(Schema::new(
Database::new(), Database::new(),
EmptyMutation::<Database>::new(), EmptyMutation::<Database>::new(),
)).mount("/", routes![post_graphql_handler, get_graphql_handler]) ))
.mount("/", routes![post_graphql_handler, get_graphql_handler])
} }
fn make_test_response(request: &LocalRequest) -> http_tests::TestResponse { fn make_test_response(request: &LocalRequest) -> http_tests::TestResponse {

View file

@ -43,5 +43,6 @@ fn main() {
.or(homepage) .or(homepage)
.or(warp::path("graphql").and(graphql_filter)) .or(warp::path("graphql").and(graphql_filter))
.with(log), .with(log),
).run(([127, 0, 0, 1], 8080)); )
.run(([127, 0, 0, 1], 8080));
} }

View file

@ -201,7 +201,8 @@ where
let response = request.execute(&schema, &context); let response = request.execute(&schema, &context);
Ok((serde_json::to_vec(&response)?, response.is_ok())) Ok((serde_json::to_vec(&response)?, response.is_ok()))
}) })
}).and_then(|result| ::futures::future::done(Ok(build_response(result)))) })
.and_then(|result| ::futures::future::done(Ok(build_response(result))))
.map_err(|e: tokio_threadpool::BlockingError| warp::reject::custom(e)), .map_err(|e: tokio_threadpool::BlockingError| warp::reject::custom(e)),
) )
}; };
@ -234,7 +235,8 @@ where
let response = graphql_request.execute(&schema, &context); let response = graphql_request.execute(&schema, &context);
Ok((serde_json::to_vec(&response)?, response.is_ok())) Ok((serde_json::to_vec(&response)?, response.is_ok()))
}) })
}).and_then(|result| ::futures::future::done(Ok(build_response(result)))) })
.and_then(|result| ::futures::future::done(Ok(build_response(result))))
.map_err(|e: tokio_threadpool::BlockingError| warp::reject::custom(e)), .map_err(|e: tokio_threadpool::BlockingError| warp::reject::custom(e)),
) )
}; };
@ -396,7 +398,8 @@ mod tests {
{ "variables": null, "query": "{ hero(episode: NEW_HOPE) { name } }" }, { "variables": null, "query": "{ hero(episode: NEW_HOPE) { name } }" },
{ "variables": null, "query": "{ hero(episode: EMPIRE) { id name } }" } { "variables": null, "query": "{ hero(episode: EMPIRE) { id name } }" }
]"##, ]"##,
).reply(&filter); )
.reply(&filter);
assert_eq!(response.status(), http::StatusCode::OK); assert_eq!(response.status(), http::StatusCode::OK);
assert_eq!( assert_eq!(