Struct warp::test::RequestBuilder
source · [−]pub struct RequestBuilder { /* private fields */ }
Expand description
A request builder for testing filters.
See module documentation for an overview.
Implementations
sourceimpl RequestBuilder
impl RequestBuilder
sourcepub fn path(self, p: &str) -> Self
pub fn path(self, p: &str) -> Self
sourcepub fn header<K, V>(self, key: K, value: V) -> Self where
HeaderName: TryFrom<K>,
HeaderValue: TryFrom<V>,
pub fn header<K, V>(self, key: K, value: V) -> Self where
HeaderName: TryFrom<K>,
HeaderValue: TryFrom<V>,
Set a header for this request.
Example
let req = warp::test::request()
.header("accept", "application/json");
Panic
This panics if the passed strings are not able to be parsed as a valid
HeaderName
and HeaderValue
.
Examples found in repository?
src/test.rs (line 272)
≺ ≻
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
pub fn body(mut self, body: impl AsRef<[u8]>) -> Self {
let body = body.as_ref().to_vec();
let len = body.len();
*self.req.body_mut() = body.into();
self.header("content-length", len.to_string())
}
/// Set the bytes of this request body by serializing a value into JSON.
///
/// # Example
///
/// ```
/// let req = warp::test::request()
/// .json(&true);
/// ```
pub fn json(mut self, val: &impl Serialize) -> Self {
let vec = serde_json::to_vec(val).expect("json() must serialize to JSON");
let len = vec.len();
*self.req.body_mut() = vec.into();
self.header("content-length", len.to_string())
.header("content-type", "application/json")
}
/// Tries to apply the `Filter` on this request.
///
/// # Example
///
/// ```no_run
/// async {
/// let param = warp::path::param::<u32>();
///
/// let ex = warp::test::request()
/// .path("/41")
/// .filter(¶m)
/// .await
/// .unwrap();
///
/// assert_eq!(ex, 41);
///
/// assert!(
/// warp::test::request()
/// .path("/foo")
/// .filter(¶m)
/// .await
/// .is_err()
/// );
///};
/// ```
pub async fn filter<F>(self, f: &F) -> Result<<F::Extract as OneOrTuple>::Output, F::Error>
where
F: Filter,
F::Future: Send + 'static,
F::Extract: OneOrTuple + Send + 'static,
F::Error: Send + 'static,
{
self.apply_filter(f).await.map(|ex| ex.one_or_tuple())
}
/// Returns whether the `Filter` matches this request, or rejects it.
///
/// # Example
///
/// ```no_run
/// async {
/// let get = warp::get();
/// let post = warp::post();
///
/// assert!(
/// warp::test::request()
/// .method("GET")
/// .matches(&get)
/// .await
/// );
///
/// assert!(
/// !warp::test::request()
/// .method("GET")
/// .matches(&post)
/// .await
/// );
///};
/// ```
pub async fn matches<F>(self, f: &F) -> bool
where
F: Filter,
F::Future: Send + 'static,
F::Extract: Send + 'static,
F::Error: Send + 'static,
{
self.apply_filter(f).await.is_ok()
}
/// Returns `Response` provided by applying the `Filter`.
///
/// This requires that the supplied `Filter` return a [`Reply`](Reply).
pub async fn reply<F>(self, f: &F) -> Response<Bytes>
where
F: Filter + 'static,
F::Extract: Reply + Send,
F::Error: IsReject + Send,
{
// TODO: de-duplicate this and apply_filter()
assert!(!route::is_set(), "nested test filter calls");
let route = Route::new(self.req, self.remote_addr);
let mut fut = Box::pin(
route::set(&route, move || f.filter(crate::filter::Internal)).then(|result| {
let res = match result {
Ok(rep) => rep.into_response(),
Err(rej) => {
tracing::debug!("rejected: {:?}", rej);
rej.into_response()
}
};
let (parts, body) = res.into_parts();
hyper::body::to_bytes(body)
.map_ok(|chunk| Response::from_parts(parts, chunk.into()))
}),
);
let fut = future::poll_fn(move |cx| route::set(&route, || fut.as_mut().poll(cx)));
fut.await.expect("reply shouldn't fail")
}
fn apply_filter<F>(self, f: &F) -> impl Future<Output = Result<F::Extract, F::Error>>
where
F: Filter,
F::Future: Send + 'static,
F::Extract: Send + 'static,
F::Error: Send + 'static,
{
assert!(!route::is_set(), "nested test filter calls");
let route = Route::new(self.req, self.remote_addr);
let mut fut = Box::pin(route::set(&route, move || {
f.filter(crate::filter::Internal)
}));
future::poll_fn(move |cx| route::set(&route, || fut.as_mut().poll(cx)))
}
}
#[cfg(feature = "websocket")]
impl WsBuilder {
/// Sets the request path of this builder.
///
/// The default is not set is `/`.
///
/// # Example
///
/// ```
/// let req = warp::test::ws()
/// .path("/chat");
/// ```
///
/// # Panic
///
/// This panics if the passed string is not able to be parsed as a valid
/// `Uri`.
pub fn path(self, p: &str) -> Self {
WsBuilder {
req: self.req.path(p),
}
}
/// Set a header for this request.
///
/// # Example
///
/// ```
/// let req = warp::test::ws()
/// .header("foo", "bar");
/// ```
///
/// # Panic
///
/// This panics if the passed strings are not able to be parsed as a valid
/// `HeaderName` and `HeaderValue`.
pub fn header<K, V>(self, key: K, value: V) -> Self
where
HeaderName: TryFrom<K>,
HeaderValue: TryFrom<V>,
{
WsBuilder {
req: self.req.header(key, value),
}
}
/// Execute this Websocket request against the provided filter.
///
/// If the handshake succeeds, returns a `WsClient`.
///
/// # Example
///
/// ```no_run
/// use futures::future;
/// use warp::Filter;
/// #[tokio::main]
/// # async fn main() {
///
/// // Some route that accepts websockets (but drops them immediately).
/// let route = warp::ws()
/// .map(|ws: warp::ws::Ws| {
/// ws.on_upgrade(|_| future::ready(()))
/// });
///
/// let client = warp::test::ws()
/// .handshake(route)
/// .await
/// .expect("handshake");
/// # }
/// ```
pub async fn handshake<F>(self, f: F) -> Result<WsClient, WsError>
where
F: Filter + Clone + Send + Sync + 'static,
F::Extract: Reply + Send,
F::Error: IsReject + Send,
{
let (upgraded_tx, upgraded_rx) = oneshot::channel();
let (wr_tx, wr_rx) = mpsc::unbounded_channel();
let wr_rx = UnboundedReceiverStream::new(wr_rx);
let (rd_tx, rd_rx) = mpsc::unbounded_channel();
tokio::spawn(async move {
use tokio_tungstenite::tungstenite::protocol;
let (addr, srv) = crate::serve(f).bind_ephemeral(([127, 0, 0, 1], 0));
let mut req = self
.req
.header("connection", "upgrade")
.header("upgrade", "websocket")
.header("sec-websocket-version", "13")
.header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==")
.req;
let query_string = match req.uri().query() {
Some(q) => format!("?{}", q),
None => String::from(""),
};
let uri = format!("http://{}{}{}", addr, req.uri().path(), query_string)
.parse()
.expect("addr + path is valid URI");
*req.uri_mut() = uri;
// let mut rt = current_thread::Runtime::new().unwrap();
tokio::spawn(srv);
let upgrade = ::hyper::Client::builder()
.build(AddrConnect(addr))
.request(req)
.and_then(|res| hyper::upgrade::on(res));
let upgraded = match upgrade.await {
Ok(up) => {
let _ = upgraded_tx.send(Ok(()));
up
}
Err(err) => {
let _ = upgraded_tx.send(Err(err));
return;
}
};
let ws = crate::ws::WebSocket::from_raw_socket(
upgraded,
protocol::Role::Client,
Default::default(),
)
.await;
let (tx, rx) = ws.split();
let write = wr_rx.map(Ok).forward(tx).map(|_| ());
let read = rx
.take_while(|result| match result {
Err(_) => future::ready(false),
Ok(m) => future::ready(!m.is_close()),
})
.for_each(move |item| {
rd_tx.send(item).expect("ws receive error");
future::ready(())
});
future::join(write, read).await;
});
match upgraded_rx.await {
Ok(Ok(())) => Ok(WsClient {
tx: wr_tx,
rx: rd_rx,
}),
Ok(Err(err)) => Err(WsError::new(err)),
Err(_canceled) => panic!("websocket handshake thread panicked"),
}
}
sourcepub fn remote_addr(self, addr: SocketAddr) -> Self
pub fn remote_addr(self, addr: SocketAddr) -> Self
Set the remote address of this request
Default is no remote address.
Example
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
let req = warp::test::request()
.remote_addr(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080));
sourcepub fn extension<T>(self, ext: T) -> Self where
T: Send + Sync + 'static,
pub fn extension<T>(self, ext: T) -> Self where
T: Send + Sync + 'static,
Add a type to the request’s http::Extensions
.
sourcepub fn body(self, body: impl AsRef<[u8]>) -> Self
pub fn body(self, body: impl AsRef<[u8]>) -> Self
Set the bytes of this request body.
Default is an empty body.
Example
let req = warp::test::request()
.body("foo=bar&baz=quux");
sourcepub fn json(self, val: &impl Serialize) -> Self
pub fn json(self, val: &impl Serialize) -> Self
Set the bytes of this request body by serializing a value into JSON.
Example
let req = warp::test::request()
.json(&true);
sourcepub async fn filter<F>(
self,
f: &F
) -> Result<<F::Extract as OneOrTuple>::Output, F::Error> where
F: Filter,
F::Future: Send + 'static,
F::Extract: OneOrTuple + Send + 'static,
F::Error: Send + 'static,
pub async fn filter<F>(
self,
f: &F
) -> Result<<F::Extract as OneOrTuple>::Output, F::Error> where
F: Filter,
F::Future: Send + 'static,
F::Extract: OneOrTuple + Send + 'static,
F::Error: Send + 'static,
Tries to apply the Filter
on this request.
Example
async {
let param = warp::path::param::<u32>();
let ex = warp::test::request()
.path("/41")
.filter(¶m)
.await
.unwrap();
assert_eq!(ex, 41);
assert!(
warp::test::request()
.path("/foo")
.filter(¶m)
.await
.is_err()
);
};
sourcepub async fn matches<F>(self, f: &F) -> bool where
F: Filter,
F::Future: Send + 'static,
F::Extract: Send + 'static,
F::Error: Send + 'static,
pub async fn matches<F>(self, f: &F) -> bool where
F: Filter,
F::Future: Send + 'static,
F::Extract: Send + 'static,
F::Error: Send + 'static,
Returns whether the Filter
matches this request, or rejects it.
Example
async {
let get = warp::get();
let post = warp::post();
assert!(
warp::test::request()
.method("GET")
.matches(&get)
.await
);
assert!(
!warp::test::request()
.method("GET")
.matches(&post)
.await
);
};
Trait Implementations
Auto Trait Implementations
impl !RefUnwindSafe for RequestBuilder
impl Send for RequestBuilder
impl Sync for RequestBuilder
impl Unpin for RequestBuilder
impl !UnwindSafe for RequestBuilder
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcepub fn borrow_mut(&mut self) -> &mut T
pub fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Instruments this type with the provided Span
, returning an
Instrumented
wrapper. Read more
sourcefn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
impl<T> Same<T> for T
impl<T> Same<T> for T
type Output = T
type Output = T
Should always be Self