Newer
Older
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#![cfg(test)]
use std::sync::Arc;
use std::time::Duration;
use helpers::{http_server, http_server_with_access_control, websocket_server, websocket_server_with_subscription};
use jsonrpsee::core::client::{ClientT, IdKind, Subscription, SubscriptionClientT};
use jsonrpsee::core::error::SubscriptionClosed;
use jsonrpsee::core::{Error, JsonValue};
use jsonrpsee::http_client::HttpClientBuilder;
use jsonrpsee::rpc_params;
use jsonrpsee::types::error::ErrorObject;
use tokio::time::interval;
use tokio_stream::wrappers::IntervalStream;
#[tokio::test]
async fn ws_subscription_works() {
Niklas Adolfsson
committed
let (server_addr, _) = websocket_server_with_subscription().await;
let server_url = format!("ws://{}", server_addr);
let client = WsClientBuilder::default().build(&server_url).await.unwrap();
let mut hello_sub: Subscription<String> =
client.subscribe("subscribe_hello", None, "unsubscribe_hello").await.unwrap();
let mut foo_sub: Subscription<u64> = client.subscribe("subscribe_foo", None, "unsubscribe_foo").await.unwrap();
let hello = hello_sub.next().await.unwrap().unwrap();
let foo = foo_sub.next().await.unwrap().unwrap();
assert_eq!(hello, "hello from subscription".to_string());
assert_eq!(foo, 1337);
#[tokio::test]
async fn ws_subscription_with_input_works() {
Niklas Adolfsson
committed
let (server_addr, _) = websocket_server_with_subscription().await;
let server_url = format!("ws://{}", server_addr);
let client = WsClientBuilder::default().build(&server_url).await.unwrap();
let mut add_one: Subscription<u64> =
client.subscribe("subscribe_add_one", rpc_params![1], "unsubscribe_add_one").await.unwrap();
for i in 2..4 {
let next = add_one.next().await.unwrap().unwrap();
assert_eq!(next, i);
}
}
#[tokio::test]
async fn ws_method_call_works() {
let server_url = format!("ws://{}", server_addr);
let client = WsClientBuilder::default().build(&server_url).await.unwrap();
let response: String = client.request("say_hello", None).await.unwrap();
assert_eq!(&response, "hello");
#[tokio::test]
async fn ws_method_call_str_id_works() {
let server_addr = websocket_server().await;
let server_url = format!("ws://{}", server_addr);
let client = WsClientBuilder::default().id_format(IdKind::String).build(&server_url).await.unwrap();
let response: String = client.request("say_hello", None).await.unwrap();
assert_eq!(&response, "hello");
}
#[tokio::test]
async fn http_method_call_works() {
Niklas Adolfsson
committed
let (server_addr, _handle) = http_server().await;
let uri = format!("http://{}", server_addr);
let client = HttpClientBuilder::default().build(&uri).unwrap();
let response: String = client.request("say_hello", None).await.unwrap();
#[tokio::test]
async fn http_method_call_str_id_works() {
let (server_addr, _handle) = http_server().await;
let uri = format!("http://{}", server_addr);
let client = HttpClientBuilder::default().id_format(IdKind::String).build(&uri).unwrap();
let response: String = client.request("say_hello", None).await.unwrap();
assert_eq!(&response, "hello");
}
#[tokio::test]
async fn http_concurrent_method_call_limits_works() {
Niklas Adolfsson
committed
let (server_addr, _handle) = http_server().await;
let uri = format!("http://{}", server_addr);
let client = HttpClientBuilder::default().max_concurrent_requests(1).build(&uri).unwrap();
let (first, second) =
tokio::join!(client.request::<String>("say_hello", None), client.request::<String>("say_hello", None),);
assert!(first.is_ok());
assert!(matches!(second, Err(Error::MaxSlotsExceeded)));
}
#[tokio::test]
async fn ws_subscription_several_clients() {
Niklas Adolfsson
committed
let (server_addr, _) = websocket_server_with_subscription().await;
let server_url = format!("ws://{}", server_addr);
let mut clients = Vec::with_capacity(10);
for _ in 0..10 {
let client = WsClientBuilder::default().build(&server_url).await.unwrap();
let hello_sub: Subscription<JsonValue> =
client.subscribe("subscribe_hello", None, "unsubscribe_hello").await.unwrap();
let foo_sub: Subscription<JsonValue> =
client.subscribe("subscribe_foo", None, "unsubscribe_foo").await.unwrap();
clients.push((client, hello_sub, foo_sub))
}
}
#[tokio::test]
async fn ws_subscription_several_clients_with_drop() {
Niklas Adolfsson
committed
let (server_addr, _) = websocket_server_with_subscription().await;
let server_url = format!("ws://{}", server_addr);
let mut clients = Vec::with_capacity(10);
for _ in 0..10 {
let client =
WsClientBuilder::default().max_notifs_per_subscription(u32::MAX as usize).build(&server_url).await.unwrap();
let hello_sub: Subscription<String> =
client.subscribe("subscribe_hello", None, "unsubscribe_hello").await.unwrap();
let foo_sub: Subscription<u64> = client.subscribe("subscribe_foo", None, "unsubscribe_foo").await.unwrap();
clients.push((client, hello_sub, foo_sub))
}
for _ in 0..10 {
for (_client, hello_sub, foo_sub) in &mut clients {
let hello = hello_sub.next().await.unwrap().unwrap();
let foo = foo_sub.next().await.unwrap().unwrap();
assert_eq!(&hello, "hello from subscription");
assert_eq!(foo, 1337);
let (client, hello_sub, foo_sub) = clients.remove(i);
drop(hello_sub);
drop(foo_sub);
assert!(client.is_connected());
Niklas Adolfsson
committed
// make sure nothing weird happened after dropping half of the clients (should be `unsubscribed` in the server)
// would be good to know that subscriptions actually were removed but not possible to verify at
// this layer.
for _ in 0..10 {
Niklas Adolfsson
committed
for (client, hello_sub, foo_sub) in &mut clients {
assert!(client.is_connected());
let hello = hello_sub.next().await.unwrap().unwrap();
let foo = foo_sub.next().await.unwrap().unwrap();
assert_eq!(&hello, "hello from subscription");
assert_eq!(foo, 1337);
}
}
}
#[tokio::test]
async fn ws_subscription_without_polling_doesnt_make_client_unuseable() {
Niklas Adolfsson
committed
let (server_addr, _) = websocket_server_with_subscription().await;
let server_url = format!("ws://{}", server_addr);
let client = WsClientBuilder::default().max_notifs_per_subscription(4).build(&server_url).await.unwrap();
let mut hello_sub: Subscription<JsonValue> =
client.subscribe("subscribe_hello", None, "unsubscribe_hello").await.unwrap();
// don't poll the subscription stream for 2 seconds, should be full now.
tokio::time::sleep(Duration::from_secs(2)).await;
// Capacity is `num_sender` + `capacity`
for _ in 0..5 {
assert!(hello_sub.next().await.unwrap().is_ok());
}
// NOTE: this is now unuseable and unregistered.
assert!(hello_sub.next().await.is_none());
// The client should still be useable => make sure it still works.
let _hello_req: JsonValue = client.request("say_hello", None).await.unwrap();
// The same subscription should be possible to register again.
let mut other_sub: Subscription<JsonValue> =
client.subscribe("subscribe_hello", None, "unsubscribe_hello").await.unwrap();
other_sub.next().await.unwrap().unwrap();
async fn ws_making_more_requests_than_allowed_should_not_deadlock() {
let server_url = format!("ws://{}", server_addr);
let client = Arc::new(WsClientBuilder::default().max_concurrent_requests(2).build(&server_url).await.unwrap());
for _ in 0..6 {
let c = client.clone();
requests.push(tokio::spawn(async move { c.request::<String>("say_hello", None).await }));
let _ = req.await.unwrap();
Niklas Adolfsson
committed
#[tokio::test]
async fn http_making_more_requests_than_allowed_should_not_deadlock() {
Niklas Adolfsson
committed
let (server_addr, _handle) = http_server().await;
let server_url = format!("http://{}", server_addr);
let client = HttpClientBuilder::default().max_concurrent_requests(2).build(&server_url).unwrap();
let client = Arc::new(client);
let mut requests = Vec::new();
for _ in 0..6 {
let c = client.clone();
requests.push(tokio::spawn(async move { c.request::<String>("say_hello", None).await }));
}
for req in requests {
let _ = req.await.unwrap();
}
}
let client = HttpClientBuilder::default().build("https://kusama-rpc.polkadot.io").unwrap();
let response: String = client.request("system_chain", None).await.unwrap();
assert_eq!(&response, "Kusama");
}
Niklas Adolfsson
committed
#[tokio::test]
Niklas Adolfsson
committed
async fn wss_works() {
let client = WsClientBuilder::default().build("wss://kusama-rpc.polkadot.io").await.unwrap();
let response: String = client.request("system_chain", None).await.unwrap();
Niklas Adolfsson
committed
assert_eq!(&response, "Kusama");
}
#[tokio::test]
async fn ws_with_non_ascii_url_doesnt_hang_or_panic() {
let err = WsClientBuilder::default().build("wss://♥♥♥♥♥♥∀∂").await;
assert!(matches!(err, Err(Error::Transport(_))));
Niklas Adolfsson
committed
}
#[tokio::test]
async fn http_with_non_ascii_url_doesnt_hang_or_panic() {
let err = HttpClientBuilder::default().build("http://♥♥♥♥♥♥∀∂");
assert!(matches!(err, Err(Error::Transport(_))));
Niklas Adolfsson
committed
}
#[tokio::test]
async fn ws_unsubscribe_releases_request_slots() {
Niklas Adolfsson
committed
let (server_addr, _) = websocket_server_with_subscription().await;
let server_url = format!("ws://{}", server_addr);
let client = WsClientBuilder::default().max_concurrent_requests(1).build(&server_url).await.unwrap();
let sub1: Subscription<JsonValue> = client.subscribe("subscribe_hello", None, "unsubscribe_hello").await.unwrap();
let _: Subscription<JsonValue> = client.subscribe("subscribe_hello", None, "unsubscribe_hello").await.unwrap();
#[tokio::test]
async fn server_should_be_able_to_close_subscriptions() {
tracing_subscriber::FmtSubscriber::builder()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.try_init()
.expect("setting default subscriber failed");
Niklas Adolfsson
committed
let (server_addr, _) = websocket_server_with_subscription().await;
let server_url = format!("ws://{}", server_addr);
let client = WsClientBuilder::default().build(&server_url).await.unwrap();
let mut sub: Subscription<String> = client.subscribe("subscribe_noop", None, "unsubscribe_noop").await.unwrap();
assert!(sub.next().await.is_none());
Niklas Adolfsson
committed
#[tokio::test]
async fn ws_close_pending_subscription_when_server_terminated() {
let (server_addr, handle) = websocket_server_with_subscription().await;
Niklas Adolfsson
committed
let server_url = format!("ws://{}", server_addr);
let c1 = WsClientBuilder::default().build(&server_url).await.unwrap();
let mut sub: Subscription<String> = c1.subscribe("subscribe_hello", None, "unsubscribe_hello").await.unwrap();
Niklas Adolfsson
committed
assert!(matches!(sub.next().await, Some(Ok(_))));
Niklas Adolfsson
committed
Niklas Adolfsson
committed
let sub2: Result<Subscription<String>, _> = c1.subscribe("subscribe_hello", None, "unsubscribe_hello").await;
Niklas Adolfsson
committed
// no new request should be accepted.
assert!(matches!(sub2, Err(_)));
for _ in 0..2 {
match sub.next().await {
// All good, exit test
None => return,
// Try again
_ => continue,
}
}
panic!("subscription keeps sending messages after server shutdown");
Niklas Adolfsson
committed
}
Niklas Adolfsson
committed
#[tokio::test]
async fn ws_server_should_stop_subscription_after_client_drop() {
use futures::{channel::mpsc, SinkExt, StreamExt};
use jsonrpsee::{ws_server::WsServerBuilder, RpcModule};
let server = WsServerBuilder::default().build("127.0.0.1:0").await.unwrap();
let server_url = format!("ws://{}", server.local_addr().unwrap());
let (tx, mut rx) = mpsc::channel(1);
let mut module = RpcModule::new(tx);
module
.register_subscription("subscribe_hello", "subscribe_hello", "unsubscribe_hello", |_, pending, mut tx| {
let mut sink = pending.accept().unwrap();
Niklas Adolfsson
committed
tokio::spawn(async move {
let close_err = loop {
if !sink.send(&1_usize).expect("usize can be serialized; qed") {
break ErrorObject::borrowed(0, &"Subscription terminated successfully", None);
Niklas Adolfsson
committed
}
tokio::time::sleep(Duration::from_millis(100)).await;
};
let send_back = Arc::make_mut(&mut tx);
send_back.feed(close_err).await.unwrap();
});
})
.unwrap();
Niklas Adolfsson
committed
let client = WsClientBuilder::default().build(&server_url).await.unwrap();
let mut sub: Subscription<usize> = client.subscribe("subscribe_hello", None, "unsubscribe_hello").await.unwrap();
Niklas Adolfsson
committed
let res = sub.next().await.unwrap().unwrap();
Niklas Adolfsson
committed
assert_eq!(res, 1);
Niklas Adolfsson
committed
drop(client);
let close_err = rx.next().await.unwrap();
Niklas Adolfsson
committed
// assert that the server received `SubscriptionClosed` after the client was dropped.
assert_eq!(close_err, ErrorObject::borrowed(0, &"Subscription terminated successfully", None));
Niklas Adolfsson
committed
}
#[tokio::test]
Niklas Adolfsson
committed
async fn ws_server_cancels_subscriptions_on_reset_conn() {
use futures::{channel::mpsc, SinkExt, StreamExt};
use jsonrpsee::{ws_server::WsServerBuilder, RpcModule};
let server = WsServerBuilder::default().build("127.0.0.1:0").await.unwrap();
let server_url = format!("ws://{}", server.local_addr().unwrap());
Niklas Adolfsson
committed
let (tx, rx) = mpsc::channel(1);
let mut module = RpcModule::new(tx);
module
.register_subscription("subscribe_for_ever", "n", "unsubscribe_for_ever", |_, pending, mut tx| {
Niklas Adolfsson
committed
// Create stream that produce one item then sleeps for an hour.
let interval = interval(Duration::from_secs(60 * 60));
let stream = IntervalStream::new(interval).map(move |_| 0_usize);
let mut sink = match pending.accept() {
Some(sink) => sink,
_ => return,
};
tokio::spawn(async move {
sink.pipe_from_stream(stream).await;
let send_back = Arc::make_mut(&mut tx);
Niklas Adolfsson
committed
send_back.send(()).await.unwrap();
});
})
.unwrap();
server.start(module).unwrap();
let client = WsClientBuilder::default().build(&server_url).await.unwrap();
Niklas Adolfsson
committed
let mut subs = Vec::new();
for _ in 0..10 {
subs.push(client.subscribe::<usize>("subscribe_for_ever", None, "unsubscribe_for_ever").await.unwrap());
}
// terminate connection.
drop(client);
Niklas Adolfsson
committed
let rx_len = rx.take(10).fold(0, |acc, _| async move { acc + 1 }).await;
assert_eq!(rx_len, 10);
Niklas Adolfsson
committed
#[tokio::test]
async fn ws_server_cancels_sub_stream_after_err() {
use jsonrpsee::{ws_server::WsServerBuilder, RpcModule};
let err: &'static str = "error on the stream";
let server = WsServerBuilder::default().build("127.0.0.1:0").await.unwrap();
let server_url = format!("ws://{}", server.local_addr().unwrap());
let mut module = RpcModule::new(());
module
.register_subscription(
"subscribe_with_err_on_stream",
"n",
"unsubscribe_with_err_on_stream",
move |_, pending, _| {
let mut sink = match pending.accept() {
Some(sink) => sink,
_ => return,
};
Niklas Adolfsson
committed
// create stream that produce an error which will cancel the subscription.
let stream = futures::stream::iter(vec![Ok(1_u32), Err(err), Ok(2), Ok(3)]);
tokio::spawn(async move {
match sink.pipe_from_try_stream(stream).await {
SubscriptionClosed::Failed(e) => sink.close(e),
_ => unreachable!(),
};
Niklas Adolfsson
committed
});
},
)
.unwrap();
server.start(module).unwrap();
let client = WsClientBuilder::default().build(&server_url).await.unwrap();
let mut sub: Subscription<serde_json::Value> =
Niklas Adolfsson
committed
client.subscribe("subscribe_with_err_on_stream", None, "unsubscribe_with_err_on_stream").await.unwrap();
assert_eq!(sub.next().await.unwrap().unwrap(), 1);
// The server closed down the subscription with the underlying error from the stream.
Niklas Adolfsson
committed
assert!(sub.next().await.is_none());
Niklas Adolfsson
committed
}
#[tokio::test]
async fn ws_server_subscribe_with_stream() {
use futures::StreamExt;
use jsonrpsee::{ws_server::WsServerBuilder, RpcModule};
let server = WsServerBuilder::default().build("127.0.0.1:0").await.unwrap();
let server_url = format!("ws://{}", server.local_addr().unwrap());
let mut module = RpcModule::new(());
module
.register_subscription("subscribe_5_ints", "n", "unsubscribe_5_ints", |_, pending, _| {
let mut sink = match pending.accept() {
Some(sink) => sink,
_ => return,
};
tokio::spawn(async move {
let interval = interval(Duration::from_millis(50));
let stream = IntervalStream::new(interval).zip(futures::stream::iter(1..=5)).map(|(_, c)| c);
match sink.pipe_from_stream(stream).await {
SubscriptionClosed::Success => {
sink.close(SubscriptionClosed::Success);
}
_ => unreachable!(),
};
});
})
.unwrap();
server.start(module).unwrap();
let client = WsClientBuilder::default().build(&server_url).await.unwrap();
let mut sub1: Subscription<usize> = client.subscribe("subscribe_5_ints", None, "unsubscribe_5_ints").await.unwrap();
let mut sub2: Subscription<usize> = client.subscribe("subscribe_5_ints", None, "unsubscribe_5_ints").await.unwrap();
let (r1, r2) = futures::future::try_join(
sub1.by_ref().take(2).try_collect::<Vec<_>>(),
sub2.by_ref().take(3).try_collect::<Vec<_>>(),
)
.await
.unwrap();
assert_eq!(r1, vec![1, 2]);
assert_eq!(r2, vec![1, 2, 3]);
// Be rude, don't run the destructor
std::mem::forget(sub2);
// sub1 is still in business, read remaining items.
assert_eq!(sub1.by_ref().take(3).try_collect::<Vec<usize>>().await.unwrap(), vec![3, 4, 5]);
assert!(sub1.next().await.is_none());
#[tokio::test]
async fn ws_batch_works() {
let server_addr = websocket_server().await;
let server_url = format!("ws://{}", server_addr);
let client = WsClientBuilder::default().build(&server_url).await.unwrap();
let mut batch = Vec::new();
batch.push(("say_hello", rpc_params![]));
batch.push(("slow_hello", rpc_params![]));
let responses: Vec<String> = client.batch_request(batch).await.unwrap();
assert_eq!(responses, vec!["hello".to_string(), "hello".to_string()]);
}
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
#[tokio::test]
async fn http_unsupported_methods_dont_work() {
use hyper::{Body, Client, Method, Request};
let (server_addr, _handle) = http_server().await;
let http_client = Client::new();
let uri = format!("http://{}", server_addr);
let req_is_client_error = |method| async {
let req = Request::builder()
.method(method)
.uri(&uri)
.header("content-type", "application/json")
.body(Body::from(r#"{ "jsonrpc": "2.0", method: "say_hello", "id": 1 }"#))
.expect("request builder");
let res = http_client.request(req).await.unwrap();
res.status().is_client_error()
};
for verb in [Method::GET, Method::PUT, Method::PATCH, Method::DELETE] {
assert!(req_is_client_error(verb).await);
}
for verb in [Method::POST] {
assert!(!req_is_client_error(verb).await);
}
}
#[tokio::test]
async fn http_correct_content_type_required() {
use hyper::{Body, Client, Method, Request};
let (server_addr, _handle) = http_server().await;
let http_client = Client::new();
let uri = format!("http://{}", server_addr);
// We don't set content-type at all
let req = Request::builder()
.method(Method::POST)
.uri(&uri)
.body(Body::from(r#"{ "jsonrpc": "2.0", method: "say_hello", "id": 1 }"#))
.expect("request builder");
let res = http_client.request(req).await.unwrap();
assert!(res.status().is_client_error());
// We use the wrong content-type
let req = Request::builder()
.method(Method::POST)
.uri(&uri)
.header("content-type", "application/text")
.body(Body::from(r#"{ "jsonrpc": "2.0", method: "say_hello", "id": 1 }"#))
.expect("request builder");
let res = http_client.request(req).await.unwrap();
assert!(res.status().is_client_error());
// We use the correct content-type
let req = Request::builder()
.method(Method::POST)
.uri(&uri)
.header("content-type", "application/json")
.body(Body::from(r#"{ "jsonrpc": "2.0", method: "say_hello", "id": 1 }"#))
.expect("request builder");
let res = http_client.request(req).await.unwrap();
assert!(res.status().is_success());
}
#[tokio::test]
async fn http_cors_preflight_works() {
use hyper::{Body, Client, Method, Request};
use jsonrpsee::http_server::AccessControlBuilder;
let acl = AccessControlBuilder::new().set_allowed_origins(vec!["https://foo.com"]).unwrap().build();
let (server_addr, _handle) = http_server_with_access_control(acl).await;
let http_client = Client::new();
let uri = format!("http://{}", server_addr);
// First, make a preflight request.
// See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#preflighted_requests for examples.
// See https://fetch.spec.whatwg.org/#http-cors-protocol for the spec.
let preflight_req = Request::builder()
.method(Method::OPTIONS)
.uri(&uri)
.header("host", "bar.com") // <- host that request is being sent _to_
.header("origin", "https://foo.com") // <- where request is being sent _from_
.header("access-control-request-method", "POST")
.header("access-control-request-headers", "content-type")
.body(Body::empty())
.expect("preflight request builder");
let has = |v: &[String], s| v.iter().any(|v| v == s);
let preflight_res = http_client.request(preflight_req).await.unwrap();
let preflight_headers = preflight_res.headers();
let allow_origins = comma_separated_header_values(preflight_headers, "access-control-allow-origin");
let allow_methods = comma_separated_header_values(preflight_headers, "access-control-allow-methods");
let allow_headers = comma_separated_header_values(preflight_headers, "access-control-allow-headers");
// We expect the preflight response to tell us that our origin, methods and headers are all OK to use.
// If they aren't, the browser will not make the actual request. Note that if these `access-control-*`
// headers aren't return, the default is that the origin/method/headers are not allowed, I think.
assert!(preflight_res.status().is_success());
assert!(has(&allow_origins, "https://foo.com") || has(&allow_origins, "*"));
assert!(has(&allow_methods, "post") || has(&allow_methods, "*"));
assert!(has(&allow_headers, "content-type") || has(&allow_headers, "*"));
// Assuming that that was successful, we now make the actual request. No CORS headers are needed here
// as the browser checked their validity in the preflight request.
let req = Request::builder()
.method(Method::POST)
.uri(&uri)
.header("host", "bar.com")
.header("origin", "https://foo.com")
.header("content-type", "application/json")
.body(Body::from(r#"{ "jsonrpc": "2.0", method: "say_hello", "id": 1 }"#))
.expect("actual request builder");
let res = http_client.request(req).await.unwrap();
assert!(res.status().is_success());
assert!(has(&allow_origins, "https://foo.com") || has(&allow_origins, "*"));
}
fn comma_separated_header_values(headers: &hyper::HeaderMap, header: &str) -> Vec<String> {
headers
.get_all(header)
.into_iter()
.flat_map(|value| value.to_str().unwrap().split(',').map(|val| val.trim()))
.map(|header| header.to_ascii_lowercase())
.collect()
}
#[tokio::test]
async fn ws_subscribe_with_bad_params() {
let (server_addr, _handle) = websocket_server_with_subscription().await;
let server_url = format!("ws://{}", server_addr);
let client = WsClientBuilder::default().build(&server_url).await.unwrap();
let err = client
.subscribe::<serde_json::Value>("subscribe_add_one", rpc_params!["0x0"], "unsubscribe_add_one")
.await
.unwrap_err();
assert!(matches!(err, Error::Call(_)));
}