//! The decoding and response rules, tested without a host around them. //! //! Everything here would otherwise be tested twice, once through axum and once //! through a Tauri protocol handler, and the two copies would drift. What is //! left in each host's own tests is the part only that host has: its mounting, //! its body reading and its blocking hop. use quasi_router::{Action, Class, Node, RegionKind, Response, RouteError, Screen, Slot}; use super::{DEFAULT_BODY_LIMIT, Refusal, Serves, decode, refuse, respond}; /// A renderer that says what it was handed, so a test can read it back. struct Spy; impl Serves for Spy { fn screen(&self, screen: &Screen) -> String { format!("screen:{}", screen.title) } fn fragment(&self, node: &Node) -> String { match node { Node::Text { text, .. } => format!("text:{text}"), Node::Notice { tone, text, .. } => format!("notice:{tone:?}:{text}"), other => format!("other:{other:?}"), } } fn invalidated(&self, region: &str, node: &Node) -> String { format!("[oob:{region}:{}]", self.fragment(node)) } } /// Decode a request built from its parts. fn read( method: &str, uri: &str, content_type: Option<&str>, body: &str, ) -> Result { let mut builder = http::Request::builder().method(method).uri(uri); if let Some(kind) = content_type { builder = builder.header(http::header::CONTENT_TYPE, kind); } let request = builder.body(()).unwrap(); decode( request.method(), request.uri(), request.headers(), body.as_bytes(), DEFAULT_BODY_LIMIT, ) } /// A form POST, which is the shape every action arrives in. fn form(uri: &str, body: &str) -> Result { read("POST", uri, Some("application/x-www-form-urlencoded"), body) } /// Everything that arrived, flattened, so an assertion reads like the wire did. fn joined(incoming: &super::Incoming) -> String { incoming .payload .iter() .chain(incoming.carried.iter()) .map(|(k, v)| format!("{k}={v}")) .collect::>() .join(",") } /// What was asked, for a `respond` that has to decide whether the answer is a /// place. Built through `decode` rather than by hand, so the URL a push carries /// is the one a real request would have produced. fn asked(method: &str, uri: &str) -> super::Asked { super::Asked::new(&read(method, uri, None, "").unwrap()) } /// The body of a response, as text. fn text(response: &http::Response>) -> String { String::from_utf8(response.body().clone()).unwrap() } #[test] fn a_path_arrives_with_no_scheme_or_host_on_it() { // The spike's finding is what makes this one assertion enough for every // platform: wry reverts the Windows workaround before the handler is // called, so a custom-protocol request is `://localhost/` // everywhere and `Uri::path` is the whole address either way. let incoming = read("GET", "quasi://localhost/task/7", None, "").unwrap(); assert_eq!(incoming.path, "/task/7"); let hosted = read("GET", "/task/7", None, "").unwrap(); assert_eq!(hosted.path, "/task/7"); } #[test] fn a_query_string_is_percent_decoded() { let incoming = read("GET", "/task/7?note=a%20b&flag=1", None, "").unwrap(); assert_eq!(joined(&incoming), "note=a b,flag=1"); } #[test] fn a_form_body_is_decoded_on_a_post() { let incoming = form("/task/7/edit", "title=new+title").unwrap(); assert_eq!(joined(&incoming), "title=new title"); } #[test] fn a_form_field_and_a_query_argument_of_the_same_name_stay_apart() { // They used to be merged, form first, so this read `from-form` and the // other value was unreachable. That merge is what let a screen's filter and // a write about the same noun mean one name between them. Now the body is // what the control sent and the query is the view it was sent from, and a // handler asks for the one it means. let incoming = form("/task/7/edit?title=from-query", "title=from-form").unwrap(); assert_eq!(incoming.payload.get("title"), Some("from-form")); assert_eq!(incoming.carried.get("title"), Some("from-query")); } #[test] fn repeated_names_all_survive() { let incoming = form("/tags", "tag=rust&tag=router&tag=quasi").unwrap(); assert_eq!( incoming.payload.get_all("tag").collect::>(), ["rust", "router", "quasi"] ); } #[test] fn a_get_never_reads_a_body_even_when_one_is_sent() { // A safe verb with a body is either a confused client or a smuggling // attempt, and quasi has no route that would want it either way. let incoming = read( "GET", "/task/7", Some("application/x-www-form-urlencoded"), "title=ignored", ) .unwrap(); assert!(incoming.payload.is_empty()); } #[test] fn a_body_that_is_not_a_form_is_ignored_rather_than_guessed_at() { let incoming = read( "POST", "/task/7/edit", Some("multipart/form-data; boundary=xyz"), "--xyz--", ) .unwrap(); assert!(incoming.payload.is_empty()); } #[test] fn a_charset_on_the_form_content_type_still_reads_as_a_form() { let incoming = read( "POST", "/task/7/edit", Some("application/x-www-form-urlencoded; charset=utf-8"), "title=ok", ) .unwrap(); assert_eq!(incoming.payload.get("title"), Some("ok")); } #[test] fn a_verb_the_description_layer_lacks_is_refused() { // PATCH is the one left. DELETE and PUT arrived with `61e1b069`, because a // public server's verbs are part of its interface and a description that // cannot name them cannot address it. assert_eq!(read("PATCH", "/task/7", None, ""), Err(Refusal::Method)); assert_eq!(read("HEAD", "/task/7", None, ""), Err(Refusal::Method)); // And the two that arrived decode, rather than being accepted and then // silently read as a POST. assert_eq!( read("DELETE", "/task/7", None, "").unwrap().method.as_str(), "DELETE" ); assert_eq!( read("PUT", "/task/7", None, "").unwrap().method.as_str(), "PUT" ); } #[test] fn an_oversized_form_is_refused_before_it_is_parsed() { let request = http::Request::builder() .method("POST") .uri("/tags") .header( http::header::CONTENT_TYPE, "application/x-www-form-urlencoded", ) .body(()) .unwrap(); let body = "tag=".to_owned() + &"x".repeat(1024); let outcome = decode( request.method(), request.uri(), request.headers(), body.as_bytes(), 16, ); assert_eq!(outcome, Err(Refusal::TooLarge)); } #[test] fn a_form_body_that_is_not_utf8_is_refused() { let request = http::Request::builder() .method("POST") .uri("/tags") .header( http::header::CONTENT_TYPE, "application/x-www-form-urlencoded", ) .body(()) .unwrap(); let outcome = decode( request.method(), request.uri(), request.headers(), &[0xff, 0xfe], DEFAULT_BODY_LIMIT, ); assert_eq!(outcome, Err(Refusal::Malformed)); } #[test] fn a_refusal_of_the_verb_says_which_verbs_there_are() { let response = refuse(Refusal::Method); assert_eq!(response.status(), 405); assert_eq!( response.headers().get(http::header::ALLOW).unwrap(), // Exactly what `translate` accepts, or the header promises a verb the // decoder refuses. "GET, POST, DELETE, PUT" ); assert!(response.body().is_empty()); } #[test] fn a_screen_is_served_whole_and_names_no_target() { let screen = Screen::sidebar_content("Home").with(Slot::new("content", RegionKind::Pane)); let response = respond(&Spy, Ok(screen.into()), &asked("GET", "/")); assert_eq!(response.status(), 200); assert_eq!(text(&response), "screen:Home"); assert!(response.headers().get(super::htmx::RETARGET).is_none()); } #[test] fn a_fragment_carries_the_region_it_replaces() { let answer = Response::fragment("detail", Node::text("hello")); let response = respond(&Spy, Ok(answer), &asked("GET", "/")); assert_eq!(text(&response), "text:hello"); // A slot id becomes a CSS selector, which is what htmx wants. assert_eq!( response.headers().get(super::htmx::RETARGET).unwrap(), "#detail" ); } #[test] fn a_redirect_names_where_it_goes_and_carries_no_body() { // The finding this closes (`80afd652`): deleting the thing a screen is // about used to answer with a tombstone, because every response was content. let answer = Response::goto(Action::get("/tasks")); let response = respond(&Spy, Ok(answer), &asked("GET", "/")); assert_eq!(response.status(), 200); assert!(response.body().is_empty()); assert_eq!( response.headers().get(super::htmx::LOCATION).unwrap(), "/tasks" ); // Not a fragment, so nothing is being replaced in place. assert!(response.headers().get(super::htmx::RETARGET).is_none()); } #[test] fn a_redirect_keeps_its_params_rather_than_dropping_the_filter() { // Back to a filtered list is a different place from back to the list. let answer = Response::goto(Action::get("/tasks").with("status", "open")); let response = respond(&Spy, Ok(answer), &asked("GET", "/")); assert_eq!( response.headers().get(super::htmx::LOCATION).unwrap(), "/tasks?status=open" ); } #[test] fn a_param_that_needs_encoding_is_encoded_once() { let answer = Response::goto(Action::get("/tasks").with("q", "a b&c")); let response = respond(&Spy, Ok(answer), &asked("GET", "/")); assert_eq!( response.headers().get(super::htmx::LOCATION).unwrap(), "/tasks?q=a+b%26c" ); } #[test] fn leaving_the_app_is_a_different_header_from_going_somewhere_in_it() { // `844b5ae0`'s opening half. An external address cannot be a swap, because // nothing comes back from it. let answer = Response::goto(Action::external("file:///home/max/notes.pdf")); let response = respond(&Spy, Ok(answer), &asked("GET", "/")); assert_eq!( response.headers().get(super::htmx::REDIRECT).unwrap(), "file:///home/max/notes.pdf" ); assert!(response.headers().get(super::htmx::LOCATION).is_none()); } #[test] fn a_notice_rides_beside_the_content_rather_than_replacing_it() { // `a92ecb1e`. The fragment still lands; the message is a header, so it is // not mistaken for the region's new contents. let answer = Response::fragment("detail", Node::text("hello")) .toast(quasi_router::layout::Tone::Success, "Saved"); let response = respond(&Spy, Ok(answer), &asked("GET", "/")); assert_eq!(text(&response), "text:hello"); assert_eq!( response.headers().get(super::htmx::RETARGET).unwrap(), "#detail" ); assert_eq!( response.headers().get(super::htmx::TRIGGER).unwrap(), r#"{"quasi:notice":{"kind":"toast","tone":"success","text":"Saved"}}"# ); } #[test] fn a_notice_survives_a_redirect_which_has_no_body_to_put_one_in() { // The composition the two findings were filed apart from each other and // could not express: a delete both goes elsewhere and says it is gone. let answer = Response::goto(Action::get("/tasks")).toast(quasi_router::layout::Tone::Success, "Deleted"); let response = respond(&Spy, Ok(answer), &asked("GET", "/")); assert!(response.body().is_empty()); assert_eq!( response.headers().get(super::htmx::LOCATION).unwrap(), "/tasks" ); assert!( response .headers() .get(super::htmx::TRIGGER) .unwrap() .to_str() .unwrap() .contains(r#""text":"Deleted""#) ); } #[test] fn a_response_that_says_nothing_sets_no_trigger() { let response = respond( &Spy, Ok(Response::fragment("detail", Node::text("hello"))), &asked("GET", "/"), ); assert!(response.headers().get(super::htmx::TRIGGER).is_none()); } #[test] fn a_banner_and_a_toast_are_told_apart_at_the_boundary() { // They are dismissed differently, so a client that cannot tell them apart // shows a permanent error as a message that vanishes. let banner = respond( &Spy, Ok(Response::fragment("detail", Node::text("x")) .banner(quasi_router::layout::Tone::Danger, "Sync is down")), &asked("GET", "/"), ); assert!( banner .headers() .get(super::htmx::TRIGGER) .unwrap() .to_str() .unwrap() .contains(r#""kind":"banner""#) ); } #[test] fn every_class_becomes_its_status_with_the_notice_as_the_body() { for (error, status) in [ (RouteError::denied("not yours"), 403), (RouteError::new(Class::NotFound, "gone"), 404), (RouteError::internal("our fault"), 500), ] { let expected = format!("notice:{:?}:{}", error.tone(), error.message); let response = respond(&Spy, Err(error), &asked("GET", "/")); assert_eq!(response.status(), status); assert_eq!(text(&response), expected); } } #[test] fn an_error_body_is_sent_rather_than_left_to_the_status() { // htmx will drop it unless the page carries `htmx::CONFIG_META`, which is // exactly why that constant is not optional. let response = respond( &Spy, Err(RouteError::denied("not yours")), &asked("GET", "/"), ); assert!(!response.body().is_empty()); } #[test] fn the_content_type_is_the_renderers_answer() { struct Json; impl Serves for Json { fn screen(&self, _: &Screen) -> String { "{}".to_owned() } fn fragment(&self, _: &Node) -> String { "{}".to_owned() } fn content_type(&self) -> &'static str { "application/json" } } let screen = Screen::sidebar_content("Home"); let response = respond(&Json, Ok(screen.into()), &asked("GET", "/")); assert_eq!( response.headers().get(http::header::CONTENT_TYPE).unwrap(), "application/json" ); } /// The two history headers on a response, for the assertions below. fn history(response: &http::Response>) -> (Option<&str>, Option<&str>) { let get = |name| { response .headers() .get(name) .map(|value| value.to_str().unwrap()) }; (get(super::htmx::PUSH_URL), get(super::htmx::REPLACE_URL)) } #[test] fn a_read_of_a_screen_is_a_place_and_carries_the_address_it_was_read_from() { // The common case, and it costs a description nothing: the address is the // request's own, so no control had to predict what its answer would be. let screen = Screen::sidebar_content("Projects"); let response = respond( &Spy, Ok(screen.into()), &asked("GET", "/projects?sort=name"), ); // Params included. A filtered list is a different place from the list. assert_eq!(history(&response).0, Some("/projects?sort=name")); assert_eq!(history(&response).1, None); } #[test] fn a_write_answering_with_a_screen_is_not_a_place() { // The address is where the form was. Coming back to it should not re-offer // the write's result as a page. let screen = Screen::sidebar_content("Saved"); let response = respond(&Spy, Ok(screen.into()), &asked("POST", "/projects/7")); assert_eq!(history(&response), (None, None)); } #[test] fn a_fragment_is_not_a_place_unless_it_says_so() { let plain = respond( &Spy, Ok(Response::fragment("detail", Node::text("hello"))), &asked("GET", "/projects/7/tab/files"), ); assert_eq!(history(&plain), (None, None)); // The addressable tab panel: the answer is a fragment and a place, and the // address is not the route that was fetched. 32 of the server's panels. let addressed = respond( &Spy, Ok(Response::fragment("tab-content", Node::text("hello")).at("/dashboard#tab-projects")), &asked("GET", "/projects/7/tab/files"), ); assert_eq!(history(&addressed).0, Some("/dashboard#tab-projects")); } #[test] fn the_override_can_say_no_as_well_as_yes() { let screen = Screen::sidebar_content("Transient"); // A read of a screen that should not come back on the back button. let suppressed = respond( &Spy, Ok(Response::screen(screen.clone()).in_place()), &asked("GET", "/wizard/step-2"), ); assert_eq!(history(&suppressed), (None, None)); // And a place that takes the current entry's slot rather than adding one. let replaced = respond( &Spy, Ok(Response::screen(screen).replacing("/projects?sort=age")), &asked("GET", "/projects"), ); assert_eq!(history(&replaced).1, Some("/projects?sort=age")); assert_eq!(history(&replaced).0, None); } #[test] fn a_redirect_sets_neither_because_htmx_already_pushes() { // HX-Location issues the request client-side and htmx pushes for it, and // HX-Redirect is a real navigation. A second answer here would be two // parties deciding one thing. let response = respond( &Spy, Ok(Response::goto(Action::get("/projects"))), &asked("POST", "/projects/7/delete"), ); assert_eq!(history(&response), (None, None)); } #[test] fn a_write_naming_two_slots_carries_both_behind_the_one_it_replaced() { // The row the write was aimed at, and the count above it that also moved. // Both on one answer, in the order the router named them, so the two can // never disagree and no second request is made for a fact it already had. let response = respond( &Spy, Ok(Response::fragment("row-7", Node::text("Done")) .also("task-count", Node::text("4 left")) .also("sidebar-badge", Node::text("4"))), &asked("POST", "/tasks/7/done"), ); let body = String::from_utf8(response.body().clone()).expect("the spy answers text"); assert_eq!( body, "text:Done[oob:task-count:text:4 left][oob:sidebar-badge:text:4]" ); // The retarget still names one target. A set of invalidations is a // different fact, and conflating them was the rejected option. assert_eq!( response .headers() .get(super::htmx::RETARGET) .map(|value| value.to_str().expect("a slot id is ascii")), Some("#row-7") ); } #[test] fn a_whole_screen_and_a_redirect_carry_no_out_of_band_copy() { // Not a case being dropped. A screen replaces every slot already, so an // out-of-band copy would put a second element into the document under an // id it now has twice; a redirect has no body at all. let screen = Screen::sidebar_content("Tasks").with(Slot::new("main", RegionKind::Pane)); let swapped = respond( &Spy, Ok(Response::screen(screen).also("task-count", Node::text("4 left"))), &asked("GET", "/tasks"), ); let body = String::from_utf8(swapped.body().clone()).expect("the spy answers text"); assert_eq!(body, "screen:Tasks"); let sent = respond( &Spy, Ok(Response::goto(Action::get("/tasks")).also("task-count", Node::text("4 left"))), &asked("POST", "/tasks/7/delete"), ); assert!(sent.body().is_empty()); } #[test] fn a_renderer_that_does_not_answer_markup_drops_an_invalidation() { // The default on `Serves::invalidated`, which is the honest answer for a // renderer with no out-of-band channel rather than an oversight: a JSON // client learns what changed from the payload it already parses. struct Json; impl Serves for Json { fn screen(&self, _: &Screen) -> String { "{}".to_owned() } fn fragment(&self, _: &Node) -> String { "{}".to_owned() } } let response = respond( &Json, Ok(Response::fragment("row-7", Node::text("Done")).also("count", Node::text("4"))), &asked("POST", "/tasks/7/done"), ); assert_eq!(response.body(), b"{}"); }