Skip to content
Merged
Show file tree
Hide file tree
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
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ thiserror = "1.0.20"

# used for tests and HTTP/hyper
# the features are used only for tests but enabled because `dev-depedencies` are leaked into dependencies.
tokio = { version = "0.2.22", features = ["dns", "stream", "tcp", "rt-threaded", "macros"], optional = true }
tokio = { version = "0.2.22", features = ["stream", "rt-threaded", "macros"], optional = true }

# HTTP-related dependencies
hyper = { version = "0.13.8", features = ["stream"], optional = true }
Expand All @@ -46,4 +46,4 @@ ws = ["async-tls", "bytes", "soketto", "url", "webpki"]

[dev-dependencies]
env_logger = "0.7.1"
tokio-util = { version = "0.3", features = ["compat"] }
jsonrpsee-test-utils = { path = "test-utils" }
90 changes: 8 additions & 82 deletions src/http/tests.rs
Original file line number Diff line number Diff line change
@@ -1,41 +1,14 @@
#![cfg(test)]

use crate::common::{Id, JsonValue};
use crate::common::JsonValue;
use crate::http::HttpServer;
use futures::channel::oneshot::{self, Sender};
use futures::future::FutureExt;
use futures::{pin_mut, select};
use hyper::{Body, HeaderMap, StatusCode, Uri};
use jsonrpsee_test_utils::types::{Id, StatusCode};
use jsonrpsee_test_utils::helpers::*;
use std::net::SocketAddr;

#[derive(Debug)]
struct Response {
status: StatusCode,
header: HeaderMap,
body: String,
}

async fn request(body: Body, uri: Uri) -> Result<Response, String> {
let client = hyper::Client::new();
let r = hyper::Request::post(uri)
.header(
hyper::header::CONTENT_TYPE,
hyper::header::HeaderValue::from_static("application/json"),
)
.body(body)
.expect("uri and request headers are valid; qed");
let res = client.request(r).await.map_err(|e| format!("{:?}", e))?;

let (parts, body) = res.into_parts();
let bytes = hyper::body::to_bytes(body).await.unwrap();

Ok(Response {
status: parts.status,
header: parts.headers,
body: String::from_utf8(bytes.to_vec()).unwrap(),
})
}

async fn server(server_started_tx: Sender<SocketAddr>) {
let server = HttpServer::new("127.0.0.1:0").await.unwrap();
let mut hello = server.register_method("say_hello".to_owned()).unwrap();
Expand Down Expand Up @@ -79,53 +52,6 @@ async fn server(server_started_tx: Sender<SocketAddr>) {
}
}

fn to_http_uri(sockaddr: SocketAddr) -> Uri {
let s = sockaddr.to_string();

Uri::builder()
.scheme("http")
.authority(s.as_str())
.path_and_query("/")
.build()
.unwrap()
}

fn ok_response(result: JsonValue, id: Id) -> String {
format!(
r#"{{"jsonrpc":"2.0","result":{},"id":{}}}"#,
result,
serde_json::to_string(&id).unwrap()
)
}

fn method_not_found(id: Id) -> String {
format!(
r#"{{"jsonrpc":"2.0","error":{{"code":-32601,"message":"Method not found"}},"id":{}}}"#,
serde_json::to_string(&id).unwrap()
)
}

fn parse_error(id: Id) -> String {
format!(
r#"{{"jsonrpc":"2.0","error":{{"code":-32700,"message":"Parse error"}},"id":{}}}"#,
serde_json::to_string(&id).unwrap()
)
}

fn invalid_request(id: Id) -> String {
format!(
r#"{{"jsonrpc":"2.0","error":{{"code":-32600,"message":"Invalid request"}},"id":{}}}"#,
serde_json::to_string(&id).unwrap()
)
}

fn invalid_params(id: Id) -> String {
format!(
r#"{{"jsonrpc":"2.0","error":{{"code":-32602,"message":"Invalid params"}},"id":{}}}"#,
serde_json::to_string(&id).unwrap()
)
}

