Skip to content

Commit

Permalink
Add a method to handle empty response. (paritytech#473)
Browse files Browse the repository at this point in the history
  • Loading branch information
tomusdrw authored and debris committed Aug 6, 2019
1 parent 3e7ae2f commit 5b07faa
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
18 changes: 18 additions & 0 deletions core/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,24 @@ mod tests {
assert_eq!(called.load(atomic::Ordering::SeqCst), true);
}

#[test]
fn test_batch_notification() {
use std::sync::atomic;
use std::sync::Arc;

let mut io = IoHandler::new();

let called = Arc::new(atomic::AtomicBool::new(false));
let c = called.clone();
io.add_notification("say_hello", move |_| {
c.store(true, atomic::Ordering::SeqCst);
});

let request = r#"[{"jsonrpc": "2.0", "method": "say_hello", "params": [42, 23]}]"#;
assert_eq!(io.handle_request_sync(request), None);
assert_eq!(called.load(atomic::Ordering::SeqCst), true);
}

#[test]
fn test_send_sync() {
fn is_send_sync<T>(_obj: T) -> bool
Expand Down
23 changes: 23 additions & 0 deletions core/src/types/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,17 @@ impl Response {
}
.into()
}

/// Deserialize `Response` from given JSON string.
///
/// This method will handle an empty string as empty batch response.
pub fn from_json(s: &str) -> Result<Self, serde_json::Error> {
if s.is_empty() {
Ok(Response::Batch(vec![]))
} else {
serde_json::from_str(s)
}
}
}

impl From<Failure> for Response {
Expand Down Expand Up @@ -268,3 +279,15 @@ fn handle_incorrect_responses() {
"Expected error when deserializing invalid payload."
);
}

#[test]
fn should_parse_empty_response_as_batch() {
use serde_json;

let dsr = r#""#;

let deserialized1: Result<Response, _>= serde_json::from_str(dsr);
let deserialized2: Result<Response, _> = Response::from_json(dsr);
assert!(deserialized1.is_err(), "Empty string is not valid JSON, so we should get an error.");
assert_eq!(deserialized2.unwrap(), Response::Batch(vec![]));
}

0 comments on commit 5b07faa

Please sign in to comment.