actix_web/test/
mod.rs

1//! Various helpers for Actix applications to use during testing.
2//!
3//! # Initializing A Test Service
4//! - [`init_service`]
5//!
6//! # Off-The-Shelf Test Services
7//! - [`ok_service`]
8//! - [`status_service`]
9//!
10//! # Calling Test Service
11//! - [`TestRequest`]
12//! - [`call_service`]
13//! - [`try_call_service`]
14//! - [`call_and_read_body`]
15//! - [`call_and_read_body_json`]
16//! - [`try_call_and_read_body_json`]
17//!
18//! # Reading Response Payloads
19//! - [`read_body`]
20//! - [`try_read_body`]
21//! - [`read_body_json`]
22//! - [`try_read_body_json`]
23
24// TODO: more docs on generally how testing works with these parts
25
26pub use actix_http::test::TestBuffer;
27
28mod test_request;
29mod test_services;
30mod test_utils;
31
32#[allow(deprecated)]
33pub use self::test_services::{default_service, ok_service, simple_service, status_service};
34#[cfg(test)]
35pub(crate) use self::test_utils::try_init_service;
36#[allow(deprecated)]
37pub use self::test_utils::{read_response, read_response_json};
38pub use self::{
39    test_request::TestRequest,
40    test_utils::{
41        call_and_read_body, call_and_read_body_json, call_service, init_service, read_body,
42        read_body_json, try_call_and_read_body_json, try_call_service, try_read_body,
43        try_read_body_json,
44    },
45};
46
47/// Reduces boilerplate code when testing expected response payloads.
48///
49/// Must be used inside an async test. Works for both `ServiceRequest` and `HttpRequest`.
50///
51/// # Examples
52///
53/// ```
54/// use actix_web::{http::StatusCode, HttpResponse};
55///
56/// let res = HttpResponse::with_body(StatusCode::OK, "http response");
57/// assert_body_eq!(res, b"http response");
58/// ```
59#[cfg(test)]
60macro_rules! assert_body_eq {
61    ($res:ident, $expected:expr) => {
62        assert_eq!(
63            ::actix_http::body::to_bytes($res.into_body())
64                .await
65                .expect("error reading test response body"),
66            ::bytes::Bytes::from_static($expected),
67        )
68    };
69}
70
71#[cfg(test)]
72pub(crate) use assert_body_eq;
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77    use crate::{http::StatusCode, service::ServiceResponse, HttpResponse};
78
79    #[actix_rt::test]
80    async fn assert_body_works_for_service_and_regular_response() {
81        let res = HttpResponse::with_body(StatusCode::OK, "http response");
82        assert_body_eq!(res, b"http response");
83
84        let req = TestRequest::default().to_http_request();
85        let res = HttpResponse::with_body(StatusCode::OK, "service response");
86        let res = ServiceResponse::new(req, res);
87        assert_body_eq!(res, b"service response");
88    }
89}