1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
use std::error::Error as StdError;

use actix_http::Request;
use actix_service::IntoServiceFactory;
use serde::de::DeserializeOwned;

use crate::{
    body::{self, MessageBody},
    config::AppConfig,
    dev::{Service, ServiceFactory},
    service::ServiceResponse,
    web::Bytes,
    Error,
};

/// Initialize service from application builder instance.
///
/// # Examples
/// ```
/// use actix_service::Service;
/// use actix_web::{test, web, App, HttpResponse, http::StatusCode};
///
/// #[actix_web::test]
/// async fn test_init_service() {
///     let app = test::init_service(
///         App::new()
///             .service(web::resource("/test").to(|| async { "OK" }))
///     ).await;
///
///     // Create request object
///     let req = test::TestRequest::with_uri("/test").to_request();
///
///     // Execute application
///     let res = app.call(req).await.unwrap();
///     assert_eq!(res.status(), StatusCode::OK);
/// }
/// ```
///
/// # Panics
/// Panics if service initialization returns an error.
pub async fn init_service<R, S, B, E>(
    app: R,
) -> impl Service<Request, Response = ServiceResponse<B>, Error = E>
where
    R: IntoServiceFactory<S, Request>,
    S: ServiceFactory<Request, Config = AppConfig, Response = ServiceResponse<B>, Error = E>,
    S::InitError: std::fmt::Debug,
{
    try_init_service(app)
        .await
        .expect("service initialization failed")
}

/// Fallible version of [`init_service`] that allows testing initialization errors.
pub(crate) async fn try_init_service<R, S, B, E>(
    app: R,
) -> Result<impl Service<Request, Response = ServiceResponse<B>, Error = E>, S::InitError>
where
    R: IntoServiceFactory<S, Request>,
    S: ServiceFactory<Request, Config = AppConfig, Response = ServiceResponse<B>, Error = E>,
    S::InitError: std::fmt::Debug,
{
    let srv = app.into_factory();
    srv.new_service(AppConfig::default()).await
}

/// Calls service and waits for response future completion.
///
/// # Examples
/// ```
/// use actix_web::{test, web, App, HttpResponse, http::StatusCode};
///
/// #[actix_web::test]
/// async fn test_response() {
///     let app = test::init_service(
///         App::new()
///             .service(web::resource("/test").to(|| async {
///                 HttpResponse::Ok()
///             }))
///     ).await;
///
///     // Create request object
///     let req = test::TestRequest::with_uri("/test").to_request();
///
///     // Call application
///     let res = test::call_service(&app, req).await;
///     assert_eq!(res.status(), StatusCode::OK);
/// }
/// ```
///
/// # Panics
/// Panics if service call returns error. To handle errors use `app.call(req)`.
pub async fn call_service<S, R, B, E>(app: &S, req: R) -> S::Response
where
    S: Service<R, Response = ServiceResponse<B>, Error = E>,
    E: std::fmt::Debug,
{
    app.call(req)
        .await
        .expect("test service call returned error")
}

/// Fallible version of [`call_service`] that allows testing response completion errors.
pub async fn try_call_service<S, R, B, E>(app: &S, req: R) -> Result<S::Response, E>
where
    S: Service<R, Response = ServiceResponse<B>, Error = E>,
    E: std::fmt::Debug,
{
    app.call(req).await
}

/// Helper function that returns a response body of a TestRequest
///
/// # Examples
/// ```
/// use actix_web::{test, web, App, HttpResponse, http::header};
/// use bytes::Bytes;
///
/// #[actix_web::test]
/// async fn test_index() {
///     let app = test::init_service(
///         App::new().service(
///             web::resource("/index.html")
///                 .route(web::post().to(|| async {
///                     HttpResponse::Ok().body("welcome!")
///                 })))
///     ).await;
///
///     let req = test::TestRequest::post()
///         .uri("/index.html")
///         .header(header::CONTENT_TYPE, "application/json")
///         .to_request();
///
///     let result = test::call_and_read_body(&app, req).await;
///     assert_eq!(result, Bytes::from_static(b"welcome!"));
/// }
/// ```
///
/// # Panics
/// Panics if:
/// - service call returns error;
/// - body yields an error while it is being read.
pub async fn call_and_read_body<S, B>(app: &S, req: Request) -> Bytes
where
    S: Service<Request, Response = ServiceResponse<B>, Error = Error>,
    B: MessageBody,
{
    let res = call_service(app, req).await;
    read_body(res).await
}

