1use std::{borrow::Cow, net::SocketAddr, rc::Rc};
2
3use actix_http::{test::TestRequest as HttpTestRequest, Request};
4use serde::Serialize;
5
6#[cfg(feature = "cookies")]
7use crate::cookie::Cookie;
8use crate::{
9 app_service::AppInitServiceState,
10 config::AppConfig,
11 data::Data,
12 dev::{Extensions, Path, Payload, ResourceDef, Service, Url},
13 http::{
14 header::{ContentType, TryIntoHeaderPair},
15 Method, Uri, Version,
16 },
17 rmap::ResourceMap,
18 service::{ServiceRequest, ServiceResponse},
19 test,
20 web::Bytes,
21 HttpRequest, HttpResponse,
22};
23
24pub struct TestRequest {
62 req: HttpTestRequest,
63 rmap: ResourceMap,
64 config: AppConfig,
65 path: Path<Url>,
66 peer_addr: Option<SocketAddr>,
67 app_data: Extensions,
68 #[cfg(any(feature = "cookies", feature = "cookies-0_18"))]
69 cookies: Vec<RequestCookie>,
70}
71
72#[cfg(any(feature = "cookies", feature = "cookies-0_18"))]
73enum RequestCookie {
74 #[cfg(feature = "cookies")]
75 V0_16(Cookie<'static>),
76 #[cfg(feature = "cookies-0_18")]
77 V0_18(cookie_0_18::Cookie<'static>),
78}
79
80#[cfg(any(feature = "cookies", feature = "cookies-0_18"))]
81impl RequestCookie {
82 fn name(&self) -> &str {
83 match self {
84 #[cfg(feature = "cookies")]
85 Self::V0_16(cookie) => cookie.name(),
86 #[cfg(feature = "cookies-0_18")]
87 Self::V0_18(cookie) => cookie.name(),
88 }
89 }
90
91 fn encoded_pair(&self) -> String {
92 match self {
93 #[cfg(feature = "cookies")]
94 Self::V0_16(cookie) => cookie.stripped().encoded().to_string(),
95 #[cfg(feature = "cookies-0_18")]
96 Self::V0_18(cookie) => cookie.stripped().encoded().to_string(),
97 }
98 }
99}
100
101impl Default for TestRequest {
102 fn default() -> TestRequest {
103 TestRequest {
104 req: HttpTestRequest::default(),
105 rmap: ResourceMap::new(ResourceDef::new("")),
106 config: AppConfig::default(),
107 path: Path::new(Url::new(Uri::default())),
108 peer_addr: None,
109 app_data: Extensions::new(),
110 #[cfg(any(feature = "cookies", feature = "cookies-0_18"))]
111 cookies: Vec::new(),
112 }
113 }
114}
115
116#[allow(clippy::wrong_self_convention)]
117impl TestRequest {
118 pub fn with_uri(uri: &str) -> TestRequest {
120 TestRequest::default().uri(uri)
121 }
122
123 pub fn get() -> TestRequest {
125 TestRequest::default().method(Method::GET)
126 }
127
128 pub fn post() -> TestRequest {
130 TestRequest::default().method(Method::POST)
131 }
132
133 pub fn put() -> TestRequest {
135 TestRequest::default().method(Method::PUT)
136 }
137
138 pub fn patch() -> TestRequest {
140 TestRequest::default().method(Method::PATCH)
141 }
142
143 pub fn query() -> TestRequest {
146 TestRequest::default().method(Method::from_bytes(b"QUERY").unwrap())
147 }
148
149 pub fn delete() -> TestRequest {
151 TestRequest::default().method(Method::DELETE)
152 }
153
154 pub fn version(mut self, ver: Version) -> Self {
156 self.req.version(ver);
157 self
158 }
159
160 pub fn method(mut self, meth: Method) -> Self {
162 self.req.method(meth);
163 self
164 }
165
166 pub fn uri(mut self, path: &str) -> Self {
168 self.req.uri(path);
169 self
170 }
171
172 pub fn insert_header(mut self, header: impl TryIntoHeaderPair) -> Self {
174 self.req.insert_header(header);
175 self
176 }
177
178 pub fn append_header(mut self, header: impl TryIntoHeaderPair) -> Self {
180 self.req.append_header(header);
181 self
182 }
183
184 #[cfg(feature = "cookies")]
189 pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {
190 self.set_cookie(RequestCookie::V0_16(cookie.into_owned()));
191 self
192 }
193
194 #[cfg(feature = "cookies-0_18")]
199 pub fn cookie_0_18(mut self, cookie: cookie_0_18::Cookie<'_>) -> Self {
200 self.set_cookie(RequestCookie::V0_18(cookie.into_owned()));
201 self
202 }
203
204 #[cfg(any(feature = "cookies", feature = "cookies-0_18"))]
205 fn set_cookie(&mut self, cookie: RequestCookie) {
206 if let Some(existing) = self
207 .cookies
208 .iter_mut()
209 .find(|item| item.name() == cookie.name())
210 {
211 *existing = cookie;
212 } else {
213 self.cookies.push(cookie);
214 }
215 }
216
217 pub fn param(
228 mut self,
229 name: impl Into<Cow<'static, str>>,
230 value: impl Into<Cow<'static, str>>,
231 ) -> Self {
232 self.path.add_static(name, value);
233 self
234 }
235
236 pub fn peer_addr(mut self, addr: SocketAddr) -> Self {
238 self.peer_addr = Some(addr);
239 self
240 }
241
242 pub fn set_payload(mut self, data: impl Into<Bytes>) -> Self {
244 self.req.set_payload(data);
245 self
246 }
247
248 pub fn set_form(mut self, data: impl Serialize) -> Self {
252 let bytes = serde_urlencoded::to_string(&data)
253 .expect("Failed to serialize test data as a URL-encoded form");
254 self.req.set_payload(bytes);
255 self.req.insert_header(ContentType::form_url_encoded());
256 self
257 }
258
259 pub fn set_json(mut self, data: impl Serialize) -> Self {
263 let bytes = serde_json::to_string(&data).expect("Failed to serialize test data to json");
264 self.req.set_payload(bytes);
265 self.req.insert_header(ContentType::json());
266 self
267 }
268
269 pub fn app_data<T: 'static>(mut self, data: T) -> Self {
273 self.app_data.insert(data);
274 self
275 }
276
277 #[doc(hidden)]
281 pub fn data<T: 'static>(mut self, data: T) -> Self {
282 self.app_data.insert(Data::new(data));
283 self
284 }
285
286 #[cfg(test)]
288 pub(crate) fn rmap(mut self, rmap: ResourceMap) -> Self {
289 self.rmap = rmap;
290 self
291 }
292
293 fn finish(&mut self) -> Request {
297 #[allow(unused_mut)]
299 let mut req = self.req.finish();
300
301 #[cfg(any(feature = "cookies", feature = "cookies-0_18"))]
302 {
303 use actix_http::header::{HeaderValue, COOKIE};
304
305 let cookie = self
306 .cookies
307 .iter()
308 .map(RequestCookie::encoded_pair)
309 .collect::<Vec<_>>()
310 .join("; ");
311
312 if !cookie.is_empty() {
313 req.headers_mut()
314 .insert(COOKIE, HeaderValue::from_str(&cookie).unwrap());
315 }
316 }
317
318 req
319 }
320
321 pub fn to_request(mut self) -> Request {
323 let mut req = self.finish();
324 req.head_mut().peer_addr = self.peer_addr;
325 req
326 }
327
328 pub fn to_srv_request(mut self) -> ServiceRequest {
330 let (mut head, payload) = self.finish().into_parts();
331 head.peer_addr = self.peer_addr;
332 self.path.get_mut().update(&head.uri);
333
334 let app_state =
335 AppInitServiceState::new_without_pool(Rc::new(self.rmap), self.config.clone());
336
337 ServiceRequest::new(
338 HttpRequest::new(
339 self.path,
340 head,
341 app_state,
342 Rc::new(self.app_data),
343 None,
344 Default::default(),
345 ),
346 payload,
347 )
348 }
349
350 pub fn to_srv_response<B>(self, res: HttpResponse<B>) -> ServiceResponse<B> {
352 self.to_srv_request().into_response(res)
353 }
354
355 pub fn to_http_request(mut self) -> HttpRequest {
357 let (mut head, _) = self.finish().into_parts();
358 head.peer_addr = self.peer_addr;
359 self.path.get_mut().update(&head.uri);
360
361 let app_state =
362 AppInitServiceState::new_without_pool(Rc::new(self.rmap), self.config.clone());
363
364 HttpRequest::new(
365 self.path,
366 head,
367 app_state,
368 Rc::new(self.app_data),
369 None,
370 Default::default(),
371 )
372 }
373
374 pub fn to_http_parts(mut self) -> (HttpRequest, Payload) {
376 let (mut head, payload) = self.finish().into_parts();
377 head.peer_addr = self.peer_addr;
378 self.path.get_mut().update(&head.uri);
379
380 let app_state =
381 AppInitServiceState::new_without_pool(Rc::new(self.rmap), self.config.clone());
382
383 let req = HttpRequest::new(
384 self.path,
385 head,
386 app_state,
387 Rc::new(self.app_data),
388 None,
389 Default::default(),
390 );
391
392 (req, payload)
393 }
394
395 pub async fn send_request<S, B, E>(self, app: &S) -> S::Response
397 where
398 S: Service<Request, Response = ServiceResponse<B>, Error = E>,
399 E: std::fmt::Debug,
400 {
401 let req = self.to_request();
402 test::call_service(app, req).await
403 }
404
405 #[cfg(test)]
406 pub fn set_server_hostname(&mut self, host: &str) {
407 self.config.set_host(host)
408 }
409}
410
411#[cfg(test)]
412mod tests {
413 use std::{sync::Arc, time::SystemTime};
414
415 use super::*;
416 use crate::{http::header, test::init_service, web, App, Error, Responder};
417
418 #[cfg(feature = "cookies")]
419 #[tokio::test(flavor = "local")]
420 async fn request_cookie_omits_attributes() {
421 let cookie = Cookie::build("session", "hello world")
422 .path("/app")
423 .http_only(true)
424 .finish();
425 let req = TestRequest::default().cookie(cookie).to_http_request();
426
427 assert_eq!(
428 req.headers().get(header::COOKIE).unwrap(),
429 "session=hello%20world"
430 );
431 }
432
433 #[tokio::test(flavor = "local")]
434 async fn test_request_app_data_is_dropped() {
435 fn assert_dropped(make_request: impl FnOnce(TestRequest)) {
436 let data = Arc::new(());
437 let weak = Arc::downgrade(&data);
438 make_request(TestRequest::default().app_data(Data::new(data)));
439 assert!(weak.upgrade().is_none());
440 }
441
442 assert_dropped(|req| drop(req.to_srv_request()));
443 assert_dropped(|req| drop(req.to_http_request()));
444 assert_dropped(|req| drop(req.to_http_parts()));
445 }
446
447 #[tokio::test(flavor = "local")]
448 async fn test_basics() {
449 let req = TestRequest::default()
450 .version(Version::HTTP_2)
451 .insert_header(header::ContentType::json())
452 .insert_header(header::Date(SystemTime::now().into()))
453 .param("test", "123")
454 .data(10u32)
455 .app_data(20u64)
456 .peer_addr("127.0.0.1:8081".parse().unwrap())
457 .to_http_request();
458 assert!(req.headers().contains_key(header::CONTENT_TYPE));
459 assert!(req.headers().contains_key(header::DATE));
460 assert_eq!(
461 req.head().peer_addr,
462 Some("127.0.0.1:8081".parse().unwrap())
463 );
464 assert_eq!(&req.match_info()["test"], "123");
465 assert_eq!(req.version(), Version::HTTP_2);
466 let data = req.app_data::<Data<u32>>().unwrap();
467 assert!(req.app_data::<Data<u64>>().is_none());
468 assert_eq!(*data.get_ref(), 10);
469
470 assert!(req.app_data::<u32>().is_none());
471 let data = req.app_data::<u64>().unwrap();
472 assert_eq!(*data, 20);
473 }
474
475 #[tokio::test(flavor = "local")]
476 async fn test_send_request() {
477 let app = init_service(
478 App::new().service(
479 web::resource("/index.html")
480 .route(web::get().to(|| HttpResponse::Ok().body("welcome!"))),
481 ),
482 )
483 .await;
484
485 let resp = TestRequest::get()
486 .uri("/index.html")
487 .send_request(&app)
488 .await;
489
490 let result = test::read_body(resp).await;
491 assert_eq!(result, Bytes::from_static(b"welcome!"));
492 }
493
494 #[tokio::test(flavor = "local")]
495 async fn test_async_with_block() {
496 async fn async_with_block() -> Result<HttpResponse, Error> {
497 let res = web::block(move || Some(4usize).ok_or("wrong")).await;
498
499 match res {
500 Ok(value) => Ok(HttpResponse::Ok()
501 .content_type("text/plain")
502 .body(format!("Async with block value: {:?}", value))),
503 Err(_) => panic!("Unexpected"),
504 }
505 }
506
507 let app =
508 init_service(App::new().service(web::resource("/index.html").to(async_with_block)))
509 .await;
510
511 let req = TestRequest::post().uri("/index.html").to_request();
512 let res = app.call(req).await.unwrap();
513 assert!(res.status().is_success());
514 }
515
516 #[allow(deprecated)]
518 #[tokio::test(flavor = "local")]
519 async fn test_server_data() {
520 async fn handler(data: web::Data<usize>) -> impl Responder {
521 assert_eq!(**data, 10);
522 HttpResponse::Ok()
523 }
524
525 let app = init_service(
526 App::new()
527 .data(10usize)
528 .service(web::resource("/index.html").to(handler)),
529 )
530 .await;
531
532 let req = TestRequest::post().uri("/index.html").to_request();
533 let res = app.call(req).await.unwrap();
534 assert!(res.status().is_success());
535 }
536}