//! 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::{Accepted, 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 suggestions(&self, field: &str, options: &[quasi_router::Candidate]) -> String { format!( "suggestions:{field}:{}", options .iter() .map(|choice| choice.value.as_str()) .collect::>() .join(",") ) } 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}"), Node::StandIn { state, message, .. } => format!("standin:{state:?}:{message}"), 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 same, as htmx would have made it. /// /// Built through `decode` off a real header for `asked`'s reason: whether a /// request is an XHR is read off the wire, and a test that set the flag by hand /// would pass whether or not `decode` ever looked. fn asked_by_htmx(method: &str, uri: &str) -> super::Asked { let request = http::Request::builder() .method(method) .uri(uri) .header(super::htmx::REQUEST, "true") .body(()) .unwrap(); let incoming = decode( request.method(), request.uri(), request.headers(), b"", DEFAULT_BODY_LIMIT, ) .unwrap(); assert!(incoming.htmx, "the header was not read"); super::Asked::new(&incoming) } /// 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 4 swaps every status but 204 and 304, so the body is what the // reader sees for a denial. Under 2.x it was dropped unless the page // carried a `responseHandling` config, which is the constant that left // `htmx.rs` when the emitter moved to 4. 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 suggestions(&self, field: &str, options: &[quasi_router::Candidate]) -> String { format!("suggestions:{field}:{}", options.len()) } 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 suggestions(&self, field: &str, options: &[quasi_router::Candidate]) -> String { format!("suggestions:{field}:{}", options.len()) } 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"{}"); } /// A file answer is the bytes and the header, and no renderer is consulted on /// the way: the `Spy` says what it was handed, and it was handed nothing. #[test] fn a_binary_file_is_refused_to_htmx_rather_than_answered_corrupt() { // `3bdf1a75`. htmx leaves `responseType` unset, so the browser decodes the // body as UTF-8 before `DOWNLOAD_JS` sees it: a zip answered this way // downloads with U+FFFD where its bytes were, and looks exactly like one // that worked. Loud beats corrupt. let response = respond( &Spy, Ok(Response::file( "backup.zip", Accepted::media_type("application/zip"), vec![0x50, 0x4b, 0x03, 0x04, 0xff], )), &asked_by_htmx("POST", "/data/backup"), ); assert_eq!(response.status(), 501); assert!( response .headers() .get(http::header::CONTENT_DISPOSITION) .is_none() ); // The refusal names the media type and both ways out, because "cannot" // with no next step is a dead end. let said = text(&response); assert!(said.contains("backup.zip"), "{said}"); assert!(said.contains("application/zip"), "{said}"); assert!(said.contains("plain link"), "{said}"); } #[test] fn the_same_file_over_a_plain_navigation_is_answered() { // The no-script path is unaffected and always was: the browser navigates, // reads the same header and saves the bytes as they arrived. The guard is // about a control this renderer emits, because every such control is an // XHR. let bytes = vec![0x50, 0x4b, 0x03, 0x04, 0xff]; let response = respond( &Spy, Ok(Response::file( "backup.zip", Accepted::media_type("application/zip"), bytes.clone(), )), &asked("GET", "/data/backup"), ); assert_eq!(response.status(), 200); assert_eq!(response.body(), &bytes); } #[test] fn every_export_in_the_tree_still_downloads_over_htmx() { // The measured sites, and the reason the guard is safe to add: goingson's // three exports are the only described files a webview host answers, and // all three are text. for kind in ["application/json", "text/csv", "text/calendar"] { let response = respond( &Spy, Ok(Response::file( "export", Accepted::media_type(kind), b"x".to_vec(), )), &asked_by_htmx("POST", "/data/export"), ); assert_eq!(response.status(), 200, "{kind} was refused"); } // A charset does not change what the type is, and a structured suffix is // text by RFC 6839's construction rather than by a list anyone maintains. for kind in [ "text/csv; charset=utf-8", "application/geo+json", "image/svg+xml", ] { let response = respond( &Spy, Ok(Response::file( "export", Accepted::media_type(kind), b"x".to_vec(), )), &asked_by_htmx("POST", "/data/export"), ); assert_eq!(response.status(), 200, "{kind} was refused"); } } #[test] fn a_kind_that_is_not_a_media_type_cannot_be_shown_to_be_text() { // A `Suffix` is a name and a `Family` is a filter, and this crate keeps no // suffix table on purpose. Both answer "cannot say", which is read as "not // safe": a wrong guess here is a corrupt file rather than a wrong header. for kind in [ Accepted::suffix(".csv"), Accepted::family(quasi_router::layout::Family::Image), ] { let response = respond( &Spy, Ok(Response::file("export", kind, b"x".to_vec())), &asked_by_htmx("POST", "/data/export"), ); assert_eq!(response.status(), 501); assert!(text(&response).contains("no media type")); } } #[test] fn a_file_answer_is_the_bytes_under_an_attachment_header() { let response = respond( &Spy, Ok(Response::file( "goingson-export.json", Accepted::media_type("application/json"), br#"{"tasks":[]}"#.to_vec(), )), &asked("POST", "/data/export/json"), ); assert_eq!(response.status(), 200); assert_eq!(response.body(), br#"{"tasks":[]}"#); assert_eq!( response .headers() .get(http::header::CONTENT_TYPE) .and_then(|value| value.to_str().ok()), Some("application/json") ); let disposition = response .headers() .get(http::header::CONTENT_DISPOSITION) .and_then(|value| value.to_str().ok()) .expect("a file answer says it is an attachment"); assert!(disposition.starts_with("attachment; ")); assert!(disposition.contains(r#"filename="goingson-export.json""#)); assert!(disposition.contains("filename*=UTF-8''goingson-export.json")); } /// A kind that is not a media type is not turned into one. `.csv` says what to /// call the file and says nothing about what is in it, and guessing would mean /// this crate keeping a suffix table the description layer deliberately lacks. #[test] fn a_kind_that_is_not_a_media_type_sends_bytes() { for kind in [ Accepted::suffix(".csv"), Accepted::family(quasi_router::layout::Family::Image), ] { let response = respond( &Spy, Ok(Response::file("export", kind, b"a,b\n".to_vec())), &asked("POST", "/data/export/csv"), ); assert_eq!( response .headers() .get(http::header::CONTENT_TYPE) .and_then(|value| value.to_str().ok()), Some("application/octet-stream") ); } } /// A name is user input by the time it reaches here, and neither half of the /// header may carry what it says. A separator would be a path on the host that /// writes it and a newline would be a second header. #[test] fn a_hostile_file_name_reaches_neither_form_of_the_header() { let response = respond( &Spy, Ok(Response::file( "../../.ssh/authorized_keys\r\nX-Evil: 1", Accepted::media_type("text/plain"), b"ssh-rsa".to_vec(), )), &asked("POST", "/data/export"), ); let disposition = response .headers() .get(http::header::CONTENT_DISPOSITION) .and_then(|value| value.to_str().ok()) .expect("the header is still built"); assert!(!disposition.contains("..")); assert!(!disposition.contains('/')); assert!(!disposition.contains('\r')); assert!(!disposition.contains('\n')); assert_eq!(response.headers().get("x-evil"), None); } /// A file is not a place. A write that hands over a download leaves the address /// bar where it was, the same as every other write. #[test] fn a_file_answer_pushes_no_address() { let response = respond( &Spy, Ok(Response::file( "a.json", Accepted::media_type("application/json"), b"{}".to_vec(), )), &asked("GET", "/data/export/json"), ); assert_eq!(response.headers().get(crate::htmx::PUSH_URL), None); assert_eq!(response.headers().get(crate::htmx::RETARGET), None); } /// The notice rides along with a file the way it rides along with the other /// four outcomes, because it is a field on the response rather than a member of /// the outcome. #[test] fn a_file_answer_can_still_say_something() { let response = respond( &Spy, Ok(Response::file( "a.json", Accepted::media_type("application/json"), b"{}".to_vec(), ) .toast(quasi_router::layout::Tone::Success, "exported")), &asked("POST", "/data/export/json"), ); assert!(response.headers().contains_key(crate::htmx::TRIGGER)); } #[test] fn an_ask_for_a_place_is_refused_where_the_reader_can_see_it() { // `ec92f9cb`. This host has no picker, and the rule for a host that cannot // perform an outcome is that it says so rather than answering 200 with // nothing done. let answer = Response::locate(quasi_router::Locating::folder( "Import folder", Action::post("/import/from"), "folder", )); let response = respond(&Spy, Ok(answer), &asked("POST", "/import/open")); assert_eq!(response.status(), 501); assert_eq!( text(&response), "notice:Danger:this host cannot choose a folder: Import folder" ); } #[test] fn the_save_shape_is_refused_by_its_own_name() { // `7fda7ae3`. A browser has a download and does not have a destination it // can hand back, so the save shape is refused like the rest, and named: // "cannot choose a place" would leave a reader guessing which of the two // file dialogs the app meant. let answer = Response::locate(quasi_router::Locating::new( quasi_router::Sought::Save { name: "drums.afcl".into(), accept: vec![Accepted::suffix(".afcl")], }, "Export classifier", Action::post("/classifier/export"), "path", )); let response = respond(&Spy, Ok(answer), &asked("POST", "/classifier/open")); assert_eq!(response.status(), 501); assert_eq!( text(&response), "notice:Danger:this host cannot choose where to save: Export classifier" ); } /// An anchored answer is retargeted at the container the anchor names, not at /// the app's one overlay container -- and the swap style is left alone, which /// `htmx::RESWAP`'s docs say is not this adapter's to set. #[test] fn an_anchored_answer_is_aimed_at_the_container_its_anchor_names() { /// The overlay half of `Spy`, which answers targets for both members so a /// test can tell one from the other. struct Popovers; impl Serves for Popovers { fn screen(&self, screen: &Screen) -> String { format!("screen:{}", screen.title) } fn fragment(&self, _node: &Node) -> String { String::new() } fn suggestions(&self, _field: &str, _options: &[quasi_router::Candidate]) -> String { String::new() } fn overlay_target(&self) -> Option<&str> { Some("app-overlay") } fn anchored(&self, screen: &Screen) -> String { format!("anchored:{}", screen.title) } fn anchored_target(&self, anchor: &quasi_router::Anchor) -> Option { match anchor { quasi_router::Anchor::Region(id) | quasi_router::Anchor::Control(id) => { Some(format!("{id}-anchored")) } quasi_router::Anchor::Selection => Some("selection-anchored".to_owned()), } } } let menu = Screen::sidebar_content("Menu").with(Slot::new("menu", RegionKind::Pane)); let answer = Response::anchored(menu, quasi_router::Anchor::Region("browser".into())); let response = respond(&Popovers, Ok(answer), &asked("GET", "/menu")); assert_eq!(response.status(), 200); assert_eq!( response.headers().get(super::htmx::RETARGET).unwrap(), "#browser-anchored" ); // Not the app's overlay container, which is the whole difference between // the two outcomes on this host. assert_eq!(response.body(), b"anchored:Menu"); // The swap style travels with the element, so nothing here overrides it. assert!(response.headers().get(super::htmx::RESWAP).is_none()); } /// A renderer with no popover container answers `None` and the fragment lands /// where it was aimed. That is the bargain `Suggestions` and `Over` already /// strike, and the default `Serves` impl is what makes it the quiet path. #[test] fn a_renderer_with_no_popover_container_sends_the_menu_unaimed() { let menu = Screen::sidebar_content("Menu"); let answer = Response::anchored(menu, quasi_router::Anchor::Selection); let response = respond(&Spy, Ok(answer), &asked("GET", "/menu")); assert_eq!(response.status(), 200); assert!(response.headers().get(super::htmx::RETARGET).is_none()); // And `anchored` fell through to `overlay`, which fell through to the // screen: the menu is drawn, unlayered, rather than dropped. assert_eq!(response.body(), b"screen:Menu"); } /// Handing work off answers the region it will fill, aimed the way a fragment /// naming that region is aimed. What lands is a pending stand-in, because /// `aria-busy` is on the region element and an innerHTML swap does not reach /// it -- so on this host the wait has to be a node. #[test] fn started_aims_a_pending_standin_at_the_region_the_work_will_fill() { let answer = Response::started("backups", "Creating backup…"); let response = respond(&Spy, Ok(answer), &asked("POST", "/backups")); assert_eq!(response.status(), 200); assert_eq!( response.headers().get(super::htmx::RETARGET).unwrap(), "#backups" ); assert_eq!(text(&response), "standin:Pending:Creating backup…"); // Nothing here tells the client to poll. The region carries its own // `hx-trigger` from `Slot::live`, and a cadence the description declined to // name is not this adapter's to invent. assert!(response.headers().get(super::htmx::TRIGGER).is_none()); // And the swap style travels with the element, as everywhere else. assert!(response.headers().get(super::htmx::RESWAP).is_none()); } /// The address half: starting work is not a place. The reader stays on the /// screen that is now waiting, which is the whole point of being able to say /// this rather than redirecting. #[test] fn started_pushes_no_url_and_sends_the_reader_nowhere() { let answer = Response::started("backups", "Creating backup…"); assert_eq!(answer.target(), Some("backups")); assert!(answer.destination().is_none()); let response = respond(&Spy, Ok(answer), &asked("POST", "/backups")); assert!(response.headers().get(super::htmx::LOCATION).is_none()); }