actix_web_lab/
test_response_macros.rs1#[macro_export]
52macro_rules! assert_response_matches {
53 ($res:ident, $status:ident) => {{
54 assert_eq!($res.status(), ::actix_web::http::StatusCode::$status)
55 }};
56
57 ($res:ident, $status:ident; $($hdr_name:expr => $hdr_val:expr)+) => {{
58 assert_response_matches!($res, $status);
59
60 $(
61 assert_eq!(
62 $res.headers().get(::actix_web::http::header::HeaderName::from_static($hdr_name)).unwrap(),
63 &::actix_web::http::header::HeaderValue::from_static($hdr_val),
64 );
65 )+
66 }};
67
68 ($res:ident, $status:ident; @raw $payload:expr) => {{
69 assert_response_matches!($res, $status);
70 assert_eq!(::actix_web::test::read_body($res).await, $payload);
71 }};
72
73 ($res:ident, $status:ident; $($hdr_name:expr => $hdr_val:expr)+; @raw $payload:expr) => {{
74 assert_response_matches!($res, $status; $($hdr_name => $hdr_val)+);
75 assert_eq!(::actix_web::test::read_body($res).await, $payload);
76 }};
77
78 ($res:ident, $status:ident; @json $payload:tt) => {{
79 assert_response_matches!($res, $status);
80 assert_eq!(
81 ::actix_web::test::read_body_json::<$crate::__reexports::serde_json::Value, _>($res).await,
82 $crate::__reexports::serde_json::json!($payload),
83 );
84 }};
85}
86
87pub use assert_response_matches;
88
89#[cfg(test)]
90mod tests {
91 use actix_web::{
92 HttpResponse, dev::ServiceResponse, http::header::ContentType, test::TestRequest,
93 };
94
95 #[actix_web::test]
96 async fn response_matching() {
97 let res = ServiceResponse::new(
98 TestRequest::default().to_http_request(),
99 HttpResponse::Created()
100 .insert_header(("date", "today"))
101 .insert_header(("set-cookie", "a=b"))
102 .body("Hello World!"),
103 );
104
105 assert_response_matches!(res, CREATED);
106 assert_response_matches!(res, CREATED; "date" => "today");
107 assert_response_matches!(res, CREATED; @raw "Hello World!");
108
109 let res = ServiceResponse::new(
110 TestRequest::default().to_http_request(),
111 HttpResponse::Created()
112 .insert_header(("date", "today"))
113 .insert_header(("set-cookie", "a=b"))
114 .body("Hello World!"),
115 );
116 assert_response_matches!(res, CREATED;
117 "date" => "today"
118 "set-cookie" => "a=b";
119 @raw "Hello World!"
120 );
121
122 let res = ServiceResponse::new(
123 TestRequest::default().to_http_request(),
124 HttpResponse::Created()
125 .content_type(ContentType::json())
126 .insert_header(("date", "today"))
127 .insert_header(("set-cookie", "a=b"))
128 .body(r#"{"abc":"123"}"#),
129 );
130
131 assert_response_matches!(res, CREATED; @json { "abc": "123" });
132 }
133}