mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-06 19:00:18 +02:00
Compare commits
15 Commits
multipart-
...
web-v1.0.8
Author | SHA1 | Date | |
---|---|---|---|
4f3e97fff8 | |||
3ff01a9fc4 | |||
3d4e45a0e5 | |||
c659c33919 | |||
959f7754b2 | |||
23f04c4f38 | |||
d9af8f66ba | |||
aa39b8ca6f | |||
58c7065f08 | |||
b3783b403e | |||
e4503046de | |||
32a1c36597 | |||
7c9f9afc46 | |||
c1f99e0775 | |||
a32573bb58 |
20
CHANGES.md
20
CHANGES.md
@ -1,13 +1,25 @@
|
||||
# Changes
|
||||
## not released yet
|
||||
|
||||
## [1.0.8] - 2019-09-25
|
||||
|
||||
### Added
|
||||
|
||||
* Add `middleware::Conditon` that conditionally enables another middleware
|
||||
* Add `Scope::register_data` and `Resource::register_data` methods, parallel to
|
||||
`App::register_data`.
|
||||
|
||||
### Fixed
|
||||
* Add `middleware::Condition` that conditionally enables another middleware
|
||||
|
||||
* Allow to re-construct `ServiceRequest` from `HttpRequest` and `Payload`
|
||||
|
||||
* Add `HttpServer::listen_uds` for ability to listen on UDS FD rather than path,
|
||||
which is useful for example with systemd.
|
||||
|
||||
### Changed
|
||||
|
||||
* Make UrlEncodedError::Overflow more informativve
|
||||
|
||||
* Use actix-testing for testing utils
|
||||
|
||||
* h2 will use error response #1080
|
||||
|
||||
## [1.0.7] - 2019-08-29
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web"
|
||||
version = "1.0.7"
|
||||
version = "1.0.8"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
|
||||
readme = "README.md"
|
||||
@ -79,10 +79,11 @@ actix-router = "0.1.5"
|
||||
actix-rt = "0.2.4"
|
||||
actix-web-codegen = "0.1.2"
|
||||
actix-http = "0.2.9"
|
||||
actix-server = "0.6.0"
|
||||
actix-server = "0.6.1"
|
||||
actix-server-config = "0.1.2"
|
||||
actix-testing = "0.1.0"
|
||||
actix-threadpool = "0.1.1"
|
||||
awc = { version = "0.2.4", optional = true }
|
||||
awc = { version = "0.2.7", optional = true }
|
||||
|
||||
bytes = "0.4"
|
||||
derive_more = "0.15.0"
|
||||
|
@ -1,13 +1,25 @@
|
||||
# Changes
|
||||
|
||||
## Not released yet
|
||||
|
||||
### Added
|
||||
|
||||
* Add support for serde_json::Value to be passed as argument to ResponseBuilder.body()
|
||||
|
||||
|
||||
## [0.2.11] - 2019-09-11
|
||||
|
||||
### Added
|
||||
|
||||
* Add support for sending HTTP requests with `Rc<RequestHead>` in addition to sending HTTP requests with `RequestHead`
|
||||
|
||||
* Allow to use `std::convert::Infallible` as `actix_http::error::Error`
|
||||
|
||||
|
||||
### Fixed
|
||||
|
||||
* h2 will use error response #1080
|
||||
|
||||
* on_connect result isn't added to request extensions for http2 requests #1009
|
||||
|
||||
|
||||
|
@ -234,6 +234,12 @@ impl From<BytesMut> for Body {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<serde_json::Value> for Body {
|
||||
fn from(v: serde_json::Value) -> Body {
|
||||
Body::Bytes(v.to_string().into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> From<SizedStream<S>> for Body
|
||||
where
|
||||
S: Stream<Item = Bytes, Error = Error> + 'static,
|
||||
@ -548,4 +554,17 @@ mod tests {
|
||||
assert!(format!("{:?}", Body::Empty).contains("Body::Empty"));
|
||||
assert!(format!("{:?}", Body::Bytes(Bytes::from_static(b"1"))).contains("1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_serde_json() {
|
||||
use serde_json::json;
|
||||
assert_eq!(
|
||||
Body::from(serde_json::Value::String("test".into())).size(),
|
||||
BodySize::Sized(6)
|
||||
);
|
||||
assert_eq!(
|
||||
Body::from(json!({"test-key":"test-value"})).size(),
|
||||
BodySize::Sized(25)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -132,6 +132,14 @@ impl std::error::Error for Error {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::convert::Infallible> for Error {
|
||||
fn from(_: std::convert::Infallible) -> Self {
|
||||
// `std::convert::Infallible` indicates an error
|
||||
// that will never happen
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert `Error` to a `Response` instance
|
||||
impl From<Error> for Response {
|
||||
fn from(err: Error) -> Self {
|
||||
|
@ -1,5 +1,6 @@
|
||||
use std::io;
|
||||
use std::marker::PhantomData;
|
||||
use std::{io, mem};
|
||||
use std::mem::MaybeUninit;
|
||||
|
||||
use actix_codec::Decoder;
|
||||
use bytes::{Bytes, BytesMut};
|
||||
@ -186,11 +187,12 @@ impl MessageType for Request {
|
||||
fn decode(src: &mut BytesMut) -> Result<Option<(Self, PayloadType)>, ParseError> {
|
||||
// Unsafe: we read only this data only after httparse parses headers into.
|
||||
// performance bump for pipeline benchmarks.
|
||||
let mut headers: [HeaderIndex; MAX_HEADERS] = unsafe { mem::uninitialized() };
|
||||
let mut headers: [HeaderIndex; MAX_HEADERS] =
|
||||
unsafe { MaybeUninit::uninit().assume_init() };
|
||||
|
||||
let (len, method, uri, ver, h_len) = {
|
||||
let mut parsed: [httparse::Header; MAX_HEADERS] =
|
||||
unsafe { mem::uninitialized() };
|
||||
unsafe { MaybeUninit::uninit().assume_init() };
|
||||
|
||||
let mut req = httparse::Request::new(&mut parsed);
|
||||
match req.parse(src)? {
|
||||
@ -260,11 +262,12 @@ impl MessageType for ResponseHead {
|
||||
fn decode(src: &mut BytesMut) -> Result<Option<(Self, PayloadType)>, ParseError> {
|
||||
// Unsafe: we read only this data only after httparse parses headers into.
|
||||
// performance bump for pipeline benchmarks.
|
||||
let mut headers: [HeaderIndex; MAX_HEADERS] = unsafe { mem::uninitialized() };
|
||||
let mut headers: [HeaderIndex; MAX_HEADERS] =
|
||||
unsafe { MaybeUninit::uninit().assume_init() };
|
||||
|
||||
let (len, ver, status, h_len) = {
|
||||
let mut parsed: [httparse::Header; MAX_HEADERS] =
|
||||
unsafe { mem::uninitialized() };
|
||||
unsafe { MaybeUninit::uninit().assume_init() };
|
||||
|
||||
let mut res = httparse::Response::new(&mut parsed);
|
||||
match res.parse(src)? {
|
||||
|
@ -115,7 +115,7 @@ pub fn write_content_length(mut n: usize, bytes: &mut BytesMut) {
|
||||
|
||||
pub(crate) fn convert_usize(mut n: usize, bytes: &mut BytesMut) {
|
||||
let mut curr: isize = 39;
|
||||
let mut buf: [u8; 41] = unsafe { mem::uninitialized() };
|
||||
let mut buf: [u8; 41] = unsafe { mem::MaybeUninit::uninit().assume_init() };
|
||||
buf[39] = b'\r';
|
||||
buf[40] = b'\n';
|
||||
let buf_ptr = buf.as_mut_ptr();
|
||||
|
@ -992,6 +992,14 @@ mod tests {
|
||||
assert_eq!(resp.body().get_ref(), b"[\"v1\",\"v2\",\"v3\"]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_serde_json_in_body() {
|
||||
use serde_json::json;
|
||||
let resp =
|
||||
Response::build(StatusCode::OK).body(json!({"test-key":"test-value"}));
|
||||
assert_eq!(resp.body().get_ref(), br#"{"test-key":"test-value"}"#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_into_response() {
|
||||
let resp: Response = "test".into();
|
||||
|
@ -150,7 +150,7 @@ impl TestRequest {
|
||||
|
||||
/// Complete request creation and generate `Request` instance
|
||||
pub fn finish(&mut self) -> Request {
|
||||
let inner = self.0.take().expect("cannot reuse test request builder");;
|
||||
let inner = self.0.take().expect("cannot reuse test request builder");
|
||||
|
||||
let mut req = if let Some(pl) = inner.payload {
|
||||
Request::with_payload(pl)
|
||||
|
@ -1,5 +1,13 @@
|
||||
# Changes
|
||||
|
||||
|
||||
## [0.2.7] - 2019-09-25
|
||||
|
||||
### Added
|
||||
|
||||
* Remaining getter methods for `ClientRequest`'s private `head` field #1101
|
||||
|
||||
|
||||
## [0.2.6] - 2019-09-12
|
||||
|
||||
### Added
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "awc"
|
||||
version = "0.2.6"
|
||||
version = "0.2.7"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix http client."
|
||||
readme = "README.md"
|
||||
|
@ -96,7 +96,7 @@ impl ClientRequest {
|
||||
self
|
||||
}
|
||||
|
||||
/// Get HTTP URI of request
|
||||
/// Get HTTP URI of request.
|
||||
pub fn get_uri(&self) -> &Uri {
|
||||
&self.head.uri
|
||||
}
|
||||
@ -132,6 +132,16 @@ impl ClientRequest {
|
||||
self
|
||||
}
|
||||
|
||||
/// Get HTTP version of this request.
|
||||
pub fn get_version(&self) -> &Version {
|
||||
&self.head.version
|
||||
}
|
||||
|
||||
/// Get peer address of this request.
|
||||
pub fn get_peer_addr(&self) -> &Option<net::SocketAddr> {
|
||||
&self.head.peer_addr
|
||||
}
|
||||
|
||||
#[inline]
|
||||
/// Returns request's headers.
|
||||
pub fn headers(&self) -> &HeaderMap {
|
||||
|
13
src/error.rs
13
src/error.rs
@ -32,8 +32,12 @@ pub enum UrlencodedError {
|
||||
#[display(fmt = "Can not decode chunked transfer encoding")]
|
||||
Chunked,
|
||||
/// Payload size is bigger than allowed. (default: 256kB)
|
||||
#[display(fmt = "Urlencoded payload size is bigger than allowed (default: 256kB)")]
|
||||
Overflow,
|
||||
#[display(
|
||||
fmt = "Urlencoded payload size is bigger ({} bytes) than allowed (default: {} bytes)",
|
||||
size,
|
||||
limit
|
||||
)]
|
||||
Overflow { size: usize, limit: usize },
|
||||
/// Payload size is now known
|
||||
#[display(fmt = "Payload size is now known")]
|
||||
UnknownLength,
|
||||
@ -52,7 +56,7 @@ pub enum UrlencodedError {
|
||||
impl ResponseError for UrlencodedError {
|
||||
fn error_response(&self) -> HttpResponse {
|
||||
match *self {
|
||||
UrlencodedError::Overflow => {
|
||||
UrlencodedError::Overflow { .. } => {
|
||||
HttpResponse::new(StatusCode::PAYLOAD_TOO_LARGE)
|
||||
}
|
||||
UrlencodedError::UnknownLength => {
|
||||
@ -164,7 +168,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_urlencoded_error() {
|
||||
let resp: HttpResponse = UrlencodedError::Overflow.error_response();
|
||||
let resp: HttpResponse =
|
||||
UrlencodedError::Overflow { size: 0, limit: 0 }.error_response();
|
||||
assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
|
||||
let resp: HttpResponse = UrlencodedError::UnknownLength.error_response();
|
||||
assert_eq!(resp.status(), StatusCode::LENGTH_REQUIRED);
|
||||
|
@ -189,11 +189,21 @@ where
|
||||
/// ));
|
||||
/// }
|
||||
/// ```
|
||||
pub fn data<U: 'static>(mut self, data: U) -> Self {
|
||||
pub fn data<U: 'static>(self, data: U) -> Self {
|
||||
self.register_data(Data::new(data))
|
||||
}
|
||||
|
||||
/// Set or override application data.
|
||||
///
|
||||
/// This method has the same effect as [`Resource::data`](#method.data),
|
||||
/// except that instead of taking a value of some type `T`, it expects a
|
||||
/// value of type `Data<T>`. Use a `Data<T>` extractor to retrieve its
|
||||
/// value.
|
||||
pub fn register_data<U: 'static>(mut self, data: Data<U>) -> Self {
|
||||
if self.data.is_none() {
|
||||
self.data = Some(Extensions::new());
|
||||
}
|
||||
self.data.as_mut().unwrap().insert(Data::new(data));
|
||||
self.data.as_mut().unwrap().insert(data);
|
||||
self
|
||||
}
|
||||
|
||||
@ -763,4 +773,34 @@ mod tests {
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::NO_CONTENT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_data() {
|
||||
let mut srv = init_service(
|
||||
App::new()
|
||||
.data(1.0f64)
|
||||
.data(1usize)
|
||||
.register_data(web::Data::new('-'))
|
||||
.service(
|
||||
web::resource("/test")
|
||||
.data(10usize)
|
||||
.register_data(web::Data::new('*'))
|
||||
.guard(guard::Get())
|
||||
.to(
|
||||
|data1: web::Data<usize>,
|
||||
data2: web::Data<char>,
|
||||
data3: web::Data<f64>| {
|
||||
assert_eq!(*data1, 10);
|
||||
assert_eq!(*data2, '*');
|
||||
assert_eq!(*data3, 1.0);
|
||||
HttpResponse::Ok()
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
let req = TestRequest::get().uri("/test").to_request();
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
}
|
||||
|
35
src/scope.rs
35
src/scope.rs
@ -148,11 +148,20 @@ where
|
||||
/// );
|
||||
/// }
|
||||
/// ```
|
||||
pub fn data<U: 'static>(mut self, data: U) -> Self {
|
||||
pub fn data<U: 'static>(self, data: U) -> Self {
|
||||
self.register_data(Data::new(data))
|
||||
}
|
||||
|
||||
/// Set or override application data.
|
||||
///
|
||||
/// This method has the same effect as [`Scope::data`](#method.data), except
|
||||
/// that instead of taking a value of some type `T`, it expects a value of
|
||||
/// type `Data<T>`. Use a `Data<T>` extractor to retrieve its value.
|
||||
pub fn register_data<U: 'static>(mut self, data: Data<U>) -> Self {
|
||||
if self.data.is_none() {
|
||||
self.data = Some(Extensions::new());
|
||||
}
|
||||
self.data.as_mut().unwrap().insert(Data::new(data));
|
||||
self.data.as_mut().unwrap().insert(data);
|
||||
self
|
||||
}
|
||||
|
||||
@ -1082,6 +1091,28 @@ mod tests {
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_override_register_data() {
|
||||
let mut srv = init_service(
|
||||
App::new().register_data(web::Data::new(1usize)).service(
|
||||
web::scope("app")
|
||||
.register_data(web::Data::new(10usize))
|
||||
.route(
|
||||
"/t",
|
||||
web::get().to(|data: web::Data<usize>| {
|
||||
assert_eq!(*data, 10);
|
||||
let _ = data.clone();
|
||||
HttpResponse::Ok()
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
let req = TestRequest::with_uri("/app/t").to_request();
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scope_config() {
|
||||
let mut srv =
|
||||
|
@ -435,6 +435,37 @@ where
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
#[cfg(feature = "uds")]
|
||||
/// Start listening for unix domain connections on existing listener.
|
||||
///
|
||||
/// This method is available with `uds` feature.
|
||||
pub fn listen_uds(
|
||||
mut self,
|
||||
lst: std::os::unix::net::UnixListener,
|
||||
) -> io::Result<Self> {
|
||||
let cfg = self.config.clone();
|
||||
let factory = self.factory.clone();
|
||||
// todo duplicated:
|
||||
self.sockets.push(Socket {
|
||||
scheme: "http",
|
||||
addr: net::SocketAddr::new(
|
||||
net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)),
|
||||
8080,
|
||||
),
|
||||
});
|
||||
|
||||
let addr = format!("actix-web-service-{:?}", lst.local_addr()?);
|
||||
|
||||
self.builder = self.builder.listen_uds(addr, lst, move || {
|
||||
let c = cfg.lock();
|
||||
HttpService::build()
|
||||
.keep_alive(c.keep_alive)
|
||||
.client_timeout(c.client_timeout)
|
||||
.finish(factory())
|
||||
})?;
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
#[cfg(feature = "uds")]
|
||||
/// Start listening for incoming unix domain connections.
|
||||
///
|
||||
|
@ -68,6 +68,34 @@ impl ServiceRequest {
|
||||
(self.0, pl)
|
||||
}
|
||||
|
||||
/// Construct request from parts.
|
||||
///
|
||||
/// `ServiceRequest` can be re-constructed only if `req` hasnt been cloned.
|
||||
pub fn from_parts(
|
||||
mut req: HttpRequest,
|
||||
pl: Payload,
|
||||
) -> Result<Self, (HttpRequest, Payload)> {
|
||||
if Rc::strong_count(&req.0) == 1 && Rc::weak_count(&req.0) == 0 {
|
||||
Rc::get_mut(&mut req.0).unwrap().payload = pl;
|
||||
Ok(ServiceRequest(req))
|
||||
} else {
|
||||
Err((req, pl))
|
||||
}
|
||||
}
|
||||
|
||||
/// Construct request from request.
|
||||
///
|
||||
/// `HttpRequest` implements `Clone` trait via `Rc` type. `ServiceRequest`
|
||||
/// can be re-constructed only if rc's strong pointers count eq 1 and
|
||||
/// weak pointers count is 0.
|
||||
pub fn from_request(req: HttpRequest) -> Result<Self, HttpRequest> {
|
||||
if Rc::strong_count(&req.0) == 1 && Rc::weak_count(&req.0) == 0 {
|
||||
Ok(ServiceRequest(req))
|
||||
} else {
|
||||
Err(req)
|
||||
}
|
||||
}
|
||||
|
||||
/// Create service response
|
||||
#[inline]
|
||||
pub fn into_response<B, R: Into<Response<B>>>(self, res: R) -> ServiceResponse<B> {
|
||||
@ -514,6 +542,27 @@ mod tests {
|
||||
use crate::test::{call_service, init_service, TestRequest};
|
||||
use crate::{guard, http, web, App, HttpResponse};
|
||||
|
||||
#[test]
|
||||
fn test_service_request() {
|
||||
let req = TestRequest::default().to_srv_request();
|
||||
let (r, pl) = req.into_parts();
|
||||
assert!(ServiceRequest::from_parts(r, pl).is_ok());
|
||||
|
||||
let req = TestRequest::default().to_srv_request();
|
||||
let (r, pl) = req.into_parts();
|
||||
let _r2 = r.clone();
|
||||
assert!(ServiceRequest::from_parts(r, pl).is_err());
|
||||
|
||||
let req = TestRequest::default().to_srv_request();
|
||||
let (r, _pl) = req.into_parts();
|
||||
assert!(ServiceRequest::from_request(r).is_ok());
|
||||
|
||||
let req = TestRequest::default().to_srv_request();
|
||||
let (r, _pl) = req.into_parts();
|
||||
let _r2 = r.clone();
|
||||
assert!(ServiceRequest::from_request(r).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_service() {
|
||||
let mut srv = init_service(
|
||||
|
77
src/test.rs
77
src/test.rs
@ -1,5 +1,4 @@
|
||||
//! Various helpers for Actix applications to use during testing.
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_http::http::header::{ContentType, Header, HeaderName, IntoHeaderValue};
|
||||
@ -7,17 +6,17 @@ use actix_http::http::{HttpTryFrom, Method, StatusCode, Uri, Version};
|
||||
use actix_http::test::TestRequest as HttpTestRequest;
|
||||
use actix_http::{cookie::Cookie, Extensions, Request};
|
||||
use actix_router::{Path, ResourceDef, Url};
|
||||
use actix_rt::{System, SystemRunner};
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::{IntoNewService, IntoService, NewService, Service};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use futures::future::{lazy, ok, Future, IntoFuture};
|
||||
use futures::future::{ok, Future};
|
||||
use futures::Stream;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::Serialize;
|
||||
use serde_json;
|
||||
|
||||
pub use actix_http::test::TestBuffer;
|
||||
pub use actix_testing::{block_fn, block_on, run_on};
|
||||
|
||||
use crate::config::{AppConfig, AppConfigInner};
|
||||
use crate::data::Data;
|
||||
@ -27,78 +26,6 @@ use crate::rmap::ResourceMap;
|
||||
use crate::service::{ServiceRequest, ServiceResponse};
|
||||
use crate::{Error, HttpRequest, HttpResponse};
|
||||
|
||||
thread_local! {
|
||||
static RT: RefCell<Inner> = {
|
||||
RefCell::new(Inner(Some(System::builder().build())))
|
||||
};
|
||||
}
|
||||
|
||||
struct Inner(Option<SystemRunner>);
|
||||
|
||||
impl Inner {
|
||||
fn get_mut(&mut self) -> &mut SystemRunner {
|
||||
self.0.as_mut().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Inner {
|
||||
fn drop(&mut self) {
|
||||
std::mem::forget(self.0.take().unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the provided future, blocking the current thread until the future
|
||||
/// completes.
|
||||
///
|
||||
/// This function can be used to synchronously block the current thread
|
||||
/// until the provided `future` has resolved either successfully or with an
|
||||
/// error. The result of the future is then returned from this function
|
||||
/// call.
|
||||
///
|
||||
/// Note that this function is intended to be used only for testing purpose.
|
||||
/// This function panics on nested call.
|
||||
pub fn block_on<F>(f: F) -> Result<F::Item, F::Error>
|
||||
where
|
||||
F: IntoFuture,
|
||||
{
|
||||
RT.with(move |rt| rt.borrow_mut().get_mut().block_on(f.into_future()))
|
||||
}
|
||||
|
||||
/// Runs the provided function, blocking the current thread until the result
|
||||
/// future completes.
|
||||
///
|
||||
/// This function can be used to synchronously block the current thread
|
||||
/// until the provided `future` has resolved either successfully or with an
|
||||
/// error. The result of the future is then returned from this function
|
||||
/// call.
|
||||
///
|
||||
/// Note that this function is intended to be used only for testing purpose.
|
||||
/// This function panics on nested call.
|
||||
pub fn block_fn<F, R>(f: F) -> Result<R::Item, R::Error>
|
||||
where
|
||||
F: FnOnce() -> R,
|
||||
R: IntoFuture,
|
||||
{
|
||||
RT.with(move |rt| rt.borrow_mut().get_mut().block_on(lazy(f)))
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
/// Runs the provided function, with runtime enabled.
|
||||
///
|
||||
/// Note that this function is intended to be used only for testing purpose.
|
||||
/// This function panics on nested call.
|
||||
pub fn run_on<F, R>(f: F) -> R
|
||||
where
|
||||
F: FnOnce() -> R,
|
||||
{
|
||||
RT.with(move |rt| {
|
||||
rt.borrow_mut()
|
||||
.get_mut()
|
||||
.block_on(lazy(|| Ok::<_, ()>(f())))
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Create service that always responds with `HttpResponse::Ok()`
|
||||
pub fn ok_service(
|
||||
) -> impl Service<Request = ServiceRequest, Response = ServiceResponse<Body>, Error = Error>
|
||||
|
@ -318,7 +318,7 @@ where
|
||||
let limit = self.limit;
|
||||
if let Some(len) = self.length.take() {
|
||||
if len > limit {
|
||||
return Err(UrlencodedError::Overflow);
|
||||
return Err(UrlencodedError::Overflow { size: len, limit });
|
||||
}
|
||||
}
|
||||
|
||||
@ -331,7 +331,10 @@ where
|
||||
.from_err()
|
||||
.fold(BytesMut::with_capacity(8192), move |mut body, chunk| {
|
||||
if (body.len() + chunk.len()) > limit {
|
||||
Err(UrlencodedError::Overflow)
|
||||
Err(UrlencodedError::Overflow {
|
||||
size: body.len() + chunk.len(),
|
||||
limit,
|
||||
})
|
||||
} else {
|
||||
body.extend_from_slice(&chunk);
|
||||
Ok(body)
|
||||
@ -390,8 +393,8 @@ mod tests {
|
||||
|
||||
fn eq(err: UrlencodedError, other: UrlencodedError) -> bool {
|
||||
match err {
|
||||
UrlencodedError::Overflow => match other {
|
||||
UrlencodedError::Overflow => true,
|
||||
UrlencodedError::Overflow { .. } => match other {
|
||||
UrlencodedError::Overflow { .. } => true,
|
||||
_ => false,
|
||||
},
|
||||
UrlencodedError::UnknownLength => match other {
|
||||
@ -420,7 +423,10 @@ mod tests {
|
||||
.header(CONTENT_LENGTH, "1000000")
|
||||
.to_http_parts();
|
||||
let info = block_on(UrlEncoded::<Info>::new(&req, &mut pl));
|
||||
assert!(eq(info.err().unwrap(), UrlencodedError::Overflow));
|
||||
assert!(eq(
|
||||
info.err().unwrap(),
|
||||
UrlencodedError::Overflow { size: 0, limit: 0 }
|
||||
));
|
||||
|
||||
let (req, mut pl) = TestRequest::with_header(CONTENT_TYPE, "text/plain")
|
||||
.header(CONTENT_LENGTH, "10")
|
||||
|
@ -1,10 +1,15 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.5] - 2019-0917
|
||||
|
||||
### Changed
|
||||
|
||||
* Update serde_urlencoded to "0.6.1"
|
||||
|
||||
### Fixed
|
||||
|
||||
* Do not override current `System`
|
||||
|
||||
|
||||
## [0.2.4] - 2019-07-18
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-http-test"
|
||||
version = "0.2.4"
|
||||
version = "0.2.5"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix http test server"
|
||||
readme = "README.md"
|
||||
@ -35,7 +35,7 @@ actix-rt = "0.2.2"
|
||||
actix-service = "0.4.1"
|
||||
actix-server = "0.6.0"
|
||||
actix-utils = "0.4.1"
|
||||
awc = "0.2.2"
|
||||
awc = "0.2.6"
|
||||
actix-connect = "0.2.2"
|
||||
|
||||
base64 = "0.10"
|
||||
@ -56,5 +56,5 @@ tokio-timer = "0.2"
|
||||
openssl = { version="0.10", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-web = "1.0.0"
|
||||
actix-http = "0.2.4"
|
||||
actix-web = "1.0.7"
|
||||
actix-http = "0.2.9"
|
||||
|
@ -103,8 +103,8 @@ pub struct TestServer;
|
||||
/// Test server controller
|
||||
pub struct TestServerRuntime {
|
||||
addr: net::SocketAddr,
|
||||
rt: Runtime,
|
||||
client: Client,
|
||||
system: System,
|
||||
}
|
||||
|
||||
impl TestServer {
|
||||
@ -130,45 +130,47 @@ impl TestServer {
|
||||
});
|
||||
|
||||
let (system, addr) = rx.recv().unwrap();
|
||||
let mut rt = Runtime::new().unwrap();
|
||||
|
||||
let client = rt
|
||||
.block_on(lazy(move || {
|
||||
let connector = {
|
||||
#[cfg(feature = "ssl")]
|
||||
{
|
||||
use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
|
||||
let client = block_on(lazy(move || {
|
||||
let connector = {
|
||||
#[cfg(feature = "ssl")]
|
||||
{
|
||||
use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
|
||||
|
||||
let mut builder =
|
||||
SslConnector::builder(SslMethod::tls()).unwrap();
|
||||
builder.set_verify(SslVerifyMode::NONE);
|
||||
let _ = builder.set_alpn_protos(b"\x02h2\x08http/1.1").map_err(
|
||||
|e| log::error!("Can not set alpn protocol: {:?}", e),
|
||||
);
|
||||
Connector::new()
|
||||
.conn_lifetime(time::Duration::from_secs(0))
|
||||
.timeout(time::Duration::from_millis(500))
|
||||
.ssl(builder.build())
|
||||
.finish()
|
||||
}
|
||||
#[cfg(not(feature = "ssl"))]
|
||||
{
|
||||
Connector::new()
|
||||
.conn_lifetime(time::Duration::from_secs(0))
|
||||
.timeout(time::Duration::from_millis(500))
|
||||
.finish()
|
||||
}
|
||||
};
|
||||
let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
|
||||
builder.set_verify(SslVerifyMode::NONE);
|
||||
let _ = builder
|
||||
.set_alpn_protos(b"\x02h2\x08http/1.1")
|
||||
.map_err(|e| log::error!("Can not set alpn protocol: {:?}", e));
|
||||
Connector::new()
|
||||
.conn_lifetime(time::Duration::from_secs(0))
|
||||
.timeout(time::Duration::from_millis(500))
|
||||
.ssl(builder.build())
|
||||
.finish()
|
||||
}
|
||||
#[cfg(not(feature = "ssl"))]
|
||||
{
|
||||
Connector::new()
|
||||
.conn_lifetime(time::Duration::from_secs(0))
|
||||
.timeout(time::Duration::from_millis(500))
|
||||
.finish()
|
||||
}
|
||||
};
|
||||
|
||||
Ok::<Client, ()>(Client::build().connector(connector).finish())
|
||||
}))
|
||||
.unwrap();
|
||||
rt.block_on(lazy(
|
||||
Ok::<Client, ()>(Client::build().connector(connector).finish())
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
block_on(lazy(
|
||||
|| Ok::<_, ()>(actix_connect::start_default_resolver()),
|
||||
))
|
||||
.unwrap();
|
||||
System::set_current(system);
|
||||
TestServerRuntime { addr, rt, client }
|
||||
|
||||
TestServerRuntime {
|
||||
addr,
|
||||
client,
|
||||
system,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get first available unused address
|
||||
@ -188,7 +190,7 @@ impl TestServerRuntime {
|
||||
where
|
||||
F: Future<Item = I, Error = E>,
|
||||
{
|
||||
self.rt.block_on(fut)
|
||||
block_on(fut)
|
||||
}
|
||||
|
||||
/// Execute future on current core
|
||||
@ -197,7 +199,7 @@ impl TestServerRuntime {
|
||||
F: FnOnce() -> R,
|
||||
R: Future,
|
||||
{
|
||||
self.rt.block_on(lazy(f))
|
||||
block_on(lazy(f))
|
||||
}
|
||||
|
||||
/// Execute function on current core
|
||||
@ -205,7 +207,7 @@ impl TestServerRuntime {
|
||||
where
|
||||
F: FnOnce() -> R,
|
||||
{
|
||||
self.rt.block_on(lazy(|| Ok::<_, ()>(fut()))).unwrap()
|
||||
block_on(lazy(|| Ok::<_, ()>(fut()))).unwrap()
|
||||
}
|
||||
|
||||
/// Construct test server url
|
||||
@ -324,8 +326,7 @@ impl TestServerRuntime {
|
||||
{
|
||||
let url = self.url(path);
|
||||
let connect = self.client.ws(url).connect();
|
||||
self.rt
|
||||
.block_on(lazy(move || connect.map(|(_, framed)| framed)))
|
||||
block_on(lazy(move || connect.map(|(_, framed)| framed)))
|
||||
}
|
||||
|
||||
/// Connect to a websocket server
|
||||
@ -338,7 +339,7 @@ impl TestServerRuntime {
|
||||
|
||||
/// Stop http server
|
||||
fn stop(&mut self) {
|
||||
System::current().stop();
|
||||
self.system.stop();
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user