Skip to content

Commit 46cde4f

Browse files
authored
Fix parsing f64 from Scalar::Int (#777)
1 parent f914322 commit 46cde4f

File tree

1 file changed

+44
-3
lines changed

1 file changed

+44
-3
lines changed

juniper/src/types/scalars.rs

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,11 @@ where
325325

326326
fn from_str<'a>(value: ScalarToken<'a>) -> ParseScalarResult<'a, S> {
327327
match value {
328-
ScalarToken::Int(v) | ScalarToken::Float(v) => v
328+
ScalarToken::Int(v) => v
329+
.parse()
330+
.map_err(|_| ParseError::UnexpectedToken(Token::Scalar(value)))
331+
.map(|s: i32| f64::from(s).into()),
332+
ScalarToken::Float(v) => v
329333
.parse()
330334
.map_err(|_| ParseError::UnexpectedToken(Token::Scalar(value)))
331335
.map(|s: f64| s.into()),
@@ -334,7 +338,7 @@ where
334338
}
335339
}
336340

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

458462
#[cfg(test)]
459463
mod tests {
460-
use super::{EmptyMutation, EmptySubscription, ID};
461464
use crate::{
462465
parser::ScalarToken,
463466
value::{DefaultScalarValue, ParseScalarValue},
464467
};
465468

469+
use super::{EmptyMutation, EmptySubscription, ID};
470+
466471
#[test]
467472
fn test_id_from_string() {
468473
let actual = ID::from(String::from("foo"));
@@ -505,6 +510,42 @@ mod tests {
505510
);
506511
}
507512

513+
#[test]
514+
fn parse_f64_from_int() {
515+
for (v, expected) in &[
516+
("0", 0),
517+
("128", 128),
518+
("1601942400", 1601942400),
519+
("1696550400", 1696550400),
520+
("-1", -1),
521+
] {
522+
let n = <f64 as ParseScalarValue<DefaultScalarValue>>::from_str(ScalarToken::Int(v));
523+
assert!(n.is_ok(), "A parsing error occurred: {:?}", n.unwrap_err());
524+
525+
let n: Option<f64> = n.unwrap().into();
526+
assert!(n.is_some(), "No f64 returned");
527+
assert_eq!(n.unwrap(), f64::from(*expected));
528+
}
529+
}
530+
531+
#[test]
532+
fn parse_f64_from_float() {
533+
for (v, expected) in &[
534+
("0.", 0.),
535+
("1.2", 1.2),
536+
("1601942400.", 1601942400.),
537+
("1696550400.", 1696550400.),
538+
("-1.2", -1.2),
539+
] {
540+
let n = <f64 as ParseScalarValue<DefaultScalarValue>>::from_str(ScalarToken::Float(v));
541+
assert!(n.is_ok(), "A parsing error occurred: {:?}", n.unwrap_err());
542+
543+
let n: Option<f64> = n.unwrap().into();
544+
assert!(n.is_some(), "No f64 returned");
545+
assert_eq!(n.unwrap(), *expected);
546+
}
547+
}
548+
508549
#[test]
509550
fn empty_mutation_is_send() {
510551
fn check_if_send<T: Send>() {}

0 commit comments

Comments
 (0)