|
| 1 | +//! A server builder helper for the integration tests. |
| 2 | +
|
| 3 | +use std::io::{Read, Write}; |
| 4 | +use std::net; |
| 5 | +use std::thread; |
| 6 | + |
| 7 | +pub struct Server { |
| 8 | + addr: net::SocketAddr, |
| 9 | +} |
| 10 | + |
| 11 | +impl Server { |
| 12 | + pub fn addr(&self) -> net::SocketAddr { |
| 13 | + self.addr |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +static DEFAULT_USER_AGENT: &'static str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")); |
| 18 | + |
| 19 | +pub fn spawn(txns: Vec<(Vec<u8>, Vec<u8>)>) -> Server { |
| 20 | + let listener = net::TcpListener::bind("0.0.0.0:0").unwrap(); |
| 21 | + let addr = listener.local_addr().unwrap(); |
| 22 | + thread::spawn(move || { |
| 23 | + for (mut expected, reply) in txns { |
| 24 | + let (mut socket, _addr) = listener.accept().unwrap(); |
| 25 | + replace_expected_vars(&mut expected, addr.to_string().as_ref(), DEFAULT_USER_AGENT.as_ref()); |
| 26 | + let mut buf = [0; 4096]; |
| 27 | + let n = socket.read(&mut buf).unwrap(); |
| 28 | + |
| 29 | + match (::std::str::from_utf8(&expected), ::std::str::from_utf8(&buf[..n])) { |
| 30 | + (Ok(expected), Ok(received)) => assert_eq!(expected, received), |
| 31 | + _ => assert_eq!(expected, &buf[..n]) |
| 32 | + } |
| 33 | + socket.write_all(&reply).unwrap(); |
| 34 | + } |
| 35 | + }); |
| 36 | + |
| 37 | + Server { |
| 38 | + addr: addr, |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +fn replace_expected_vars(bytes: &mut Vec<u8>, host: &[u8], ua: &[u8]) { |
| 43 | + // plenty horrible, but these are just tests, and gets the job done |
| 44 | + let mut index = 0; |
| 45 | + loop { |
| 46 | + if index == bytes.len() { |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + for b in (&bytes[index..]).iter() { |
| 51 | + index += 1; |
| 52 | + if *b == b'$' { |
| 53 | + break; |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + let has_host = (&bytes[index..]).starts_with(b"HOST"); |
| 58 | + if has_host { |
| 59 | + bytes.drain(index - 1..index + 4); |
| 60 | + for (i, b) in host.iter().enumerate() { |
| 61 | + bytes.insert(index - 1 + i, *b); |
| 62 | + } |
| 63 | + } else { |
| 64 | + let has_ua = (&bytes[index..]).starts_with(b"USERAGENT"); |
| 65 | + if has_ua { |
| 66 | + bytes.drain(index - 1..index + 9); |
| 67 | + for (i, b) in ua.iter().enumerate() { |
| 68 | + bytes.insert(index - 1 + i, *b); |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +#[macro_export] |
| 76 | +macro_rules! server { |
| 77 | + ($(request: $req:expr, response: $res:expr),*) => ({ |
| 78 | + let txns = vec![ |
| 79 | + $(((&$req[..]).into(), (&$res[..]).into()),)* |
| 80 | + ]; |
| 81 | + ::server::spawn(txns) |
| 82 | + }) |
| 83 | +} |
0 commit comments