#[tokio::test]
async fn single_method_call_works() {
let (server_started_tx, server_started_rx) = oneshot::channel::<SocketAddr>();
Expand All @@ -135,7 +61,7 @@ async fn single_method_call_works() {

for i in 0..10 {
let req = format!(r#"{{"jsonrpc":"2.0","method":"say_hello","id":{}}}"#, i);
let response = request(req.into(), uri.clone()).await.unwrap();
let response = http_request(req.into(), uri.clone()).await.unwrap();
assert_eq!(response.status, StatusCode::OK);
assert_eq!(
response.body,
Expand All @@ -151,7 +77,7 @@ async fn single_method_call_with_params() {
let server_addr = server_started_rx.await.unwrap();

let req = r#"{"jsonrpc":"2.0","method":"add", "params":[1, 2],"id":1}"#;
let response = request(req.into(), to_http_uri(server_addr)).await.unwrap();
let response = http_request(req.into(), to_http_uri(server_addr)).await.unwrap();
assert_eq!(response.status, StatusCode::OK);
assert_eq!(
response.body,
Expand All @@ -166,7 +92,7 @@ async fn should_return_method_not_found() {
let server_addr = server_started_rx.await.unwrap();

let req = r#"{"jsonrpc":"2.0","method":"bar","id":"foo"}"#;
let response = request(req.into(), to_http_uri(server_addr)).await.unwrap();
let response = http_request(req.into(), to_http_uri(server_addr)).await.unwrap();
assert_eq!(response.status, StatusCode::OK);
assert_eq!(response.body, method_not_found(Id::Str("foo".into())));
}
Expand All @@ -178,7 +104,7 @@ async fn invalid_json_id_missing_value() {
let server_addr = server_started_rx.await.unwrap();

let req = r#"{"jsonrpc":"2.0","method":"say_hello","id"}"#;
let response = request(req.into(), to_http_uri(server_addr)).await.unwrap();
let response = http_request(req.into(), to_http_uri(server_addr)).await.unwrap();
// If there was an error in detecting the id in the Request object (e.g. Parse error/Invalid Request), it MUST be Null.
assert_eq!(response.body, parse_error(Id::Null));
}
Expand All @@ -190,7 +116,7 @@ async fn invalid_request_object() {
let server_addr = server_started_rx.await.unwrap();

let req = r#"{"jsonrpc":"2.0","method":"bar","id":1,"is_not_request_object":1}"#;
let response = request(req.into(), to_http_uri(server_addr)).await.unwrap();
let response = http_request(req.into(), to_http_uri(server_addr)).await.unwrap();
assert_eq!(response.status, StatusCode::OK);
assert_eq!(response.body, invalid_request(Id::Num(1)));
}
9 changes: 3 additions & 6 deletions src/ws/raw/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,10 @@
use crate::client::WsTransportClient;
use crate::common::{self, Call, MethodCall, Notification, Params, Request, Version};
use crate::ws::{RawWsServer, RawWsServerEvent, WsTransportServer};
use jsonrpsee_test_utils::helpers::*;
use serde_json::Value;
use std::net::SocketAddr;

fn to_uri(sockaddr: SocketAddr) -> String {
format!("ws://{}", sockaddr)
}

async fn raw_server() -> (RawWsServer, SocketAddr) {
let server = WsTransportServer::builder("127.0.0.1:0".parse().unwrap())
.build()
Expand All @@ -50,7 +47,7 @@ async fn request_work() {
let (mut server, server_addr) = raw_server().await;

tokio::spawn(async move {
let mut client = WsTransportClient::new(&to_uri(server_addr)).await.unwrap();
let mut client = WsTransportClient::new(&to_ws_uri_string(server_addr)).await.unwrap();
let call = Call::MethodCall(MethodCall {
jsonrpc: Version::V2,
method: "hello_world".to_owned(),
Expand Down Expand Up @@ -78,7 +75,7 @@ async fn notification_work() {
let (mut server, server_addr) = raw_server().await;

tokio::spawn(async move {
let mut client = WsTransportClient::new(&to_uri(server_addr)).await.unwrap();
let mut client = WsTransportClient::new(&to_ws_uri_string(server_addr)).await.unwrap();
let n = Notification {
jsonrpc: Version::V2,
method: "hello_world".to_owned(),
Expand Down
Loading