1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
use std::{cell, io, net, time};
use std::net::{TcpListener, TcpStream};
use hyper::{self, client, server};
use futures::{future, Future, Stream};
use tokio_core::reactor;
use mio;
pub struct TestServer<S> {
core: reactor::Core,
http: server::Http,
timeout: u64,
new_service: S,
}
#[derive(Debug)]
pub enum TestRequestError {
TimedOut,
IoError(io::Error),
HyperError(hyper::Error),
}
impl<S> TestServer<S>
where
S: server::NewService<
Request = server::Request,
Response = server::Response,
Error = hyper::Error,
>,
S::Instance: 'static,
{
pub fn new(new_service: S) -> Result<TestServer<S>, io::Error> {
reactor::Core::new().map(|core| {
TestServer {
core: core,
http: server::Http::new(),
timeout: 10,
new_service: new_service,
}
})
}
pub fn timeout(self, t: u64) -> TestServer<S> {
TestServer { timeout: t, ..self }
}
pub fn client(&self, client_addr: net::SocketAddr) -> io::Result<client::Client<TestConnect>> {
let handle = self.core.handle();
let (cs, ss) = {
let listener = TcpListener::bind("localhost:0")?;
let listener_addr = listener.local_addr()?;
let client = TcpStream::connect(listener_addr)?;
let (server, _client_addr) = listener.accept()?;
(client, server)
};
let cs = mio::net::TcpStream::from_stream(cs)?;
let cs = reactor::PollEvented::new(cs, &handle)?;
let ss = mio::net::TcpStream::from_stream(ss)?;
let ss = reactor::PollEvented::new(ss, &handle)?;
let service = self.new_service.new_service()?;
self.http.bind_connection(&handle, ss, client_addr, service);
Ok(
client::Client::configure()
.connector(TestConnect { stream: cell::RefCell::new(Some(cs)) })
.build(&self.core.handle()),
)
}
pub fn run_request<F>(&mut self, f: F) -> Result<F::Item, TestRequestError>
where
F: Future<Error = hyper::Error>,
{
let timeout_duration = time::Duration::from_secs(self.timeout);
let timeout = reactor::Timeout::new(timeout_duration, &self.core.handle())
.map_err(|e| TestRequestError::IoError(e))?;
let run_result = self.core.run(f.select2(timeout));
match run_result {
Ok(future::Either::A((item, _))) => Ok(item),
Ok(future::Either::B(_)) => Err(TestRequestError::TimedOut),
Err(future::Either::A((e, _))) => Err(TestRequestError::HyperError(e)),
Err(future::Either::B((e, _))) => Err(TestRequestError::IoError(e)),
}
}
pub fn read_body(&mut self, response: client::Response) -> hyper::Result<Vec<u8>> {
let mut buf = Vec::new();
let r = {
let f: hyper::Body = response.body();
let f = f.for_each(|chunk| future::ok(buf.extend(chunk.into_iter())));
self.core.run(f)
};
r.map(|_| buf)
}
}
pub struct TestConnect {
stream: cell::RefCell<Option<reactor::PollEvented<mio::net::TcpStream>>>,
}
impl client::Service for TestConnect {
type Request = hyper::Uri;
type Error = io::Error;
type Response = reactor::PollEvented<mio::net::TcpStream>;
type Future = future::FutureResult<Self::Response, Self::Error>;
fn call(&self, _req: Self::Request) -> Self::Future {
match self.stream.try_borrow_mut().map(|ref mut o| o.take()) {
Ok(Some(stream)) => future::ok(stream),
Ok(None) => future::err(io::Error::new(io::ErrorKind::Other, "stream already taken")),
Err(_) => {
future::err(io::Error::new(
io::ErrorKind::Other,
"stream.try_borrow_mut() failed",
))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::{SystemTime, UNIX_EPOCH};
use hyper::StatusCode;
#[derive(Clone)]
struct TestService {
response: String,
}
impl server::Service for TestService {
type Request = server::Request;
type Response = server::Response;
type Error = hyper::Error;
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
fn call(&self, req: Self::Request) -> Self::Future {
match req.path() {
"/" => {
let response = server::Response::new()
.with_status(StatusCode::Ok)
.with_body(self.response.clone());
future::ok(response).boxed()
}
"/timeout" => future::empty().boxed(),
"/myaddr" => {
let response = server::Response::new()
.with_status(StatusCode::Ok)
.with_body(format!("{}", req.remote_addr().unwrap()));
future::ok(response).boxed()
}
_ => unreachable!(),
}
}
}
#[test]
fn serves_requests() {
let ticks = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let new_service = move || Ok(TestService { response: format!("time: {}", ticks) });
let uri = "http://localhost/".parse().unwrap();
let mut test_server = TestServer::new(new_service).unwrap();
let response = test_server
.client("127.0.0.1:0".parse().unwrap())
.unwrap()
.get(uri);
let response = test_server.run_request(response).unwrap();
assert_eq!(response.status(), StatusCode::Ok);
let buf = test_server.read_body(response).unwrap();
assert_eq!(buf.as_slice(), format!("time: {}", ticks).as_bytes());
}
#[test]
fn times_out() {
let new_service = || Ok(TestService { response: "".to_owned() });
let mut test_server = TestServer::new(new_service).unwrap().timeout(1);
let uri = "http://localhost/timeout".parse().unwrap();
let response = test_server
.client("127.0.0.1:0".parse().unwrap())
.unwrap()
.get(uri);
match test_server.run_request(response) {
Err(TestRequestError::TimedOut) => (),
e @ Err(_) => {
e.unwrap();
}
Ok(_) => panic!("expected timeout, but was Ok(_)"),
}
}
#[test]
fn sets_client_addr() {
let ticks = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let new_service = move || Ok(TestService { response: format!("time: {}", ticks) });
let client_addr = "9.8.7.6:58901".parse().unwrap();
let uri = "http://localhost/myaddr".parse().unwrap();
let mut test_server = TestServer::new(new_service).unwrap();
let response = test_server.client(client_addr).unwrap().get(uri);
let response = test_server.run_request(response).unwrap();
assert_eq!(response.status(), StatusCode::Ok);
let buf = test_server.read_body(response).unwrap();
let received_addr: net::SocketAddr = String::from_utf8(buf).unwrap().parse().unwrap();
assert_eq!(received_addr, client_addr);
}
}