|
| 1 | +use super::*; |
| 2 | +use axum::http::StatusCode as SC; |
| 3 | +use axum::{body::Body, http::Request}; |
| 4 | +use http_body_util::BodyExt; |
| 5 | +use tower::ServiceExt; |
| 6 | + |
| 7 | +const INDEX_HTML: &str = include_str!("../assets/index.html"); |
| 8 | +const SCRIPT_JS: &str = include_str!("../assets/script.js"); |
| 9 | + |
| 10 | +const JS: &str = "text/javascript"; |
| 11 | +const HTML: &str = "text/html"; |
| 12 | + |
| 13 | +async fn get_page(app: Router, path: &str) -> (StatusCode, String, String) { |
| 14 | + let response = app |
| 15 | + .oneshot(Request::builder().uri(path).body(Body::empty()).unwrap()) |
| 16 | + .await |
| 17 | + .unwrap(); |
| 18 | + |
| 19 | + let status = response.status(); |
| 20 | + let content_type = match response.headers().get("content-type") { |
| 21 | + Some(content_type) => content_type.to_str().unwrap().to_owned(), |
| 22 | + None => String::new(), |
| 23 | + }; |
| 24 | + |
| 25 | + let body = response.into_body(); |
| 26 | + let bytes = body.collect().await.unwrap().to_bytes(); |
| 27 | + let html = String::from_utf8(bytes.to_vec()).unwrap(); |
| 28 | + |
| 29 | + (status, content_type, html) |
| 30 | +} |
| 31 | + |
| 32 | +async fn check(app: Router, path: &str, status: StatusCode, content_type: &str, content: &str) { |
| 33 | + let (actual_status, actual_content_type, actual_content) = get_page(app, path).await; |
| 34 | + assert_eq!(status, actual_status); |
| 35 | + assert_eq!(content_type, actual_content_type); |
| 36 | + assert_eq!(content, actual_content); |
| 37 | +} |
| 38 | + |
| 39 | +#[tokio::test] |
| 40 | +async fn test_using_serve_dir() { |
| 41 | + let app = using_serve_dir; |
| 42 | + check(app(), "/assets/index.html", SC::OK, HTML, INDEX_HTML).await; |
| 43 | + check(app(), "/assets/script.js", SC::OK, JS, SCRIPT_JS).await; |
| 44 | + check(app(), "/assets/", SC::OK, HTML, INDEX_HTML).await; |
| 45 | + |
| 46 | + check(app(), "/assets/other.html", SC::NOT_FOUND, "", "").await; |
| 47 | +} |
| 48 | + |
| 49 | +#[tokio::test] |
| 50 | +async fn test_using_serve_dir_with_assets_fallback() { |
| 51 | + let app = using_serve_dir_with_assets_fallback; |
| 52 | + check(app(), "/assets/index.html", SC::OK, HTML, INDEX_HTML).await; |
| 53 | + check(app(), "/assets/script.js", SC::OK, JS, SCRIPT_JS).await; |
| 54 | + check(app(), "/assets/", SC::OK, HTML, INDEX_HTML).await; |
| 55 | + |
| 56 | + check( |
| 57 | + app(), |
| 58 | + "/foo", |
| 59 | + SC::OK, |
| 60 | + "text/plain; charset=utf-8", |
| 61 | + "Hi from /foo", |
| 62 | + ) |
| 63 | + .await; |
| 64 | +} |
0 commit comments