2017-12-27 01:35:00 +01:00
|
|
|
//! Various helpers for Actix applications to use during testing.
|
2021-01-15 03:11:10 +01:00
|
|
|
|
2019-12-20 11:11:51 +01:00
|
|
|
use std::net::SocketAddr;
|
2019-03-03 01:24:14 +01:00
|
|
|
use std::rc::Rc;
|
2019-12-12 17:28:47 +01:00
|
|
|
use std::sync::mpsc;
|
|
|
|
use std::{fmt, net, thread, time};
|
2017-12-27 01:35:00 +01:00
|
|
|
|
2019-12-12 17:28:47 +01:00
|
|
|
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
2021-01-15 03:11:10 +01:00
|
|
|
use actix_http::http::header::{ContentType, IntoHeaderPair};
|
|
|
|
use actix_http::http::{Method, StatusCode, Uri, Version};
|
2019-03-03 07:03:45 +01:00
|
|
|
use actix_http::test::TestRequest as HttpTestRequest;
|
2019-12-12 17:28:47 +01:00
|
|
|
use actix_http::{cookie::Cookie, ws, Extensions, HttpService, Request};
|
2019-03-09 16:39:34 +01:00
|
|
|
use actix_router::{Path, ResourceDef, Url};
|
2021-01-04 00:47:04 +01:00
|
|
|
use actix_rt::{time::sleep, System};
|
2021-02-12 00:03:17 +01:00
|
|
|
use actix_service::{map_config, IntoService, IntoServiceFactory, Service, ServiceFactory};
|
2019-12-12 17:28:47 +01:00
|
|
|
use awc::error::PayloadError;
|
|
|
|
use awc::{Client, ClientRequest, ClientResponse, Connector};
|
2019-04-15 01:25:45 +02:00
|
|
|
use bytes::{Bytes, BytesMut};
|
2020-05-18 04:47:20 +02:00
|
|
|
use futures_core::Stream;
|
|
|
|
use futures_util::future::ok;
|
|
|
|
use futures_util::StreamExt;
|
2019-04-15 01:25:45 +02:00
|
|
|
use serde::de::DeserializeOwned;
|
2019-05-22 20:18:33 +02:00
|
|
|
use serde::Serialize;
|
2020-05-19 02:34:37 +02:00
|
|
|
use socket2::{Domain, Protocol, Socket, Type};
|
2017-12-27 01:35:00 +01:00
|
|
|
|
2019-04-12 23:00:45 +02:00
|
|
|
pub use actix_http::test::TestBuffer;
|
|
|
|
|
2021-01-10 23:59:44 +01:00
|
|
|
use crate::app_service::AppInitServiceState;
|
2019-12-20 11:04:51 +01:00
|
|
|
use crate::config::AppConfig;
|
2019-05-05 04:43:49 +02:00
|
|
|
use crate::data::Data;
|
2019-12-25 09:10:28 +01:00
|
|
|
use crate::dev::{Body, MessageBody, Payload, Server};
|
2019-03-09 16:39:34 +01:00
|
|
|
use crate::rmap::ResourceMap;
|
2019-04-07 23:43:07 +02:00
|
|
|
use crate::service::{ServiceRequest, ServiceResponse};
|
2019-03-24 05:29:16 +01:00
|
|
|
use crate::{Error, HttpRequest, HttpResponse};
|
2018-03-20 19:23:35 +01:00
|
|
|
|
2019-03-30 18:04:38 +01:00
|
|
|
/// Create service that always responds with `HttpResponse::Ok()`
|
2019-04-13 23:50:54 +02:00
|
|
|
pub fn ok_service(
|
2021-01-04 00:47:04 +01:00
|
|
|
) -> impl Service<ServiceRequest, Response = ServiceResponse<Body>, Error = Error> {
|
2019-03-24 05:29:16 +01:00
|
|
|
default_service(StatusCode::OK)
|
|
|
|
}
|
|
|
|
|
2019-03-30 18:04:38 +01:00
|
|
|
/// Create service that responds with response with specified status code
|
2019-03-24 05:29:16 +01:00
|
|
|
pub fn default_service(
|
|
|
|
status_code: StatusCode,
|
2021-01-04 00:47:04 +01:00
|
|
|
) -> impl Service<ServiceRequest, Response = ServiceResponse<Body>, Error = Error> {
|
2019-05-12 17:34:51 +02:00
|
|
|
(move |req: ServiceRequest| {
|
2019-11-20 18:33:22 +01:00
|
|
|
ok(req.into_response(HttpResponse::build(status_code).finish()))
|
2019-03-24 05:29:16 +01:00
|
|
|
})
|
2019-05-12 17:34:51 +02:00
|
|
|
.into_service()
|
2019-03-24 05:29:16 +01:00
|
|
|
}
|
|
|
|
|
2019-03-06 03:47:18 +01:00
|
|
|
/// This method accepts application builder instance, and constructs
|
|
|
|
/// service.
|
|
|
|
///
|
2019-04-15 04:52:12 +02:00
|
|
|
/// ```rust
|
2019-03-06 03:52:29 +01:00
|
|
|
/// use actix_service::Service;
|
2019-03-25 01:13:17 +01:00
|
|
|
/// use actix_web::{test, web, App, HttpResponse, http::StatusCode};
|
2019-03-06 03:47:18 +01:00
|
|
|
///
|
2019-11-26 06:25:50 +01:00
|
|
|
/// #[actix_rt::test]
|
|
|
|
/// async fn test_init_service() {
|
2021-02-07 02:00:40 +01:00
|
|
|
/// let app = test::init_service(
|
2019-03-06 03:47:18 +01:00
|
|
|
/// App::new()
|
2019-11-21 16:34:04 +01:00
|
|
|
/// .service(web::resource("/test").to(|| async { HttpResponse::Ok() }))
|
2019-12-21 03:47:18 +01:00
|
|
|
/// ).await;
|
2019-03-06 03:47:18 +01:00
|
|
|
///
|
2019-03-06 03:52:29 +01:00
|
|
|
/// // Create request object
|
|
|
|
/// let req = test::TestRequest::with_uri("/test").to_request();
|
|
|
|
///
|
|
|
|
/// // Execute application
|
2019-11-26 06:25:50 +01:00
|
|
|
/// let resp = app.call(req).await.unwrap();
|
2019-03-06 03:47:18 +01:00
|
|
|
/// assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
/// }
|
|
|
|
/// ```
|
2019-11-20 18:33:22 +01:00
|
|
|
pub async fn init_service<R, S, B, E>(
|
2019-03-06 03:47:18 +01:00
|
|
|
app: R,
|
2021-01-04 00:47:04 +01:00
|
|
|
) -> impl Service<Request, Response = ServiceResponse<B>, Error = E>
|
2020-04-29 08:38:53 +02:00
|
|
|
where
|
2021-01-04 00:47:04 +01:00
|
|
|
R: IntoServiceFactory<S, Request>,
|
2021-02-12 00:03:17 +01:00
|
|
|
S: ServiceFactory<Request, Config = AppConfig, Response = ServiceResponse<B>, Error = E>,
|
2020-04-29 08:38:53 +02:00
|
|
|
S::InitError: std::fmt::Debug,
|
|
|
|
{
|
2020-05-21 10:56:53 +02:00
|
|
|
try_init_service(app)
|
|
|
|
.await
|
|
|
|
.expect("service initilization failed")
|
2020-04-29 08:38:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Fallible version of init_service that allows testing data factory errors.
|
|
|
|
pub(crate) async fn try_init_service<R, S, B, E>(
|
|
|
|
app: R,
|
2021-01-04 00:47:04 +01:00
|
|
|
) -> Result<impl Service<Request, Response = ServiceResponse<B>, Error = E>, S::InitError>
|
2019-03-06 03:47:18 +01:00
|
|
|
where
|
2021-01-04 00:47:04 +01:00
|
|
|
R: IntoServiceFactory<S, Request>,
|
2021-02-12 00:03:17 +01:00
|
|
|
S: ServiceFactory<Request, Config = AppConfig, Response = ServiceResponse<B>, Error = E>,
|
2019-03-06 03:47:18 +01:00
|
|
|
S::InitError: std::fmt::Debug,
|
|
|
|
{
|
2019-11-20 18:33:22 +01:00
|
|
|
let srv = app.into_factory();
|
2020-04-29 08:38:53 +02:00
|
|
|
srv.new_service(AppConfig::default()).await
|
2019-03-06 03:47:18 +01:00
|
|
|
}
|
|
|
|
|
2019-03-06 07:10:08 +01:00
|
|
|
/// Calls service and waits for response future completion.
|
|
|
|
///
|
2019-04-15 04:52:12 +02:00
|
|
|
/// ```rust
|
2020-01-28 00:09:46 +01:00
|
|
|
/// use actix_web::{test, web, App, HttpResponse, http::StatusCode};
|
2019-03-06 07:10:08 +01:00
|
|
|
///
|
2020-01-28 00:09:46 +01:00
|
|
|
/// #[actix_rt::test]
|
|
|
|
/// async fn test_response() {
|
2021-02-07 02:00:40 +01:00
|
|
|
/// let app = test::init_service(
|
2019-03-06 07:10:08 +01:00
|
|
|
/// App::new()
|
2019-11-21 16:34:04 +01:00
|
|
|
/// .service(web::resource("/test").to(|| async {
|
|
|
|
/// HttpResponse::Ok()
|
|
|
|
/// }))
|
|
|
|
/// ).await;
|
2019-03-06 07:10:08 +01:00
|
|
|
///
|
|
|
|
/// // Create request object
|
|
|
|
/// let req = test::TestRequest::with_uri("/test").to_request();
|
|
|
|
///
|
|
|
|
/// // Call application
|
2021-02-07 02:00:40 +01:00
|
|
|
/// let resp = test::call_service(&app, req).await;
|
2019-03-06 07:10:08 +01:00
|
|
|
/// assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
/// }
|
|
|
|
/// ```
|
2021-02-07 02:00:40 +01:00
|
|
|
pub async fn call_service<S, R, B, E>(app: &S, req: R) -> S::Response
|
2019-03-06 07:10:08 +01:00
|
|
|
where
|
2021-01-04 00:47:04 +01:00
|
|
|
S: Service<R, Response = ServiceResponse<B>, Error = E>,
|
2019-03-06 07:10:08 +01:00
|
|
|
E: std::fmt::Debug,
|
|
|
|
{
|
2019-11-20 18:33:22 +01:00
|
|
|
app.call(req).await.unwrap()
|
2019-03-06 07:10:08 +01:00
|
|
|
}
|
|
|
|
|
2019-04-15 04:52:12 +02:00
|
|
|
/// Helper function that returns a response body of a TestRequest
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use actix_web::{test, web, App, HttpResponse, http::header};
|
|
|
|
/// use bytes::Bytes;
|
|
|
|
///
|
2019-11-26 06:25:50 +01:00
|
|
|
/// #[actix_rt::test]
|
|
|
|
/// async fn test_index() {
|
2021-02-07 02:00:40 +01:00
|
|
|
/// let app = test::init_service(
|
2019-04-15 04:52:12 +02:00
|
|
|
/// App::new().service(
|
|
|
|
/// web::resource("/index.html")
|
2019-11-21 16:34:04 +01:00
|
|
|
/// .route(web::post().to(|| async {
|
|
|
|
/// HttpResponse::Ok().body("welcome!")
|
|
|
|
/// })))
|
|
|
|
/// ).await;
|
2019-04-15 04:52:12 +02:00
|
|
|
///
|
|
|
|
/// let req = test::TestRequest::post()
|
|
|
|
/// .uri("/index.html")
|
|
|
|
/// .header(header::CONTENT_TYPE, "application/json")
|
|
|
|
/// .to_request();
|
|
|
|
///
|
2021-02-07 02:00:40 +01:00
|
|
|
/// let result = test::read_response(&app, req).await;
|
2019-04-15 04:52:12 +02:00
|
|
|
/// assert_eq!(result, Bytes::from_static(b"welcome!"));
|
|
|
|
/// }
|
|
|
|
/// ```
|
2021-02-07 02:00:40 +01:00
|
|
|
pub async fn read_response<S, B>(app: &S, req: Request) -> Bytes
|
2019-04-15 04:52:12 +02:00
|
|
|
where
|
2021-01-04 00:47:04 +01:00
|
|
|
S: Service<Request, Response = ServiceResponse<B>, Error = Error>,
|
2020-02-18 19:48:37 +01:00
|
|
|
B: MessageBody + Unpin,
|
2019-04-15 04:52:12 +02:00
|
|
|
{
|
2019-11-20 18:33:22 +01:00
|
|
|
let mut resp = app
|
|
|
|
.call(req)
|
|
|
|
.await
|
2019-11-26 06:25:50 +01:00
|
|
|
.unwrap_or_else(|_| panic!("read_response failed at application call"));
|
2019-11-20 18:33:22 +01:00
|
|
|
|
|
|
|
let mut body = resp.take_body();
|
|
|
|
let mut bytes = BytesMut::new();
|
|
|
|
while let Some(item) = body.next().await {
|
|
|
|
bytes.extend_from_slice(&item.unwrap());
|
|
|
|
}
|
|
|
|
bytes.freeze()
|
2019-04-15 04:52:12 +02:00
|
|
|
}
|
|
|
|
|
2019-04-22 23:22:08 +02:00
|
|
|
/// Helper function that returns a response body of a ServiceResponse.
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use actix_web::{test, web, App, HttpResponse, http::header};
|
|
|
|
/// use bytes::Bytes;
|
|
|
|
///
|
2019-11-26 06:25:50 +01:00
|
|
|
/// #[actix_rt::test]
|
|
|
|
/// async fn test_index() {
|
2021-02-07 02:00:40 +01:00
|
|
|
/// let app = test::init_service(
|
2019-04-22 23:22:08 +02:00
|
|
|
/// App::new().service(
|
|
|
|
/// web::resource("/index.html")
|
2019-11-21 16:34:04 +01:00
|
|
|
/// .route(web::post().to(|| async {
|
|
|
|
/// HttpResponse::Ok().body("welcome!")
|
|
|
|
/// })))
|
|
|
|
/// ).await;
|
2019-04-22 23:22:08 +02:00
|
|
|
///
|
|
|
|
/// let req = test::TestRequest::post()
|
|
|
|
/// .uri("/index.html")
|
|
|
|
/// .header(header::CONTENT_TYPE, "application/json")
|
|
|
|
/// .to_request();
|
|
|
|
///
|
2021-02-07 02:00:40 +01:00
|
|
|
/// let resp = test::call_service(&app, req).await;
|
2020-03-12 21:52:58 +01:00
|
|
|
/// let result = test::read_body(resp).await;
|
2019-04-22 23:22:08 +02:00
|
|
|
/// assert_eq!(result, Bytes::from_static(b"welcome!"));
|
|
|
|
/// }
|
|
|
|
/// ```
|
2019-11-20 18:33:22 +01:00
|
|
|
pub async fn read_body<B>(mut res: ServiceResponse<B>) -> Bytes
|
2019-04-22 23:22:08 +02:00
|
|
|
where
|
2020-02-18 19:48:37 +01:00
|
|
|
B: MessageBody + Unpin,
|
2019-04-22 23:22:08 +02:00
|
|
|
{
|
2019-11-20 18:33:22 +01:00
|
|
|
let mut body = res.take_body();
|
|
|
|
let mut bytes = BytesMut::new();
|
|
|
|
while let Some(item) = body.next().await {
|
|
|
|
bytes.extend_from_slice(&item.unwrap());
|
|
|
|
}
|
|
|
|
bytes.freeze()
|
|
|
|
}
|
|
|
|
|
2020-04-05 21:12:44 +02:00
|
|
|
/// Helper function that returns a deserialized response body of a ServiceResponse.
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use actix_web::{App, test, web, HttpResponse, http::header};
|
|
|
|
/// use serde::{Serialize, Deserialize};
|
|
|
|
///
|
|
|
|
/// #[derive(Serialize, Deserialize)]
|
|
|
|
/// pub struct Person {
|
|
|
|
/// id: String,
|
|
|
|
/// name: String,
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// #[actix_rt::test]
|
|
|
|
/// async fn test_post_person() {
|
2021-02-07 02:00:40 +01:00
|
|
|
/// let app = test::init_service(
|
2020-04-05 21:12:44 +02:00
|
|
|
/// App::new().service(
|
|
|
|
/// web::resource("/people")
|
|
|
|
/// .route(web::post().to(|person: web::Json<Person>| async {
|
|
|
|
/// HttpResponse::Ok()
|
2021-01-18 13:14:29 +01:00
|
|
|
/// .json(person)})
|
2020-04-05 21:12:44 +02:00
|
|
|
/// ))
|
|
|
|
/// ).await;
|
|
|
|
///
|
|
|
|
/// let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes();
|
|
|
|
///
|
|
|
|
/// let resp = test::TestRequest::post()
|
|
|
|
/// .uri("/people")
|
|
|
|
/// .header(header::CONTENT_TYPE, "application/json")
|
|
|
|
/// .set_payload(payload)
|
|
|
|
/// .send_request(&mut app)
|
|
|
|
/// .await;
|
|
|
|
///
|
|
|
|
/// assert!(resp.status().is_success());
|
|
|
|
///
|
|
|
|
/// let result: Person = test::read_body_json(resp).await;
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
pub async fn read_body_json<T, B>(res: ServiceResponse<B>) -> T
|
|
|
|
where
|
|
|
|
B: MessageBody + Unpin,
|
|
|
|
T: DeserializeOwned,
|
|
|
|
{
|
|
|
|
let body = read_body(res).await;
|
|
|
|
|
2021-02-12 00:03:17 +01:00
|
|
|
serde_json::from_slice(&body)
|
|
|
|
.unwrap_or_else(|e| panic!("read_response_json failed during deserialization: {}", e))
|
2020-04-05 21:12:44 +02:00
|
|
|
}
|
|
|
|
|
2019-11-20 18:33:22 +01:00
|
|
|
pub async fn load_stream<S>(mut stream: S) -> Result<Bytes, Error>
|
|
|
|
where
|
|
|
|
S: Stream<Item = Result<Bytes, Error>> + Unpin,
|
|
|
|
{
|
|
|
|
let mut data = BytesMut::new();
|
|
|
|
while let Some(item) = stream.next().await {
|
|
|
|
data.extend_from_slice(&item?);
|
|
|
|
}
|
|
|
|
Ok(data.freeze())
|
2019-04-22 23:22:08 +02:00
|
|
|
}
|
|
|
|
|
2019-04-15 04:52:12 +02:00
|
|
|
/// Helper function that returns a deserialized response body of a TestRequest
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use actix_web::{App, test, web, HttpResponse, http::header};
|
|
|
|
/// use serde::{Serialize, Deserialize};
|
|
|
|
///
|
|
|
|
/// #[derive(Serialize, Deserialize)]
|
|
|
|
/// pub struct Person {
|
|
|
|
/// id: String,
|
|
|
|
/// name: String
|
|
|
|
/// }
|
|
|
|
///
|
2019-11-26 06:25:50 +01:00
|
|
|
/// #[actix_rt::test]
|
|
|
|
/// async fn test_add_person() {
|
2021-02-07 02:00:40 +01:00
|
|
|
/// let app = test::init_service(
|
2019-04-15 04:52:12 +02:00
|
|
|
/// App::new().service(
|
|
|
|
/// web::resource("/people")
|
2019-11-21 16:34:04 +01:00
|
|
|
/// .route(web::post().to(|person: web::Json<Person>| async {
|
2019-04-15 04:52:12 +02:00
|
|
|
/// HttpResponse::Ok()
|
2021-01-18 13:14:29 +01:00
|
|
|
/// .json(person)})
|
2019-11-21 16:34:04 +01:00
|
|
|
/// ))
|
|
|
|
/// ).await;
|
2019-04-15 04:52:12 +02:00
|
|
|
///
|
|
|
|
/// let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes();
|
|
|
|
///
|
|
|
|
/// let req = test::TestRequest::post()
|
|
|
|
/// .uri("/people")
|
|
|
|
/// .header(header::CONTENT_TYPE, "application/json")
|
|
|
|
/// .set_payload(payload)
|
|
|
|
/// .to_request();
|
|
|
|
///
|
2019-11-21 16:34:04 +01:00
|
|
|
/// let result: Person = test::read_response_json(&mut app, req).await;
|
2019-04-15 04:52:12 +02:00
|
|
|
/// }
|
|
|
|
/// ```
|
2021-02-07 02:00:40 +01:00
|
|
|
pub async fn read_response_json<S, B, T>(app: &S, req: Request) -> T
|
2019-04-15 04:52:12 +02:00
|
|
|
where
|
2021-01-04 00:47:04 +01:00
|
|
|
S: Service<Request, Response = ServiceResponse<B>, Error = Error>,
|
2020-02-18 19:48:37 +01:00
|
|
|
B: MessageBody + Unpin,
|
2019-04-15 04:52:12 +02:00
|
|
|
T: DeserializeOwned,
|
|
|
|
{
|
2019-11-20 18:33:22 +01:00
|
|
|
let body = read_response(app, req).await;
|
|
|
|
|
|
|
|
serde_json::from_slice(&body)
|
|
|
|
.unwrap_or_else(|_| panic!("read_response_json failed during deserialization"))
|
2019-04-15 04:52:12 +02:00
|
|
|
}
|
|
|
|
|
2019-03-04 22:25:35 +01:00
|
|
|
/// Test `Request` builder.
|
|
|
|
///
|
|
|
|
/// For unit testing, actix provides a request builder type and a simple handler runner. TestRequest implements a builder-like pattern.
|
|
|
|
/// You can generate various types of request via TestRequest's methods:
|
|
|
|
/// * `TestRequest::to_request` creates `actix_http::Request` instance.
|
2019-04-30 03:42:21 +02:00
|
|
|
/// * `TestRequest::to_srv_request` creates `ServiceRequest` instance, which is used for testing middlewares and chain adapters.
|
|
|
|
/// * `TestRequest::to_srv_response` creates `ServiceResponse` instance.
|
2019-03-04 22:25:35 +01:00
|
|
|
/// * `TestRequest::to_http_request` creates `HttpRequest` instance, which is used for testing handlers.
|
2018-03-29 06:49:50 +02:00
|
|
|
///
|
2019-04-15 04:52:12 +02:00
|
|
|
/// ```rust
|
2019-03-06 04:03:59 +01:00
|
|
|
/// use actix_web::{test, HttpRequest, HttpResponse, HttpMessage};
|
|
|
|
/// use actix_web::http::{header, StatusCode};
|
2017-12-27 04:48:02 +01:00
|
|
|
///
|
2019-11-21 16:34:04 +01:00
|
|
|
/// async fn index(req: HttpRequest) -> HttpResponse {
|
2017-12-27 04:48:02 +01:00
|
|
|
/// if let Some(hdr) = req.headers().get(header::CONTENT_TYPE) {
|
2018-03-31 08:07:33 +02:00
|
|
|
/// HttpResponse::Ok().into()
|
2017-12-27 04:48:02 +01:00
|
|
|
/// } else {
|
2018-03-31 08:07:33 +02:00
|
|
|
/// HttpResponse::BadRequest().into()
|
2017-12-27 04:48:02 +01:00
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
///
|
2019-04-15 04:52:12 +02:00
|
|
|
/// #[test]
|
|
|
|
/// fn test_index() {
|
2021-01-15 03:11:10 +01:00
|
|
|
/// let req = test::TestRequest::default().insert_header("content-type", "text/plain")
|
2019-03-04 22:25:35 +01:00
|
|
|
/// .to_http_request();
|
|
|
|
///
|
2019-11-21 16:34:04 +01:00
|
|
|
/// let resp = index(req).await.unwrap();
|
2017-12-27 04:48:02 +01:00
|
|
|
/// assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
///
|
2019-03-04 22:25:35 +01:00
|
|
|
/// let req = test::TestRequest::default().to_http_request();
|
2019-11-21 16:34:04 +01:00
|
|
|
/// let resp = index(req).await.unwrap();
|
2017-12-27 04:48:02 +01:00
|
|
|
/// assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
|
|
|
/// }
|
|
|
|
/// ```
|
2019-03-03 07:03:45 +01:00
|
|
|
pub struct TestRequest {
|
|
|
|
req: HttpTestRequest,
|
2019-03-09 16:39:34 +01:00
|
|
|
rmap: ResourceMap,
|
2019-12-20 11:04:51 +01:00
|
|
|
config: AppConfig,
|
2019-04-15 04:52:12 +02:00
|
|
|
path: Path<Url>,
|
2019-12-20 11:11:51 +01:00
|
|
|
peer_addr: Option<SocketAddr>,
|
2019-05-05 04:43:49 +02:00
|
|
|
app_data: Extensions,
|
2017-12-27 04:48:02 +01:00
|
|
|
}
|
|
|
|
|
2019-03-03 07:03:45 +01:00
|
|
|
impl Default for TestRequest {
|
|
|
|
fn default() -> TestRequest {
|
|
|
|
TestRequest {
|
|
|
|
req: HttpTestRequest::default(),
|
2019-03-09 16:39:34 +01:00
|
|
|
rmap: ResourceMap::new(ResourceDef::new("")),
|
2019-12-20 11:04:51 +01:00
|
|
|
config: AppConfig::default(),
|
2019-04-15 04:52:12 +02:00
|
|
|
path: Path::new(Url::new(Uri::default())),
|
2019-12-20 11:11:51 +01:00
|
|
|
peer_addr: None,
|
2019-05-05 04:43:49 +02:00
|
|
|
app_data: Extensions::new(),
|
2017-12-27 04:48:02 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-17 05:35:02 +01:00
|
|
|
#[allow(clippy::wrong_self_convention)]
|
2019-03-03 07:03:45 +01:00
|
|
|
impl TestRequest {
|
2018-01-15 22:47:25 +01:00
|
|
|
/// Create TestRequest and set request uri
|
2019-03-03 07:03:45 +01:00
|
|
|
pub fn with_uri(path: &str) -> TestRequest {
|
2019-04-12 20:15:58 +02:00
|
|
|
TestRequest::default().uri(path)
|
2017-12-27 04:48:02 +01:00
|
|
|
}
|
|
|
|
|
2019-03-06 03:47:18 +01:00
|
|
|
/// Create TestRequest and set method to `Method::GET`
|
|
|
|
pub fn get() -> TestRequest {
|
2019-04-12 20:15:58 +02:00
|
|
|
TestRequest::default().method(Method::GET)
|
2019-03-06 03:47:18 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Create TestRequest and set method to `Method::POST`
|
|
|
|
pub fn post() -> TestRequest {
|
2019-04-12 20:15:58 +02:00
|
|
|
TestRequest::default().method(Method::POST)
|
2019-03-06 03:47:18 +01:00
|
|
|
}
|
2019-04-20 02:23:17 +02:00
|
|
|
|
2019-04-19 00:06:32 +02:00
|
|
|
/// Create TestRequest and set method to `Method::PUT`
|
|
|
|
pub fn put() -> TestRequest {
|
|
|
|
TestRequest::default().method(Method::PUT)
|
|
|
|
}
|
2019-04-20 02:23:17 +02:00
|
|
|
|
2019-04-19 00:06:32 +02:00
|
|
|
/// Create TestRequest and set method to `Method::PATCH`
|
|
|
|
pub fn patch() -> TestRequest {
|
|
|
|
TestRequest::default().method(Method::PATCH)
|
|
|
|
}
|
2019-03-06 03:47:18 +01:00
|
|
|
|
2019-04-29 18:14:36 +02:00
|
|
|
/// Create TestRequest and set method to `Method::DELETE`
|
|
|
|
pub fn delete() -> TestRequest {
|
|
|
|
TestRequest::default().method(Method::DELETE)
|
|
|
|
}
|
|
|
|
|
2017-12-27 04:48:02 +01:00
|
|
|
/// Set HTTP version of this request
|
|
|
|
pub fn version(mut self, ver: Version) -> Self {
|
2019-03-03 01:24:14 +01:00
|
|
|
self.req.version(ver);
|
2017-12-27 04:48:02 +01:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set HTTP method of this request
|
|
|
|
pub fn method(mut self, meth: Method) -> Self {
|
2019-03-03 01:24:14 +01:00
|
|
|
self.req.method(meth);
|
2017-12-27 04:48:02 +01:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set HTTP Uri of this request
|
|
|
|
pub fn uri(mut self, path: &str) -> Self {
|
2019-03-03 01:24:14 +01:00
|
|
|
self.req.uri(path);
|
2017-12-27 04:48:02 +01:00
|
|
|
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) -> Self
|
|
|
|
where
|
|
|
|
H: IntoHeaderPair,
|
|
|
|
{
|
|
|
|
self.req.insert_header(header);
|
2019-03-03 01:24:14 +01:00
|
|
|
self
|
2018-03-06 04:28:42 +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) -> Self
|
2018-04-14 01:02:01 +02:00
|
|
|
where
|
2021-01-15 03:11:10 +01:00
|
|
|
H: IntoHeaderPair,
|
2017-12-27 04:48:02 +01:00
|
|
|
{
|
2021-01-15 03:11:10 +01:00
|
|
|
self.req.append_header(header);
|
2017-12-27 04:48:02 +01:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2021-01-15 03:11:10 +01:00
|
|
|
/// Set cookie for this request.
|
2019-12-07 19:46:51 +01:00
|
|
|
pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {
|
2019-03-11 01:10:41 +01:00
|
|
|
self.req.cookie(cookie);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-04-15 04:52:12 +02:00
|
|
|
/// Set request path pattern parameter
|
|
|
|
pub fn param(mut self, name: &'static str, value: &'static str) -> Self {
|
|
|
|
self.path.add_static(name, value);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-12-20 11:11:51 +01:00
|
|
|
/// Set peer addr
|
|
|
|
pub fn peer_addr(mut self, addr: SocketAddr) -> Self {
|
|
|
|
self.peer_addr = Some(addr);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2018-02-20 05:01:38 +01:00
|
|
|
/// Set request payload
|
2019-03-02 07:51:32 +01:00
|
|
|
pub fn set_payload<B: Into<Bytes>>(mut self, data: B) -> Self {
|
2019-03-03 01:24:14 +01:00
|
|
|
self.req.set_payload(data);
|
2018-02-20 05:01:38 +01:00
|
|
|
self
|
|
|
|
}
|
2018-03-02 04:12:59 +01:00
|
|
|
|
2019-08-28 17:32:17 +02:00
|
|
|
/// Serialize `data` to a URL encoded form and set it as the request payload. The `Content-Type`
|
|
|
|
/// header is set to `application/x-www-form-urlencoded`.
|
|
|
|
pub fn set_form<T: Serialize>(mut self, data: &T) -> Self {
|
|
|
|
let bytes = serde_urlencoded::to_string(data)
|
|
|
|
.expect("Failed to serialize test data as a urlencoded form");
|
|
|
|
self.req.set_payload(bytes);
|
2021-01-15 03:11:10 +01:00
|
|
|
self.req.insert_header(ContentType::form_url_encoded());
|
2019-08-28 17:32:17 +02:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-05-19 04:36:28 +02:00
|
|
|
/// Serialize `data` to JSON and set it as the request payload. The `Content-Type` header is
|
|
|
|
/// set to `application/json`.
|
|
|
|
pub fn set_json<T: Serialize>(mut self, data: &T) -> Self {
|
2021-02-12 00:03:17 +01:00
|
|
|
let bytes = serde_json::to_string(data).expect("Failed to serialize test data to json");
|
2019-05-19 04:36:28 +02:00
|
|
|
self.req.set_payload(bytes);
|
2021-01-15 03:11:10 +01:00
|
|
|
self.req.insert_header(ContentType::json());
|
2019-05-19 04:36:28 +02:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-03-17 17:52:41 +01:00
|
|
|
/// Set application data. This is equivalent of `App::data()` method
|
|
|
|
/// for testing purpose.
|
2019-05-05 04:43:49 +02:00
|
|
|
pub fn data<T: 'static>(mut self, data: T) -> Self {
|
|
|
|
self.app_data.insert(Data::new(data));
|
2019-03-17 17:52:41 +01:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-12-20 12:13:09 +01:00
|
|
|
/// Set application data. This is equivalent of `App::app_data()` method
|
|
|
|
/// for testing purpose.
|
|
|
|
pub fn app_data<T: 'static>(mut self, data: T) -> Self {
|
|
|
|
self.app_data.insert(data);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-03-09 23:06:24 +01:00
|
|
|
#[cfg(test)]
|
|
|
|
/// Set request config
|
|
|
|
pub(crate) fn rmap(mut self, rmap: ResourceMap) -> Self {
|
|
|
|
self.rmap = rmap;
|
2019-03-04 00:32:47 +01:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-04-07 23:43:07 +02:00
|
|
|
/// Complete request creation and generate `Request` instance
|
2019-04-13 23:50:54 +02:00
|
|
|
pub fn to_request(mut self) -> Request {
|
2019-12-20 11:11:51 +01:00
|
|
|
let mut req = self.req.finish();
|
|
|
|
req.head_mut().peer_addr = self.peer_addr;
|
|
|
|
req
|
2019-04-07 23:43:07 +02:00
|
|
|
}
|
|
|
|
|
2019-03-03 01:24:14 +01:00
|
|
|
/// Complete request creation and generate `ServiceRequest` instance
|
2019-04-13 23:50:54 +02:00
|
|
|
pub fn to_srv_request(mut self) -> ServiceRequest {
|
2019-12-20 11:11:51 +01:00
|
|
|
let (mut head, payload) = self.req.finish().into_parts();
|
|
|
|
head.peer_addr = self.peer_addr;
|
2019-04-15 04:52:12 +02:00
|
|
|
self.path.get_mut().update(&head.uri);
|
2019-03-03 01:24:14 +01:00
|
|
|
|
2021-02-12 00:03:17 +01:00
|
|
|
let app_state = AppInitServiceState::new(Rc::new(self.rmap), self.config.clone());
|
2021-01-10 23:59:44 +01:00
|
|
|
|
2021-01-11 02:29:16 +01:00
|
|
|
ServiceRequest::new(
|
|
|
|
HttpRequest::new(self.path, head, app_state, Rc::new(self.app_data)),
|
2019-05-22 20:49:27 +02:00
|
|
|
payload,
|
2021-01-11 02:29:16 +01:00
|
|
|
)
|
2019-03-03 01:24:14 +01:00
|
|
|
}
|
|
|
|
|
2019-04-01 05:43:00 +02:00
|
|
|
/// Complete request creation and generate `ServiceResponse` instance
|
|
|
|
pub fn to_srv_response<B>(self, res: HttpResponse<B>) -> ServiceResponse<B> {
|
|
|
|
self.to_srv_request().into_response(res)
|
|
|
|
}
|
|
|
|
|
2017-12-27 04:48:02 +01:00
|
|
|
/// Complete request creation and generate `HttpRequest` instance
|
2019-03-04 06:02:01 +01:00
|
|
|
pub fn to_http_request(mut self) -> HttpRequest {
|
2021-01-11 02:29:16 +01:00
|
|
|
let (mut head, _) = self.req.finish().into_parts();
|
2019-12-20 11:11:51 +01:00
|
|
|
head.peer_addr = self.peer_addr;
|
2019-04-15 04:52:12 +02:00
|
|
|
self.path.get_mut().update(&head.uri);
|
2019-03-03 01:24:14 +01:00
|
|
|
|
2021-02-12 00:03:17 +01:00
|
|
|
let app_state = AppInitServiceState::new(Rc::new(self.rmap), self.config.clone());
|
2021-01-10 23:59:44 +01:00
|
|
|
|
2021-01-11 02:29:16 +01:00
|
|
|
HttpRequest::new(self.path, head, app_state, Rc::new(self.app_data))
|
2019-03-03 01:24:14 +01:00
|
|
|
}
|
2019-03-03 09:57:48 +01:00
|
|
|
|
2019-04-07 23:43:07 +02:00
|
|
|
/// Complete request creation and generate `HttpRequest` and `Payload` instances
|
|
|
|
pub fn to_http_parts(mut self) -> (HttpRequest, Payload) {
|
2019-12-20 11:11:51 +01:00
|
|
|
let (mut head, payload) = self.req.finish().into_parts();
|
|
|
|
head.peer_addr = self.peer_addr;
|
2019-04-15 04:52:12 +02:00
|
|
|
self.path.get_mut().update(&head.uri);
|
2019-03-03 09:57:48 +01:00
|
|
|
|
2021-02-12 00:03:17 +01:00
|
|
|
let app_state = AppInitServiceState::new(Rc::new(self.rmap), self.config.clone());
|
2021-01-10 23:59:44 +01:00
|
|
|
|
2021-01-11 02:29:16 +01:00
|
|
|
let req = HttpRequest::new(self.path, head, app_state, Rc::new(self.app_data));
|
2019-05-05 04:43:49 +02:00
|
|
|
|
2019-04-08 08:06:21 +02:00
|
|
|
(req, payload)
|
2019-03-03 09:57:48 +01:00
|
|
|
}
|
2020-04-05 21:12:44 +02:00
|
|
|
|
|
|
|
/// Complete request creation, calls service and waits for response future completion.
|
2021-02-07 02:00:40 +01:00
|
|
|
pub async fn send_request<S, B, E>(self, app: &S) -> S::Response
|
2020-04-05 21:12:44 +02:00
|
|
|
where
|
2021-01-04 00:47:04 +01:00
|
|
|
S: Service<Request, Response = ServiceResponse<B>, Error = E>,
|
2020-04-29 08:38:53 +02:00
|
|
|
E: std::fmt::Debug,
|
2020-04-05 21:12:44 +02:00
|
|
|
{
|
|
|
|
let req = self.to_request();
|
|
|
|
call_service(app, req).await
|
|
|
|
}
|
2019-04-15 04:52:12 +02:00
|
|
|
}
|
2019-04-15 01:25:45 +02:00
|
|
|
|
2019-12-12 17:28:47 +01:00
|
|
|
/// Start test server with default configuration
|
|
|
|
///
|
|
|
|
/// Test server is very simple server that simplify process of writing
|
|
|
|
/// integration tests cases for actix web applications.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use actix_web::{web, test, App, HttpResponse, Error};
|
|
|
|
///
|
|
|
|
/// async fn my_handler() -> Result<HttpResponse, Error> {
|
|
|
|
/// Ok(HttpResponse::Ok().into())
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// #[actix_rt::test]
|
|
|
|
/// async fn test_example() {
|
2021-02-07 02:00:40 +01:00
|
|
|
/// let srv = test::start(
|
2019-12-12 17:28:47 +01:00
|
|
|
/// || App::new().service(
|
|
|
|
/// web::resource("/").to(my_handler))
|
|
|
|
/// );
|
|
|
|
///
|
|
|
|
/// let req = srv.get("/");
|
|
|
|
/// let response = req.send().await.unwrap();
|
|
|
|
/// assert!(response.status().is_success());
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
pub fn start<F, I, S, B>(factory: F) -> TestServer
|
|
|
|
where
|
|
|
|
F: Fn() -> I + Send + Clone + 'static,
|
2021-01-04 00:47:04 +01:00
|
|
|
I: IntoServiceFactory<S, Request>,
|
|
|
|
S: ServiceFactory<Request, Config = AppConfig> + 'static,
|
2019-12-12 17:28:47 +01:00
|
|
|
S::Error: Into<Error> + 'static,
|
|
|
|
S::InitError: fmt::Debug,
|
|
|
|
S::Response: Into<HttpResponse<B>> + 'static,
|
2021-01-04 00:47:04 +01:00
|
|
|
<S::Service as Service<Request>>::Future: 'static,
|
2019-12-12 17:28:47 +01:00
|
|
|
B: MessageBody + 'static,
|
|
|
|
{
|
|
|
|
start_with(TestServerConfig::default(), factory)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Start test server with custom configuration
|
|
|
|
///
|
|
|
|
/// Test server could be configured in different ways, for details check
|
|
|
|
/// `TestServerConfig` docs.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use actix_web::{web, test, App, HttpResponse, Error};
|
|
|
|
///
|
|
|
|
/// async fn my_handler() -> Result<HttpResponse, Error> {
|
|
|
|
/// Ok(HttpResponse::Ok().into())
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// #[actix_rt::test]
|
|
|
|
/// async fn test_example() {
|
2021-02-07 02:00:40 +01:00
|
|
|
/// let srv = test::start_with(test::config().h1(), ||
|
2019-12-12 17:28:47 +01:00
|
|
|
/// App::new().service(web::resource("/").to(my_handler))
|
|
|
|
/// );
|
|
|
|
///
|
|
|
|
/// let req = srv.get("/");
|
|
|
|
/// let response = req.send().await.unwrap();
|
|
|
|
/// assert!(response.status().is_success());
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
pub fn start_with<F, I, S, B>(cfg: TestServerConfig, factory: F) -> TestServer
|
|
|
|
where
|
|
|
|
F: Fn() -> I + Send + Clone + 'static,
|
2021-01-04 00:47:04 +01:00
|
|
|
I: IntoServiceFactory<S, Request>,
|
|
|
|
S: ServiceFactory<Request, Config = AppConfig> + 'static,
|
2019-12-12 17:28:47 +01:00
|
|
|
S::Error: Into<Error> + 'static,
|
|
|
|
S::InitError: fmt::Debug,
|
|
|
|
S::Response: Into<HttpResponse<B>> + 'static,
|
2021-01-04 00:47:04 +01:00
|
|
|
<S::Service as Service<Request>>::Future: 'static,
|
2019-12-12 17:28:47 +01:00
|
|
|
B: MessageBody + 'static,
|
|
|
|
{
|
|
|
|
let (tx, rx) = mpsc::channel();
|
|
|
|
|
|
|
|
let ssl = match cfg.stream {
|
|
|
|
StreamType::Tcp => false,
|
|
|
|
#[cfg(feature = "openssl")]
|
|
|
|
StreamType::Openssl(_) => true,
|
|
|
|
#[cfg(feature = "rustls")]
|
|
|
|
StreamType::Rustls(_) => true,
|
|
|
|
};
|
|
|
|
|
|
|
|
// run server in separate thread
|
|
|
|
thread::spawn(move || {
|
2021-02-07 02:00:40 +01:00
|
|
|
let sys = System::new();
|
2019-12-12 17:28:47 +01:00
|
|
|
let tcp = net::TcpListener::bind("127.0.0.1:0").unwrap();
|
|
|
|
let local_addr = tcp.local_addr().unwrap();
|
|
|
|
let factory = factory.clone();
|
|
|
|
let cfg = cfg.clone();
|
|
|
|
let ctimeout = cfg.client_timeout;
|
|
|
|
let builder = Server::build().workers(1).disable_signals();
|
|
|
|
|
2019-12-25 09:10:28 +01:00
|
|
|
let srv = match cfg.stream {
|
2019-12-12 17:28:47 +01:00
|
|
|
StreamType::Tcp => match cfg.tp {
|
|
|
|
HttpVer::Http1 => builder.listen("test", tcp, move || {
|
2021-02-12 00:03:17 +01:00
|
|
|
let cfg = AppConfig::new(false, local_addr, format!("{}", local_addr));
|
2019-12-12 17:28:47 +01:00
|
|
|
HttpService::build()
|
|
|
|
.client_timeout(ctimeout)
|
2019-12-22 13:39:25 +01:00
|
|
|
.h1(map_config(factory(), move |_| cfg.clone()))
|
2019-12-12 17:28:47 +01:00
|
|
|
.tcp()
|
|
|
|
}),
|
|
|
|
HttpVer::Http2 => builder.listen("test", tcp, move || {
|
2021-02-12 00:03:17 +01:00
|
|
|
let cfg = AppConfig::new(false, local_addr, format!("{}", local_addr));
|
2019-12-12 17:28:47 +01:00
|
|
|
HttpService::build()
|
|
|
|
.client_timeout(ctimeout)
|
2019-12-22 13:39:25 +01:00
|
|
|
.h2(map_config(factory(), move |_| cfg.clone()))
|
2019-12-12 17:28:47 +01:00
|
|
|
.tcp()
|
|
|
|
}),
|
|
|
|
HttpVer::Both => builder.listen("test", tcp, move || {
|
2021-02-12 00:03:17 +01:00
|
|
|
let cfg = AppConfig::new(false, local_addr, format!("{}", local_addr));
|
2019-12-12 17:28:47 +01:00
|
|
|
HttpService::build()
|
|
|
|
.client_timeout(ctimeout)
|
2019-12-22 13:39:25 +01:00
|
|
|
.finish(map_config(factory(), move |_| cfg.clone()))
|
2019-12-12 17:28:47 +01:00
|
|
|
.tcp()
|
|
|
|
}),
|
|
|
|
},
|
|
|
|
#[cfg(feature = "openssl")]
|
|
|
|
StreamType::Openssl(acceptor) => match cfg.tp {
|
|
|
|
HttpVer::Http1 => builder.listen("test", tcp, move || {
|
2021-02-12 00:03:17 +01:00
|
|
|
let cfg = AppConfig::new(true, local_addr, format!("{}", local_addr));
|
2019-12-12 17:28:47 +01:00
|
|
|
HttpService::build()
|
|
|
|
.client_timeout(ctimeout)
|
2019-12-22 13:39:25 +01:00
|
|
|
.h1(map_config(factory(), move |_| cfg.clone()))
|
2019-12-12 17:28:47 +01:00
|
|
|
.openssl(acceptor.clone())
|
|
|
|
}),
|
|
|
|
HttpVer::Http2 => builder.listen("test", tcp, move || {
|
2021-02-12 00:03:17 +01:00
|
|
|
let cfg = AppConfig::new(true, local_addr, format!("{}", local_addr));
|
2019-12-12 17:28:47 +01:00
|
|
|
HttpService::build()
|
|
|
|
.client_timeout(ctimeout)
|
2019-12-22 13:39:25 +01:00
|
|
|
.h2(map_config(factory(), move |_| cfg.clone()))
|
2019-12-12 17:28:47 +01:00
|
|
|
.openssl(acceptor.clone())
|
|
|
|
}),
|
|
|
|
HttpVer::Both => builder.listen("test", tcp, move || {
|
2021-02-12 00:03:17 +01:00
|
|
|
let cfg = AppConfig::new(true, local_addr, format!("{}", local_addr));
|
2019-12-12 17:28:47 +01:00
|
|
|
HttpService::build()
|
|
|
|
.client_timeout(ctimeout)
|
2019-12-22 13:39:25 +01:00
|
|
|
.finish(map_config(factory(), move |_| cfg.clone()))
|
2019-12-12 17:28:47 +01:00
|
|
|
.openssl(acceptor.clone())
|
|
|
|
}),
|
|
|
|
},
|
|
|
|
#[cfg(feature = "rustls")]
|
|
|
|
StreamType::Rustls(config) => match cfg.tp {
|
|
|
|
HttpVer::Http1 => builder.listen("test", tcp, move || {
|
2021-02-12 00:03:17 +01:00
|
|
|
let cfg = AppConfig::new(true, local_addr, format!("{}", local_addr));
|
2019-12-12 17:28:47 +01:00
|
|
|
HttpService::build()
|
|
|
|
.client_timeout(ctimeout)
|
2019-12-22 13:39:25 +01:00
|
|
|
.h1(map_config(factory(), move |_| cfg.clone()))
|
2019-12-12 17:28:47 +01:00
|
|
|
.rustls(config.clone())
|
|
|
|
}),
|
|
|
|
HttpVer::Http2 => builder.listen("test", tcp, move || {
|
2021-02-12 00:03:17 +01:00
|
|
|
let cfg = AppConfig::new(true, local_addr, format!("{}", local_addr));
|
2019-12-12 17:28:47 +01:00
|
|
|
HttpService::build()
|
|
|
|
.client_timeout(ctimeout)
|
2019-12-22 13:39:25 +01:00
|
|
|
.h2(map_config(factory(), move |_| cfg.clone()))
|
2019-12-12 17:28:47 +01:00
|
|
|
.rustls(config.clone())
|
|
|
|
}),
|
|
|
|
HttpVer::Both => builder.listen("test", tcp, move || {
|
2021-02-12 00:03:17 +01:00
|
|
|
let cfg = AppConfig::new(true, local_addr, format!("{}", local_addr));
|
2019-12-12 17:28:47 +01:00
|
|
|
HttpService::build()
|
|
|
|
.client_timeout(ctimeout)
|
2019-12-22 13:39:25 +01:00
|
|
|
.finish(map_config(factory(), move |_| cfg.clone()))
|
2019-12-12 17:28:47 +01:00
|
|
|
.rustls(config.clone())
|
|
|
|
}),
|
|
|
|
},
|
|
|
|
}
|
2021-01-04 00:47:04 +01:00
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
sys.block_on(async {
|
2021-02-07 02:00:40 +01:00
|
|
|
let srv = srv.run();
|
2021-01-04 00:47:04 +01:00
|
|
|
tx.send((System::current(), srv, local_addr)).unwrap();
|
|
|
|
});
|
2019-12-12 17:28:47 +01:00
|
|
|
|
|
|
|
sys.run()
|
|
|
|
});
|
|
|
|
|
2019-12-25 09:10:28 +01:00
|
|
|
let (system, server, addr) = rx.recv().unwrap();
|
2019-12-12 17:28:47 +01:00
|
|
|
|
|
|
|
let client = {
|
|
|
|
let connector = {
|
|
|
|
#[cfg(feature = "openssl")]
|
|
|
|
{
|
2021-02-07 04:54:58 +01:00
|
|
|
use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
|
2019-12-12 17:28:47 +01:00
|
|
|
|
|
|
|
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))
|
2019-12-25 17:52:20 +01:00
|
|
|
.timeout(time::Duration::from_millis(30000))
|
2019-12-12 17:28:47 +01:00
|
|
|
.ssl(builder.build())
|
|
|
|
.finish()
|
|
|
|
}
|
|
|
|
#[cfg(not(feature = "openssl"))]
|
|
|
|
{
|
|
|
|
Connector::new()
|
|
|
|
.conn_lifetime(time::Duration::from_secs(0))
|
2019-12-25 17:52:20 +01:00
|
|
|
.timeout(time::Duration::from_millis(30000))
|
2019-12-12 17:28:47 +01:00
|
|
|
.finish()
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2020-09-11 10:24:39 +02:00
|
|
|
Client::builder().connector(connector).finish()
|
2019-12-12 17:28:47 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
TestServer {
|
|
|
|
ssl,
|
|
|
|
addr,
|
|
|
|
client,
|
|
|
|
system,
|
2019-12-25 09:10:28 +01:00
|
|
|
server,
|
2019-12-12 17:28:47 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct TestServerConfig {
|
|
|
|
tp: HttpVer,
|
|
|
|
stream: StreamType,
|
|
|
|
client_timeout: u64,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
enum HttpVer {
|
|
|
|
Http1,
|
|
|
|
Http2,
|
|
|
|
Both,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
enum StreamType {
|
|
|
|
Tcp,
|
|
|
|
#[cfg(feature = "openssl")]
|
2021-02-07 04:54:58 +01:00
|
|
|
Openssl(openssl::ssl::SslAcceptor),
|
2019-12-12 17:28:47 +01:00
|
|
|
#[cfg(feature = "rustls")]
|
2021-02-07 04:54:58 +01:00
|
|
|
Rustls(rustls::ServerConfig),
|
2019-12-12 17:28:47 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for TestServerConfig {
|
|
|
|
fn default() -> Self {
|
|
|
|
TestServerConfig::new()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Create default test server config
|
|
|
|
pub fn config() -> TestServerConfig {
|
|
|
|
TestServerConfig::new()
|
|
|
|
}
|
|
|
|
|
|
|
|
impl TestServerConfig {
|
|
|
|
/// Create default server configuration
|
|
|
|
pub(crate) fn new() -> TestServerConfig {
|
|
|
|
TestServerConfig {
|
|
|
|
tp: HttpVer::Both,
|
|
|
|
stream: StreamType::Tcp,
|
|
|
|
client_timeout: 5000,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-11 23:39:54 +01:00
|
|
|
/// Start HTTP/1.1 server only
|
2019-12-12 17:28:47 +01:00
|
|
|
pub fn h1(mut self) -> Self {
|
|
|
|
self.tp = HttpVer::Http1;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2021-02-11 23:39:54 +01:00
|
|
|
/// Start HTTP/2 server only
|
2019-12-12 17:28:47 +01:00
|
|
|
pub fn h2(mut self) -> Self {
|
|
|
|
self.tp = HttpVer::Http2;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Start openssl server
|
|
|
|
#[cfg(feature = "openssl")]
|
2021-02-07 04:54:58 +01:00
|
|
|
pub fn openssl(mut self, acceptor: openssl::ssl::SslAcceptor) -> Self {
|
2019-12-12 17:28:47 +01:00
|
|
|
self.stream = StreamType::Openssl(acceptor);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Start rustls server
|
|
|
|
#[cfg(feature = "rustls")]
|
2021-02-07 04:54:58 +01:00
|
|
|
pub fn rustls(mut self, config: rustls::ServerConfig) -> Self {
|
2019-12-12 17:28:47 +01:00
|
|
|
self.stream = StreamType::Rustls(config);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set server client timeout in milliseconds for first request.
|
|
|
|
pub fn client_timeout(mut self, val: u64) -> Self {
|
|
|
|
self.client_timeout = val;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Get first available unused address
|
|
|
|
pub fn unused_addr() -> net::SocketAddr {
|
|
|
|
let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
|
2021-02-12 00:03:17 +01:00
|
|
|
let socket = Socket::new(Domain::ipv4(), Type::stream(), Some(Protocol::tcp())).unwrap();
|
2020-05-19 02:34:37 +02:00
|
|
|
socket.bind(&addr.into()).unwrap();
|
|
|
|
socket.set_reuse_address(true).unwrap();
|
|
|
|
let tcp = socket.into_tcp_listener();
|
2019-12-12 17:28:47 +01:00
|
|
|
tcp.local_addr().unwrap()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Test server controller
|
|
|
|
pub struct TestServer {
|
|
|
|
addr: net::SocketAddr,
|
|
|
|
client: awc::Client,
|
|
|
|
system: actix_rt::System,
|
|
|
|
ssl: bool,
|
2019-12-25 09:10:28 +01:00
|
|
|
server: Server,
|
2019-12-12 17:28:47 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
impl TestServer {
|
|
|
|
/// Construct test server url
|
|
|
|
pub fn addr(&self) -> net::SocketAddr {
|
|
|
|
self.addr
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Construct test server url
|
|
|
|
pub fn url(&self, uri: &str) -> String {
|
|
|
|
let scheme = if self.ssl { "https" } else { "http" };
|
|
|
|
|
|
|
|
if uri.starts_with('/') {
|
|
|
|
format!("{}://localhost:{}{}", scheme, self.addr.port(), uri)
|
|
|
|
} else {
|
|
|
|
format!("{}://localhost:{}/{}", scheme, self.addr.port(), uri)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Create `GET` request
|
|
|
|
pub fn get<S: AsRef<str>>(&self, path: S) -> ClientRequest {
|
|
|
|
self.client.get(self.url(path.as_ref()).as_str())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Create `POST` request
|
|
|
|
pub fn post<S: AsRef<str>>(&self, path: S) -> ClientRequest {
|
|
|
|
self.client.post(self.url(path.as_ref()).as_str())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Create `HEAD` request
|
|
|
|
pub fn head<S: AsRef<str>>(&self, path: S) -> ClientRequest {
|
|
|
|
self.client.head(self.url(path.as_ref()).as_str())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Create `PUT` request
|
|
|
|
pub fn put<S: AsRef<str>>(&self, path: S) -> ClientRequest {
|
|
|
|
self.client.put(self.url(path.as_ref()).as_str())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Create `PATCH` request
|
|
|
|
pub fn patch<S: AsRef<str>>(&self, path: S) -> ClientRequest {
|
|
|
|
self.client.patch(self.url(path.as_ref()).as_str())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Create `DELETE` request
|
|
|
|
pub fn delete<S: AsRef<str>>(&self, path: S) -> ClientRequest {
|
|
|
|
self.client.delete(self.url(path.as_ref()).as_str())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Create `OPTIONS` request
|
|
|
|
pub fn options<S: AsRef<str>>(&self, path: S) -> ClientRequest {
|
|
|
|
self.client.options(self.url(path.as_ref()).as_str())
|
|
|
|
}
|
|
|
|
|
2021-02-11 23:39:54 +01:00
|
|
|
/// Connect to test HTTP server
|
2019-12-12 17:28:47 +01:00
|
|
|
pub fn request<S: AsRef<str>>(&self, method: Method, path: S) -> ClientRequest {
|
|
|
|
self.client.request(method, path.as_ref())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn load_body<S>(
|
|
|
|
&mut self,
|
|
|
|
mut response: ClientResponse<S>,
|
|
|
|
) -> Result<Bytes, PayloadError>
|
|
|
|
where
|
|
|
|
S: Stream<Item = Result<Bytes, PayloadError>> + Unpin + 'static,
|
|
|
|
{
|
|
|
|
response.body().limit(10_485_760).await
|
|
|
|
}
|
|
|
|
|
2021-02-12 01:27:20 +01:00
|
|
|
/// Connect to WebSocket server at a given path.
|
2019-12-12 17:28:47 +01:00
|
|
|
pub async fn ws_at(
|
|
|
|
&mut self,
|
|
|
|
path: &str,
|
2021-02-12 00:03:17 +01:00
|
|
|
) -> Result<Framed<impl AsyncRead + AsyncWrite, ws::Codec>, awc::error::WsClientError> {
|
2019-12-12 17:28:47 +01:00
|
|
|
let url = self.url(path);
|
|
|
|
let connect = self.client.ws(url).connect();
|
|
|
|
connect.await.map(|(_, framed)| framed)
|
|
|
|
}
|
|
|
|
|
2021-02-12 01:27:20 +01:00
|
|
|
/// Connect to a WebSocket server.
|
2019-12-12 17:28:47 +01:00
|
|
|
pub async fn ws(
|
|
|
|
&mut self,
|
2021-02-12 00:03:17 +01:00
|
|
|
) -> Result<Framed<impl AsyncRead + AsyncWrite, ws::Codec>, awc::error::WsClientError> {
|
2019-12-12 17:28:47 +01:00
|
|
|
self.ws_at("/").await
|
|
|
|
}
|
|
|
|
|
2021-02-11 23:39:54 +01:00
|
|
|
/// Gracefully stop HTTP server
|
2019-12-25 09:10:28 +01:00
|
|
|
pub async fn stop(self) {
|
|
|
|
self.server.stop(true).await;
|
2019-12-12 17:28:47 +01:00
|
|
|
self.system.stop();
|
2021-01-04 00:47:04 +01:00
|
|
|
sleep(time::Duration::from_millis(100)).await;
|
2019-12-12 17:28:47 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for TestServer {
|
|
|
|
fn drop(&mut self) {
|
2019-12-25 09:10:28 +01:00
|
|
|
self.system.stop()
|
2019-12-12 17:28:47 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-15 04:52:12 +02:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2021-02-11 23:39:54 +01:00
|
|
|
use actix_http::HttpMessage;
|
2019-04-15 04:52:12 +02:00
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use std::time::SystemTime;
|
|
|
|
|
|
|
|
use super::*;
|
2019-12-20 18:18:59 +01:00
|
|
|
use crate::{http::header, web, App, HttpResponse, Responder};
|
2019-04-15 04:52:12 +02:00
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_basics() {
|
2021-01-15 03:11:10 +01:00
|
|
|
let req = TestRequest::default()
|
2019-11-26 06:25:50 +01:00
|
|
|
.version(Version::HTTP_2)
|
2021-01-15 03:11:10 +01:00
|
|
|
.insert_header(header::ContentType::json())
|
|
|
|
.insert_header(header::Date(SystemTime::now().into()))
|
2019-11-26 06:25:50 +01:00
|
|
|
.param("test", "123")
|
|
|
|
.data(10u32)
|
2019-12-20 12:13:09 +01:00
|
|
|
.app_data(20u64)
|
2019-12-20 11:11:51 +01:00
|
|
|
.peer_addr("127.0.0.1:8081".parse().unwrap())
|
2019-11-26 06:25:50 +01:00
|
|
|
.to_http_request();
|
|
|
|
assert!(req.headers().contains_key(header::CONTENT_TYPE));
|
|
|
|
assert!(req.headers().contains_key(header::DATE));
|
2019-12-20 11:11:51 +01:00
|
|
|
assert_eq!(
|
|
|
|
req.head().peer_addr,
|
|
|
|
Some("127.0.0.1:8081".parse().unwrap())
|
|
|
|
);
|
2019-11-26 06:25:50 +01:00
|
|
|
assert_eq!(&req.match_info()["test"], "123");
|
|
|
|
assert_eq!(req.version(), Version::HTTP_2);
|
2019-12-20 12:13:09 +01:00
|
|
|
let data = req.app_data::<Data<u32>>().unwrap();
|
|
|
|
assert!(req.app_data::<Data<u64>>().is_none());
|
2019-11-26 06:25:50 +01:00
|
|
|
assert_eq!(*data.get_ref(), 10);
|
|
|
|
|
2019-12-20 12:13:09 +01:00
|
|
|
assert!(req.app_data::<u32>().is_none());
|
|
|
|
let data = req.app_data::<u64>().unwrap();
|
|
|
|
assert_eq!(*data, 20);
|
2019-11-26 06:25:50 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_request_methods() {
|
2021-02-07 02:00:40 +01:00
|
|
|
let app = init_service(
|
2019-11-26 06:25:50 +01:00
|
|
|
App::new().service(
|
|
|
|
web::resource("/index.html")
|
2020-09-11 12:29:17 +02:00
|
|
|
.route(web::put().to(|| HttpResponse::Ok().body("put!")))
|
|
|
|
.route(web::patch().to(|| HttpResponse::Ok().body("patch!")))
|
|
|
|
.route(web::delete().to(|| HttpResponse::Ok().body("delete!"))),
|
2019-11-26 06:25:50 +01:00
|
|
|
),
|
|
|
|
)
|
|
|
|
.await;
|
2019-11-20 18:33:22 +01:00
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
let put_req = TestRequest::put()
|
|
|
|
.uri("/index.html")
|
2021-01-15 03:11:10 +01:00
|
|
|
.insert_header((header::CONTENT_TYPE, "application/json"))
|
2019-11-26 06:25:50 +01:00
|
|
|
.to_request();
|
2019-11-20 18:33:22 +01:00
|
|
|
|
2021-02-07 02:00:40 +01:00
|
|
|
let result = read_response(&app, put_req).await;
|
2019-11-26 06:25:50 +01:00
|
|
|
assert_eq!(result, Bytes::from_static(b"put!"));
|
2019-11-20 18:33:22 +01:00
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
let patch_req = TestRequest::patch()
|
|
|
|
.uri("/index.html")
|
2021-01-15 03:11:10 +01:00
|
|
|
.insert_header((header::CONTENT_TYPE, "application/json"))
|
2019-11-26 06:25:50 +01:00
|
|
|
.to_request();
|
2019-11-20 18:33:22 +01:00
|
|
|
|
2021-02-07 02:00:40 +01:00
|
|
|
let result = read_response(&app, patch_req).await;
|
2019-11-26 06:25:50 +01:00
|
|
|
assert_eq!(result, Bytes::from_static(b"patch!"));
|
2019-11-20 18:33:22 +01:00
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
let delete_req = TestRequest::delete().uri("/index.html").to_request();
|
2021-02-07 02:00:40 +01:00
|
|
|
let result = read_response(&app, delete_req).await;
|
2019-11-26 06:25:50 +01:00
|
|
|
assert_eq!(result, Bytes::from_static(b"delete!"));
|
2019-04-19 00:06:32 +02:00
|
|
|
}
|
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_response() {
|
2021-02-07 02:00:40 +01:00
|
|
|
let app = init_service(
|
2020-09-11 12:29:17 +02:00
|
|
|
App::new().service(
|
|
|
|
web::resource("/index.html")
|
|
|
|
.route(web::post().to(|| HttpResponse::Ok().body("welcome!"))),
|
|
|
|
),
|
|
|
|
)
|
|
|
|
.await;
|
2019-11-20 18:33:22 +01:00
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
let req = TestRequest::post()
|
|
|
|
.uri("/index.html")
|
2021-01-15 03:11:10 +01:00
|
|
|
.insert_header((header::CONTENT_TYPE, "application/json"))
|
2019-11-26 06:25:50 +01:00
|
|
|
.to_request();
|
2019-11-20 18:33:22 +01:00
|
|
|
|
2021-02-07 02:00:40 +01:00
|
|
|
let result = read_response(&app, req).await;
|
2019-11-26 06:25:50 +01:00
|
|
|
assert_eq!(result, Bytes::from_static(b"welcome!"));
|
2019-04-15 04:52:12 +02:00
|
|
|
}
|
|
|
|
|
2020-04-05 21:12:44 +02:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_send_request() {
|
2021-02-07 02:00:40 +01:00
|
|
|
let app = init_service(
|
2020-09-11 12:29:17 +02:00
|
|
|
App::new().service(
|
|
|
|
web::resource("/index.html")
|
|
|
|
.route(web::get().to(|| HttpResponse::Ok().body("welcome!"))),
|
|
|
|
),
|
|
|
|
)
|
|
|
|
.await;
|
2020-04-05 21:12:44 +02:00
|
|
|
|
|
|
|
let resp = TestRequest::get()
|
|
|
|
.uri("/index.html")
|
2021-02-07 02:00:40 +01:00
|
|
|
.send_request(&app)
|
2020-04-05 21:12:44 +02:00
|
|
|
.await;
|
|
|
|
|
|
|
|
let result = read_body(resp).await;
|
|
|
|
assert_eq!(result, Bytes::from_static(b"welcome!"));
|
|
|
|
}
|
|
|
|
|
2019-04-15 04:52:12 +02:00
|
|
|
#[derive(Serialize, Deserialize)]
|
|
|
|
pub struct Person {
|
|
|
|
id: String,
|
|
|
|
name: String,
|
|
|
|
}
|
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_response_json() {
|
2021-02-07 02:00:40 +01:00
|
|
|
let app = init_service(App::new().service(web::resource("/people").route(
|
2021-01-18 13:14:29 +01:00
|
|
|
web::post().to(|person: web::Json<Person>| HttpResponse::Ok().json(person)),
|
2019-11-26 06:25:50 +01:00
|
|
|
)))
|
|
|
|
.await;
|
|
|
|
|
|
|
|
let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes();
|
|
|
|
|
|
|
|
let req = TestRequest::post()
|
|
|
|
.uri("/people")
|
2021-01-15 03:11:10 +01:00
|
|
|
.insert_header((header::CONTENT_TYPE, "application/json"))
|
2019-11-26 06:25:50 +01:00
|
|
|
.set_payload(payload)
|
|
|
|
.to_request();
|
|
|
|
|
2021-02-07 02:00:40 +01:00
|
|
|
let result: Person = read_response_json(&app, req).await;
|
2019-11-26 06:25:50 +01:00
|
|
|
assert_eq!(&result.id, "12345");
|
|
|
|
}
|
|
|
|
|
2020-04-05 21:12:44 +02:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_body_json() {
|
2021-02-07 02:00:40 +01:00
|
|
|
let app = init_service(App::new().service(web::resource("/people").route(
|
2021-01-18 13:14:29 +01:00
|
|
|
web::post().to(|person: web::Json<Person>| HttpResponse::Ok().json(person)),
|
2020-04-05 21:12:44 +02:00
|
|
|
)))
|
|
|
|
.await;
|
|
|
|
|
|
|
|
let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes();
|
|
|
|
|
|
|
|
let resp = TestRequest::post()
|
|
|
|
.uri("/people")
|
2021-01-15 03:11:10 +01:00
|
|
|
.insert_header((header::CONTENT_TYPE, "application/json"))
|
2020-04-05 21:12:44 +02:00
|
|
|
.set_payload(payload)
|
2021-02-07 02:00:40 +01:00
|
|
|
.send_request(&app)
|
2020-04-05 21:12:44 +02:00
|
|
|
.await;
|
|
|
|
|
|
|
|
let result: Person = read_body_json(resp).await;
|
|
|
|
assert_eq!(&result.name, "User name");
|
|
|
|
}
|
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_request_response_form() {
|
2021-02-07 02:00:40 +01:00
|
|
|
let app = init_service(App::new().service(web::resource("/people").route(
|
2021-01-18 13:14:29 +01:00
|
|
|
web::post().to(|person: web::Form<Person>| HttpResponse::Ok().json(person)),
|
2019-11-26 06:25:50 +01:00
|
|
|
)))
|
|
|
|
.await;
|
|
|
|
|
|
|
|
let payload = Person {
|
|
|
|
id: "12345".to_string(),
|
|
|
|
name: "User name".to_string(),
|
|
|
|
};
|
|
|
|
|
|
|
|
let req = TestRequest::post()
|
|
|
|
.uri("/people")
|
|
|
|
.set_form(&payload)
|
|
|
|
.to_request();
|
|
|
|
|
|
|
|
assert_eq!(req.content_type(), "application/x-www-form-urlencoded");
|
|
|
|
|
2021-02-07 02:00:40 +01:00
|
|
|
let result: Person = read_response_json(&app, req).await;
|
2019-11-26 06:25:50 +01:00
|
|
|
assert_eq!(&result.id, "12345");
|
|
|
|
assert_eq!(&result.name, "User name");
|
|
|
|
}
|
|
|
|
|
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_request_response_json() {
|
2021-02-07 02:00:40 +01:00
|
|
|
let app = init_service(App::new().service(web::resource("/people").route(
|
2021-01-18 13:14:29 +01:00
|
|
|
web::post().to(|person: web::Json<Person>| HttpResponse::Ok().json(person)),
|
2019-11-26 06:25:50 +01:00
|
|
|
)))
|
|
|
|
.await;
|
|
|
|
|
|
|
|
let payload = Person {
|
|
|
|
id: "12345".to_string(),
|
|
|
|
name: "User name".to_string(),
|
|
|
|
};
|
|
|
|
|
|
|
|
let req = TestRequest::post()
|
|
|
|
.uri("/people")
|
|
|
|
.set_json(&payload)
|
|
|
|
.to_request();
|
|
|
|
|
|
|
|
assert_eq!(req.content_type(), "application/json");
|
|
|
|
|
2021-02-07 02:00:40 +01:00
|
|
|
let result: Person = read_response_json(&app, req).await;
|
2019-11-26 06:25:50 +01:00
|
|
|
assert_eq!(&result.id, "12345");
|
|
|
|
assert_eq!(&result.name, "User name");
|
|
|
|
}
|
|
|
|
|
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_async_with_block() {
|
|
|
|
async fn async_with_block() -> Result<HttpResponse, Error> {
|
|
|
|
let res = web::block(move || Some(4usize).ok_or("wrong")).await;
|
|
|
|
|
2019-12-02 18:33:39 +01:00
|
|
|
match res {
|
2019-11-26 06:25:50 +01:00
|
|
|
Ok(value) => Ok(HttpResponse::Ok()
|
|
|
|
.content_type("text/plain")
|
2021-02-06 17:23:59 +01:00
|
|
|
.body(format!("Async with block value: {:?}", value))),
|
2019-11-26 06:25:50 +01:00
|
|
|
Err(_) => panic!("Unexpected"),
|
2019-11-20 18:33:22 +01:00
|
|
|
}
|
2019-11-26 06:25:50 +01:00
|
|
|
}
|
2019-04-29 18:45:37 +02:00
|
|
|
|
2021-02-12 00:03:17 +01:00
|
|
|
let app =
|
|
|
|
init_service(App::new().service(web::resource("/index.html").to(async_with_block)))
|
|
|
|
.await;
|
2019-04-29 18:45:37 +02:00
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
let req = TestRequest::post().uri("/index.html").to_request();
|
|
|
|
let res = app.call(req).await.unwrap();
|
|
|
|
assert!(res.status().is_success());
|
2019-04-29 18:45:37 +02:00
|
|
|
}
|
2019-06-12 12:15:06 +02:00
|
|
|
|
2019-12-20 18:18:59 +01:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_server_data() {
|
|
|
|
async fn handler(data: web::Data<usize>) -> impl Responder {
|
|
|
|
assert_eq!(**data, 10);
|
|
|
|
HttpResponse::Ok()
|
|
|
|
}
|
|
|
|
|
2021-02-07 02:00:40 +01:00
|
|
|
let app = init_service(
|
2019-12-20 18:18:59 +01:00
|
|
|
App::new()
|
|
|
|
.data(10usize)
|
|
|
|
.service(web::resource("/index.html").to(handler)),
|
|
|
|
)
|
|
|
|
.await;
|
|
|
|
|
|
|
|
let req = TestRequest::post().uri("/index.html").to_request();
|
|
|
|
let res = app.call(req).await.unwrap();
|
|
|
|
assert!(res.status().is_success());
|
|
|
|
}
|
2019-03-03 01:24:14 +01:00
|
|
|
}
|