oxedyne/fe2o3/fe2o3_net/tests/url_request.rs
2.1 KiB, 1 run
created by r657228385:78350, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | #![cfg(feature = "async")] |
| 2 | //! A request by URL: the scheme picks the transport, the status is read off the answer, and a |
| 3 | //! peer that never answers is refused as a `Timeout` within the wait. |
| 4 | |
| 5 | use oxedyne_fe2o3_core::prelude::*; |
| 6 | use oxedyne_fe2o3_net::http::{ |
| 7 | client, |
| 8 | header::HttpMethod, |
| 9 | loc::Url, |
| 10 | status::HttpStatus, |
| 11 | }; |
| 12 | |
| 13 | use std::time::Duration; |
| 14 | |
| 15 | use tokio::{ |
| 16 | io::{ |
| 17 | AsyncReadExt, |
| 18 | AsyncWriteExt, |
| 19 | }, |
| 20 | net::TcpListener, |
| 21 | }; |
| 22 | |
| 23 | |
| 24 | /// A loopback server that answers each connection's first read with `reply`, or, when it is |
| 25 | /// empty, holds the connection and says nothing. |
| 26 | async fn serve(reply: &'static str) -> Url { |
| 27 | let l = TcpListener::bind("127.0.0.1:0").await.expect("bind"); |
| 28 | let port = l.local_addr().expect("addr").port(); |
| 29 | tokio::spawn(async move { |
| 30 | while let Ok((mut s, _)) = l.accept().await { |
| 31 | tokio::spawn(async move { |
| 32 | let mut b = [0u8; 4096]; |
| 33 | let _ = s.read(&mut b).await; |
| 34 | if reply.is_empty() { |
| 35 | tokio::time::sleep(Duration::from_secs(5)).await; |
| 36 | } else { |
| 37 | let _ = s.write_all(reply.as_bytes()).await; |
| 38 | } |
| 39 | }); |
| 40 | } |
| 41 | }); |
| 42 | Url::parse(&fmt!("http://127.0.0.1:{}/x", port)).expect("url") |
| 43 | } |
| 44 | |
| 45 | #[tokio::test] |
| 46 | async fn an_http_url_is_asked_and_its_status_read() { |
| 47 | let url = serve("HTTP/1.1 202 Accepted\r\nContent-Length: 2\r\n\r\nok").await; |
| 48 | let msg = client::url_request(&url, HttpMethod::POST, "/x?a=1", &[("Content-Type", "application/json")], |
| 49 | b"{}", None, None, Duration::from_secs(5)).await.expect("answered"); |
| 50 | assert_eq!(msg.status(), Some(HttpStatus::Accepted)); |
| 51 | assert_eq!(msg.body_as_string(), "ok"); |
| 52 | } |
| 53 | |
| 54 | #[tokio::test] |
| 55 | async fn a_silent_peer_is_refused_as_a_timeout() { |
| 56 | let url = serve("").await; |
| 57 | match client::url_request(&url, HttpMethod::GET, &url.target, &[], &[], None, None, |
| 58 | Duration::from_millis(200)).await |
| 59 | { |
| 60 | Ok(m) => panic!("a silent peer answered {:?}", m.status()), |
| 61 | Err(e) => assert!(e.tags().contains(&ErrTag::Timeout) && fmt!("{}", e).contains("within 200 ms"), "{}", e), |
| 62 | } |
| 63 | } |