Skip to content
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

Extract TestTransport to web3::transports #402

Merged
merged 5 commits into from
Nov 9, 2020
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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,6 @@ ws-tokio = ["soketto", "url", "tokio", "tokio-util"]
ws-async-std = ["soketto", "url", "async-std"]
ws-tls-tokio = ["async-native-tls", "native-tls", "async-native-tls/runtime-tokio", "ws-tokio"]
ws-tls-async-std = ["async-native-tls", "native-tls", "async-native-tls/runtime-async-std", "ws-async-std"]
test = []

[workspace]
2 changes: 1 addition & 1 deletion src/api/accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,8 +234,8 @@ impl Transaction {
#[cfg(test)]
mod tests {
use super::*;
use crate::helpers::tests::TestTransport;
use crate::signing::{SecretKey, SecretKeyRef};
use crate::transports::test::TestTransport;
use crate::types::Bytes;
use rustc_hex::FromHex;
use serde_json::json;
Expand Down
2 changes: 1 addition & 1 deletion src/api/eth_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,8 +202,8 @@ impl<T: Transport> EthFilter<T> {
mod tests {
use super::EthFilter;
use crate::api::Namespace;
use crate::helpers::tests::TestTransport;
use crate::rpc::Value;
use crate::transports::test::TestTransport;
use crate::types::{Address, Bytes, FilterBuilder, Log, H256};
use futures::stream::StreamExt;
use std::time::Duration;
Expand Down
2 changes: 1 addition & 1 deletion src/confirm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,8 @@ where
#[cfg(test)]
mod tests {
use super::send_transaction_with_confirmation;
use crate::helpers::tests::TestTransport;
use crate::rpc::Value;
use crate::transports::test::TestTransport;
use crate::types::{Address, TransactionReceipt, TransactionRequest, H256, U64};
use serde_json::json;
use std::time::Duration;
Expand Down
2 changes: 1 addition & 1 deletion src/contract/deploy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,8 @@ impl<T: Transport> Builder<T> {
mod tests {
use crate::api::{self, Namespace};
use crate::contract::{Contract, Options};
use crate::helpers::tests::TestTransport;
use crate::rpc;
use crate::transports::test::TestTransport;
use crate::types::{Address, U256};
use serde_json::Value;
use std::collections::HashMap;
Expand Down
2 changes: 1 addition & 1 deletion src/contract/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,8 +323,8 @@ impl<T: Transport> Contract<T> {
mod tests {
use super::{Contract, Options};
use crate::api::{self, Namespace};
use crate::helpers::tests::TestTransport;
use crate::rpc;
use crate::transports::test::TestTransport;
use crate::types::{Address, BlockId, BlockNumber, H256, U256};
use crate::Transport;

Expand Down
72 changes: 2 additions & 70 deletions src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,74 +95,6 @@ pub fn to_result_from_output(output: rpc::Output) -> error::Result<rpc::Value> {
#[macro_use]
#[cfg(test)]
pub mod tests {
use crate::error::{self, Error};
use crate::rpc;
use crate::{RequestId, Transport};
use futures::future::{self, BoxFuture, FutureExt};
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;

type Result<T> = BoxFuture<'static, error::Result<T>>;

#[derive(Debug, Default, Clone)]
pub struct TestTransport {
asserted: usize,
requests: Rc<RefCell<Vec<(String, Vec<rpc::Value>)>>>,
responses: Rc<RefCell<VecDeque<rpc::Value>>>,
}

impl Transport for TestTransport {
type Out = Result<rpc::Value>;

fn prepare(&self, method: &str, params: Vec<rpc::Value>) -> (RequestId, rpc::Call) {
let request = super::build_request(1, method, params.clone());
self.requests.borrow_mut().push((method.into(), params));
(self.requests.borrow().len(), request)
}

fn send(&self, id: RequestId, request: rpc::Call) -> Result<rpc::Value> {
future::ready(match self.responses.borrow_mut().pop_front() {
Some(response) => Ok(response),
None => {
println!("Unexpected request (id: {:?}): {:?}", id, request);
Err(Error::Unreachable)
}
})
.boxed()
}
}

impl TestTransport {
pub fn set_response(&mut self, value: rpc::Value) {
*self.responses.borrow_mut() = vec![value].into();
}

pub fn add_response(&mut self, value: rpc::Value) {
self.responses.borrow_mut().push_back(value);
}

pub fn assert_request(&mut self, method: &str, params: &[String]) {
let idx = self.asserted;
self.asserted += 1;

let (m, p) = self.requests.borrow().get(idx).expect("Expected result.").clone();
assert_eq!(&m, method);
let p: Vec<String> = p.into_iter().map(|p| serde_json::to_string(&p).unwrap()).collect();
assert_eq!(p, params);
}

pub fn assert_no_more_requests(&self) {
let requests = self.requests.borrow();
assert_eq!(
self.asserted,
requests.len(),
"Expected no more requests, got: {:?}",
&requests[self.asserted..]
);
}
}

macro_rules! rpc_test {
// With parameters
(
Expand All @@ -172,7 +104,7 @@ pub mod tests {
#[test]
fn $test_name() {
// given
let mut transport = $crate::helpers::tests::TestTransport::default();
let mut transport = $crate::transports::test::TestTransport::default();
transport.set_response($returned);
let result = {
let eth = $namespace::new(&transport);
Expand Down Expand Up @@ -207,7 +139,7 @@ pub mod tests {
#[test]
fn $test_name() {
// given
let mut transport = $crate::helpers::tests::TestTransport::default();
let mut transport = $crate::transports::test::TestTransport::default();
transport.set_response($returned);
let result = {
let eth = $namespace::new(&transport);
Expand Down
3 changes: 3 additions & 0 deletions src/transports/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ pub mod ws;
#[cfg(any(feature = "ws-tokio", feature = "ws-async-std"))]
pub use self::ws::WebSocket;

#[cfg(any(feature = "test", test))]
pub mod test;

#[cfg(feature = "url")]
impl From<url::ParseError> for crate::Error {
fn from(err: url::ParseError) -> Self {
Expand Down
75 changes: 75 additions & 0 deletions src/transports/test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
//! Test Transport

use crate::error::{self, Error};
use crate::helpers;
use crate::rpc;
use crate::{RequestId, Transport};
use futures::future::{self, BoxFuture, FutureExt};
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;

type Result<T> = BoxFuture<'static, error::Result<T>>;

/// Test Transport
#[derive(Debug, Default, Clone)]
pub struct TestTransport {
asserted: usize,
requests: Rc<RefCell<Vec<(String, Vec<rpc::Value>)>>>,
responses: Rc<RefCell<VecDeque<rpc::Value>>>,
}

impl Transport for TestTransport {
type Out = Result<rpc::Value>;

fn prepare(&self, method: &str, params: Vec<rpc::Value>) -> (RequestId, rpc::Call) {
let request = helpers::build_request(1, method, params.clone());
self.requests.borrow_mut().push((method.into(), params));
(self.requests.borrow().len(), request)
}

fn send(&self, id: RequestId, request: rpc::Call) -> Result<rpc::Value> {
future::ready(match self.responses.borrow_mut().pop_front() {
Some(response) => Ok(response),
None => {
println!("Unexpected request (id: {:?}): {:?}", id, request);
Err(Error::Unreachable)
}
})
.boxed()
}
}

impl TestTransport {
/// Set response
pub fn set_response(&mut self, value: rpc::Value) {
*self.responses.borrow_mut() = vec![value].into();
}

/// Add response
pub fn add_response(&mut self, value: rpc::Value) {
self.responses.borrow_mut().push_back(value);
}

/// Assert request
pub fn assert_request(&mut self, method: &str, params: &[String]) {
let idx = self.asserted;
self.asserted += 1;

let (m, p) = self.requests.borrow().get(idx).expect("Expected result.").clone();
assert_eq!(&m, method);
let p: Vec<String> = p.into_iter().map(|p| serde_json::to_string(&p).unwrap()).collect();
assert_eq!(p, params);
}

/// Assert no more requests
pub fn assert_no_more_requests(&self) {
let requests = self.requests.borrow();
assert_eq!(
self.asserted,
requests.len(),
"Expected no more requests, got: {:?}",
&requests[self.asserted..]
);
}
}