From f4b4875cb12d1bd7c880b76258d1f80b376c70da Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Mon, 29 Apr 2019 09:34:14 -0700 Subject: [PATCH] Add helper function for executing futures test::block_fn() --- CHANGES.md | 5 +++++ src/app.rs | 6 ++++-- src/test.rs | 25 +++++++++++++++++++++---- 3 files changed, 30 insertions(+), 6 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 53ff98cc4..3b7a30e20 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,10 @@ # Changes +### Added + +* Add helper function for executing futures `test::block_fn()` + + ### Changed * Allow to construct `Data` instances to avoid double `Arc` for `Send + Sync` types. diff --git a/src/app.rs b/src/app.rs index 0e306a00b..7e5cd3945 100644 --- a/src/app.rs +++ b/src/app.rs @@ -445,7 +445,9 @@ mod tests { use super::*; use crate::http::{header, HeaderValue, Method, StatusCode}; use crate::service::{ServiceRequest, ServiceResponse}; - use crate::test::{block_on, call_service, init_service, read_body, TestRequest}; + use crate::test::{ + block_fn, block_on, call_service, init_service, read_body, TestRequest, + }; use crate::{web, Error, HttpRequest, HttpResponse}; #[test] @@ -454,7 +456,7 @@ mod tests { App::new().service(web::resource("/test").to(|| HttpResponse::Ok())), ); let req = TestRequest::with_uri("/test").to_request(); - let resp = block_on(srv.call(req)).unwrap(); + let resp = block_fn(|| srv.call(req)).unwrap(); assert_eq!(resp.status(), StatusCode::OK); let req = TestRequest::with_uri("/blah").to_request(); diff --git a/src/test.rs b/src/test.rs index dc55df639..2fc3e2a74 100644 --- a/src/test.rs +++ b/src/test.rs @@ -12,10 +12,8 @@ use actix_rt::Runtime; use actix_server_config::ServerConfig; use actix_service::{FnService, IntoNewService, NewService, Service}; use bytes::{Bytes, BytesMut}; -use futures::{ - future::{lazy, ok, Future}, - stream::Stream, -}; +use futures::future::{lazy, ok, Future, IntoFuture}; +use futures::Stream; use serde::de::DeserializeOwned; use serde_json; @@ -52,6 +50,25 @@ where RT.with(move |rt| rt.borrow_mut().block_on(f)) } +/// Runs the provided function, blocking the current thread until the resul +/// 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: F) -> Result +where + F: FnOnce() -> R, + R: IntoFuture, +{ + RT.with(move |rt| rt.borrow_mut().block_on(f().into_future())) +} + +#[doc(hidden)] /// Runs the provided function, with runtime enabled. /// /// Note that this function is intended to be used only for testing purpose.