#[doc(hidden)]
#[deprecated(since = "4.0.0", note = "Renamed to `call_and_read_body`.")]
pub async fn read_response<S, B>(app: &S, req: Request) -> Bytes
where
    S: Service<Request, Response = ServiceResponse<B>, Error = Error>,
    B: MessageBody,
{
    let res = call_service(app, req).await;
    read_body(res).await
}

/// Helper function that returns a response body of a ServiceResponse.
///
/// # Examples
/// ```
/// use actix_web::{test, web, App, HttpResponse, http::header};
/// use bytes::Bytes;
///
/// #[actix_web::test]
/// async fn test_index() {
///     let app = test::init_service(
///         App::new().service(
///             web::resource("/index.html")
///                 .route(web::post().to(|| async {
///                     HttpResponse::Ok().body("welcome!")
///                 })))
///     ).await;
///
///     let req = test::TestRequest::post()
///         .uri("/index.html")
///         .header(header::CONTENT_TYPE, "application/json")
///         .to_request();
///
///     let res = test::call_service(&app, req).await;
///     let result = test::read_body(res).await;
///     assert_eq!(result, Bytes::from_static(b"welcome!"));
/// }
/// ```
///
/// # Panics
/// Panics if body yields an error while it is being read.
pub async fn read_body<B>(res: ServiceResponse<B>) -> Bytes
where
    B: MessageBody,
{
    try_read_body(res)
        .await
        .map_err(Into::<Box<dyn StdError>>::into)
        .expect("error reading test response body")
}

/// Fallible version of [`read_body`] that allows testing MessageBody reading errors.
pub async fn try_read_body<B>(
    res: ServiceResponse<B>,
) -> Result<Bytes, <B as MessageBody>::Error>
where
    B: MessageBody,
{
    let body = res.into_body();
    body::to_bytes(body).await
}

/// Helper function that returns a deserialized response body of a ServiceResponse.
///
/// # Examples
/// ```
/// use actix_web::{App, test, web, HttpResponse, http::header};
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Serialize, Deserialize)]
/// pub struct Person {
///     id: String,
///     name: String,
/// }
///
/// #[actix_web::test]
/// async fn test_post_person() {
///     let app = test::init_service(
///         App::new().service(
///             web::resource("/people")
///                 .route(web::post().to(|person: web::Json<Person>| async {
///                     HttpResponse::Ok()
///                         .json(person)})
///                     ))
///     ).await;
///
///     let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes();
///
///     let res = test::TestRequest::post()
///         .uri("/people")
///         .header(header::CONTENT_TYPE, "application/json")
///         .set_payload(payload)
///         .send_request(&mut app)
///         .await;
///
///     assert!(res.status().is_success());
///
///     let result: Person = test::read_body_json(res).await;
/// }
/// ```
///
/// # Panics
/// Panics if:
/// - body yields an error while it is being read;
/// - received body is not a valid JSON representation of `T`.
pub async fn read_body_json<T, B>(res: ServiceResponse<B>) -> T
where
    B: MessageBody,
    T: DeserializeOwned,
{
    try_read_body_json(res).await.unwrap_or_else(|err| {
        panic!(
            "could not deserialize body into a {}\nerr: {}",
            std::any::type_name::<T>(),
            err,
        )
    })
}

/// Fallible version of [`read_body_json`] that allows testing response deserialization errors.
pub async fn try_read_body_json<T, B>(res: ServiceResponse<B>) -> Result<T, Box<dyn StdError>>
where
    B: MessageBody,
    T: DeserializeOwned,
{
    let body = try_read_body(res)
        .await
        .map_err(Into::<Box<dyn StdError>>::into)?;
    serde_json::from_slice(&body).map_err(Into::<Box<dyn StdError>>::into)
}

