|
3 | 3 | extern crate warp; |
4 | 4 |
|
5 | 5 | use futures_util::future; |
| 6 | +use warp::path::Tail; |
6 | 7 | use warp::Filter; |
7 | 8 |
|
8 | 9 | #[tokio::test] |
@@ -59,6 +60,71 @@ async fn param() { |
59 | 60 | ); |
60 | 61 | } |
61 | 62 |
|
| 63 | +#[tokio::test] |
| 64 | +async fn custom() { |
| 65 | + let _ = pretty_env_logger::try_init(); |
| 66 | + |
| 67 | + // extracting path segment and advancing |
| 68 | + let simple = warp::path::custom(|remaining| { |
| 69 | + if let Some(pos) = remaining.rfind('/') { |
| 70 | + let ret = &remaining[0..pos]; |
| 71 | + Ok((ret.len(), (ret.to_string(),))) |
| 72 | + } else { |
| 73 | + Err(warp::reject::not_found()) |
| 74 | + } |
| 75 | + }) |
| 76 | + .and(warp::path::tail()) |
| 77 | + .map(|m, t: Tail| (m, t.as_str().to_string())); |
| 78 | + |
| 79 | + let req = warp::test::request().path("/one/two/three"); |
| 80 | + assert_eq!( |
| 81 | + req.filter(&simple).await.unwrap(), |
| 82 | + ("one/two".to_string(), "three".to_string()) |
| 83 | + ); |
| 84 | + |
| 85 | + // no extracting |
| 86 | + let no_extract = warp::path::custom(|remaining| { |
| 87 | + if remaining.ends_with(".bmp") { |
| 88 | + Ok((0, ())) |
| 89 | + } else { |
| 90 | + Err(warp::reject::not_found()) |
| 91 | + } |
| 92 | + }) |
| 93 | + .and(warp::path::tail()) |
| 94 | + .map(|t: Tail| (t.as_str().to_string())); |
| 95 | + |
| 96 | + let req = warp::test::request().path("/one/two/three.bmp"); |
| 97 | + assert_eq!( |
| 98 | + req.filter(&no_extract).await.unwrap(), |
| 99 | + ("one/two/three.bmp".to_string()) |
| 100 | + ); |
| 101 | + |
| 102 | + let req = warp::test::request().path("/one/two/three.png"); |
| 103 | + assert!( |
| 104 | + !req.matches(&no_extract).await, |
| 105 | + "custom() doesn't match .png" |
| 106 | + ); |
| 107 | + |
| 108 | + // prefixed and postfixed path() matching |
| 109 | + let mixed = warp::path::path("prefix") |
| 110 | + .and(warp::path::custom(|remaining| { |
| 111 | + if let Some(pos) = remaining.rfind('/') { |
| 112 | + let ret = &remaining[0..pos]; |
| 113 | + Ok((ret.len(), (ret.to_string(),))) |
| 114 | + } else { |
| 115 | + Err(warp::reject::not_found()) |
| 116 | + } |
| 117 | + })) |
| 118 | + .and(warp::path::path("postfix")) |
| 119 | + .and(warp::path::end()); |
| 120 | + |
| 121 | + let req = warp::test::request().path("/prefix/middle/area/postfix"); |
| 122 | + assert_eq!( |
| 123 | + req.filter(&mixed).await.unwrap(), |
| 124 | + ("middle/area".to_string()) |
| 125 | + ); |
| 126 | +} |
| 127 | + |
62 | 128 | #[tokio::test] |
63 | 129 | async fn end() { |
64 | 130 | let _ = pretty_env_logger::try_init(); |
|
0 commit comments