fake_fetch/
lib.rs

1// Copyright 2015-2020 Parity Technologies (UK) Ltd.
2// This file is part of Tetsy Vapory.
3
4// Tetsy Vapory is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Tetsy Vapory is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Tetsy Vapory.  If not, see <http://www.gnu.org/licenses/>.
16
17extern crate tetsy_fetch;
18extern crate hyper;
19extern crate futures;
20
21use hyper::{StatusCode, Body};
22use futures::{future, future::FutureResult};
23use tetsy_fetch::{Fetch, Url, Request};
24
25#[derive(Clone, Default)]
26pub struct FakeFetch<T> where T: Clone + Send + Sync {
27	val: Option<T>,
28}
29
30impl<T> FakeFetch<T> where T: Clone + Send + Sync {
31	pub fn new(t: Option<T>) -> Self {
32		FakeFetch { val : t }
33	}
34}
35
36impl<T: 'static> Fetch for FakeFetch<T> where T: Clone + Send+ Sync {
37	type Result = FutureResult<tetsy_fetch::Response, tetsy_fetch::Error>;
38
39	fn fetch(&self, request: Request, abort: tetsy_fetch::Abort) -> Self::Result {
40		let u = request.url().clone();
41		future::ok(if self.val.is_some() {
42			let r = hyper::Response::new("Some content".into());
43			tetsy_fetch::client::Response::new(u, r, abort)
44		} else {
45			let r = hyper::Response::builder()
46				.status(StatusCode::NOT_FOUND)
47				.body(Body::empty()).expect("Nothing to parse, can not fail; qed");
48			tetsy_fetch::client::Response::new(u, r, abort)
49		})
50	}
51
52	fn get(&self, url: &str, abort: tetsy_fetch::Abort) -> Self::Result {
53		let url: Url = match url.parse() {
54			Ok(u) => u,
55			Err(e) => return future::err(e.into())
56		};
57		self.fetch(Request::get(url), abort)
58	}
59
60	fn post(&self, url: &str, abort: tetsy_fetch::Abort) -> Self::Result {
61		let url: Url = match url.parse() {
62			Ok(u) => u,
63			Err(e) => return future::err(e.into())
64		};
65		self.fetch(Request::post(url), abort)
66	}
67}