A now defunct web server engine that is notable for its overuse of unsafe code, the memory safety bugs caused by that, and its deletion by its creator.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

818 lines
25 KiB

  1. use std::collections::HashMap;
  2. use std::io::{Read, Write};
  3. use std::sync::atomic::{AtomicUsize, Ordering};
  4. use std::sync::Arc;
  5. use std::time::Duration;
  6. use brotli2::write::BrotliEncoder;
  7. use bytes::Bytes;
  8. use flate2::read::GzDecoder;
  9. use flate2::write::GzEncoder;
  10. use flate2::Compression;
  11. use futures::future::ok;
  12. use rand::Rng;
  13. use actix_http::HttpService;
  14. use actix_http_test::test_server;
  15. use actix_service::{map_config, pipeline_factory, IntoServiceFactory};
  16. use actix_web::dev::{AppConfig, BodyEncoding};
  17. use actix_web::http::Cookie;
  18. use actix_web::middleware::Compress;
  19. use actix_web::{
  20. http::header, test, web, App, Error, HttpMessage, HttpRequest, HttpResponse,
  21. };
  22. use awc::error::SendRequestError;
  23. const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
  24. Hello World Hello World Hello World Hello World Hello World \
  25. Hello World Hello World Hello World Hello World Hello World \
  26. Hello World Hello World Hello World Hello World Hello World \
  27. Hello World Hello World Hello World Hello World Hello World \
  28. Hello World Hello World Hello World Hello World Hello World \
  29. Hello World Hello World Hello World Hello World Hello World \
  30. Hello World Hello World Hello World Hello World Hello World \
  31. Hello World Hello World Hello World Hello World Hello World \
  32. Hello World Hello World Hello World Hello World Hello World \
  33. Hello World Hello World Hello World Hello World Hello World \
  34. Hello World Hello World Hello World Hello World Hello World \
  35. Hello World Hello World Hello World Hello World Hello World \
  36. Hello World Hello World Hello World Hello World Hello World \
  37. Hello World Hello World Hello World Hello World Hello World \
  38. Hello World Hello World Hello World Hello World Hello World \
  39. Hello World Hello World Hello World Hello World Hello World \
  40. Hello World Hello World Hello World Hello World Hello World \
  41. Hello World Hello World Hello World Hello World Hello World \
  42. Hello World Hello World Hello World Hello World Hello World \
  43. Hello World Hello World Hello World Hello World Hello World";
  44. #[actix_rt::test]
  45. async fn test_simple() {
  46. let srv = test::start(|| {
  47. App::new()
  48. .service(web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))))
  49. });
  50. let request = srv.get("/").header("x-test", "111").send();
  51. let mut response = request.await.unwrap();
  52. assert!(response.status().is_success());
  53. // read response
  54. let bytes = response.body().await.unwrap();
  55. assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
  56. let mut response = srv.post("/").send().await.unwrap();
  57. assert!(response.status().is_success());
  58. // read response
  59. let bytes = response.body().await.unwrap();
  60. assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
  61. // camel case
  62. let response = srv.post("/").camel_case().send().await.unwrap();
  63. assert!(response.status().is_success());
  64. }
  65. #[actix_rt::test]
  66. async fn test_json() {
  67. let srv = test::start(|| {
  68. App::new().service(
  69. web::resource("/").route(web::to(|_: web::Json<String>| HttpResponse::Ok())),
  70. )
  71. });
  72. let request = srv
  73. .get("/")
  74. .header("x-test", "111")
  75. .send_json(&"TEST".to_string());
  76. let response = request.await.unwrap();
  77. assert!(response.status().is_success());
  78. }
  79. #[actix_rt::test]
  80. async fn test_form() {
  81. let srv = test::start(|| {
  82. App::new().service(web::resource("/").route(web::to(
  83. |_: web::Form<HashMap<String, String>>| HttpResponse::Ok(),
  84. )))
  85. });
  86. let mut data = HashMap::new();
  87. let _ = data.insert("key".to_string(), "TEST".to_string());
  88. let request = srv.get("/").header("x-test", "111").send_form(&data);
  89. let response = request.await.unwrap();
  90. assert!(response.status().is_success());
  91. }
  92. #[actix_rt::test]
  93. async fn test_timeout() {
  94. let srv = test::start(|| {
  95. App::new().service(web::resource("/").route(web::to(|| {
  96. async {
  97. actix_rt::time::delay_for(Duration::from_millis(200)).await;
  98. Ok::<_, Error>(HttpResponse::Ok().body(STR))
  99. }
  100. })))
  101. });
  102. let connector = awc::Connector::new()
  103. .connector(actix_connect::new_connector(
  104. actix_connect::start_default_resolver(),
  105. ))
  106. .timeout(Duration::from_secs(15))
  107. .finish();
  108. let client = awc::Client::build()
  109. .connector(connector)
  110. .timeout(Duration::from_millis(50))
  111. .finish();
  112. let request = client.get(srv.url("/")).send();
  113. match request.await {
  114. Err(SendRequestError::Timeout) => (),
  115. _ => panic!(),
  116. }
  117. }
  118. #[actix_rt::test]
  119. async fn test_timeout_override() {
  120. let srv = test::start(|| {
  121. App::new().service(web::resource("/").route(web::to(|| {
  122. async {
  123. actix_rt::time::delay_for(Duration::from_millis(200)).await;
  124. Ok::<_, Error>(HttpResponse::Ok().body(STR))
  125. }
  126. })))
  127. });
  128. let client = awc::Client::build()
  129. .timeout(Duration::from_millis(50000))
  130. .finish();
  131. let request = client
  132. .get(srv.url("/"))
  133. .timeout(Duration::from_millis(50))
  134. .send();
  135. match request.await {
  136. Err(SendRequestError::Timeout) => (),
  137. _ => panic!(),
  138. }
  139. }
  140. #[actix_rt::test]
  141. async fn test_connection_reuse() {
  142. let num = Arc::new(AtomicUsize::new(0));
  143. let num2 = num.clone();
  144. let srv = test_server(move || {
  145. let num2 = num2.clone();
  146. pipeline_factory(move |io| {
  147. num2.fetch_add(1, Ordering::Relaxed);
  148. ok(io)
  149. })
  150. .and_then(
  151. HttpService::new(map_config(
  152. App::new()
  153. .service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
  154. |_| AppConfig::default(),
  155. ))
  156. .tcp(),
  157. )
  158. });
  159. let client = awc::Client::default();
  160. // req 1
  161. let request = client.get(srv.url("/")).send();
  162. let response = request.await.unwrap();
  163. assert!(response.status().is_success());
  164. // req 2
  165. let req = client.post(srv.url("/"));
  166. let response = req.send().await.unwrap();
  167. assert!(response.status().is_success());
  168. // one connection
  169. assert_eq!(num.load(Ordering::Relaxed), 1);
  170. }
  171. #[actix_rt::test]
  172. async fn test_connection_force_close() {
  173. let num = Arc::new(AtomicUsize::new(0));
  174. let num2 = num.clone();
  175. let srv = test_server(move || {
  176. let num2 = num2.clone();
  177. pipeline_factory(move |io| {
  178. num2.fetch_add(1, Ordering::Relaxed);
  179. ok(io)
  180. })
  181. .and_then(
  182. HttpService::new(map_config(
  183. App::new()
  184. .service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
  185. |_| AppConfig::default(),
  186. ))
  187. .tcp(),
  188. )
  189. });
  190. let client = awc::Client::default();
  191. // req 1
  192. let request = client.get(srv.url("/")).force_close().send();
  193. let response = request.await.unwrap();
  194. assert!(response.status().is_success());
  195. // req 2
  196. let req = client.post(srv.url("/")).force_close();
  197. let response = req.send().await.unwrap();
  198. assert!(response.status().is_success());
  199. // two connection
  200. assert_eq!(num.load(Ordering::Relaxed), 2);
  201. }
  202. #[actix_rt::test]
  203. async fn test_connection_server_close() {
  204. let num = Arc::new(AtomicUsize::new(0));
  205. let num2 = num.clone();
  206. let srv = test_server(move || {
  207. let num2 = num2.clone();
  208. pipeline_factory(move |io| {
  209. num2.fetch_add(1, Ordering::Relaxed);
  210. ok(io)
  211. })
  212. .and_then(
  213. HttpService::new(map_config(
  214. App::new().service(
  215. web::resource("/")
  216. .route(web::to(|| HttpResponse::Ok().force_close().finish())),
  217. ),
  218. |_| AppConfig::default(),
  219. ))
  220. .tcp(),
  221. )
  222. });
  223. let client = awc::Client::default();
  224. // req 1
  225. let request = client.get(srv.url("/")).send();
  226. let response = request.await.unwrap();
  227. assert!(response.status().is_success());
  228. // req 2
  229. let req = client.post(srv.url("/"));
  230. let response = req.send().await.unwrap();
  231. assert!(response.status().is_success());
  232. // two connection
  233. assert_eq!(num.load(Ordering::Relaxed), 2);
  234. }
  235. #[actix_rt::test]
  236. async fn test_connection_wait_queue() {
  237. let num = Arc::new(AtomicUsize::new(0));
  238. let num2 = num.clone();
  239. let srv = test_server(move || {
  240. let num2 = num2.clone();
  241. pipeline_factory(move |io| {
  242. num2.fetch_add(1, Ordering::Relaxed);
  243. ok(io)
  244. })
  245. .and_then(
  246. HttpService::new(map_config(
  247. App::new().service(
  248. web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))),
  249. ),
  250. |_| AppConfig::default(),
  251. ))
  252. .tcp(),
  253. )
  254. });
  255. let client = awc::Client::build()
  256. .connector(awc::Connector::new().limit(1).finish())
  257. .finish();
  258. // req 1
  259. let request = client.get(srv.url("/")).send();
  260. let mut response = request.await.unwrap();
  261. assert!(response.status().is_success());
  262. // req 2
  263. let req2 = client.post(srv.url("/"));
  264. let req2_fut = req2.send();
  265. // read response 1
  266. let bytes = response.body().await.unwrap();
  267. assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
  268. // req 2
  269. let response = req2_fut.await.unwrap();
  270. assert!(response.status().is_success());
  271. // two connection
  272. assert_eq!(num.load(Ordering::Relaxed), 1);
  273. }
  274. #[actix_rt::test]
  275. async fn test_connection_wait_queue_force_close() {
  276. let num = Arc::new(AtomicUsize::new(0));
  277. let num2 = num.clone();
  278. let srv = test_server(move || {
  279. let num2 = num2.clone();
  280. pipeline_factory(move |io| {
  281. num2.fetch_add(1, Ordering::Relaxed);
  282. ok(io)
  283. })
  284. .and_then(
  285. HttpService::new(map_config(
  286. App::new().service(
  287. web::resource("/")
  288. .route(web::to(|| HttpResponse::Ok().force_close().body(STR))),
  289. ),
  290. |_| AppConfig::default(),
  291. ))
  292. .tcp(),
  293. )
  294. });
  295. let client = awc::Client::build()
  296. .connector(awc::Connector::new().limit(1).finish())
  297. .finish();
  298. // req 1
  299. let request = client.get(srv.url("/")).send();
  300. let mut response = request.await.unwrap();
  301. assert!(response.status().is_success());
  302. // req 2
  303. let req2 = client.post(srv.url("/"));
  304. let req2_fut = req2.send();
  305. // read response 1
  306. let bytes = response.body().await.unwrap();
  307. assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
  308. // req 2
  309. let response = req2_fut.await.unwrap();
  310. assert!(response.status().is_success());
  311. // two connection
  312. assert_eq!(num.load(Ordering::Relaxed), 2);
  313. }
  314. #[actix_rt::test]
  315. async fn test_with_query_parameter() {
  316. let srv = test::start(|| {
  317. App::new().service(web::resource("/").to(|req: HttpRequest| {
  318. if req.query_string().contains("qp") {
  319. HttpResponse::Ok()
  320. } else {
  321. HttpResponse::BadRequest()
  322. }
  323. }))
  324. });
  325. let res = awc::Client::new()
  326. .get(srv.url("/?qp=5"))
  327. .send()
  328. .await
  329. .unwrap();
  330. assert!(res.status().is_success());
  331. }
  332. #[actix_rt::test]
  333. async fn test_no_decompress() {
  334. let srv = test::start(|| {
  335. App::new()
  336. .wrap(Compress::default())
  337. .service(web::resource("/").route(web::to(|| {
  338. let mut res = HttpResponse::Ok().body(STR);
  339. res.encoding(header::ContentEncoding::Gzip);
  340. res
  341. })))
  342. });
  343. let mut res = awc::Client::new()
  344. .get(srv.url("/"))
  345. .no_decompress()
  346. .send()
  347. .await
  348. .unwrap();
  349. assert!(res.status().is_success());
  350. // read response
  351. let bytes = res.body().await.unwrap();
  352. let mut e = GzDecoder::new(&bytes[..]);
  353. let mut dec = Vec::new();
  354. e.read_to_end(&mut dec).unwrap();
  355. assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
  356. // POST
  357. let mut res = awc::Client::new()
  358. .post(srv.url("/"))
  359. .no_decompress()
  360. .send()
  361. .await
  362. .unwrap();
  363. assert!(res.status().is_success());
  364. let bytes = res.body().await.unwrap();
  365. let mut e = GzDecoder::new(&bytes[..]);
  366. let mut dec = Vec::new();
  367. e.read_to_end(&mut dec).unwrap();
  368. assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
  369. }
  370. #[actix_rt::test]
  371. async fn test_client_gzip_encoding() {
  372. let srv = test::start(|| {
  373. App::new().service(web::resource("/").route(web::to(|| {
  374. let mut e = GzEncoder::new(Vec::new(), Compression::default());
  375. e.write_all(STR.as_ref()).unwrap();
  376. let data = e.finish().unwrap();
  377. HttpResponse::Ok()
  378. .header("content-encoding", "gzip")
  379. .body(data)
  380. })))
  381. });
  382. // client request
  383. let mut response = srv.post("/").send().await.unwrap();
  384. assert!(response.status().is_success());
  385. // read response
  386. let bytes = response.body().await.unwrap();
  387. assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
  388. }
  389. #[actix_rt::test]
  390. async fn test_client_gzip_encoding_large() {
  391. let srv = test::start(|| {
  392. App::new().service(web::resource("/").route(web::to(|| {
  393. let mut e = GzEncoder::new(Vec::new(), Compression::default());
  394. e.write_all(STR.repeat(10).as_ref()).unwrap();
  395. let data = e.finish().unwrap();
  396. HttpResponse::Ok()
  397. .header("content-encoding", "gzip")
  398. .body(data)
  399. })))
  400. });
  401. // client request
  402. let mut response = srv.post("/").send().await.unwrap();
  403. assert!(response.status().is_success());
  404. // read response
  405. let bytes = response.body().await.unwrap();
  406. assert_eq!(bytes, Bytes::from(STR.repeat(10)));
  407. }
  408. #[actix_rt::test]
  409. async fn test_client_gzip_encoding_large_random() {
  410. let data = rand::thread_rng()
  411. .sample_iter(&rand::distributions::Alphanumeric)
  412. .take(100_000)
  413. .collect::<String>();
  414. let srv = test::start(|| {
  415. App::new().service(web::resource("/").route(web::to(|data: Bytes| {
  416. let mut e = GzEncoder::new(Vec::new(), Compression::default());
  417. e.write_all(&data).unwrap();
  418. let data = e.finish().unwrap();
  419. HttpResponse::Ok()
  420. .header("content-encoding", "gzip")
  421. .body(data)
  422. })))
  423. });
  424. // client request
  425. let mut response = srv.post("/").send_body(data.clone()).await.unwrap();
  426. assert!(response.status().is_success());
  427. // read response
  428. let bytes = response.body().await.unwrap();
  429. assert_eq!(bytes, Bytes::from(data));
  430. }
  431. #[actix_rt::test]
  432. async fn test_client_brotli_encoding() {
  433. let srv = test::start(|| {
  434. App::new().service(web::resource("/").route(web::to(|data: Bytes| {
  435. let mut e = BrotliEncoder::new(Vec::new(), 5);
  436. e.write_all(&data).unwrap();
  437. let data = e.finish().unwrap();
  438. HttpResponse::Ok()
  439. .header("content-encoding", "br")
  440. .body(data)
  441. })))
  442. });
  443. // client request
  444. let mut response = srv.post("/").send_body(STR).await.unwrap();
  445. assert!(response.status().is_success());
  446. // read response
  447. let bytes = response.body().await.unwrap();
  448. assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
  449. }
  450. #[actix_rt::test]
  451. async fn test_client_brotli_encoding_large_random() {
  452. let data = rand::thread_rng()
  453. .sample_iter(&rand::distributions::Alphanumeric)
  454. .take(70_000)
  455. .collect::<String>();
  456. let srv = test::start(|| {
  457. App::new().service(web::resource("/").route(web::to(|data: Bytes| {
  458. let mut e = BrotliEncoder::new(Vec::new(), 5);
  459. e.write_all(&data).unwrap();
  460. let data = e.finish().unwrap();
  461. HttpResponse::Ok()
  462. .header("content-encoding", "br")
  463. .body(data)
  464. })))
  465. });
  466. // client request
  467. let mut response = srv.post("/").send_body(data.clone()).await.unwrap();
  468. assert!(response.status().is_success());
  469. // read response
  470. let bytes = response.body().await.unwrap();
  471. assert_eq!(bytes.len(), data.len());
  472. assert_eq!(bytes, Bytes::from(data));
  473. }
  474. // #[actix_rt::test]
  475. // async fn test_client_deflate_encoding() {
  476. // let srv = test::TestServer::start(|app| {
  477. // app.handler(|req: &HttpRequest| {
  478. // req.body()
  479. // .and_then(|bytes: Bytes| {
  480. // Ok(HttpResponse::Ok()
  481. // .content_encoding(http::ContentEncoding::Br)
  482. // .body(bytes))
  483. // })
  484. // .responder()
  485. // })
  486. // });
  487. // // client request
  488. // let request = srv
  489. // .post()
  490. // .content_encoding(http::ContentEncoding::Deflate)
  491. // .body(STR)
  492. // .unwrap();
  493. // let response = srv.execute(request.send()).unwrap();
  494. // assert!(response.status().is_success());
  495. // // read response
  496. // let bytes = srv.execute(response.body()).unwrap();
  497. // assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
  498. // }
  499. // #[actix_rt::test]
  500. // async fn test_client_deflate_encoding_large_random() {
  501. // let data = rand::thread_rng()
  502. // .sample_iter(&rand::distributions::Alphanumeric)
  503. // .take(70_000)
  504. // .collect::<String>();
  505. // let srv = test::TestServer::start(|app| {
  506. // app.handler(|req: &HttpRequest| {
  507. // req.body()
  508. // .and_then(|bytes: Bytes| {
  509. // Ok(HttpResponse::Ok()
  510. // .content_encoding(http::ContentEncoding::Br)
  511. // .body(bytes))
  512. // })
  513. // .responder()
  514. // })
  515. // });
  516. // // client request
  517. // let request = srv
  518. // .post()
  519. // .content_encoding(http::ContentEncoding::Deflate)
  520. // .body(data.clone())
  521. // .unwrap();
  522. // let response = srv.execute(request.send()).unwrap();
  523. // assert!(response.status().is_success());
  524. // // read response
  525. // let bytes = srv.execute(response.body()).unwrap();
  526. // assert_eq!(bytes, Bytes::from(data));
  527. // }
  528. // #[actix_rt::test]
  529. // async fn test_client_streaming_explicit() {
  530. // let srv = test::TestServer::start(|app| {
  531. // app.handler(|req: &HttpRequest| {
  532. // req.body()
  533. // .map_err(Error::from)
  534. // .and_then(|body| {
  535. // Ok(HttpResponse::Ok()
  536. // .chunked()
  537. // .content_encoding(http::ContentEncoding::Identity)
  538. // .body(body))
  539. // })
  540. // .responder()
  541. // })
  542. // });
  543. // let body = once(Ok(Bytes::from_static(STR.as_ref())));
  544. // let request = srv.get("/").body(Body::Streaming(Box::new(body))).unwrap();
  545. // let response = srv.execute(request.send()).unwrap();
  546. // assert!(response.status().is_success());
  547. // // read response
  548. // let bytes = srv.execute(response.body()).unwrap();
  549. // assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
  550. // }
  551. // #[actix_rt::test]
  552. // async fn test_body_streaming_implicit() {
  553. // let srv = test::TestServer::start(|app| {
  554. // app.handler(|_| {
  555. // let body = once(Ok(Bytes::from_static(STR.as_ref())));
  556. // HttpResponse::Ok()
  557. // .content_encoding(http::ContentEncoding::Gzip)
  558. // .body(Body::Streaming(Box::new(body)))
  559. // })
  560. // });
  561. // let request = srv.get("/").finish().unwrap();
  562. // let response = srv.execute(request.send()).unwrap();
  563. // assert!(response.status().is_success());
  564. // // read response
  565. // let bytes = srv.execute(response.body()).unwrap();
  566. // assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
  567. // }
  568. #[actix_rt::test]
  569. async fn test_client_cookie_handling() {
  570. use std::io::{Error as IoError, ErrorKind};
  571. let cookie1 = Cookie::build("cookie1", "value1").finish();
  572. let cookie2 = Cookie::build("cookie2", "value2")
  573. .domain("www.example.org")
  574. .path("/")
  575. .secure(true)
  576. .http_only(true)
  577. .finish();
  578. // Q: are all these clones really necessary? A: Yes, possibly
  579. let cookie1b = cookie1.clone();
  580. let cookie2b = cookie2.clone();
  581. let srv = test::start(move || {
  582. let cookie1 = cookie1b.clone();
  583. let cookie2 = cookie2b.clone();
  584. App::new().route(
  585. "/",
  586. web::to(move |req: HttpRequest| {
  587. let cookie1 = cookie1.clone();
  588. let cookie2 = cookie2.clone();
  589. async move {
  590. // Check cookies were sent correctly
  591. let res: Result<(), Error> = req
  592. .cookie("cookie1")
  593. .ok_or(())
  594. .and_then(|c1| {
  595. if c1.value() == "value1" {
  596. Ok(())
  597. } else {
  598. Err(())
  599. }
  600. })
  601. .and_then(|()| req.cookie("cookie2").ok_or(()))
  602. .and_then(|c2| {
  603. if c2.value() == "value2" {
  604. Ok(())
  605. } else {
  606. Err(())
  607. }
  608. })
  609. .map_err(|_| Error::from(IoError::from(ErrorKind::NotFound)));
  610. if let Err(e) = res {
  611. Err(e)
  612. } else {
  613. // Send some cookies back
  614. Ok::<_, Error>(
  615. HttpResponse::Ok().cookie(cookie1).cookie(cookie2).finish(),
  616. )
  617. }
  618. }
  619. }),
  620. )
  621. });
  622. let request = srv.get("/").cookie(cookie1.clone()).cookie(cookie2.clone());
  623. let response = request.send().await.unwrap();
  624. assert!(response.status().is_success());
  625. let c1 = response.cookie("cookie1").expect("Missing cookie1");
  626. assert_eq!(c1, cookie1);
  627. let c2 = response.cookie("cookie2").expect("Missing cookie2");
  628. assert_eq!(c2, cookie2);
  629. }
  630. // #[actix_rt::test]
  631. // fn client_read_until_eof() {
  632. // let addr = test::TestServer::unused_addr();
  633. // thread::spawn(move || {
  634. // let lst = net::TcpListener::bind(addr).unwrap();
  635. // for stream in lst.incoming() {
  636. // let mut stream = stream.unwrap();
  637. // let mut b = [0; 1000];
  638. // let _ = stream.read(&mut b).unwrap();
  639. // let _ = stream
  640. // .write_all(b"HTTP/1.1 200 OK\r\nconnection: close\r\n\r\nwelcome!");
  641. // }
  642. // });
  643. // let mut sys = actix::System::new("test");
  644. // // client request
  645. // let req = client::ClientRequest::get(format!("http://{}/", addr).as_str())
  646. // .finish()
  647. // .unwrap();
  648. // let response = req.send().await.unwrap();
  649. // assert!(response.status().is_success());
  650. // // read response
  651. // let bytes = response.body().await.unwrap();
  652. // assert_eq!(bytes, Bytes::from_static(b"welcome!"));
  653. // }
  654. #[actix_rt::test]
  655. async fn client_basic_auth() {
  656. let srv = test::start(|| {
  657. App::new().route(
  658. "/",
  659. web::to(|req: HttpRequest| {
  660. if req
  661. .headers()
  662. .get(header::AUTHORIZATION)
  663. .unwrap()
  664. .to_str()
  665. .unwrap()
  666. == "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
  667. {
  668. HttpResponse::Ok()
  669. } else {
  670. HttpResponse::BadRequest()
  671. }
  672. }),
  673. )
  674. });
  675. // set authorization header to Basic <base64 encoded username:password>
  676. let request = srv.get("/").basic_auth("username", Some("password"));
  677. let response = request.send().await.unwrap();
  678. assert!(response.status().is_success());
  679. }
  680. #[actix_rt::test]
  681. async fn client_bearer_auth() {
  682. let srv = test::start(|| {
  683. App::new().route(
  684. "/",
  685. web::to(|req: HttpRequest| {
  686. if req
  687. .headers()
  688. .get(header::AUTHORIZATION)
  689. .unwrap()
  690. .to_str()
  691. .unwrap()
  692. == "Bearer someS3cr3tAutht0k3n"
  693. {
  694. HttpResponse::Ok()
  695. } else {
  696. HttpResponse::BadRequest()
  697. }
  698. }),
  699. )
  700. });
  701. // set authorization header to Bearer <token>
  702. let request = srv.get("/").bearer_auth("someS3cr3tAutht0k3n");
  703. let response = request.send().await.unwrap();
  704. assert!(response.status().is_success());
  705. }