2020-12-23 02:28:17 +01:00
|
|
|
//! Various testing helpers for use in internal and app tests.
|
|
|
|
|
|
|
|
use std::{
|
|
|
|
cell::{Ref, RefCell},
|
|
|
|
io::{self, Read, Write},
|
|
|
|
pin::Pin,
|
|
|
|
rc::Rc,
|
|
|
|
str::FromStr,
|
|
|
|
task::{Context, Poll},
|
|
|
|
};
|
2019-03-26 19:54:35 +01:00
|
|
|
|
2021-01-04 00:47:04 +01:00
|
|
|
use actix_codec::{AsyncRead, AsyncWrite, ReadBuf};
|
2019-11-26 06:25:50 +01:00
|
|
|
use bytes::{Bytes, BytesMut};
|
2021-02-13 16:08:43 +01:00
|
|
|
use http::{Method, Uri, Version};
|
2019-03-26 19:54:35 +01:00
|
|
|
|
2021-02-13 16:08:43 +01:00
|
|
|
#[cfg(feature = "cookies")]
|
2021-01-15 03:11:10 +01:00
|
|
|
use crate::{
|
|
|
|
cookie::{Cookie, CookieJar},
|
2021-02-13 16:08:43 +01:00
|
|
|
header::{self, HeaderValue},
|
|
|
|
};
|
|
|
|
use crate::{
|
2021-01-15 03:11:10 +01:00
|
|
|
header::{HeaderMap, IntoHeaderPair},
|
|
|
|
payload::Payload,
|
|
|
|
Request,
|
|
|
|
};
|
2019-03-26 19:54:35 +01:00
|
|
|
|
|
|
|
/// Test `Request` builder
|
|
|
|
///
|
|
|
|
/// ```rust,ignore
|
|
|
|
/// # use http::{header, StatusCode};
|
|
|
|
/// # use actix_web::*;
|
|
|
|
/// use actix_web::test::TestRequest;
|
|
|
|
///
|
|
|
|
/// fn index(req: &HttpRequest) -> Response {
|
|
|
|
/// if let Some(hdr) = req.headers().get(header::CONTENT_TYPE) {
|
|
|
|
/// Response::Ok().into()
|
|
|
|
/// } else {
|
|
|
|
/// Response::BadRequest().into()
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
///
|
2021-01-15 03:11:10 +01:00
|
|
|
/// let resp = TestRequest::default().insert_header("content-type", "text/plain")
|
2019-12-08 07:31:16 +01:00
|
|
|
/// .run(&index)
|
|
|
|
/// .unwrap();
|
|
|
|
/// assert_eq!(resp.status(), StatusCode::OK);
|
2019-03-26 19:54:35 +01:00
|
|
|
///
|
2019-12-08 07:31:16 +01:00
|
|
|
/// let resp = TestRequest::default().run(&index).unwrap();
|
|
|
|
/// assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
2019-03-26 19:54:35 +01:00
|
|
|
/// ```
|
|
|
|
pub struct TestRequest(Option<Inner>);
|
|
|
|
|
|
|
|
struct Inner {
|
|
|
|
version: Version,
|
|
|
|
method: Method,
|
|
|
|
uri: Uri,
|
|
|
|
headers: HeaderMap,
|
2021-02-13 16:08:43 +01:00
|
|
|
#[cfg(feature = "cookies")]
|
2019-03-26 19:54:35 +01:00
|
|
|
cookies: CookieJar,
|
|
|
|
payload: Option<Payload>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for TestRequest {
|
|
|
|
fn default() -> TestRequest {
|
|
|
|
TestRequest(Some(Inner {
|
|
|
|
method: Method::GET,
|
|
|
|
uri: Uri::from_str("/").unwrap(),
|
|
|
|
version: Version::HTTP_11,
|
|
|
|
headers: HeaderMap::new(),
|
2021-02-13 16:08:43 +01:00
|
|
|
#[cfg(feature = "cookies")]
|
2019-03-26 19:54:35 +01:00
|
|
|
cookies: CookieJar::new(),
|
|
|
|
payload: None,
|
|
|
|
}))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl TestRequest {
|
2021-01-15 03:11:10 +01:00
|
|
|
/// Create a default TestRequest and then set its URI.
|
2019-03-26 19:54:35 +01:00
|
|
|
pub fn with_uri(path: &str) -> TestRequest {
|
|
|
|
TestRequest::default().uri(path).take()
|
|
|
|
}
|
|
|
|
|
2021-01-15 03:11:10 +01:00
|
|
|
/// Set HTTP version of this request.
|
2019-03-26 19:54:35 +01:00
|
|
|
pub fn version(&mut self, ver: Version) -> &mut Self {
|
|
|
|
parts(&mut self.0).version = ver;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2021-01-15 03:11:10 +01:00
|
|
|
/// Set HTTP method of this request.
|
2019-03-26 19:54:35 +01:00
|
|
|
pub fn method(&mut self, meth: Method) -> &mut Self {
|
|
|
|
parts(&mut self.0).method = meth;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2021-01-15 03:11:10 +01:00
|
|
|
/// Set URI of this request.
|
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
/// If provided URI is invalid.
|
2019-03-26 19:54:35 +01:00
|
|
|
pub fn uri(&mut self, path: &str) -> &mut Self {
|
|
|
|
parts(&mut self.0).uri = Uri::from_str(path).unwrap();
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2021-01-15 03:11:10 +01:00
|
|
|
/// Insert a header, replacing any that were set with an equivalent field name.
|
|
|
|
pub fn insert_header<H>(&mut self, header: H) -> &mut Self
|
|
|
|
where
|
|
|
|
H: IntoHeaderPair,
|
|
|
|
{
|
|
|
|
match header.try_into_header_pair() {
|
|
|
|
Ok((key, value)) => {
|
|
|
|
parts(&mut self.0).headers.insert(key, value);
|
|
|
|
}
|
|
|
|
Err(err) => {
|
|
|
|
panic!("Error inserting test header: {}.", err.into());
|
|
|
|
}
|
2019-03-26 19:54:35 +01:00
|
|
|
}
|
2021-01-15 03:11:10 +01:00
|
|
|
|
|
|
|
self
|
2019-03-26 19:54:35 +01:00
|
|
|
}
|
|
|
|
|
2021-01-15 03:11:10 +01:00
|
|
|
/// Append a header, keeping any that were set with an equivalent field name.
|
|
|
|
pub fn append_header<H>(&mut self, header: H) -> &mut Self
|
2019-03-26 19:54:35 +01:00
|
|
|
where
|
2021-01-15 03:11:10 +01:00
|
|
|
H: IntoHeaderPair,
|
2019-03-26 19:54:35 +01:00
|
|
|
{
|
2021-01-15 03:11:10 +01:00
|
|
|
match header.try_into_header_pair() {
|
|
|
|
Ok((key, value)) => {
|
2019-03-26 19:54:35 +01:00
|
|
|
parts(&mut self.0).headers.append(key, value);
|
2021-01-15 03:11:10 +01:00
|
|
|
}
|
|
|
|
Err(err) => {
|
|
|
|
panic!("Error inserting test header: {}.", err.into());
|
2019-03-26 19:54:35 +01:00
|
|
|
}
|
|
|
|
}
|
2021-01-15 03:11:10 +01:00
|
|
|
|
|
|
|
self
|
2019-03-26 19:54:35 +01:00
|
|
|
}
|
|
|
|
|
2021-01-15 03:11:10 +01:00
|
|
|
/// Set cookie for this request.
|
2021-02-13 16:08:43 +01:00
|
|
|
#[cfg(feature = "cookies")]
|
2019-03-26 19:54:35 +01:00
|
|
|
pub fn cookie<'a>(&mut self, cookie: Cookie<'a>) -> &mut Self {
|
|
|
|
parts(&mut self.0).cookies.add(cookie.into_owned());
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2021-01-15 03:11:10 +01:00
|
|
|
/// Set request payload.
|
2019-03-26 19:54:35 +01:00
|
|
|
pub fn set_payload<B: Into<Bytes>>(&mut self, data: B) -> &mut Self {
|
|
|
|
let mut payload = crate::h1::Payload::empty();
|
|
|
|
payload.unread_data(data.into());
|
|
|
|
parts(&mut self.0).payload = Some(payload.into());
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn take(&mut self) -> TestRequest {
|
|
|
|
TestRequest(self.0.take())
|
|
|
|
}
|
|
|
|
|
2021-01-15 03:11:10 +01:00
|
|
|
/// Complete request creation and generate `Request` instance.
|
2019-03-26 19:54:35 +01:00
|
|
|
pub fn finish(&mut self) -> Request {
|
2019-09-16 00:52:23 +02:00
|
|
|
let inner = self.0.take().expect("cannot reuse test request builder");
|
2019-03-26 19:54:35 +01:00
|
|
|
|
|
|
|
let mut req = if let Some(pl) = inner.payload {
|
|
|
|
Request::with_payload(pl)
|
|
|
|
} else {
|
|
|
|
Request::with_payload(crate::h1::Payload::empty().into())
|
|
|
|
};
|
|
|
|
|
|
|
|
let head = req.head_mut();
|
|
|
|
head.uri = inner.uri;
|
|
|
|
head.method = inner.method;
|
|
|
|
head.version = inner.version;
|
|
|
|
head.headers = inner.headers;
|
|
|
|
|
2021-02-13 16:08:43 +01:00
|
|
|
#[cfg(feature = "cookies")]
|
|
|
|
{
|
|
|
|
let cookie: String = inner
|
|
|
|
.cookies
|
|
|
|
.delta()
|
|
|
|
// ensure only name=value is written to cookie header
|
|
|
|
.map(|c| Cookie::new(c.name(), c.value()).encoded().to_string())
|
|
|
|
.collect::<Vec<_>>()
|
|
|
|
.join("; ");
|
|
|
|
|
|
|
|
if !cookie.is_empty() {
|
|
|
|
head.headers
|
|
|
|
.insert(header::COOKIE, HeaderValue::from_str(&cookie).unwrap());
|
|
|
|
}
|
2019-03-26 19:54:35 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
req
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
2019-04-08 08:06:21 +02:00
|
|
|
fn parts(parts: &mut Option<Inner>) -> &mut Inner {
|
2019-03-26 19:54:35 +01:00
|
|
|
parts.as_mut().expect("cannot reuse test request builder")
|
|
|
|
}
|
2019-04-11 04:43:09 +02:00
|
|
|
|
2020-12-23 02:28:17 +01:00
|
|
|
/// Async I/O test buffer.
|
2019-04-11 04:43:09 +02:00
|
|
|
pub struct TestBuffer {
|
|
|
|
pub read_buf: BytesMut,
|
|
|
|
pub write_buf: BytesMut,
|
|
|
|
pub err: Option<io::Error>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl TestBuffer {
|
2020-12-23 02:28:17 +01:00
|
|
|
/// Create new `TestBuffer` instance with initial read buffer.
|
|
|
|
pub fn new<T>(data: T) -> Self
|
2019-04-11 04:43:09 +02:00
|
|
|
where
|
2020-12-23 02:28:17 +01:00
|
|
|
T: Into<BytesMut>,
|
2019-04-11 04:43:09 +02:00
|
|
|
{
|
2020-12-23 02:28:17 +01:00
|
|
|
Self {
|
|
|
|
read_buf: data.into(),
|
2019-04-11 04:43:09 +02:00
|
|
|
write_buf: BytesMut::new(),
|
|
|
|
err: None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-23 02:28:17 +01:00
|
|
|
/// Create new empty `TestBuffer` instance.
|
|
|
|
pub fn empty() -> Self {
|
|
|
|
Self::new("")
|
2019-04-11 04:57:34 +02:00
|
|
|
}
|
|
|
|
|
2020-12-23 02:28:17 +01:00
|
|
|
/// Add data to read buffer.
|
2019-04-11 04:43:09 +02:00
|
|
|
pub fn extend_read_buf<T: AsRef<[u8]>>(&mut self, data: T) {
|
|
|
|
self.read_buf.extend_from_slice(data.as_ref())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl io::Read for TestBuffer {
|
|
|
|
fn read(&mut self, dst: &mut [u8]) -> Result<usize, io::Error> {
|
|
|
|
if self.read_buf.is_empty() {
|
|
|
|
if self.err.is_some() {
|
|
|
|
Err(self.err.take().unwrap())
|
|
|
|
} else {
|
|
|
|
Err(io::Error::new(io::ErrorKind::WouldBlock, ""))
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
let size = std::cmp::min(self.read_buf.len(), dst.len());
|
|
|
|
let b = self.read_buf.split_to(size);
|
|
|
|
dst[..size].copy_from_slice(&b);
|
|
|
|
Ok(size)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl io::Write for TestBuffer {
|
|
|
|
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
|
|
|
self.write_buf.extend(buf);
|
|
|
|
Ok(buf.len())
|
|
|
|
}
|
2020-12-23 02:28:17 +01:00
|
|
|
|
2019-04-11 04:43:09 +02:00
|
|
|
fn flush(&mut self) -> io::Result<()> {
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-18 13:42:27 +01:00
|
|
|
impl AsyncRead for TestBuffer {
|
|
|
|
fn poll_read(
|
|
|
|
self: Pin<&mut Self>,
|
|
|
|
_: &mut Context<'_>,
|
2021-01-04 00:47:04 +01:00
|
|
|
buf: &mut ReadBuf<'_>,
|
|
|
|
) -> Poll<io::Result<()>> {
|
|
|
|
let dst = buf.initialize_unfilled();
|
|
|
|
let res = self.get_mut().read(dst).map(|n| buf.advance(n));
|
|
|
|
Poll::Ready(res)
|
2019-11-18 13:42:27 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl AsyncWrite for TestBuffer {
|
|
|
|
fn poll_write(
|
|
|
|
self: Pin<&mut Self>,
|
|
|
|
_: &mut Context<'_>,
|
|
|
|
buf: &[u8],
|
|
|
|
) -> Poll<io::Result<usize>> {
|
|
|
|
Poll::Ready(self.get_mut().write(buf))
|
|
|
|
}
|
2019-04-11 04:43:09 +02:00
|
|
|
|
2019-11-18 13:42:27 +01:00
|
|
|
fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
|
|
|
|
Poll::Ready(Ok(()))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
|
|
|
|
Poll::Ready(Ok(()))
|
|
|
|
}
|
|
|
|
}
|
2020-12-23 02:28:17 +01:00
|
|
|
|
|
|
|
/// Async I/O test buffer with ability to incrementally add to the read buffer.
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct TestSeqBuffer(Rc<RefCell<TestSeqInner>>);
|
|
|
|
|
|
|
|
impl TestSeqBuffer {
|
|
|
|
/// Create new `TestBuffer` instance with initial read buffer.
|
|
|
|
pub fn new<T>(data: T) -> Self
|
|
|
|
where
|
|
|
|
T: Into<BytesMut>,
|
|
|
|
{
|
|
|
|
Self(Rc::new(RefCell::new(TestSeqInner {
|
|
|
|
read_buf: data.into(),
|
|
|
|
write_buf: BytesMut::new(),
|
|
|
|
err: None,
|
|
|
|
})))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Create new empty `TestBuffer` instance.
|
|
|
|
pub fn empty() -> Self {
|
|
|
|
Self::new("")
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn read_buf(&self) -> Ref<'_, BytesMut> {
|
|
|
|
Ref::map(self.0.borrow(), |inner| &inner.read_buf)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn write_buf(&self) -> Ref<'_, BytesMut> {
|
|
|
|
Ref::map(self.0.borrow(), |inner| &inner.write_buf)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn err(&self) -> Ref<'_, Option<io::Error>> {
|
|
|
|
Ref::map(self.0.borrow(), |inner| &inner.err)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Add data to read buffer.
|
|
|
|
pub fn extend_read_buf<T: AsRef<[u8]>>(&mut self, data: T) {
|
|
|
|
self.0
|
|
|
|
.borrow_mut()
|
|
|
|
.read_buf
|
|
|
|
.extend_from_slice(data.as_ref())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct TestSeqInner {
|
|
|
|
read_buf: BytesMut,
|
|
|
|
write_buf: BytesMut,
|
|
|
|
err: Option<io::Error>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl io::Read for TestSeqBuffer {
|
|
|
|
fn read(&mut self, dst: &mut [u8]) -> Result<usize, io::Error> {
|
|
|
|
if self.0.borrow().read_buf.is_empty() {
|
|
|
|
if self.0.borrow().err.is_some() {
|
|
|
|
Err(self.0.borrow_mut().err.take().unwrap())
|
|
|
|
} else {
|
|
|
|
Err(io::Error::new(io::ErrorKind::WouldBlock, ""))
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
let size = std::cmp::min(self.0.borrow().read_buf.len(), dst.len());
|
|
|
|
let b = self.0.borrow_mut().read_buf.split_to(size);
|
|
|
|
dst[..size].copy_from_slice(&b);
|
|
|
|
Ok(size)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl io::Write for TestSeqBuffer {
|
|
|
|
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
|
|
|
self.0.borrow_mut().write_buf.extend(buf);
|
|
|
|
Ok(buf.len())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn flush(&mut self) -> io::Result<()> {
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl AsyncRead for TestSeqBuffer {
|
|
|
|
fn poll_read(
|
|
|
|
self: Pin<&mut Self>,
|
|
|
|
_: &mut Context<'_>,
|
2021-01-04 00:47:04 +01:00
|
|
|
buf: &mut ReadBuf<'_>,
|
|
|
|
) -> Poll<io::Result<()>> {
|
|
|
|
let dst = buf.initialize_unfilled();
|
|
|
|
let r = self.get_mut().read(dst);
|
2020-12-23 02:28:17 +01:00
|
|
|
match r {
|
2021-01-04 00:47:04 +01:00
|
|
|
Ok(n) => {
|
|
|
|
buf.advance(n);
|
|
|
|
Poll::Ready(Ok(()))
|
|
|
|
}
|
2020-12-23 02:28:17 +01:00
|
|
|
Err(err) if err.kind() == io::ErrorKind::WouldBlock => Poll::Pending,
|
|
|
|
Err(err) => Poll::Ready(Err(err)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl AsyncWrite for TestSeqBuffer {
|
|
|
|
fn poll_write(
|
|
|
|
self: Pin<&mut Self>,
|
|
|
|
_: &mut Context<'_>,
|
|
|
|
buf: &[u8],
|
|
|
|
) -> Poll<io::Result<usize>> {
|
|
|
|
Poll::Ready(self.get_mut().write(buf))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
|
|
|
|
Poll::Ready(Ok(()))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
|
|
|
|
Poll::Ready(Ok(()))
|
|
|
|
}
|
|
|
|
}
|