From 4cfc3fd5705fa0c951f69ab04a95a1a2d5a31b72 Mon Sep 17 00:00:00 2001 From: dowwie Date: Sun, 14 Apr 2019 16:22:33 -0400 Subject: [PATCH] added read_response_json for testing --- src/test.rs | 49 ++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/src/test.rs b/src/test.rs index 7cdf44854..16f24aa2f 100644 --- a/src/test.rs +++ b/src/test.rs @@ -11,14 +11,19 @@ use actix_router::{Path, ResourceDef, Url}; use actix_rt::Runtime; use actix_server_config::ServerConfig; use actix_service::{FnService, IntoNewService, NewService, Service}; -use bytes::Bytes; -use futures::future::{lazy, Future}; +use bytes::{Bytes, BytesMut}; +use futures::{ + future::{lazy, ok, Future}, + stream::Stream, +}; +use serde::de::DeserializeOwned; +use serde_json; pub use actix_http::test::TestBuffer; use crate::config::{AppConfig, AppConfigInner}; use crate::data::RouteData; -use crate::dev::{Body, Payload}; +use crate::dev::{Body, MessageBody, Payload}; use crate::request::HttpRequestPool; use crate::rmap::ResourceMap; use crate::service::{ServiceRequest, ServiceResponse}; @@ -363,4 +368,42 @@ impl TestRequest { { block_on(f) } + + /// Helper function that returns a deserialized response body of a TestRequest + /// This function blocks the current thread until futures complete. + /// + /// ```rust + /// use actix_web::{App, test}; + /// + /// let mut app = test::init_service(App::new()); + /// let payload = r#"{"id":"12345","name":"Nikolay Kim"}"#.as_bytes(); + /// + /// let req = test::TestRequest::post() + /// .uri("/people") + /// .header(header::CONTENT_TYPE, "application/json") + /// .set_payload(payload) + /// .to_request(); + /// + /// let result = read_response_json<_, _, _, serde_json::Value>(&mut app, req); + /// ``` + pub fn read_response_json(app: &mut S, req: R) -> T + where + B: MessageBody, + S: Service, Error = Error>, + T: DeserializeOwned, + { + block_on(app.call(req).and_then(|mut resp: ServiceResponse| { + resp.take_body() + .fold(BytesMut::new(), move |mut body, chunk| { + body.extend_from_slice(&chunk); + Ok::<_, Error>(body) + }) + .and_then(|body: BytesMut| { + ok(serde_json::from_slice(&body).unwrap_or_else(|_| { + panic!("read_response_json failed during deserialization") + })) + }) + })) + .unwrap_or_else(|_| panic!("read_response_json failed at block_on unwrap")) + } }