/// Helper function that returns a deserialized response body of a TestRequest
///
/// # Examples
/// ```
/// use actix_web::{App, test, web, HttpResponse, http::header};
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Serialize, Deserialize)]
/// pub struct Person {
///     id: String,
///     name: String
/// }
///
/// #[actix_web::test]
/// async fn test_add_person() {
///     let app = test::init_service(
///         App::new().service(
///             web::resource("/people")
///                 .route(web::post().to(|person: web::Json<Person>| async {
///                     HttpResponse::Ok()
///                         .json(person)})
///                     ))
///     ).await;
///
///     let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes();
///
///     let req = test::TestRequest::post()
///         .uri("/people")
///         .header(header::CONTENT_TYPE, "application/json")
///         .set_payload(payload)
///         .to_request();
///
///     let result: Person = test::call_and_read_body_json(&mut app, req).await;
/// }
/// ```
///
/// # Panics
/// Panics if:
/// - service call returns an error body yields an error while it is being read;
/// - body yields an error while it is being read;
/// - received body is not a valid JSON representation of `T`.
pub async fn call_and_read_body_json<S, B, T>(app: &S, req: Request) -> T
where
    S: Service<Request, Response = ServiceResponse<B>, Error = Error>,
    B: MessageBody,
    T: DeserializeOwned,
{
    try_call_and_read_body_json(app, req).await.unwrap()
}

/// Fallible version of [`call_and_read_body_json`] that allows testing service call errors.
pub async fn try_call_and_read_body_json<S, B, T>(
    app: &S,
    req: Request,
) -> Result<T, Box<dyn StdError>>
where
    S: Service<Request, Response = ServiceResponse<B>, Error = Error>,
    B: MessageBody,
    T: DeserializeOwned,
{
    let res = try_call_service(app, req)
        .await
        .map_err(Into::<Box<dyn StdError>>::into)?;
    try_read_body_json(res).await
}

#[doc(hidden)]
#[deprecated(since = "4.0.0", note = "Renamed to `call_and_read_body_json`.")]
pub async fn read_response_json<S, B, T>(app: &S, req: Request) -> T
where
    S: Service<Request, Response = ServiceResponse<B>, Error = Error>,
    B: MessageBody,
    T: DeserializeOwned,
{
    call_and_read_body_json(app, req).await
}

#[cfg(test)]
mod tests {

    use serde::{Deserialize, Serialize};

    use super::*;
    use crate::{
        dev::ServiceRequest, http::header, test::TestRequest, web, App, HttpMessage,
        HttpResponse,
    };

    #[actix_rt::test]
    async fn test_request_methods() {
        let app = init_service(
            App::new().service(
                web::resource("/index.html")
                    .route(web::put().to(|| HttpResponse::Ok().body("put!")))
                    .route(web::patch().to(|| HttpResponse::Ok().body("patch!")))
                    .route(web::delete().to(|| HttpResponse::Ok().body("delete!"))),
            ),
        )
        .await;

        let put_req = TestRequest::put()
            .uri("/index.html")
            .insert_header((header::CONTENT_TYPE, "application/json"))
            .to_request();

        let result = call_and_read_body(&app, put_req).await;
        assert_eq!(result, Bytes::from_static(b"put!"));

        let patch_req = TestRequest::patch()
            .uri("/index.html")
            .insert_header((header::CONTENT_TYPE, "application/json"))
            .to_request();

        let result = call_and_read_body(&app, patch_req).await;
        assert_eq!(result, Bytes::from_static(b"patch!"));

        let delete_req = TestRequest::delete().uri("/index.html").to_request();
        let result = call_and_read_body(&app, delete_req).await;
        assert_eq!(result, Bytes::from_static(b"delete!"));
    }

    #[derive(Serialize, Deserialize, Debug)]
    pub struct Person {
        id: String,
        name: String,
    }

    #[actix_rt::test]
    async fn test_response_json() {
        let app = init_service(App::new().service(web::resource("/people").route(
            web::post().to(|person: web::Json<Person>| HttpResponse::Ok().json(person)),
        )))
        .await;

        let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes();

        let req = TestRequest::post()
            .uri("/people")
            .insert_header((header::CONTENT_TYPE, "application/json"))
            .set_payload(payload)
            .to_request();

        let result: Person = call_and_read_body_json(&app, req).await;
        assert_eq!(&result.id, "12345");
    }

    #[actix_rt::test]
    async fn test_try_response_json_error() {
        let app = init_service(App::new().service(web::resource("/people").route(
            web::post().to(|person: web::Json<Person>| HttpResponse::Ok().json(person)),
        )))
        .await;

        let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes();

        let req = TestRequest::post()
            .uri("/animals") // Not registered to ensure an error occurs.
            .insert_header((header::CONTENT_TYPE, "application/json"))
            .set_payload(payload)
            .to_request();

        let result: Result<Person, Box<dyn StdError>> =
            try_call_and_read_body_json(&app, req).await;
        assert!(result.is_err());
    }

