Skip to content

Fix parsing f64 from Scalar::Int #777

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 8, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 44 additions & 3 deletions juniper/src/types/scalars.rs
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,11 @@ where

fn from_str<'a>(value: ScalarToken<'a>) -> ParseScalarResult<'a, S> {
match value {
ScalarToken::Int(v) | ScalarToken::Float(v) => v
ScalarToken::Int(v) => v
.parse()
.map_err(|_| ParseError::UnexpectedToken(Token::Scalar(value)))
.map(|s: i32| f64::from(s).into()),
ScalarToken::Float(v) => v
.parse()
.map_err(|_| ParseError::UnexpectedToken(Token::Scalar(value)))
.map(|s: f64| s.into()),
Expand All @@ -334,7 +338,7 @@ where
}
}

/// Utillity type to define read-only schemas
/// Utility type to define read-only schemas
///
/// If you instantiate `RootNode` with this as the mutation, no mutation will be
/// generated for the schema.
Expand Down Expand Up @@ -457,12 +461,13 @@ impl<T> Default for EmptySubscription<T> {

#[cfg(test)]
mod tests {
use super::{EmptyMutation, EmptySubscription, ID};
use crate::{
parser::ScalarToken,
value::{DefaultScalarValue, ParseScalarValue},
};

use super::{EmptyMutation, EmptySubscription, ID};

#[test]
fn test_id_from_string() {
let actual = ID::from(String::from("foo"));
Expand Down Expand Up @@ -505,6 +510,42 @@ mod tests {
);
}

#[test]
fn parse_f64_from_int() {
for (v, expected) in &[
("0", 0),
("128", 128),
("1601942400", 1601942400),
("1696550400", 1696550400),
("-1", -1),
] {
let n = <f64 as ParseScalarValue<DefaultScalarValue>>::from_str(ScalarToken::Int(v));
assert!(n.is_ok(), "A parsing error occurred: {:?}", n.unwrap_err());

let n: Option<f64> = n.unwrap().into();
assert!(n.is_some(), "No f64 returned");
assert_eq!(n.unwrap(), f64::from(*expected));
}
}

#[test]
fn parse_f64_from_float() {
for (v, expected) in &[
("0.", 0.),
("1.2", 1.2),
("1601942400.", 1601942400.),
("1696550400.", 1696550400.),
("-1.2", -1.2),
] {
let n = <f64 as ParseScalarValue<DefaultScalarValue>>::from_str(ScalarToken::Float(v));
assert!(n.is_ok(), "A parsing error occurred: {:?}", n.unwrap_err());

let n: Option<f64> = n.unwrap().into();
assert!(n.is_some(), "No f64 returned");
assert_eq!(n.unwrap(), *expected);
}
}

#[test]
fn empty_mutation_is_send() {
fn check_if_send<T: Send>() {}
Expand Down