Files
ureq/src/test/mod.rs
Jacob Hoffman-Andrews fade03b54e Rewrite the Error type. (#234)
This adds a source field to keep track of upstream errors and allow
backtraces, plus a URL field to indicate what URL an error was
associated with.

The enum variants we used to use for Error are now part of a new
ErrorKind type. For convenience within ureq, ErrorKinds can be turned
into an Error with `.new()` or `.msg("some additional information")`.

Error acts as a builder, so additional information can be added after
initial construction. For instance, we return a DnsFailed error when
name resolution fails. When that error bubbles up to Request's
`do_call`, Request adds the URL.

Fixes #232.
2020-11-21 16:14:44 -08:00

56 lines
1.5 KiB
Rust

use crate::error::Error;
use crate::stream::Stream;
use crate::unit::Unit;
use once_cell::sync::Lazy;
use std::collections::HashMap;
use std::io::{Cursor, Write};
use std::sync::{Arc, Mutex};
mod agent_test;
mod body_read;
mod body_send;
mod query_string;
mod range;
mod redirect;
mod simple;
mod timeout;
type RequestHandler = dyn Fn(&Unit) -> Result<Stream, Error> + Send + 'static;
pub(crate) static TEST_HANDLERS: Lazy<Arc<Mutex<HashMap<String, Box<RequestHandler>>>>> =
Lazy::new(|| Arc::new(Mutex::new(HashMap::new())));
pub(crate) fn set_handler<H>(path: &str, handler: H)
where
H: Fn(&Unit) -> Result<Stream, Error> + Send + 'static,
{
let mut handlers = TEST_HANDLERS.lock().unwrap();
handlers.insert(path.to_string(), Box::new(handler));
}
#[allow(clippy::write_with_newline)]
pub fn make_response(
status: u16,
status_text: &str,
headers: Vec<&str>,
mut body: Vec<u8>,
) -> Result<Stream, Error> {
let mut buf: Vec<u8> = vec![];
write!(&mut buf, "HTTP/1.1 {} {}\r\n", status, status_text).ok();
for hstr in headers.iter() {
write!(&mut buf, "{}\r\n", hstr).ok();
}
write!(&mut buf, "\r\n").ok();
buf.append(&mut body);
let cursor = Cursor::new(buf);
let write: Vec<u8> = vec![];
Ok(Stream::Test(Box::new(cursor), write))
}
pub(crate) fn resolve_handler(unit: &Unit) -> Result<Stream, Error> {
let mut handlers = TEST_HANDLERS.lock().unwrap();
let path = unit.url.path();
let handler = handlers.remove(path).unwrap();
handler(unit)
}