1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-06-02 13:29:24 +00:00

add scopes

This commit is contained in:
Nikolay Kim 2019-03-03 21:02:01 -08:00
parent 8502c32a3c
commit 34171fa7f5
6 changed files with 1004 additions and 4 deletions

View file

@ -49,6 +49,7 @@ actix-utils = "0.3.0"
actix-http = { git = "https://github.com/actix/actix-http.git" }
actix-router = { git = "https://github.com/actix/actix-net.git" }
#actix-router = { path = "../actix-net/router" }
bytes = "0.4"
derive_more = "0.14"

View file

@ -14,6 +14,7 @@ use futures::future::{ok, Either, FutureResult};
use futures::{Async, Future, IntoFuture, Poll};
use crate::resource::Resource;
use crate::scope::Scope;
use crate::service::{ServiceRequest, ServiceResponse};
use crate::state::{State, StateFactory, StateFactoryResult};
@ -112,6 +113,52 @@ where
self
}
/// Configure scope for common root path.
///
/// Scopes collect multiple paths under a common path prefix.
/// Scope path can contain variable path segments as resources.
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{App, HttpRequest, HttpResponse};
///
/// fn main() {
/// let app = App::new().scope("/{project_id}", |scope| {
/// scope
/// .resource("/path1", |r| r.to(|| HttpResponse::Ok()))
/// .resource("/path2", |r| r.to(|| HttpResponse::Ok()))
/// .resource("/path3", |r| r.to(|| HttpResponse::MethodNotAllowed()))
/// });
/// }
/// ```
///
/// In the above example, three routes get added:
/// * /{project_id}/path1
/// * /{project_id}/path2
/// * /{project_id}/path3
///
pub fn scope<F>(self, path: &str, f: F) -> AppRouter<T, P, Body, AppEntry<P>>
where
F: FnOnce(Scope<P>) -> Scope<P>,
{
let scope = f(Scope::new(path));
let rdef = scope.rdef().clone();
let default = scope.get_default();
let fref = Rc::new(RefCell::new(None));
AppRouter {
chain: self.chain,
services: vec![(rdef, boxed::new_service(scope.into_new_service()))],
default: None,
defaults: vec![default],
endpoint: AppEntry::new(fref.clone()),
factory_ref: fref,
extensions: self.extensions,
state: self.state,
_t: PhantomData,
}
}
/// Configure resource for a specific path.
///
/// Resources may have variable path segments. For example, a
@ -243,6 +290,18 @@ where
_t: PhantomData,
}
}
/// Set server host name.
///
/// Host name is used by application router aa a hostname for url
/// generation. Check [ConnectionInfo](./dev/struct.ConnectionInfo.
/// html#method.host) documentation for more information.
///
/// By default host name is set to a "localhost" value.
pub fn hostname(self, _val: &str) -> Self {
// self.host = val.to_owned();
self
}
}
/// Application router builder - Structure that follows the builder pattern
@ -270,6 +329,42 @@ where
InitError = (),
>,
{
/// Configure scope for common root path.
///
/// Scopes collect multiple paths under a common path prefix.
/// Scope path can contain variable path segments as resources.
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{App, HttpRequest, HttpResponse};
///
/// fn main() {
/// let app = App::new().scope("/{project_id}", |scope| {
/// scope
/// .resource("/path1", |r| r.to(|| HttpResponse::Ok()))
/// .resource("/path2", |r| r.to(|| HttpResponse::Ok()))
/// .resource("/path3", |r| r.to(|| HttpResponse::MethodNotAllowed()))
/// });
/// }
/// ```
///
/// In the above example, three routes get added:
/// * /{project_id}/path1
/// * /{project_id}/path2
/// * /{project_id}/path3
///
pub fn scope<F>(mut self, path: &str, f: F) -> Self
where
F: FnOnce(Scope<P>) -> Scope<P>,
{
let scope = f(Scope::new(path));
let rdef = scope.rdef().clone();
self.defaults.push(scope.get_default());
self.services
.push((rdef, boxed::new_service(scope.into_new_service())));
self
}
/// Configure resource for a specific path.
///
/// Resources may have variable path segments. For example, a
@ -466,6 +561,7 @@ where
// set factory
*self.factory_ref.borrow_mut() = Some(AppRoutingFactory {
default: self.default.clone(),
services: Rc::new(self.services),
});
@ -480,6 +576,7 @@ where
pub struct AppRoutingFactory<P> {
services: Rc<Vec<(ResourceDef, HttpNewService<P>)>>,
default: Option<Rc<HttpNewService<P>>>,
}
impl<P: 'static> NewService for AppRoutingFactory<P> {
@ -491,6 +588,12 @@ impl<P: 'static> NewService for AppRoutingFactory<P> {
type Future = AppRoutingFactoryResponse<P>;
fn new_service(&self, _: &()) -> Self::Future {
let default_fut = if let Some(ref default) = self.default {
Some(default.new_service(&()))
} else {
None
};
AppRoutingFactoryResponse {
fut: self
.services
@ -502,6 +605,8 @@ impl<P: 'static> NewService for AppRoutingFactory<P> {
)
})
.collect(),
default: None,
default_fut,
}
}
}
@ -512,6 +617,8 @@ type HttpServiceFut<P> = Box<Future<Item = HttpService<P>, Error = ()>>;
#[doc(hidden)]
pub struct AppRoutingFactoryResponse<P> {
fut: Vec<CreateAppRoutingItem<P>>,
default: Option<HttpService<P>>,
default_fut: Option<Box<Future<Item = HttpService<P>, Error = ()>>>,
}
enum CreateAppRoutingItem<P> {
@ -526,6 +633,13 @@ impl<P> Future for AppRoutingFactoryResponse<P> {
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let mut done = true;
if let Some(ref mut fut) = self.default_fut {
match fut.poll()? {
Async::Ready(default) => self.default = Some(default),
Async::NotReady => done = false,
}
}
// poll http services
for item in &mut self.fut {
let res = match item {
@ -560,8 +674,9 @@ impl<P> Future for AppRoutingFactoryResponse<P> {
router
});
Ok(Async::Ready(AppRouting {
router: router.finish(),
ready: None,
router: router.finish(),
default: self.default.take(),
}))
} else {
Ok(Async::NotReady)
@ -572,6 +687,7 @@ impl<P> Future for AppRoutingFactoryResponse<P> {
pub struct AppRouting<P> {
router: Router<HttpService<P>>,
ready: Option<(ServiceRequest<P>, ResourceInfo)>,
default: Option<HttpService<P>>,
}
impl<P> Service for AppRouting<P> {
@ -591,6 +707,8 @@ impl<P> Service for AppRouting<P> {
fn call(&mut self, mut req: ServiceRequest<P>) -> Self::Future {
if let Some((srv, _info)) = self.router.recognize_mut(req.match_info_mut()) {
Either::A(srv.call(req))
} else if let Some(ref mut default) = self.default {
Either::A(default.call(req))
} else {
let req = req.into_request();
Either::B(ok(ServiceResponse::new(req, Response::NotFound().finish())))

View file

@ -312,7 +312,9 @@ mod tests {
#[test]
fn test_preds() {
let r = TestRequest::default().method(Method::TRACE).to_request();
let r = TestRequest::default()
.method(Method::TRACE)
.to_http_request();
assert!(Not(Get()).check(&r,));
assert!(!Not(Trace()).check(&r,));

View file

@ -11,6 +11,7 @@ mod request;
mod resource;
mod responder;
mod route;
mod scope;
mod service;
mod state;
pub mod test;
@ -25,6 +26,7 @@ pub use crate::request::HttpRequest;
pub use crate::resource::Resource;
pub use crate::responder::{Either, Responder};
pub use crate::route::Route;
pub use crate::scope::Scope;
pub use crate::service::{ServiceFromRequest, ServiceRequest, ServiceResponse};
pub use crate::state::State;

872
src/scope.rs Normal file
View file

@ -0,0 +1,872 @@
use std::cell::RefCell;
use std::rc::Rc;
use actix_http::Response;
use actix_router::{ResourceDef, ResourceInfo, Router};
use actix_service::boxed::{self, BoxedNewService, BoxedService};
use actix_service::{
ApplyNewService, IntoNewService, IntoNewTransform, NewService, NewTransform, Service,
};
use futures::future::{ok, Either, Future, FutureResult};
use futures::{Async, Poll};
use crate::guard::Guard;
use crate::resource::Resource;
use crate::route::Route;
use crate::service::{ServiceRequest, ServiceResponse};
type HttpService<P> = BoxedService<ServiceRequest<P>, ServiceResponse, ()>;
type HttpNewService<P> = BoxedNewService<(), ServiceRequest<P>, ServiceResponse, (), ()>;
type BoxedResponse = Box<Future<Item = ServiceResponse, Error = ()>>;
/// Resources scope
///
/// Scope is a set of resources with common root path.
/// Scopes collect multiple paths under a common path prefix.
/// Scope path can contain variable path segments as resources.
/// Scope prefix is always complete path segment, i.e `/app` would
/// be converted to a `/app/` and it would not match `/app` path.
///
/// You can get variable path segments from `HttpRequest::match_info()`.
/// `Path` extractor also is able to extract scope level variable segments.
///
/// ```rust
/// use actix_web::{App, HttpResponse};
///
/// fn main() {
/// let app = App::new().scope("/{project_id}/", |scope| {
/// scope
/// .resource("/path1", |r| r.to(|| HttpResponse::Ok()))
/// .resource("/path2", |r| r.to(|| HttpResponse::Ok()))
/// .resource("/path3", |r| r.to(|| HttpResponse::MethodNotAllowed()))
/// });
/// }
/// ```
///
/// In the above example three routes get registered:
/// * /{project_id}/path1 - reponds to all http method
/// * /{project_id}/path2 - `GET` requests
/// * /{project_id}/path3 - `HEAD` requests
///
pub struct Scope<P, T = ScopeEndpoint<P>> {
endpoint: T,
rdef: ResourceDef,
services: Vec<(ResourceDef, HttpNewService<P>)>,
guards: Rc<Vec<Box<Guard>>>,
default: Rc<RefCell<Option<Rc<HttpNewService<P>>>>>,
defaults: Vec<Rc<RefCell<Option<Rc<HttpNewService<P>>>>>>,
factory_ref: Rc<RefCell<Option<ScopeFactory<P>>>>,
}
impl<P: 'static> Scope<P> {
/// Create a new scope
pub fn new(path: &str) -> Scope<P> {
let fref = Rc::new(RefCell::new(None));
let rdef = ResourceDef::prefix(&insert_slash(path));
Scope {
endpoint: ScopeEndpoint::new(fref.clone()),
rdef: rdef.clone(),
guards: Rc::new(Vec::new()),
services: Vec::new(),
default: Rc::new(RefCell::new(None)),
defaults: Vec::new(),
factory_ref: fref,
}
}
}
impl<P: 'static, T> Scope<P, T>
where
T: NewService<
Request = ServiceRequest<P>,
Response = ServiceResponse,
Error = (),
InitError = (),
>,
{
#[inline]
pub(crate) fn rdef(&self) -> &ResourceDef {
&self.rdef
}
/// Add guard to a scope.
///
/// ```rust
/// use actix_web::{web, guard, App, HttpRequest, HttpResponse, extract::Path};
///
/// fn index(data: Path<(String, String)>) -> &'static str {
/// "Welcome!"
/// }
///
/// fn main() {
/// let app = App::new().scope("/app", |scope| {
/// scope
/// .guard(guard::Header("content-type", "text/plain"))
/// .route("/test1",web::get().to(index))
/// .route("/test2", web::post().to(|r: HttpRequest| {
/// HttpResponse::MethodNotAllowed()
/// }))
/// });
/// }
/// ```
pub fn guard<G: Guard + 'static>(mut self, guard: G) -> Self {
Rc::get_mut(&mut self.guards).unwrap().push(Box::new(guard));
self
}
/// Create nested scope.
///
/// ```rust
/// use actix_web::{App, HttpRequest};
///
/// struct AppState;
///
/// fn index(req: HttpRequest) -> &'static str {
/// "Welcome!"
/// }
///
/// fn main() {
/// let app = App::new().scope("/app", |scope| {
/// scope.nested("/v1", |scope| scope.resource("/test1", |r| r.to(index)))
/// });
/// }
/// ```
pub fn nested<F>(mut self, path: &str, f: F) -> Self
where
F: FnOnce(Scope<P>) -> Scope<P>,
{
let scope = f(Scope::new(path));
let rdef = scope.rdef().clone();
self.defaults.push(scope.get_default());
self.services
.push((rdef, boxed::new_service(scope.into_new_service())));
self
}
/// Configure route for a specific path.
///
/// This is a simplified version of the `Scope::resource()` method.
/// This method can not be could multiple times, in that case
/// multiple resources with one route would be registered for same resource path.
///
/// ```rust
/// use actix_web::{web, App, HttpResponse, extract::Path};
///
/// fn index(data: Path<(String, String)>) -> &'static str {
/// "Welcome!"
/// }
///
/// fn main() {
/// let app = App::new().scope("/app", |scope| {
/// scope.route("/test1", web::get().to(index))
/// .route("/test2", web::post().to(|| HttpResponse::MethodNotAllowed()))
/// });
/// }
/// ```
pub fn route(self, path: &str, route: Route<P>) -> Self {
self.resource(path, move |r| r.route(route))
}
/// configure resource for a specific path.
///
/// This method is similar to an `App::resource()` method.
/// Resources may have variable path segments. Resource path uses scope
/// path as a path prefix.
///
/// ```rust
/// use actix_web::*;
///
/// fn main() {
/// let app = App::new().scope("/api", |scope| {
/// scope.resource("/users/{userid}/{friend}", |r| {
/// r.route(web::get().to(|| HttpResponse::Ok()))
/// .route(web::head().to(|| HttpResponse::MethodNotAllowed()))
/// .route(web::route()
/// .guard(guard::Any(guard::Get()).or(guard::Put()))
/// .guard(guard::Header("Content-Type", "text/plain"))
/// .to(|| HttpResponse::Ok()))
/// })
/// });
/// }
/// ```
pub fn resource<F, U>(mut self, path: &str, f: F) -> Self
where
F: FnOnce(Resource<P>) -> Resource<P, U>,
U: NewService<
Request = ServiceRequest<P>,
Response = ServiceResponse,
Error = (),
InitError = (),
> + 'static,
{
// add resource
let rdef = ResourceDef::new(&insert_slash(path));
let resource = f(Resource::new());
self.defaults.push(resource.get_default());
self.services
.push((rdef, boxed::new_service(resource.into_new_service())));
self
}
/// Default resource to be used if no matching route could be found.
pub fn default_resource<F, U>(mut self, f: F) -> Self
where
F: FnOnce(Resource<P>) -> Resource<P, U>,
U: NewService<
Request = ServiceRequest<P>,
Response = ServiceResponse,
Error = (),
InitError = (),
> + 'static,
{
// create and configure default resource
self.default = Rc::new(RefCell::new(Some(Rc::new(boxed::new_service(
f(Resource::new()).into_new_service().map_init_err(|_| ()),
)))));
self
}
/// Register a scope middleware
///
/// This is similar to `App's` middlewares, but
/// middleware is not allowed to change response type (i.e modify response's body).
/// Middleware get invoked on scope level.
pub fn middleware<M, F>(
self,
mw: F,
) -> Scope<
P,
impl NewService<
Request = ServiceRequest<P>,
Response = ServiceResponse,
Error = (),
InitError = (),
>,
>
where
M: NewTransform<
T::Service,
Request = ServiceRequest<P>,
Response = ServiceResponse,
Error = (),
InitError = (),
>,
F: IntoNewTransform<M, T::Service>,
{
let endpoint = ApplyNewService::new(mw, self.endpoint);
Scope {
endpoint,
rdef: self.rdef,
guards: self.guards,
services: self.services,
default: self.default,
defaults: self.defaults,
factory_ref: self.factory_ref,
}
}
pub(crate) fn get_default(&self) -> Rc<RefCell<Option<Rc<HttpNewService<P>>>>> {
self.default.clone()
}
}
fn insert_slash(path: &str) -> String {
let mut path = path.to_owned();
if !path.is_empty() && !path.starts_with('/') {
path.insert(0, '/');
};
path
}
impl<P, T> IntoNewService<T> for Scope<P, T>
where
T: NewService<
Request = ServiceRequest<P>,
Response = ServiceResponse,
Error = (),
InitError = (),
>,
{
fn into_new_service(self) -> T {
// update resource default service
if let Some(ref d) = *self.default.as_ref().borrow() {
for default in &self.defaults {
if default.borrow_mut().is_none() {
*default.borrow_mut() = Some(d.clone());
}
}
}
*self.factory_ref.borrow_mut() = Some(ScopeFactory {
default: self.default.clone(),
services: Rc::new(self.services),
});
self.endpoint
}
}
pub struct ScopeFactory<P> {
services: Rc<Vec<(ResourceDef, HttpNewService<P>)>>,
default: Rc<RefCell<Option<Rc<HttpNewService<P>>>>>,
}
impl<P: 'static> NewService for ScopeFactory<P> {
type Request = ServiceRequest<P>;
type Response = ServiceResponse;
type Error = ();
type InitError = ();
type Service = ScopeService<P>;
type Future = ScopeFactoryResponse<P>;
fn new_service(&self, _: &()) -> Self::Future {
let default_fut = if let Some(ref default) = *self.default.borrow() {
Some(default.new_service(&()))
} else {
None
};
ScopeFactoryResponse {
fut: self
.services
.iter()
.map(|(path, service)| {
CreateScopeServiceItem::Future(
Some(path.clone()),
service.new_service(&()),
)
})
.collect(),
default: None,
default_fut,
}
}
}
/// Create app service
#[doc(hidden)]
pub struct ScopeFactoryResponse<P> {
fut: Vec<CreateScopeServiceItem<P>>,
default: Option<HttpService<P>>,
default_fut: Option<Box<Future<Item = HttpService<P>, Error = ()>>>,
}
type HttpServiceFut<P> = Box<Future<Item = HttpService<P>, Error = ()>>;
enum CreateScopeServiceItem<P> {
Future(Option<ResourceDef>, HttpServiceFut<P>),
Service(ResourceDef, HttpService<P>),
}
impl<P> Future for ScopeFactoryResponse<P> {
type Item = ScopeService<P>;
type Error = ();
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let mut done = true;
if let Some(ref mut fut) = self.default_fut {
match fut.poll()? {
Async::Ready(default) => self.default = Some(default),
Async::NotReady => done = false,
}
}
// poll http services
for item in &mut self.fut {
let res = match item {
CreateScopeServiceItem::Future(ref mut path, ref mut fut) => {
match fut.poll()? {
Async::Ready(service) => Some((path.take().unwrap(), service)),
Async::NotReady => {
done = false;
None
}
}
}
CreateScopeServiceItem::Service(_, _) => continue,
};
if let Some((path, service)) = res {
*item = CreateScopeServiceItem::Service(path, service);
}
}
if done {
let router = self
.fut
.drain(..)
.fold(Router::build(), |mut router, item| {
match item {
CreateScopeServiceItem::Service(path, service) => {
router.rdef(path, service)
}
CreateScopeServiceItem::Future(_, _) => unreachable!(),
}
router
});
Ok(Async::Ready(ScopeService {
router: router.finish(),
default: self.default.take(),
_ready: None,
}))
} else {
Ok(Async::NotReady)
}
}
}
pub struct ScopeService<P> {
router: Router<HttpService<P>>,
default: Option<HttpService<P>>,
_ready: Option<(ServiceRequest<P>, ResourceInfo)>,
}
impl<P> Service for ScopeService<P> {
type Request = ServiceRequest<P>;
type Response = ServiceResponse;
type Error = ();
type Future = Either<BoxedResponse, FutureResult<Self::Response, Self::Error>>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, mut req: ServiceRequest<P>) -> Self::Future {
if let Some((srv, _info)) = self.router.recognize_mut(req.match_info_mut()) {
Either::A(srv.call(req))
} else if let Some(ref mut default) = self.default {
Either::A(default.call(req))
} else {
let req = req.into_request();
Either::B(ok(ServiceResponse::new(req, Response::NotFound().finish())))
}
}
}
#[doc(hidden)]
pub struct ScopeEndpoint<P> {
factory: Rc<RefCell<Option<ScopeFactory<P>>>>,
}
impl<P> ScopeEndpoint<P> {
fn new(factory: Rc<RefCell<Option<ScopeFactory<P>>>>) -> Self {
ScopeEndpoint { factory }
}
}
impl<P: 'static> NewService for ScopeEndpoint<P> {
type Request = ServiceRequest<P>;
type Response = ServiceResponse;
type Error = ();
type InitError = ();
type Service = ScopeService<P>;
type Future = ScopeFactoryResponse<P>;
fn new_service(&self, _: &()) -> Self::Future {
self.factory.borrow_mut().as_mut().unwrap().new_service(&())
}
}
#[cfg(test)]
mod tests {
use actix_http::body::{Body, ResponseBody};
use actix_http::http::{Method, StatusCode};
use actix_service::{IntoNewService, NewService, Service};
use bytes::Bytes;
use crate::test::TestRequest;
use crate::{web, App, HttpRequest, HttpResponse};
#[test]
fn test_scope() {
let mut rt = actix_rt::Runtime::new().unwrap();
let app = App::new()
.scope("/app", |scope| {
scope.resource("/path1", |r| r.to(|| HttpResponse::Ok()))
})
.into_new_service();
let mut srv = rt.block_on(app.new_service(&())).unwrap();
let req = TestRequest::with_uri("/app/path1").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[test]
fn test_scope_root() {
let mut rt = actix_rt::Runtime::new().unwrap();
let app = App::new()
.scope("/app", |scope| {
scope
.resource("", |r| r.to(|| HttpResponse::Ok()))
.resource("/", |r| r.to(|| HttpResponse::Created()))
})
.into_new_service();
let mut srv = rt.block_on(app.new_service(&())).unwrap();
let req = TestRequest::with_uri("/app").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/app/").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
#[test]
fn test_scope_root2() {
let mut rt = actix_rt::Runtime::new().unwrap();
let app = App::new()
.scope("/app/", |scope| {
scope.resource("", |r| r.to(|| HttpResponse::Ok()))
})
.into_new_service();
let mut srv = rt.block_on(app.new_service(&())).unwrap();
let req = TestRequest::with_uri("/app").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let req = TestRequest::with_uri("/app/").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[test]
fn test_scope_root3() {
let mut rt = actix_rt::Runtime::new().unwrap();
let app = App::new()
.scope("/app/", |scope| {
scope.resource("/", |r| r.to(|| HttpResponse::Ok()))
})
.into_new_service();
let mut srv = rt.block_on(app.new_service(&())).unwrap();
let req = TestRequest::with_uri("/app").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let req = TestRequest::with_uri("/app/").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[test]
fn test_scope_route() {
let mut rt = actix_rt::Runtime::new().unwrap();
let app = App::new()
.scope("app", |scope| {
scope.resource("/path1", |r| {
r.route(web::get().to(|| HttpResponse::Ok()))
.route(web::delete().to(|| HttpResponse::Ok()))
})
})
.into_new_service();
let mut srv = rt.block_on(app.new_service(&())).unwrap();
let req = TestRequest::with_uri("/app/path1").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/app/path1")
.method(Method::DELETE)
.to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/app/path1")
.method(Method::POST)
.to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[test]
fn test_scope_route_without_leading_slash() {
let mut rt = actix_rt::Runtime::new().unwrap();
let app = App::new()
.scope("app", |scope| {
scope.resource("path1", |r| {
r.route(web::get().to(|| HttpResponse::Ok()))
.route(web::delete().to(|| HttpResponse::Ok()))
})
})
.into_new_service();
let mut srv = rt.block_on(app.new_service(&())).unwrap();
let req = TestRequest::with_uri("/app/path1").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/app/path1")
.method(Method::DELETE)
.to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/app/path1")
.method(Method::POST)
.to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
// #[test]
// fn test_scope_guard() {
// let mut rt = actix_rt::Runtime::new().unwrap();
// let app = App::new()
// .scope("/app", |scope| {
// scope
// .guard(guard::Get())
// .resource("/path1", |r| r.to(|| HttpResponse::Ok()))
// })
// .into_new_service();
// let mut srv = rt.block_on(app.new_service(&())).unwrap();
// let req = TestRequest::with_uri("/app/path1")
// .method(Method::POST)
// .to_request();
// let resp = rt.block_on(srv.call(req)).unwrap();
// assert_eq!(resp.status(), StatusCode::NOT_FOUND);
// let req = TestRequest::with_uri("/app/path1")
// .method(Method::GET)
// .to_request();
// let resp = rt.block_on(srv.call(req)).unwrap();
// assert_eq!(resp.status(), StatusCode::OK);
// }
#[test]
fn test_scope_variable_segment() {
let mut rt = actix_rt::Runtime::new().unwrap();
let app = App::new()
.scope("/ab-{project}", |scope| {
scope.resource("/path1", |r| {
r.to(|r: HttpRequest| {
HttpResponse::Ok()
.body(format!("project: {}", &r.match_info()["project"]))
})
})
})
.into_new_service();
let mut srv = rt.block_on(app.new_service(&())).unwrap();
let req = TestRequest::with_uri("/ab-project1/path1").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
match resp.body() {
ResponseBody::Body(Body::Bytes(ref b)) => {
let bytes: Bytes = b.clone().into();
assert_eq!(bytes, Bytes::from_static(b"project: project1"));
}
_ => panic!(),
}
let req = TestRequest::with_uri("/aa-project1/path1").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[test]
fn test_nested_scope() {
let mut rt = actix_rt::Runtime::new().unwrap();
let app = App::new()
.scope("/app", |scope| {
scope.nested("/t1", |scope| {
scope.resource("/path1", |r| r.to(|| HttpResponse::Created()))
})
})
.into_new_service();
let mut srv = rt.block_on(app.new_service(&())).unwrap();
let req = TestRequest::with_uri("/app/t1/path1").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
#[test]
fn test_nested_scope_no_slash() {
let mut rt = actix_rt::Runtime::new().unwrap();
let app = App::new()
.scope("/app", |scope| {
scope.nested("t1", |scope| {
scope.resource("/path1", |r| r.to(|| HttpResponse::Created()))
})
})
.into_new_service();
let mut srv = rt.block_on(app.new_service(&())).unwrap();
let req = TestRequest::with_uri("/app/t1/path1").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
#[test]
fn test_nested_scope_root() {
let mut rt = actix_rt::Runtime::new().unwrap();
let app = App::new()
.scope("/app", |scope| {
scope.nested("/t1", |scope| {
scope
.resource("", |r| r.to(|| HttpResponse::Ok()))
.resource("/", |r| r.to(|| HttpResponse::Created()))
})
})
.into_new_service();
let mut srv = rt.block_on(app.new_service(&())).unwrap();
let req = TestRequest::with_uri("/app/t1").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/app/t1/").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
// #[test]
// fn test_nested_scope_filter() {
// let app = App::new()
// .scope("/app", |scope| {
// scope.nested("/t1", |scope| {
// scope
// .filter(pred::Get())
// .resource("/path1", |r| r.f(|_| HttpResponse::Ok()))
// })
// })
// .finish();
// let req = TestRequest::with_uri("/app/t1/path1")
// .method(Method::POST)
// .request();
// let resp = app.run(req);
// assert_eq!(resp.as_msg().status(), StatusCode::NOT_FOUND);
// let req = TestRequest::with_uri("/app/t1/path1")
// .method(Method::GET)
// .request();
// let resp = app.run(req);
// assert_eq!(resp.as_msg().status(), StatusCode::OK);
// }
#[test]
fn test_nested_scope_with_variable_segment() {
let mut rt = actix_rt::Runtime::new().unwrap();
let app = App::new()
.scope("/app", |scope| {
scope.nested("/{project_id}", |scope| {
scope.resource("/path1", |r| {
r.to(|r: HttpRequest| {
HttpResponse::Created().body(format!(
"project: {}",
&r.match_info()["project_id"]
))
})
})
})
})
.into_new_service();
let mut srv = rt.block_on(app.new_service(&())).unwrap();
let req = TestRequest::with_uri("/app/project_1/path1").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
match resp.body() {
ResponseBody::Body(Body::Bytes(ref b)) => {
let bytes: Bytes = b.clone().into();
assert_eq!(bytes, Bytes::from_static(b"project: project_1"));
}
_ => panic!(),
}
}
#[test]
fn test_nested2_scope_with_variable_segment() {
let mut rt = actix_rt::Runtime::new().unwrap();
let app = App::new()
.scope("/app", |scope| {
scope.nested("/{project}", |scope| {
scope.nested("/{id}", |scope| {
scope.resource("/path1", |r| {
r.to(|r: HttpRequest| {
HttpResponse::Created().body(format!(
"project: {} - {}",
&r.match_info()["project"],
&r.match_info()["id"],
))
})
})
})
})
})
.into_new_service();
let mut srv = rt.block_on(app.new_service(&())).unwrap();
let req = TestRequest::with_uri("/app/test/1/path1").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
match resp.body() {
ResponseBody::Body(Body::Bytes(ref b)) => {
let bytes: Bytes = b.clone().into();
assert_eq!(bytes, Bytes::from_static(b"project: test - 1"));
}
_ => panic!(),
}
let req = TestRequest::with_uri("/app/test/1/path2").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[test]
fn test_default_resource() {
let mut rt = actix_rt::Runtime::new().unwrap();
let app = App::new()
.scope("/app", |scope| {
scope
.resource("/path1", |r| r.to(|| HttpResponse::Ok()))
.default_resource(|r| r.to(|| HttpResponse::BadRequest()))
})
.into_new_service();
let mut srv = rt.block_on(app.new_service(&())).unwrap();
let req = TestRequest::with_uri("/app/path2").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let req = TestRequest::with_uri("/path2").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[test]
fn test_default_resource_propagation() {
let mut rt = actix_rt::Runtime::new().unwrap();
let app = App::new()
.scope("/app1", |scope| {
scope.default_resource(|r| r.to(|| HttpResponse::BadRequest()))
})
.scope("/app2", |scope| scope)
.default_resource(|r| r.to(|| HttpResponse::MethodNotAllowed()))
.into_new_service();
let mut srv = rt.block_on(app.new_service(&())).unwrap();
let req = TestRequest::with_uri("/non-exist").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
let req = TestRequest::with_uri("/app1/non-exist").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let req = TestRequest::with_uri("/app2/non-exist").to_request();
let resp = rt.block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
}
}

View file

@ -4,7 +4,7 @@ use std::rc::Rc;
use actix_http::http::header::{Header, HeaderName, IntoHeaderValue};
use actix_http::http::{HttpTryFrom, Method, Version};
use actix_http::test::TestRequest as HttpTestRequest;
use actix_http::{Extensions, PayloadStream};
use actix_http::{Extensions, PayloadStream, Request};
use actix_router::{Path, Url};
use bytes::Bytes;
@ -135,8 +135,13 @@ impl TestRequest {
)
}
/// Complete request creation and generate `Request` instance
pub fn to_request(mut self) -> Request<PayloadStream> {
self.req.finish()
}
/// Complete request creation and generate `HttpRequest` instance
pub fn to_request(mut self) -> HttpRequest {
pub fn to_http_request(mut self) -> HttpRequest {
let req = self.req.finish();
ServiceRequest::new(