    #[actix_rt::test]
    async fn test_body_json() {
        let app = init_service(App::new().service(web::resource("/people").route(
            web::post().to(|person: web::Json<Person>| HttpResponse::Ok().json(person)),
        )))
        .await;

        let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes();

        let res = TestRequest::post()
            .uri("/people")
            .insert_header((header::CONTENT_TYPE, "application/json"))
            .set_payload(payload)
            .send_request(&app)
            .await;

        let result: Person = read_body_json(res).await;
        assert_eq!(&result.name, "User name");
    }

    #[actix_rt::test]
    async fn test_try_body_json_error() {
        let app = init_service(App::new().service(web::resource("/people").route(
            web::post().to(|person: web::Json<Person>| HttpResponse::Ok().json(person)),
        )))
        .await;

        // Use a number for id to cause a deserialization error.
        let payload = r#"{"id":12345,"name":"User name"}"#.as_bytes();

        let res = TestRequest::post()
            .uri("/people")
            .insert_header((header::CONTENT_TYPE, "application/json"))
            .set_payload(payload)
            .send_request(&app)
            .await;

        let result: Result<Person, Box<dyn StdError>> = try_read_body_json(res).await;
        assert!(result.is_err());
    }

    #[actix_rt::test]
    async fn test_request_response_form() {
        let app = init_service(App::new().service(web::resource("/people").route(
            web::post().to(|person: web::Form<Person>| HttpResponse::Ok().json(person)),
        )))
        .await;

        let payload = Person {
            id: "12345".to_string(),
            name: "User name".to_string(),
        };

        let req = TestRequest::post()
            .uri("/people")
            .set_form(&payload)
            .to_request();

        assert_eq!(req.content_type(), "application/x-www-form-urlencoded");

        let result: Person = call_and_read_body_json(&app, req).await;
        assert_eq!(&result.id, "12345");
        assert_eq!(&result.name, "User name");
    }

    #[actix_rt::test]
    async fn test_response() {
        let app = init_service(
            App::new().service(
                web::resource("/index.html")
                    .route(web::post().to(|| HttpResponse::Ok().body("welcome!"))),
            ),
        )
        .await;

        let req = TestRequest::post()
            .uri("/index.html")
            .insert_header((header::CONTENT_TYPE, "application/json"))
            .to_request();

        let result = call_and_read_body(&app, req).await;
        assert_eq!(result, Bytes::from_static(b"welcome!"));
    }

    #[actix_rt::test]
    async fn test_request_response_json() {
        let app = init_service(App::new().service(web::resource("/people").route(
            web::post().to(|person: web::Json<Person>| HttpResponse::Ok().json(person)),
        )))
        .await;

        let payload = Person {
            id: "12345".to_string(),
            name: "User name".to_string(),
        };

        let req = TestRequest::post()
            .uri("/people")
            .set_json(&payload)
            .to_request();

        assert_eq!(req.content_type(), "application/json");

        let result: Person = call_and_read_body_json(&app, req).await;
        assert_eq!(&result.id, "12345");
        assert_eq!(&result.name, "User name");
    }

    #[actix_rt::test]
    #[allow(dead_code)]
    async fn return_opaque_types() {
        fn test_app() -> App<
            impl ServiceFactory<
                ServiceRequest,
                Config = (),
                Response = ServiceResponse<impl MessageBody>,
                Error = crate::Error,
                InitError = (),
            >,
        > {
            App::new().service(web::resource("/people").route(
                web::post().to(|person: web::Json<Person>| HttpResponse::Ok().json(person)),
            ))
        }

        async fn test_service(
        ) -> impl Service<Request, Response = ServiceResponse<impl MessageBody>, Error = crate::Error>
        {
            init_service(test_app()).await
        }

        async fn compile_test(mut req: Vec<Request>) {
            let svc = test_service().await;
            call_service(&svc, req.pop().unwrap()).await;
            call_and_read_body(&svc, req.pop().unwrap()).await;
            read_body(call_service(&svc, req.pop().unwrap()).await).await;
            let _: String = call_and_read_body_json(&svc, req.pop().unwrap()).await;
            let _: String = read_body_json(call_service(&svc, req.pop().unwrap()).await).await;
        }
    }
}