Skip to content
This repository has been archived by the owner on Nov 6, 2020. It is now read-only.

util fake-fetch #8363

Merged
merged 8 commits into from
Apr 11, 2018
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
13 changes: 13 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ rustc_version = "0.2"
pretty_assertions = "0.1"
ipnetwork = "0.12.6"
tempdir = "0.3"
fake-fetch = { path = "util/fake-fetch" }

[target.'cfg(windows)'.dependencies]
winapi = "0.2"
Expand Down
1 change: 1 addition & 0 deletions hash-fetch/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,4 @@ ethabi-contract = "5.0"
[dev-dependencies]
hyper = "0.11"
parking_lot = "0.5"
fake-fetch = { path = "../util/fake-fetch" }
53 changes: 7 additions & 46 deletions hash-fetch/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,53 +193,14 @@ fn random_temp_path() -> PathBuf {

#[cfg(test)]
mod tests {
extern crate hyper;
use fake_fetch::FakeFetch;
use rustc_hex::FromHex;
use std::sync::{Arc, mpsc};
use parking_lot::Mutex;
use futures::future;
use futures_cpupool::CpuPool;
use fetch::{self, Fetch, Url, Request};
use parity_reactor::Remote;
use urlhint::tests::{FakeRegistrar, URLHINT};
use super::{Error, Client, HashFetch, random_temp_path};
use self::hyper::StatusCode;


#[derive(Clone)]
struct FakeFetch {
return_success: bool
}

impl Fetch for FakeFetch {
type Result = future::Ok<fetch::Response, fetch::Error>;

fn fetch(&self, request: Request, abort: fetch::Abort) -> Self::Result {
assert_eq!(request.url().as_str(), "https://parity.io/assets/images/ethcore-black-horizontal.png");
let u = request.url().clone();
future::ok(if self.return_success {
fetch::client::Response::new(u, hyper::Response::new().with_body(&b"result"[..]), abort)
} else {
fetch::client::Response::new(u, hyper::Response::new().with_status(StatusCode::NotFound), abort)
})
}

fn get(&self, url: &str, abort: fetch::Abort) -> Self::Result {
let url: Url = match url.parse() {
Ok(u) => u,
Err(e) => return future::err(e.into())
};
self.fetch(Request::get(url), abort)
}

fn post(&self, url: &str, abort: fetch::Abort) -> Self::Result {
let url: Url = match url.parse() {
Ok(u) => u,
Err(e) => return future::err(e.into())
};
self.fetch(Request::post(url), abort)
}
}

fn registrar() -> FakeRegistrar {
let mut registrar = FakeRegistrar::new();
Expand All @@ -254,7 +215,7 @@ mod tests {
fn should_return_error_if_hash_not_found() {
// given
let contract = Arc::new(FakeRegistrar::new());
let fetch = FakeFetch { return_success: false };
let fetch = FakeFetch::new(None::<usize>);
let client = Client::with_fetch(contract.clone(), CpuPool::new(1), fetch, Remote::new_sync());

// when
Expand All @@ -272,7 +233,7 @@ mod tests {
fn should_return_error_if_response_is_not_successful() {
// given
let registrar = Arc::new(registrar());
let fetch = FakeFetch { return_success: false };
let fetch = FakeFetch::new(None::<usize>);
let client = Client::with_fetch(registrar.clone(), CpuPool::new(1), fetch, Remote::new_sync());

// when
Expand All @@ -290,7 +251,7 @@ mod tests {
fn should_return_hash_mismatch() {
// given
let registrar = Arc::new(registrar());
let fetch = FakeFetch { return_success: true };
let fetch = FakeFetch::new(Some(1));
let mut client = Client::with_fetch(registrar.clone(), CpuPool::new(1), fetch, Remote::new_sync());
let path = random_temp_path();
let path2 = path.clone();
Expand All @@ -304,7 +265,7 @@ mod tests {

// then
let result = rx.recv().unwrap();
let hash = "0x06b0a4f426f6713234b2d4b2468640bc4e0bb72657a920ad24c5087153c593c8".into();
let hash = "0x2be00befcf008bc0e7d9cdefc194db9c75352e8632f48498b5a6bfce9f02c88e".into();
assert_eq!(result.unwrap_err(), Error::HashMismatch { expected: 2.into(), got: hash });
assert!(!path.exists(), "Temporary file should be removed.");
}
Expand All @@ -313,12 +274,12 @@ mod tests {
fn should_return_path_if_hash_matches() {
// given
let registrar = Arc::new(registrar());
let fetch = FakeFetch { return_success: true };
let fetch = FakeFetch::new(Some(1));
let client = Client::with_fetch(registrar.clone(), CpuPool::new(1), fetch, Remote::new_sync());

// when
let (tx, rx) = mpsc::channel();
client.fetch("0x06b0a4f426f6713234b2d4b2468640bc4e0bb72657a920ad24c5087153c593c8".into(),
client.fetch("0x2be00befcf008bc0e7d9cdefc194db9c75352e8632f48498b5a6bfce9f02c88e".into(),
Default::default(),
Box::new(move |result| { tx.send(result).unwrap(); }));

Expand Down
4 changes: 4 additions & 0 deletions hash-fetch/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ extern crate ethabi_derive;
extern crate ethabi_contract;
#[cfg(test)]
extern crate parking_lot;
#[cfg(test)]
extern crate hyper;
#[cfg(test)]
extern crate fake_fetch;

mod client;

Expand Down
1 change: 1 addition & 0 deletions price-info/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ serde_json = "1.0"
[dev-dependencies]
hyper = "0.11"
parking_lot = "0.5"
fake-fetch = { path = "../util/fake-fetch" }
65 changes: 9 additions & 56 deletions price-info/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ extern crate serde_json;
#[macro_use]
extern crate log;

#[cfg(test)]
extern crate fake_fetch;

pub extern crate fetch;

use std::cmp;
Expand Down Expand Up @@ -133,68 +136,18 @@ impl<F: Fetch> Client<F> {

#[cfg(test)]
mod test {
extern crate hyper;
extern crate parking_lot;

use self::parking_lot::Mutex;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use fetch;
use fetch::{Fetch, Url, Request};
use futures_cpupool::CpuPool;
use futures::future::{self, FutureResult};
use Client;
use self::hyper::StatusCode;

#[derive(Clone)]
struct FakeFetch(Option<String>, Arc<Mutex<u64>>);

impl FakeFetch {
fn new() -> Result<Self, fetch::Error> {
Ok(FakeFetch(None, Default::default()))
}
}

impl Fetch for FakeFetch {
type Result = FutureResult<fetch::Response, fetch::Error>;

fn fetch(&self, request: Request, abort: fetch::Abort) -> Self::Result {
assert_eq!(request.url().as_str(), "https://api.etherscan.io/api?module=stats&action=ethprice");
let u = request.url().clone();
let mut val = self.1.lock();
*val = *val + 1;
if let Some(ref response) = self.0 {
let r = hyper::Response::new().with_body(response.clone());
future::ok(fetch::client::Response::new(u, r, abort))
} else {
let r = hyper::Response::new().with_status(StatusCode::NotFound);
future::ok(fetch::client::Response::new(u, r, abort))
}
}

fn get(&self, url: &str, abort: fetch::Abort) -> Self::Result {
let url: Url = match url.parse() {
Ok(u) => u,
Err(e) => return future::err(e.into())
};
self.fetch(Request::get(url), abort)
}

fn post(&self, url: &str, abort: fetch::Abort) -> Self::Result {
let url: Url = match url.parse() {
Ok(u) => u,
Err(e) => return future::err(e.into())
};
self.fetch(Request::post(url), abort)
}
}
use std::sync::atomic::{AtomicBool, Ordering};
use fake_fetch::FakeFetch;

fn price_info_ok(response: &str) -> Client<FakeFetch> {
Client::new(FakeFetch(Some(response.to_owned()), Default::default()), CpuPool::new(1))
fn price_info_ok(response: &str) -> Client<FakeFetch<String>> {
Client::new(FakeFetch::new(Some(response.to_owned())), CpuPool::new(1))
}

fn price_info_not_found() -> Client<FakeFetch> {
Client::new(FakeFetch::new().unwrap(), CpuPool::new(1))
fn price_info_not_found() -> Client<FakeFetch<String>> {
Client::new(FakeFetch::new(None::<String>), CpuPool::new(1))
}

#[test]
Expand Down
1 change: 1 addition & 0 deletions rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,4 @@ pretty_assertions = "0.1"
macros = { path = "../util/macros" }
ethcore-network = { path = "../util/network" }
kvdb-memorydb = { path = "../util/kvdb-memorydb" }
fake-fetch = { path = "../util/fake-fetch" }
3 changes: 3 additions & 0 deletions rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ extern crate macros;
#[cfg(test)]
extern crate kvdb_memorydb;

#[cfg(test)]
extern crate fake_fetch;

extern crate tempdir;

pub extern crate jsonrpc_ws_server as ws;
Expand Down
2 changes: 0 additions & 2 deletions rpc/src/v1/tests/helpers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,12 @@
//! Test rpc services.

mod dapps;
mod fetch;
mod miner_service;
mod snapshot_service;
mod sync_provider;
mod update_service;

pub use self::dapps::TestDappsService;
pub use self::fetch::TestFetch;
pub use self::miner_service::TestMinerService;
pub use self::snapshot_service::TestSnapshotService;
pub use self::sync_provider::{Config, TestSyncProvider};
Expand Down
8 changes: 5 additions & 3 deletions rpc/src/v1/tests/mocked/parity_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,11 @@ use futures_cpupool::CpuPool;

use jsonrpc_core::IoHandler;
use v1::{ParitySet, ParitySetClient};
use v1::tests::helpers::{TestMinerService, TestFetch, TestUpdater, TestDappsService};
use v1::tests::helpers::{TestMinerService, TestUpdater, TestDappsService};
use super::manage_network::TestManageNetwork;

use fake_fetch::FakeFetch;

fn miner_service() -> Arc<TestMinerService> {
Arc::new(TestMinerService::default())
}
Expand All @@ -45,7 +47,7 @@ fn updater_service() -> Arc<TestUpdater> {
Arc::new(TestUpdater::default())
}

pub type TestParitySetClient = ParitySetClient<TestBlockChainClient, TestMinerService, TestUpdater, TestFetch>;
pub type TestParitySetClient = ParitySetClient<TestBlockChainClient, TestMinerService, TestUpdater, FakeFetch<usize>>;

fn parity_set_client(
client: &Arc<TestBlockChainClient>,
Expand All @@ -55,7 +57,7 @@ fn parity_set_client(
) -> TestParitySetClient {
let dapps_service = Arc::new(TestDappsService);
let pool = CpuPool::new(1);
ParitySetClient::new(client, miner, updater, &(net.clone() as Arc<ManageNetwork>), Some(dapps_service), TestFetch::default(), pool)
ParitySetClient::new(client, miner, updater, &(net.clone() as Arc<ManageNetwork>), Some(dapps_service), FakeFetch::new(Some(1)), pool)
}

#[test]
Expand Down
11 changes: 11 additions & 0 deletions util/fake-fetch/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
description = "Mock fetcher for testing"
name = "fake-fetch"
version = "0.0.1"
license = "GPL-3.0"
authors = ["Parity Technologies <[email protected]>"]

[dependencies]
fetch = { path = "../fetch" }
futures = "0.1"
hyper = "0.11"
Loading